lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
mit
error: pathspec 'src/main/java/leetcode/Problem354.java' did not match any file(s) known to git
73248344d82c2bfd0fcb558e288b88cad1312916
1
fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode
package leetcode; /** * https://leetcode.com/problems/russian-doll-envelopes/ */ public class Problem354 { public int maxEnvelopes(int[][] envelopes) { // TODO return 0; } public static void main(String[] args) { Problem354 prob = new Problem354(); System.out.println(prob.maxEnvelopes(new int[][]{ {5, 4}, {6, 4}, {6, 7}, {2, 3} })); } }
src/main/java/leetcode/Problem354.java
Skeleton for problem 354
src/main/java/leetcode/Problem354.java
Skeleton for problem 354
Java
mit
error: pathspec 'src/prove/CopyElemFromArrayToArrays.java' did not match any file(s) known to git
43d0acb28736f4ca7c9ceaed2f7661ad34175f29
1
persey86/my_study
package prove; import java.io.BufferedReader; import java.io.InputStreamReader; /** * Created by Anastasia on 13.09.2016. */ public class CopyElemFromArrayToArrays { public static void main(String[] args) throws Exception { BufferedReader rs = new BufferedReader(new InputStreamReader(System.in)); int mas[] = new int[20]; int mas1[] = new int[10]; int mas2[] = new int[10]; for (int i = 0; i < 20; i++) { mas[i] = Integer.parseInt(rs.readLine()); } System.arraycopy(mas, 0, mas1, 0, 10); System.arraycopy(mas, 10, mas2, 0, 10); for(int i = 0; i < mas2.length; i++) { System.out.println(mas2[i]); } } }
src/prove/CopyElemFromArrayToArrays.java
There were created method which may copy definites elements from any array to others arrays
src/prove/CopyElemFromArrayToArrays.java
There were created method which may copy definites elements from any array to others arrays
Java
mit
error: pathspec 'standingordersystem/OrderEntrySystem.java' did not match any file(s) known to git
4fe36733d7e46a8ed93df107e7635a6b2a5911ec
1
youldash/NCCC,youldash/NCCC
/** * @author Mustafa Youldash <mmyouldash@uqu.edu.sa>. * @copyright (c) 2016 Umm Al-Qura University. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the author nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Standing Order System package created using TextMate version 2.0 on a Mac OS X 10.10.5 system. */ package standingordersystem; import java.util.Set; import java.util.HashSet; import java.lang.String; /** * OrderEntrySystem class. */ public class OrderEntrySystem { protected Set<Customer> customerList; protected Set<Product> productList; protected Set<Order> orderList; protected Set<Delivery> deliveryList; protected Set<Invoice> invoiceList; protected Set<Address> addressList; /** * Default constructor. */ public OrderEntrySystem() { /* * Initialize all collections for later use. */ this.customerList = new HashSet<Customer>(); this.productList = new HashSet<Product>(); this.orderList = new HashSet<Order>(); this.deliveryList = new HashSet<Delivery>(); this.invoiceList = new HashSet<Invoice>(); this.addressList = new HashSet<Address>(); } /** * @return a string description */ public String toString() { /* * Retrieve all existing customers. */ String customers = new String(); for (Customer customer : customerList) { customers = customers + "\n\t" + customer; } /* * Retrieve all existing addresses. */ String addresses = new String(); for (Address address : addressList) { addresses = addresses + "\n\t" + address; } /* * Retrieve all existing products. */ String products = new String(); for (Product product: productList) { products = products + "\n\t" + product; } /* * Retrieve all existing orders. */ String orders = new String(); for (Order order : orderList) { orders = orders + "\n\t" + order; } /* * Retrieve all deliveries. */ String deliveries = new String(); for (Delivery delivery : deliveryList) { deliveries = deliveries + "\n\t" + delivery; } /* * Concatenate all data into a single string and then return it. */ return "OrderEntrySystem[" + "\ncustomerList: " + customers + "\naddressList: " + addresses + "\nproductList: " + products + "\norderList: " + orders + "\ndeliveryList: " + deliveries + "\n]"; } /** * Add a new customer. * * @param id * @param name * @throws Exception */ public void addCustomer(String id, String name) throws Exception { Customer customer = (Customer)Helper.search(customerList, id); boolean pre = (customer == null); if (!pre) { String message = "ERROR: Customer ID is not unique!"; throw new Exception(message); } customer = new Customer(id, name); customerList.add(customer); } /** * Add an address. * * @param id * @param line1 * @param line2 * @param contactPerson * @param contactPhone * @throws Exception */ public void addAddress(String id, String line1, String line2, String contactPerson, String contactPhone) throws Exception { String message; /* * Address checking. */ Address address = (Address)Helper.search(addressList, id); boolean pre = (address == null); if (!pre) { message = "ERROR addAddress: Cannot add Customer; Address Id is not unique!"; throw new Exception(message); } /* * Finally, create the new address, and add it to the appropriate list. */ address = new Address(id, line1, line2, contactPerson, contactPhone); addressList.add(address); } /** * Add an address to an existing customer. * * @param customerId * @param address * @throws Exception */ public void addAddressToCustomer(String customerId, Address address) throws Exception { String message; /* * Customer checking. */ Customer customer = (Customer)Helper.search(customerList, customerId); boolean pre1 = (customer != null); if (!pre1) { message = "ERROR addAddressToCustomer: Customer ID does not exist!"; throw new Exception(message); } /* * Address checking. */ boolean pre2 = ((Address)Helper.search(addressList, address.getId()) == null); if (!pre2) { message = "ERROR addAddressToCustomer: Cannot add Address; Address Id is not unique!"; throw new Exception(message); } /* * Finally, create the new address, and add it to the appropriate list. */ addressList.add(address); /* * Also add the address to that customer. */ customer.getAddresses().add(address); } /** * Add a new product. * * @param number * @param name * @param price * @param quantity * @throws Exception */ public void addProduct(String number, String name, double price, int quantity) throws Exception { Product product = (Product)Helper.search(productList, number); boolean pre = (product == null); if (!pre) { String message = "ERROR addProduct: Product Number is not unique!"; throw new Exception(message); } product = new Product(number, name, price, quantity); productList.add(product); } /** * Add a standing order to an existing customer. * * @param number * @param customerId * @param addressId * @param productId * @param quantities * @throws Exception */ public void addOrder( String number, String customerId, String addressId, String productId, int[] quantities, int startDate, int endDate, OrderStatus status) throws Exception { /* * Assume two arrays are of of the same length. In fact, * we should check that this condition is satisfied (as another precondition). */ String message; /* * Order checking. */ Order order = (Order)Helper.search(orderList, number); boolean pre1 = (order == null); if (!pre1) { message = "ERROR addOrder: Order Number is not unique!"; throw new Exception(message); } /* * Order checking. */ Customer customer = (Customer)Helper.search(customerList, customerId); boolean pre2 = (customer != null); if (!pre2) { message = "ERROR addOrder: Cannot add Order; Customer does not exist!"; throw new Exception(message); } /* * Product checking. */ Product product = (Product)Helper.search(productList, productId); boolean pre3 = (product != null); if (!pre3) { message = "ERROR addOrder: Cannot add Order; Product does not exist!"; throw new Exception(message); } /* * Address checking. */ Address address = (Address)Helper.search(addressList, addressId); boolean pre4 = (address != null); if (!pre4) { message = "ERROR addOrder: Cannot add Order; Address does not exist!"; throw new Exception(message); } /* * Quantity checking. */ boolean pre5 = true; for (int quantity : quantities) { if (quantity < 0) { pre5 = false; break; } } if (!pre5) { message = "ERROR addOrder: Cannot add Order; Quantities entered are invalid!"; throw new Exception(message); } /* * Finally, create the new order, and add it to the appropriate lists. */ order = new Order(number, customer, address, product, quantities, startDate, endDate, status); orderList.add(order); customer.getOrders().add(order); } /** * Print any standing orders according to a given date. * Informs whether the print found any orders or not. * * @param date */ public void listStandingOrders(int date) throws Exception { String message; /* * Orders checking. */ boolean pre1 = (!orderList.isEmpty()); if (!pre1) { message = "ERROR listStandingOrders: Cannot list Orders; List is empty!"; throw new Exception(message); } /* * Print standing orders according to a given date, listed by customers. */ int ordersCount = 0; for (Customer customer : customerList) { System.out.println("Standing Orders for Customer " + customer.getID() + ":"); for (Order order : customer.getOrders()) { if (order.getStartDate() == date) { System.out.println(order.toString()); ordersCount++; } } } /* * Order match checking. */ if (ordersCount == 0) { message = "ERROR listStandingOrders: Cannot list Orders; No match found!"; throw new Exception(message); } } /** * Add a new delivery. * * @param deliveryId * @param customerId * @param addressId * @param date * @param dayOfWeek * @throws Exception */ public void addDelivery(Delivery delivery, DeliveryItem deliveryItem) throws Exception { String message; /* * Customer checking. // Pass the delivery object. */ Customer customer = (Customer)Helper.search(customerList, delivery.getCustomer().getID()); boolean pre1 = (customer != null); if (!pre1) { message = "ERROR addDelivery: Cannot add Delivery; Customer does not exist!"; throw new Exception(message); } /* * Customer address checking. */ Address address = (Address)Helper.search(addressList, delivery.getAddress().getId()); boolean pre2 = (address != null); if (!pre2) { message = "ERROR addDelivery: Cannot add Delivery; Customer does not exist!\n"; throw new Exception(message); } /* * Add the new delivery. */ delivery.addDeliveryItem(deliveryItem); deliveryList.add(delivery); } /** * List existing customers. * * @param endDate * @throws Exception */ public void listCustomers(int endDate) throws Exception { String message; /* * Delivery checking. */ for (Delivery delivery : deliveryList) { Customer customer = (Customer)Helper.search(customerList, delivery.getCustomer().getID()); boolean pre1 = (customer != null); if (!pre1) { message = "ERROR listCustomers: Customer does not exist!"; throw new Exception(message); } /* * Order checking. */ for (Order order : customer.getOrders()) { if (endDate <= order.getEndDate()) { System.out.println("listCustomers: " + customer.toString()); } } } } /** * Add a new invoice for an existing customer. * * @param customer * @throws Exception */ public void addInvoice( String id, int fromDate, int toDate, Delivery delivery, double totalCost, int payDate) throws Exception { String message; /* * Customer checking. */ Customer customer = (Customer)Helper.search(customerList, delivery.getCustomer().getID()); boolean pre1 = (customer != null); if (!pre1) { message = "ERROR addDelivery: Cannot add Delivery; Customer does not exist!"; throw new Exception(message); } /* * Add the invoice, then add the delivery. */ Invoice invoice = new Invoice(id, fromDate, toDate, customer, totalCost, payDate); invoice.addDelivery(delivery); this.invoiceList.add(invoice); } }
standingordersystem/OrderEntrySystem.java
Java class added. Java class added.
standingordersystem/OrderEntrySystem.java
Java class added.
Java
mit
error: pathspec 'Gapful_numbers/Java/src/GapfulNumbers.java' did not match any file(s) known to git
ddd41717dfab9e4d2a905c89d902b5cf4e3719f6
1
ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta,ncoe/rosetta
import java.util.List; public class GapfulNumbers { private static String commatize(long n) { StringBuilder sb = new StringBuilder(Long.toString(n)); int le = sb.length(); for (int i = le - 3; i >= 1; i -= 3) { sb.insert(i, ','); } return sb.toString(); } public static void main(String[] args) { List<Long> starts = List.of((long) 1e2, (long) 1e6, (long) 1e7, (long) 1e9, (long) 7123); List<Integer> counts = List.of(30, 15, 15, 10, 25); for (int i = 0; i < starts.size(); ++i) { int count = 0; Long j = starts.get(i); long pow = 100; while (j >= pow * 10) { pow *= 10; } System.out.printf("First %d gapful numbers starting at %s:\n", counts.get(i), commatize(starts.get(i))); while (count < counts.get(i)) { long fl = (j / pow) * 10 + (j % 10); if (j % fl == 0) { System.out.printf("%d ", j); count++; } j++; if (j >= 10 * pow) { pow *= 10; } } System.out.println('\n'); } } }
Gapful_numbers/Java/src/GapfulNumbers.java
Added solution to the gapful numbers problem using java
Gapful_numbers/Java/src/GapfulNumbers.java
Added solution to the gapful numbers problem using java
Java
mit
error: pathspec 'ctci/ed6/arrays-and-strings/ZeroMatrix.java' did not match any file(s) known to git
456f6db9ed6b18368398c93b86a0bf0c70e76e87
1
vmaudgalya/misc
import java.util.List; import java.util.ArrayList; public class ZeroMatrix { public static int[][] zeroMatrix(int[][] matrix) { if (matrix == null) { return null; } int rows = matrix.length; int columns = matrix[0].length; int[] rowNums = new int[rows]; int[] colNums = new int[columns]; initializeArray(rowNums); initializeArray(colNums); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (matrix[i][j] == 0) { rowNums[i] = i; colNums[j] = j; } } } for (int row : rowNums) { if (row != -1) { for (int i = 0; i < matrix.length; i++) { matrix[row][i] = 0; } } } for (int col : colNums) { if (col != -1) { for (int i = 0; i < matrix.length; i++) { matrix[i][col] = 0; } } } return matrix; } public static void main(String[] args) { int[][] matrix = {{0, 2, 1, 8}, {6, 4, 6, 1}, {7, 5, 9, 5}, {6, 1, 1, 0}}; String[] rows = java.util.Arrays.deepToString(zeroMatrix(matrix)).split("], "); for (String row : rows) { System.out.println(row); } } private static void initializeArray(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = -1; } } }
ctci/ed6/arrays-and-strings/ZeroMatrix.java
bruteforce for ZeroMatrix
ctci/ed6/arrays-and-strings/ZeroMatrix.java
bruteforce for ZeroMatrix
Java
mit
error: pathspec 'src/com/aopphp/go/parser/PointcutLexer.java' did not match any file(s) known to git
81e1f4ea9710ab83706b48010424e3da2a2a1ff8
1
goaop/idea-plugin
/* The following code was generated by JFlex 1.4.3 on 08.05.15 9:48 */ package com.aopphp.go.parser; import com.intellij.lexer.*; import com.intellij.psi.tree.IElementType; import static com.aopphp.go.psi.PointcutTypes.*; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.3 * on 08.05.15 9:48 from the specification file * <tt>/src/com/aopphp/go/parser/PointcutLexer.flex</tt> */ public class PointcutLexer implements FlexLexer { /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\1\1\2\1\0\1\1\1\1\22\0\1\1\1\0\1\10"+ "\4\0\1\6\7\0\1\3\12\5\6\0\1\11\32\4\1\0\1\7"+ "\2\0\1\4\1\0\1\12\1\31\1\13\1\32\1\14\1\30\1\4"+ "\1\25\1\21\2\4\1\26\1\34\1\23\1\22\1\35\1\4\1\36"+ "\1\15\1\20\1\17\1\37\1\24\1\16\1\33\1\27\4\0\201\4"+ "\uff00\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\1\2\1\1\1\3\1\1\1\4\1\1"+ "\1\5\11\3\1\6\1\0\1\7\3\0\46\3\1\10"+ "\4\3\1\11\4\3\1\12\1\3\1\13\6\3\1\14"+ "\1\15\7\3\1\16\2\3\1\17\1\20\11\3\1\21"+ "\5\3\1\22"; private static int [] zzUnpackAction() { int [] result = new int[111]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\40\0\100\0\140\0\200\0\240\0\40\0\300"+ "\0\40\0\340\0\u0100\0\u0120\0\u0140\0\u0160\0\u0180\0\u01a0"+ "\0\u01c0\0\u01e0\0\u0200\0\240\0\40\0\u0220\0\300\0\u0240"+ "\0\u0260\0\u0280\0\u02a0\0\u02c0\0\u02e0\0\u0300\0\u0320\0\u0340"+ "\0\u0360\0\u0380\0\u03a0\0\u03c0\0\u03e0\0\u0400\0\u0420\0\u0440"+ "\0\u0460\0\u0480\0\u04a0\0\u04c0\0\u04e0\0\u0500\0\u0520\0\u0540"+ "\0\u0560\0\u0580\0\u05a0\0\u05c0\0\u05e0\0\u0600\0\u0620\0\u0640"+ "\0\u0660\0\u0680\0\u06a0\0\u06c0\0\u06e0\0\u0700\0\200\0\u0720"+ "\0\u0740\0\u0760\0\u0780\0\200\0\u07a0\0\u07c0\0\u07e0\0\u0800"+ "\0\200\0\u0820\0\200\0\u0840\0\u0860\0\u0880\0\u08a0\0\u08c0"+ "\0\u08e0\0\200\0\200\0\u0900\0\u0920\0\u0940\0\u0960\0\u0980"+ "\0\u09a0\0\u09c0\0\200\0\u09e0\0\u0a00\0\200\0\200\0\u0a20"+ "\0\u0a40\0\u0a60\0\u0a80\0\u0aa0\0\u0ac0\0\u0ae0\0\u0b00\0\u0b20"+ "\0\200\0\u0b40\0\u0b60\0\u0b80\0\u0ba0\0\u0bc0\0\200"; private static int [] zzUnpackRowMap() { int [] result = new int[111]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\2\2\3\1\4\1\5\1\2\1\6\1\7\1\10"+ "\1\11\1\12\1\13\1\14\1\15\3\5\1\16\2\5"+ "\1\17\3\5\1\20\1\5\1\21\2\5\1\22\2\5"+ "\41\0\2\3\40\0\1\23\40\0\2\5\4\0\26\5"+ "\6\24\1\25\1\26\30\24\7\27\1\30\1\25\27\27"+ "\4\0\2\5\4\0\1\5\1\31\24\5\4\0\2\5"+ "\4\0\16\5\1\32\7\5\4\0\2\5\4\0\4\5"+ "\1\33\21\5\4\0\2\5\4\0\6\5\1\34\17\5"+ "\4\0\2\5\4\0\11\5\1\35\14\5\4\0\2\5"+ "\4\0\7\5\1\36\16\5\4\0\2\5\4\0\7\5"+ "\1\37\16\5\4\0\2\5\4\0\21\5\1\40\4\5"+ "\4\0\2\5\4\0\5\5\1\41\16\5\1\42\1\5"+ "\2\23\1\0\35\23\2\24\1\0\35\24\2\27\1\0"+ "\35\27\4\0\2\5\4\0\1\5\1\43\24\5\4\0"+ "\2\5\4\0\14\5\1\44\11\5\4\0\2\5\4\0"+ "\2\5\1\45\23\5\4\0\2\5\4\0\1\46\25\5"+ "\4\0\2\5\4\0\7\5\1\47\16\5\4\0\2\5"+ "\4\0\6\5\1\50\17\5\4\0\2\5\4\0\11\5"+ "\1\51\14\5\4\0\2\5\4\0\11\5\1\52\14\5"+ "\4\0\2\5\4\0\17\5\1\53\6\5\4\0\2\5"+ "\4\0\7\5\1\54\1\55\15\5\4\0\2\5\4\0"+ "\2\5\1\56\23\5\4\0\2\5\4\0\10\5\1\57"+ "\15\5\4\0\2\5\4\0\1\5\1\60\24\5\4\0"+ "\2\5\4\0\6\5\1\61\17\5\4\0\2\5\4\0"+ "\6\5\1\62\17\5\4\0\2\5\4\0\13\5\1\63"+ "\12\5\4\0\2\5\4\0\1\64\25\5\4\0\2\5"+ "\4\0\1\65\25\5\4\0\2\5\4\0\14\5\1\66"+ "\11\5\4\0\2\5\4\0\25\5\1\67\4\0\2\5"+ "\4\0\6\5\1\70\17\5\4\0\2\5\4\0\3\5"+ "\1\71\22\5\4\0\2\5\4\0\12\5\1\72\13\5"+ "\4\0\2\5\4\0\5\5\1\73\20\5\4\0\2\5"+ "\4\0\7\5\1\74\16\5\4\0\2\5\4\0\7\5"+ "\1\75\16\5\4\0\2\5\4\0\7\5\1\76\16\5"+ "\4\0\2\5\4\0\14\5\1\77\11\5\4\0\2\5"+ "\4\0\22\5\1\100\3\5\4\0\2\5\4\0\7\5"+ "\1\101\16\5\4\0\2\5\4\0\1\102\25\5\4\0"+ "\2\5\4\0\2\5\1\103\23\5\4\0\2\5\4\0"+ "\3\5\1\104\22\5\4\0\2\5\4\0\17\5\1\105"+ "\6\5\4\0\2\5\4\0\6\5\1\106\17\5\4\0"+ "\2\5\4\0\1\5\1\107\24\5\4\0\2\5\4\0"+ "\1\110\25\5\4\0\2\5\4\0\11\5\1\111\14\5"+ "\4\0\2\5\4\0\7\5\1\112\16\5\4\0\2\5"+ "\4\0\1\5\1\113\24\5\4\0\2\5\4\0\6\5"+ "\1\114\17\5\4\0\2\5\4\0\1\5\1\115\24\5"+ "\4\0\2\5\4\0\2\5\1\116\23\5\4\0\2\5"+ "\4\0\7\5\1\117\16\5\4\0\2\5\4\0\7\5"+ "\1\120\16\5\4\0\2\5\4\0\14\5\1\121\11\5"+ "\4\0\2\5\4\0\1\5\1\122\24\5\4\0\2\5"+ "\4\0\2\5\1\123\23\5\4\0\2\5\4\0\6\5"+ "\1\124\17\5\4\0\2\5\4\0\14\5\1\125\11\5"+ "\4\0\2\5\4\0\10\5\1\126\15\5\4\0\2\5"+ "\4\0\11\5\1\127\14\5\4\0\2\5\4\0\7\5"+ "\1\130\16\5\4\0\2\5\4\0\2\5\1\131\23\5"+ "\4\0\2\5\4\0\10\5\1\132\15\5\4\0\2\5"+ "\4\0\11\5\1\133\14\5\4\0\2\5\4\0\7\5"+ "\1\134\16\5\4\0\2\5\4\0\15\5\1\135\10\5"+ "\4\0\2\5\4\0\20\5\1\136\5\5\4\0\2\5"+ "\4\0\12\5\1\137\13\5\4\0\2\5\4\0\6\5"+ "\1\140\17\5\4\0\2\5\4\0\1\141\25\5\4\0"+ "\2\5\4\0\7\5\1\142\16\5\4\0\2\5\4\0"+ "\6\5\1\143\17\5\4\0\2\5\4\0\1\144\25\5"+ "\4\0\2\5\4\0\7\5\1\145\16\5\4\0\2\5"+ "\4\0\14\5\1\146\11\5\4\0\2\5\4\0\10\5"+ "\1\147\15\5\4\0\2\5\4\0\7\5\1\150\16\5"+ "\4\0\2\5\4\0\11\5\1\151\14\5\4\0\2\5"+ "\4\0\15\5\1\152\10\5\4\0\2\5\4\0\1\153"+ "\25\5\4\0\2\5\4\0\6\5\1\154\17\5\4\0"+ "\2\5\4\0\7\5\1\155\16\5\4\0\2\5\4\0"+ "\10\5\1\156\15\5\4\0\2\5\4\0\11\5\1\157"+ "\14\5"; private static int [] zzUnpackTrans() { int [] result = new int[3040]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; private static final char[] EMPTY_BUFFER = new char[0]; private static final int YYEOF = -1; private static java.io.Reader zzReader = null; // Fake /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\4\1\1\11\1\1\1\11\12\1\1\0"+ "\1\11\3\0\127\1"; private static int [] zzUnpackAttribute() { int [] result = new int[111]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private CharSequence zzBuffer = ""; /** this buffer may contains the current text array to be matched when it is cheap to acquire it */ private char[] zzBufferArray; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the textposition at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /* user code: */ public PointcutLexer() { this((java.io.Reader)null); } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public PointcutLexer(java.io.Reader in) { this.zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 102) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } public final int getTokenStart(){ return zzStartRead; } public final int getTokenEnd(){ return getTokenStart() + yylength(); } public void reset(CharSequence buffer, int start, int end,int initialState){ zzBuffer = buffer; zzBufferArray = com.intellij.util.text.CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; zzPushbackPos = 0; zzAtEOF = false; zzAtBOL = true; zzEndRead = end; yybegin(initialState); } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { return true; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; CharSequence zzBufferL = zzBuffer; char[] zzBufferArrayL = zzBufferArray; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 10: { return com.aopphp.go.psi.PointcutTypes.WITHIN; } case 19: break; case 18: { return com.aopphp.go.psi.PointcutTypes.STATICINITIALIZATION; } case 20: break; case 5: { return com.aopphp.go.psi.PointcutTypes.ANNOTATION; } case 21: break; case 11: { return com.aopphp.go.psi.PointcutTypes.PUBLIC; } case 22: break; case 1: { return com.intellij.psi.TokenType.BAD_CHARACTER; } case 23: break; case 4: { return com.aopphp.go.psi.PointcutTypes.NSSEPARATOR; } case 24: break; case 15: { return com.aopphp.go.psi.PointcutTypes.PROTECTED; } case 25: break; case 6: { return com.aopphp.go.psi.PointcutTypes.COMMENT; } case 26: break; case 16: { return com.aopphp.go.psi.PointcutTypes.CFLOWBELOW; } case 27: break; case 9: { return com.aopphp.go.psi.PointcutTypes.ACCESS; } case 28: break; case 17: { return com.aopphp.go.psi.PointcutTypes.INITIALIZATION; } case 29: break; case 12: { return com.aopphp.go.psi.PointcutTypes.DYNAMIC; } case 30: break; case 14: { return com.aopphp.go.psi.PointcutTypes.EXECUTION; } case 31: break; case 8: { return com.aopphp.go.psi.PointcutTypes.FINAL; } case 32: break; case 13: { return com.aopphp.go.psi.PointcutTypes.PRIVATE; } case 33: break; case 3: { return com.aopphp.go.psi.PointcutTypes.NAMEPART; } case 34: break; case 2: { return com.intellij.psi.TokenType.WHITE_SPACE; } case 35: break; case 7: { return com.aopphp.go.psi.PointcutTypes.STRING; } case 36: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; return null; } else { zzScanError(ZZ_NO_MATCH); } } } } }
src/com/aopphp/go/parser/PointcutLexer.java
Add generated lexer
src/com/aopphp/go/parser/PointcutLexer.java
Add generated lexer
Java
mit
error: pathspec 'src/test/java/me/coley/recaf/InputTest.java' did not match any file(s) known to git
4ebb70047a968d12b8afcd27fe98dd34031e1a9c
1
Col-E/Recaf,Col-E/Recaf
package me.coley.recaf; import me.coley.event.Bus; import me.coley.recaf.event.ClassRenameEvent; import me.coley.recaf.event.MethodRenameEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.io.File; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; /** * Tests for the Input class. * * @author Matt */ public class InputTest { private final static int CLASS_COUNT = 9; private Input input; @BeforeEach public void setup() throws IOException { ClassLoader classLoader = HierarchyTest.class.getClassLoader(); File file = new File(classLoader.getResource("inherit.jar").getFile()); input = new Input(file); } @Test public void testGetEquality() { // They should alias to the same call. // The first call will generate a ClassNode from the raw backing map. // The second call will load the cached ClassNode from the first call. ClassNode c1 = input.getClasses().get("test/Yoda"); ClassNode c2 = input.getClass("test/Yoda"); assertEquals(c1, c2); } @Test public void testCacheInvalidation() { // Backing raw map will generate a ClassNode for this call ClassNode c1 = input.getClass("test/Yoda"); // Remove the cached ClassNode input.getClasses().remove("test/Yoda"); // Backing raw map will generate a new ClassNode for this call. ClassNode c2 = input.getClass("test/Yoda"); // ClassNode instances do not match assertNotEquals(c1, c2); } @Test public void testSize() { // Technically, the map size is 0, but the backing map size should be 9. // Since we want to treat the classes map values as a sort of cache to work off of, // we want to get the backing map's size and then any time we need a value that isn't // in the map it will be generated based off of the raw backing map. assertEquals(CLASS_COUNT, input.getClasses().size()); } @Test public void testEntrySet() { AtomicInteger count = new AtomicInteger(); input.getClasses().entrySet().stream().forEach(e -> { ClassNode actual = e.getValue(); ClassNode fetched = input.getClass(e.getKey()); // Entry values should not be null assertNotNull(actual); assertNotNull(fetched); // get calls and the entry values should reference the same cached ClassNodes assertEquals(actual, fetched); // increment count count.incrementAndGet(); }); // Every item in the jar should be visited assertEquals(CLASS_COUNT, count.intValue()); } @Test public void testClassRename() { // We're going to rename the super-class. // This cached copy should be invalidated after the rename. ClassNode yoda = input.getClass("test/Yoda"); assertEquals("test/Jedi", yoda.superName); // // Invoke rename ClassNode jedi = input.getClass("test/Jedi"); Bus.post(new ClassRenameEvent(jedi, "test/Jedi", "test/GoodGuy")); // // The number of classes should stay the same assertEquals(CLASS_COUNT, input.getClasses().size()); // The old class should no longer exist assertNull(input.getClass("test/Jedi")); // The new class should exist assertNotNull(input.getClass("test/GoodGuy")); // Yoda's superName should be updated now. yoda = input.getClass("test/Yoda"); assertEquals("test/GoodGuy", yoda.superName); } @Test public void testMethodRename() { ClassNode yoda = input.getClass("test/Yoda"); MethodNode say = yoda.methods.get(1); // // Invoke rename Bus.post(new MethodRenameEvent(yoda, say, "say", "tell")); // All of these usages should be renamed assertEquals("tell", input.getClass("test/Greetings").methods.get(0).name); assertEquals("tell", input.getClass("test/Person").methods.get(1).name); assertEquals("tell", input.getClass("test/Jedi").methods.get(1).name); assertEquals("tell", input.getClass("test/Yoda").methods.get(1).name); assertEquals("tell", input.getClass("test/Sith").methods.get(1).name); // This should not change since it is not linked assertEquals("say", input.getClass("test/Speech").methods.get(0).name); } }
src/test/java/me/coley/recaf/InputTest.java
Unit tests for Input
src/test/java/me/coley/recaf/InputTest.java
Unit tests for Input
Java
mit
error: pathspec 'InfiniteHouseOfPancakes/InfiniteHouseOfPancakes.java' did not match any file(s) known to git
ae59d14594169a19250c79a675174bf3d8ff5a90
1
Nearsoft/google-code-jam,Nearsoft/google-code-jam,Nearsoft/google-code-jam,Nearsoft/google-code-jam,Nearsoft/google-code-jam,Nearsoft/google-code-jam,Nearsoft/google-code-jam
import java.io.*; import java.util.*; import java.io.PrintWriter; public class InfiniteHouseOfPancakes{ int minutes = 0; public static void main(String arg[]){ new InfiniteHouseOfPancakes(); } public InfiniteHouseOfPancakes(){ WriteFile("small-output.txt",outputString("B-small-practice.in")); WriteFile("large-output.txt",outputString("B-large-practice.in")); /*String[] arr = new String[]{"9"}; test2(1,arr.length,arr);*/ } public ArrayList<String> outputString(String file){ String data[] = ReadFile(file); int tests = Integer.parseInt(data[0]); int index = 1; ArrayList<String> outputString = new ArrayList<String>(); for(int i=0; i<tests; i++){ int arraysize = Integer.parseInt(data[index]); index++; String[] arrayString = data[index].split(" "); index++; outputString.add(test2(i+1,arraysize,arrayString)); } return outputString; } public void WriteFile(String name, ArrayList<String> outputString){ try{ PrintWriter out = new PrintWriter(new File(name)); for(String s:outputString){ //System.out.println(s); out.write(s); out.println(); } out.close(); }catch(FileNotFoundException e){} } //The test method solve some of the cases but not all of them public void test(int caseNumber, int arraysize, String[] arrayString){ ArrayList<Integer> array = new ArrayList<Integer>(); for(String s : arrayString){ array.add(Integer.parseInt(s)); } boolean finished = false; while(!finished){ /*for(int i : array) System.out.print(i+" "); System.out.println("");*/ int max = Collections.max(array); if(max>0){ boolean normal = isNormalMinute(max,array); //System.out.println(max+" "+normal); if(normal||max==1){ normalMinute(array); minutes++; } else{ //System.out.print("Minuto especial No encontre duplicados"); specialMinute(array,max); } //System.out.println("Minutos: "+ minutes); } else finished = true; } System.out.println("Case #"+caseNumber+": "+ minutes); minutes = 0; } public boolean isNormalMinute(int max, ArrayList<Integer> array){ int count = 0; for(int i : array){ if(i==max) count++; } double minByDividing = max/2.0+count; //System.out.println("w"+minByDividing); if(Math.ceil(minByDividing)>=max) return true;//normal minute return false;//special minute } public void normalMinute(ArrayList<Integer> array){ int size = array.size(); for(int i=0; i<size; i++){ if(array.get(i)>0) array.set(i, array.get(i)-1); } } public void specialMinute(ArrayList<Integer> array, int max){ ArrayList<Integer> indexes = getIndexesOfMax(array,max); for(int i:indexes){ if(max%2==0){ array.set(i, max/2); array.add(max/2); } else{ array.set(i, (max/2)+1); array.add((max/2)); } minutes++; } } public ArrayList<Integer> getIndexesOfMax(ArrayList<Integer> array, int max){ ArrayList<Integer> indexes = new ArrayList<Integer>(); for(int i=0; i<array.size(); i++){ if(array.get(i)==max) indexes.add(i); } return indexes; } public String[] ReadFile(String fileName){ // This will reference one line at a time String line = null; String fileString = ""; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { fileString += line+","; } // Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println( "Error reading file '" + fileName + "'"); // Or we could just do this: // ex.printStackTrace(); } return fileString.split(","); } //test2 does solve all of the cases. It tries every posibility, and returns the minimum value public String test2(int caseNumber, int arraysize, String[] arrayString){ //List of pancakes int[] input = new int[arraysize]; for (int i = 0; i < arraysize; i++) input[i] = Integer.parseInt(arrayString[i]); int best = 9001;//Over 9000! for (int time = 1; time < 1000; time++) { int moves = 0; for (int p : input) moves += ((int) Math.ceil(p / (time*1.0))) - 1; best = Math.min(best, moves + time); } String s = "Case #"+caseNumber+": " + best; System.out.println(s); return s; } }
InfiniteHouseOfPancakes/InfiniteHouseOfPancakes.java
Se construye repo para hacer PR
InfiniteHouseOfPancakes/InfiniteHouseOfPancakes.java
Se construye repo para hacer PR
Java
mit
error: pathspec 'src/main/java/com/tree_bit/rcdl/blocks/SingleInstanceSet.java' did not match any file(s) known to git
71c64b4cb20b272edb1b60987e3fe8aeee6479b2
1
ssauermann/BlockAPI
package com.tree_bit.rcdl.blocks; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; final class SingleInstanceSet<E> implements Set<E> { private Map<Class<? extends E>, E> map = new HashMap<>(); @Override public int size() { // TODO Auto-generated method stub return 0; } @Override public boolean isEmpty() { // TODO Auto-generated method stub return false; } @Override public boolean contains(final Object o) { // TODO Auto-generated method stub return false; } @Override public Iterator<E> iterator() { return this.map.values().iterator(); } @Override public Object[] toArray() { // TODO Auto-generated method stub return null; } @Override public <T> T[] toArray(final T[] a) { // TODO Auto-generated method stub return null; } @SuppressWarnings("unchecked") @Override public boolean add(final @Nullable E e) { if (e == null) { throw new NullPointerException("Parameter musn't be null"); } if (this.map.put((@NonNull Class<? extends E>) e.getClass(), e) == null) { return false; } return true; } @Override public boolean remove(final @Nullable Object o) { if (o == null) { throw new NullPointerException("Parameter musn't be null"); } return (this.map.remove(o.getClass()) != null); } @Override public boolean containsAll(final @Nullable Collection<?> c) { if (c == null) { throw new NullPointerException("Parameter musn't be null"); } // TODO Auto-generated method stub return false; } @Override public boolean addAll(final @Nullable Collection<? extends E> c) { if (c == null) { throw new NullPointerException("Parameter musn't be null"); } boolean wasChanged = false; for (final E element : c) { wasChanged |= this.add(element); } return wasChanged; } @Override public boolean retainAll(final @Nullable Collection<?> c) { if (c == null) { throw new NullPointerException("Parameter musn't be null"); } boolean wasChanged = false; final Map<Class<? extends E>, E> hm = new HashMap<>(); for (final Class<? extends E> elementClass : this.map.keySet()) { final E element = this.map.get(elementClass); if (c.contains(element)) { hm.put(elementClass, element); wasChanged = true; } } this.map = hm; return wasChanged; } @Override public boolean removeAll(final @Nullable Collection<?> c) { if (c == null) { throw new NullPointerException("Parameter musn't be null"); } boolean wasChanged = false; for (final Object o : c) { wasChanged |= this.remove(o); } return wasChanged; } @Override public void clear() { this.map.clear(); } }
src/main/java/com/tree_bit/rcdl/blocks/SingleInstanceSet.java
+ Beginning implementation of a single instance set.
src/main/java/com/tree_bit/rcdl/blocks/SingleInstanceSet.java
+ Beginning implementation of a single instance set.
Java
mit
error: pathspec 'Problems/Array/medium/870_advantage_shuffle/AdvantageShuffle.java' did not match any file(s) known to git
b3b4300d95c63eb6652a0493572cd6ab1d6d138d
1
Tao-Oak/LeetCodeProblems,Tao-Oak/LeetCodeProblems
// // Created by Joshua.Cao, 2018/11/01 // // https://leetcode.com/problems/advantage-shuffle/ // import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; /* * Given two arrays A and B of equal size, the advantage of A with respect to B * is the number of indices i for which A[i] > B[i]. * * Return any permutation of A that maximizes its advantage with respect to B. * * Example 1: * Input: A = [2,7,11,15], B = [1,10,4,11] * Output: [2,11,7,15] * * Example 2: * Input: A = [12,24,8,32], B = [13,25,32,11] * Output: [24,32,8,12] * * Note: * 1. 1 <= A.length = B.length <= 10000 * 2. 0 <= A[i] <= 10^9 * 3. 0 <= B[i] <= 10^9 */ public class AdvantageShuffle { // Accepted, beats 98.35% public int[] advantageCount(int[] A, int[] B) { int n = A.length, INDEX_SHIFTS = 14; long INDEX_MASKS = (1L << INDEX_SHIFTS) - 1L; long[] buffer = new long[n]; for (int i = 0; i < n; i++) { buffer[i] = ((long)B[i] << INDEX_SHIFTS) | (long)i; } Arrays.sort(A); Arrays.sort(buffer); int left = 0, right = n - 1; for (int v: A) { int temp = (int)(buffer[left] >>> INDEX_SHIFTS); if (v > temp) { B[(int)(buffer[left++] & INDEX_MASKS)] = v; } else { B[(int)(buffer[right--] & INDEX_MASKS)] = v; } } return B; } // Accepted, beats 59.38% public int[] advantageCount_1(int[] A, int[] B) { int n = A.length; int[] result = new int[n]; Map<Integer, List<Integer>> map = new HashMap<>(); for (int i = 0; i < n; i++) { List<Integer> list = map.getOrDefault(B[i], new ArrayList<>()); list.add(i); map.put(B[i], list); } Arrays.sort(A); Arrays.sort(B); int left = 0, right = n - 1; for (int value: A) { int target = value > B[left] ? B[left++] : B[right--]; List<Integer> list = map.get(target); int index = list.remove(list.size() - 1); result[index] = value; if (list.size() <= 0) map.remove(target); } return result; } // Accepted, beats 58.35% public int[] advantageCount_3(int[] A, int[] B) { int n = A.length; int[] result = new int[n]; TreeMap<Integer, Integer> map = new TreeMap<>(); for (int i = 0; i < n; i++) { map.put(A[i], map.getOrDefault(A[i], 0) + 1); } for (int i = 0; i < n; i++) { Map.Entry<Integer,Integer> entry = map.higherEntry(B[i]); if (entry == null) { entry = map.firstEntry(); } result[i] = entry.getKey(); int value = entry.getValue(); if (value > 1) { map.replace(result[i], value - 1); } else { map.remove(result[i]); } } return result; } public int[] advantageCount_4(int[] A, int[] B) { int n = A.length; Arrays.sort(A); int[] result = new int[n]; for (int i = 0; i < n; i++) { boolean found = false; for (int j = 0; j < n; j++) { if (A[j] > B[i]) { result[i] = A[j]; A[j] = -1; found = true; break; } } if (!found) { for (int j = 0; j < n; j++) { if (A[j] != -1) { result[i] = A[j]; break; } } } } return result; } private void test(int[] A, int[] B) { int[] result = advantageCount(A, B); System.out.println(Arrays.toString(result)); } public static void main(String[] args) { AdvantageShuffle obj = new AdvantageShuffle(); int[] A_1 = {2,7,11,15}, B_1 = {1,10,4,11}; obj.test(A_1, B_1); int[] A_2 = {12,24,8,32}, B_2 = {13,25,32,11}; obj.test(A_2, B_2); } }
Problems/Array/medium/870_advantage_shuffle/AdvantageShuffle.java
870 advantage shuffle
Problems/Array/medium/870_advantage_shuffle/AdvantageShuffle.java
870 advantage shuffle
Java
mit
error: pathspec 'src/modules/hellomodulesusingnonmodlib/src/hmod1lib/module-info.java' did not match any file(s) known to git
d800e13fa721b32ae17299e56dcb35b760cb7a3f
1
jbannick/hellokata-java,jbannick/hellokata-java
module hmod1lib { requires eventbus; }
src/modules/hellomodulesusingnonmodlib/src/hmod1lib/module-info.java
Create module-info.java
src/modules/hellomodulesusingnonmodlib/src/hmod1lib/module-info.java
Create module-info.java
Java
mit
error: pathspec 'src/main/java/io/github/thatsmusic99/headsplus/config/ConfigHeadsSelector.java' did not match any file(s) known to git
73d326ad3ede21adbc9b0dbfb22274907a6f9300
1
Thatsmusic99/HeadsPlus
package io.github.thatsmusic99.headsplus.config; public class ConfigHeadsSelector extends FeatureConfig { public ConfigHeadsSelector() { super("heads-selector"); } @Override public boolean shouldLoad() { return false; } @Override public void loadDefaults() { } }
src/main/java/io/github/thatsmusic99/headsplus/config/ConfigHeadsSelector.java
Create ConfigHeadsSelector.java
src/main/java/io/github/thatsmusic99/headsplus/config/ConfigHeadsSelector.java
Create ConfigHeadsSelector.java
Java
mit
error: pathspec 'src/test/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieCompactingTest.java' did not match any file(s) known to git
cc32f3007b243ffb762eeb4e25d3029c292e3c71
1
yeputons/DbFall2013
package net.yeputons.cscenter.dbfall2013.engines; import net.yeputons.cscenter.dbfall2013.engines.hashtrie.HashTrieEngine; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Random; import static org.junit.Assert.assertEquals; /** * Created with IntelliJ IDEA. * User: Egor Suvorov * Date: 25.10.13 * Time: 17:33 * To change this template use File | Settings | File Templates. */ public class HashTrieCompactingTest extends AbstractStressTest { final Logger log = LoggerFactory.getLogger(HashTrieCompactingTest.class); protected File storage; public HashTrieCompactingTest() throws IOException { storage = File.createTempFile("storage", ".bin"); storage.delete(); } @Test public void stressTest() throws IOException { final HashTrieEngine engine = new HashTrieEngine(this.storage); Map<ByteBuffer, ByteBuffer> real = new HashMap<ByteBuffer, ByteBuffer>(); assertEquals(real, engine); Random rnd = new Random(); for (int step = 0; step < 500; step++) { if (rnd.nextInt(100) <= 1) { new Thread(new Runnable() { @Override public void run() { try { engine.runCompaction(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { } } }).start(); } synchronized (engine) { performRandomOperation(rnd, engine, real); assertEquals(engine.size(), engine.keySet().size()); assertEquals(engine.size(), engine.entrySet().size()); assertEquals(real.keySet(), engine.keySet()); assertEquals(real.entrySet(), engine.entrySet()); assertEquals(real, engine); } } } }
src/test/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieCompactingTest.java
HashTrieCompactingTest was added
src/test/java/net/yeputons/cscenter/dbfall2013/engines/HashTrieCompactingTest.java
HashTrieCompactingTest was added
Java
mpl-2.0
87c39dfc77e104c6e4d6ca6f90329de0d38a4ce4
0
msokolov/lux,coyotesqrl/lux,msokolov/lux
package lux; import static org.junit.Assert.assertEquals; import java.util.Iterator; import lux.api.LuxException; import lux.api.QueryStats; import lux.api.ResultSet; import lux.api.ValueType; import lux.index.XmlIndexer; import lux.saxon.Expandifier; import lux.saxon.Saxon; import lux.saxon.SaxonExpr; import lux.xquery.XQuery; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.XQueryEvaluator; import net.sf.saxon.s9api.XQueryExecutable; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.s9api.XdmValue; import org.junit.AfterClass; import org.junit.BeforeClass; /** * executes all the BasicQueryTest test cases using path indexes and compares results against * an unindexed baseline. * */ public class SearchQueryTest extends BasicQueryTest { private static IndexTestSupport index; private static long elapsed=0; private static long elapsedBaseline=0; @BeforeClass public static void setup () throws Exception { index = new IndexTestSupport(); } @AfterClass public static void tearDown() throws Exception { index.close(); } @Override public String getQueryString(Q q) { switch (q) { case ACT_SCENE: return "w(\"ACT\",\"SCENE\")"; case SCENE: return "\"SCENE\""; default: throw new UnsupportedOperationException("No query string for " + q + " in " + getClass().getSimpleName()); } } @Override public String getQueryXml (Q q) { switch (q) { case ACT_SCENE: return "<SpanNear ordered=\"true\" slop=\"1\">" + "<SpanTerm>ACT</SpanTerm>" + "<SpanTerm>SCENE</SpanTerm>" + "</SpanNear>"; case SCENE: return "SCENE"; default: throw new UnsupportedOperationException("No query string for " + q + " in " + getClass().getSimpleName()); } } @Override public XmlIndexer getIndexer() { return new XmlIndexer (XmlIndexer.INDEX_PATHS); } /** * @param xpath the path to test * @param optimized ignored * @param facts ignored * @param queries ignored */ public void assertQuery (String xpath, String optimized, int facts, ValueType type, Q ... queries) { Saxon saxon = index.getEvaluator(); saxon.invalidateCache(); long t0 = System.nanoTime(); SaxonExpr saxonExpr = saxon.compile(xpath); ResultSet<?> results = saxon.evaluate(saxonExpr); if (results.getException() != null) { throw new LuxException(results.getException()); } long t = System.nanoTime() - t0; elapsed += t; System.out.println ("query evaluated in " + (t/1000000) + " msec, retrieved " + results.size() + " results from " + saxon.getQueryStats().docCount + " documents"); saxon.invalidateCache(); saxon.setQueryStats(new QueryStats()); t0 = System.nanoTime(); XQuery xq = null; try { xq = saxon.getTranslator().queryFor(saxon.getXQueryCompiler().compile(xpath)); xq = new Expandifier().expandify(xq); String expanded = xq.toString(); XQueryExecutable baseline; baseline = saxon.getXQueryCompiler().compile(expanded); XQueryEvaluator baselineEval = baseline.load(); XdmValue baseResult = baselineEval.evaluate(); assertEquals ("result count mismatch for: " + optimized, baseResult.size(), results.size()); Iterator<?> baseIter = baseResult.iterator(); Iterator<?> resultIter = results.iterator(); for (int i = 0 ; i < results.size(); i++) { XdmItem base = (XdmItem) baseIter.next(); XdmItem r = (XdmItem) resultIter.next(); assertEquals (base.isAtomicValue(), r.isAtomicValue()); assertEquals (base.getStringValue(), r.getStringValue()); } } catch (SaxonApiException e) { throw new LuxException ("error evaluting query " + xq, e); } t = System.nanoTime() - t0; System.out.println ("baseline query took " + (t/1000000) + " msec, retrieved " + results.size() + " results from " + saxon.getQueryStats().docCount + " documents"); elapsedBaseline += t; // TODO: also assert facts about query optimizations System.out.println (String.format("%dms using lux; %dms w/o lux", elapsed/1000000, elapsedBaseline/1000000)); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */
src/test/java/lux/SearchQueryTest.java
package lux; import static org.junit.Assert.assertEquals; import java.util.Iterator; import lux.api.LuxException; import lux.api.ResultSet; import lux.api.ValueType; import lux.index.XmlIndexer; import lux.saxon.Saxon; import lux.saxon.SaxonExpr; import lux.saxon.UnOptimizer; import lux.xpath.AbstractExpression; import net.sf.saxon.s9api.XdmItem; import org.junit.AfterClass; import org.junit.BeforeClass; /** * executes all the BasicQueryTest test cases using path indexes and compares results against * an unindexed baseline. * */ public class SearchQueryTest extends BasicQueryTest { private static IndexTestSupport index; @BeforeClass public static void setup () throws Exception { index = new IndexTestSupport(); } @AfterClass public static void tearDown() throws Exception { index.close(); } @Override public String getQueryString(Q q) { switch (q) { case ACT_SCENE: return "w(\"ACT\",\"SCENE\")"; case SCENE: return "\"SCENE\""; default: throw new UnsupportedOperationException("No query string for " + q + " in " + getClass().getSimpleName()); } } @Override public String getQueryXml (Q q) { switch (q) { case ACT_SCENE: return "<SpanNear ordered=\"true\" slop=\"1\">" + "<SpanTerm>ACT</SpanTerm>" + "<SpanTerm>SCENE</SpanTerm>" + "</SpanNear>"; case SCENE: return "SCENE"; default: throw new UnsupportedOperationException("No query string for " + q + " in " + getClass().getSimpleName()); } } @Override public XmlIndexer getIndexer() { return new XmlIndexer (XmlIndexer.INDEX_PATHS); } /** * @param xpath the path to test * @param optimized ignored * @param facts ignored * @param queries ignored */ public void assertQuery (String xpath, String optimized, int facts, ValueType type, Q ... queries) { Saxon saxon = index.getEvaluator(); SaxonExpr saxonExpr = saxon.compile(xpath); optimized = saxonExpr.toString(); long t = System.currentTimeMillis(); ResultSet<?> results = saxon.evaluate(saxonExpr); if (results.getException() != null) { throw new LuxException(results.getException()); } System.out.println ("query evaluated in " + (System.currentTimeMillis() - t) + " msec, retrieved " + results.size() + " results from " + saxon.getQueryStats().docCount + " documents"); AbstractExpression aex = saxonExpr.getXPath(); aex = new UnOptimizer(getIndexer().getOptions()).unoptimize(aex); // TODO: don't re-optimize here !! SaxonExpr baseline = saxon.compile(aex.toString()); ResultSet<?> baseResult = saxon.evaluate(baseline); assertEquals ("result count mismatch for: " + optimized, baseResult.size(), results.size()); Iterator<?> baseIter = baseResult.iterator(); Iterator<?> resultIter = results.iterator(); for (int i = 0 ; i < results.size(); i++) { XdmItem base = (XdmItem) baseIter.next(); XdmItem r = (XdmItem) resultIter.next(); assertEquals (base.isAtomicValue(), r.isAtomicValue()); assertEquals (base.getStringValue(), r.getStringValue()); } // TODO: also assert facts about query optimizations } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */
changed test to report comparative timings git-svn-id: 70ea2e2438545e53c1a57116d9bc498ccdd9cff9@1176 d2cdb213-60f8-4f1b-b4b2-f6b941818144
src/test/java/lux/SearchQueryTest.java
changed test to report comparative timings
Java
agpl-3.0
error: pathspec 'jpos/src/main/java/org/jpos/iso/IFB_LLLHNUM.java' did not match any file(s) known to git
01f34bf2d4aff2d834196a61bcbf730bde2b145e
1
imam-san/jPOS-1,alcarraz/jPOS,barspi/jPOS,sebastianpacheco/jPOS,alcarraz/jPOS,jpos/jPOS,fayezasar/jPOS,c0deh4xor/jPOS,barspi/jPOS,bharavi/jPOS,jpos/jPOS,bharavi/jPOS,jpos/jPOS,yinheli/jPOS,alcarraz/jPOS,chhil/jPOS,poynt/jPOS,imam-san/jPOS-1,c0deh4xor/jPOS,poynt/jPOS,yinheli/jPOS,fayezasar/jPOS,imam-san/jPOS-1,sebastianpacheco/jPOS,yinheli/jPOS,juanibdn/jPOS,atancasis/jPOS,chhil/jPOS,juanibdn/jPOS,poynt/jPOS,sebastianpacheco/jPOS,barspi/jPOS,bharavi/jPOS,atancasis/jPOS,c0deh4xor/jPOS,juanibdn/jPOS,atancasis/jPOS
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2011 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.iso; /** * ISOFieldPackager Binary LLL Hex NUM * Almost the same as IFB_LLLNUM but len is encoded as a binary * value. A len of 16 is encoded as 0x10 instead of 0x16 * * @author apr@jpos.org * @version $Id$ * @see ISOComponent */ public class IFB_LLLHNUM extends ISOStringFieldPackager { public IFB_LLLHNUM() { super(NullPadder.INSTANCE, BCDInterpreter.RIGHT_PADDED, BinaryPrefixer.BB); } /** * @param len - field len * @param description symbolic descrption */ public IFB_LLLHNUM(int len, String description, boolean pad) { super(len, description, NullPadder.INSTANCE, pad ? BCDInterpreter.LEFT_PADDED : BCDInterpreter.RIGHT_PADDED, BinaryPrefixer.BB); this.pad = pad; checkLength(len, 65535); } public void setLength(int len) { checkLength(len, 65535); super.setLength(len); } public void setPad(boolean pad) { this.pad = pad; setInterpreter(pad ? BCDInterpreter.LEFT_PADDED : BCDInterpreter.RIGHT_PADDED); } }
jpos/src/main/java/org/jpos/iso/IFB_LLLHNUM.java
Added IFB_LLLHNUM Field Packager
jpos/src/main/java/org/jpos/iso/IFB_LLLHNUM.java
Added IFB_LLLHNUM Field Packager
Java
agpl-3.0
error: pathspec 'common/src/main/java/bisq/common/util/ReflectionUtils.java' did not match any file(s) known to git
32ed7ac4060cb050f782cf745054bb4fd54ced25
1
bitsquare/bitsquare,bitsquare/bitsquare,bisq-network/exchange,bisq-network/exchange
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.common.util; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static java.util.Arrays.stream; import static org.apache.commons.lang3.StringUtils.capitalize; public class ReflectionUtils { /** * Recursively loads a list of fields for a given class and its superclasses, * using a filter predicate to exclude any unwanted fields. * * @param fields The list of fields being loaded for a class hierarchy. * @param clazz The lowest level class in a hierarchy; excluding Object.class. * @param isExcludedField The field exclusion predicate. */ public static void loadFieldListForClassHierarchy(List<Field> fields, Class<?> clazz, Predicate<Field> isExcludedField) { fields.addAll(stream(clazz.getDeclaredFields()) .filter(f -> !isExcludedField.test(f)) .collect(Collectors.toList())); Class<?> superclass = clazz.getSuperclass(); if (!Objects.equals(superclass, Object.class)) loadFieldListForClassHierarchy(fields, superclass, isExcludedField); } /** * Returns an Optional of a setter method for a given field and a class hierarchy, * or Optional.empty() if it does not exist. * * @param field The field used to find a setter method. * @param clazz The lowest level class in a hierarchy; excluding Object.class. * @return Optional<Method> of the setter method for a field in the class hierarchy, * or Optional.empty() if it does not exist. */ public static Optional<Method> getSetterMethodForFieldInClassHierarchy(Field field, Class<?> clazz) { Optional<Method> setter = stream(clazz.getDeclaredMethods()) .filter((m) -> isSetterForField(m, field)) .findFirst(); if (setter.isPresent()) return setter; Class<?> superclass = clazz.getSuperclass(); if (!Objects.equals(superclass, Object.class)) { setter = getSetterMethodForFieldInClassHierarchy(field, superclass); if (setter.isPresent()) return setter; } return Optional.empty(); } public static boolean isSetterForField(Method m, Field f) { return m.getName().startsWith("set") && m.getName().endsWith(capitalize(f.getName())) && m.getReturnType().getName().equals("void") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().equals(f.getType().getName()); } public static boolean isSetterOnClass(Method setter, Class<?> clazz) { return clazz.equals(setter.getDeclaringClass()); } public static String getVisibilityModifierAsString(Field field) { if (Modifier.isPrivate(field.getModifiers())) return "private"; else if (Modifier.isProtected(field.getModifiers())) return "protected"; else if (Modifier.isPublic(field.getModifiers())) return "public"; else return ""; } }
common/src/main/java/bisq/common/util/ReflectionUtils.java
Add ReflectionUtils to common.util pkg This class will aid the api's (create) PaymentAccount json form serialization/de-serialization.
common/src/main/java/bisq/common/util/ReflectionUtils.java
Add ReflectionUtils to common.util pkg
Java
lgpl-2.1
fdb2e9a80c70e2da6a2d7e5fa1acecdbc3a90620
0
alisdev/dss,openlimit-signcubes/dss,zsoltii/dss,zsoltii/dss,openlimit-signcubes/dss,alisdev/dss,esig/dss,esig/dss
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.client.http; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.DSSException; /** * Implementation of native java DataLoader using the java.net.URL class. * */ public class NativeHTTPDataLoader implements DataLoader { public enum HttpMethod { GET, POST } private static final Logger LOGGER = LoggerFactory.getLogger(NativeHTTPDataLoader.class); private long maxInputSize; /** * Timeout of the full request processing time (send and retrieve data). */ private long timeout = 0; protected byte[] request(String url, HttpMethod method, byte[] content, boolean refresh) { NativeDataLoaderCall task = new NativeDataLoaderCall(url, content, refresh, maxInputSize); ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future<byte[]> result = executorService.submit(task); return timeout > 0 ? result.get(timeout, TimeUnit.MILLISECONDS) : result.get(); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new DSSException(e); } finally { executorService.shutdown(); } } @Override public DataAndUrl get(List<String> urlStrings) { for (final String urlString : urlStrings) { try { final byte[] bytes = get(urlString); if (bytes != null) { return new DataAndUrl(bytes, urlString); } } catch (Exception e) { LOGGER.warn("Impossible to obtain data using {}", urlString, e); } } throw new DSSException(String.format("Impossible to obtain data using with given urls %s", urlStrings)); } @Override public byte[] get(String url) { return get(url, false); } @Override public byte[] get(String url, boolean refresh) { return request(url, HttpMethod.GET, null, !refresh); } @Override public byte[] post(String url, byte[] content) { return request(url, HttpMethod.POST, content, false); } @Override public void setContentType(String contentType) { throw new DSSException("Not implemented"); } public long getMaxInputSize() { return maxInputSize; } public void setMaxInputSize(long maxInputSize) { this.maxInputSize = maxInputSize; } public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } }
dss-spi/src/main/java/eu/europa/esig/dss/client/http/NativeHTTPDataLoader.java
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.client.http; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.europa.esig.dss.DSSException; /** * Implementation of native java DataLoader using the java.net.URL class. * */ public class NativeHTTPDataLoader implements DataLoader { public enum HttpMethod { GET, POST } private static final Logger LOGGER = LoggerFactory.getLogger(NativeHTTPDataLoader.class); private long maxInputSize; /** * Timeout of the full request processing time (send and retrieve data). */ private long timeout = 0; protected byte[] request(String url, HttpMethod method, byte[] content, boolean refresh) { NativeDataLoaderCall task = new NativeDataLoaderCall(url, content, refresh, maxInputSize); Future<byte[]> result = Executors.newSingleThreadExecutor().submit(task); try { return timeout > 0 ? result.get(timeout, TimeUnit.MILLISECONDS) : result.get(); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new DSSException(e); } } @Override public DataAndUrl get(List<String> urlStrings) { for (final String urlString : urlStrings) { try { final byte[] bytes = get(urlString); if (bytes != null) { return new DataAndUrl(bytes, urlString); } } catch (Exception e) { LOGGER.warn("Impossible to obtain data using {}", urlString, e); } } throw new DSSException(String.format("Impossible to obtain data using with given urls %s", urlStrings)); } @Override public byte[] get(String url) { return get(url, false); } @Override public byte[] get(String url, boolean refresh) { return request(url, HttpMethod.GET, null, !refresh); } @Override public byte[] post(String url, byte[] content) { return request(url, HttpMethod.POST, content, false); } @Override public void setContentType(String contentType) { throw new DSSException("Not implemented"); } public long getMaxInputSize() { return maxInputSize; } public void setMaxInputSize(long maxInputSize) { this.maxInputSize = maxInputSize; } public long getTimeout() { return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } }
DSS-1227 : Use of OnlineTSPSource does not shutdown ExecutorService
dss-spi/src/main/java/eu/europa/esig/dss/client/http/NativeHTTPDataLoader.java
DSS-1227 : Use of OnlineTSPSource does not shutdown ExecutorService
Java
lgpl-2.1
error: pathspec 'src/org/biojava/bio/symbol/PackedDnaSymbolList.java' did not match any file(s) known to git
b7de8892185213f48ad7c49e2770453482b771b9
1
sbliven/biojava,sbliven/biojava,sbliven/biojava
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.symbol; import org.biojava.bio.BioException; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; /** * a class that implements storage of symbols * in packed form (2 symbols per byte). * * @author David Huen * @since 1.2 */ public class PackedDnaSymbolList extends AbstractSymbolList { /* * The data is organised at two levels:- * i) underlying storage: byte in my case * ii) cache line : 2**n number of bytes * * in this case all but the terminal cache and * byte have a fixed, known number of bytes * and 4-bit nibbles to process. * * in the terminal cache line, the number of bytes * to be processed and the number of nibbles in the * final byte may vary from that in the other cache * lines. */ // class variables // sequence length int length = 0; // 2's exponent expressing number of packed symbols per // storage unit (2 packed symbols per storage unit) // log2PackedSymsPerStorageUnit and storageUnitOffsetMask // MUST be kept consistent int log2PackedSymsPerStorageUnit = 1; int packedSymsPerStorageUnit = 0; int storageUnitOffsetMask = 0x0001; // size of the array in multiples of underlying storage units // (ignore the zero, just a compiler suppression initialisation). int storageUnitSize = 0; // array for storing packed symbols of type storage unit byte [] packedSymbolArray = null; // 2's exponent expressing number of symbols per // cache line. (in this implementation, 16 per cache line) // log2SymsPerCacheLine and cacheLineOffsetMask // MUST be kept consistent int log2SymsPerCacheLine = 4; int cacheLineOffsetMask = 0x000F; // symbol cache Symbol [] symbolCache = null; int currCacheIndex = -1; // terminal cache line/storage unit parameters // number of packed symbols in final storage unit // (ignore zero value here, initialised later) int cacheLineCount = 0; int symsInFinalStorageUnit = 0; int symsInFinalCacheLine = 0; int fullStorageUnitsInFinalCacheLine = 0; int log2StorageUnitsPerCacheLine = 0; int storageUnitsPerCacheLine = 0; static AlphabetIndex alfaIndex = null; /** * constructor taking another symbol list. */ public PackedDnaSymbolList(SymbolList symList) throws BioException, IllegalAlphabetException { // check that SymbolList is on DNA alphabet if ( symList.getAlphabet() != DNATools.getDNA() ) throw new IllegalAlphabetException(); // create cache array symbolCache = new Symbol[0x0001<<log2SymsPerCacheLine]; // compute derived shifts log2StorageUnitsPerCacheLine = log2SymsPerCacheLine - log2PackedSymsPerStorageUnit; storageUnitsPerCacheLine = 0x0001 << log2StorageUnitsPerCacheLine; packedSymsPerStorageUnit = 0x0001 << log2PackedSymsPerStorageUnit; // compute the size of array required length = symList.length(); storageUnitSize = length >> log2PackedSymsPerStorageUnit; symsInFinalStorageUnit = length & storageUnitOffsetMask; // create the array if (symsInFinalStorageUnit == 0) packedSymbolArray = new byte[storageUnitSize]; else packedSymbolArray = new byte[storageUnitSize + 1]; // compute number of full cache lines cacheLineCount = length >> log2SymsPerCacheLine; // compute number of storage units in final cache line // if = 0, then final line is a full line symsInFinalCacheLine = length & cacheLineOffsetMask; // note that this is for FILLED storage units. fullStorageUnitsInFinalCacheLine = symsInFinalCacheLine >> log2PackedSymsPerStorageUnit; // get access to an AlphabetIndex if (alfaIndex == null) alfaIndex = new FullDnaAlphabetIndex(); // now copy over contents into array // I will assume LSB first! int symbolPointer = 1; int bytePointer = 0; // load the all the completely filled storage units. // note that the types will have to be changed here if the storage unit is changed byte currByte = 0; // System.out.println("storageUnitSize: " + storageUnitSize); for (int i=0; i<storageUnitSize; i++) { // each byte consists of 4 bit nibbles // process each separately for (int j=0; j < 2; j++) { currByte = (byte) (currByte<<4 | alfaIndex.indexForSymbol(symList.symbolAt(symbolPointer))); symbolPointer++; } packedSymbolArray[bytePointer] = currByte; // System.out.println("setting position " + bytePointer + " to " + Integer.toString((int) currByte, 16)); bytePointer++; } // now handle the final incompletely filled storage unit currByte=0; // System.out.println("symsInFinalStorageUnit: " + symsInFinalStorageUnit); if (symsInFinalStorageUnit != 0) { for (int i=0; i<symsInFinalStorageUnit; i++) { currByte = (byte) (currByte<<4 | alfaIndex.indexForSymbol(symList.symbolAt(symbolPointer))); // System.out.println("value is " + alfaIndex.indexForSymbol(symList.symbolAt(symbolPointer))); symbolPointer++; } packedSymbolArray[bytePointer] = currByte; // System.out.println("setting position " + bytePointer + " to " + Integer.toString((int) currByte, 16)); } } /** * constructor taking a byte array previously * created by another PackedDnaSymbolList object. */ public PackedDnaSymbolList(int length, byte [] byteArray) throws BioException { // initialise the class variables storageUnitSize = length>>log2PackedSymsPerStorageUnit; symsInFinalStorageUnit = length & storageUnitOffsetMask; // check that the array is correct in size int expectedArraySize; if (symsInFinalStorageUnit == 0) expectedArraySize = storageUnitSize; else expectedArraySize = storageUnitSize + 1; if (byteArray.length < expectedArraySize) throw new BioException("array is too small to represent given sequence length."); packedSymbolArray = byteArray; } /*************************/ /* SymbolList operations */ /*************************/ public int length() { return length; } public Alphabet getAlphabet() { return DNATools.getDNA(); } public Symbol symbolAt(int index) { // index is origin1; // compute cache index if (index < 1) throw new IndexOutOfBoundsException(""); if (index > length) throw new IndexOutOfBoundsException(""); int cacheIndex = (index-1)>>log2SymsPerCacheLine; int cacheOffset = (index-1) & cacheLineOffsetMask; // System.out.println("index,cacheIndex,cacheOffset: " + index + " " + cacheIndex + " " + cacheOffset); // check if access is to current cache line if (currCacheIndex != cacheIndex) { // fill symbol cache // do we have a full cache line // or is this a partially-filled final cache line? int storageUnitIndex = cacheIndex << log2StorageUnitsPerCacheLine; // System.out.println("storageUnitIndex,cacheLineCount,symsInFinalCacheLine " + storageUnitIndex + " " + cacheLineCount + " " + symsInFinalCacheLine); if ((cacheIndex == cacheLineCount) && (symsInFinalCacheLine !=0)) { // incomplete cache line, deal with it int symIndex = 0; byte currStorageUnit=-1; // transfer the filled storage units // System.out.println("fullStorageUnitsInFinalCacheLine: " + fullStorageUnitsInFinalCacheLine); if (fullStorageUnitsInFinalCacheLine != 0) { for (int i=0; i < fullStorageUnitsInFinalCacheLine; i++) { currStorageUnit = packedSymbolArray[storageUnitIndex]; // remember that packedSymbolArray shifts then loads latest nibble into low order end // when decoding, it is necessary to reverse the order here. for (int j=packedSymsPerStorageUnit-1; j >= 0; j--) { symbolCache[symIndex + j] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); currStorageUnit = (byte) (currStorageUnit>>4); } symIndex += packedSymsPerStorageUnit; storageUnitIndex++; } } // transfer the last incompletely-filled storage unit if ( symsInFinalStorageUnit !=0) { currStorageUnit = packedSymbolArray[storageUnitIndex]; // System.out.println("symIndex, symsInFinalStorageUnit: " + symIndex + " " + symsInFinalStorageUnit); for (int j=symsInFinalStorageUnit-1; j >=0; j--) { symbolCache[symIndex+j] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); currStorageUnit = (byte) (currStorageUnit>>4); } } } else { // complete cache line // logically-driven version int symIndex = 0; for (int i=0; i < storageUnitsPerCacheLine; i++) { byte currStorageUnit = packedSymbolArray[storageUnitIndex]; // remember that packedSymbolArray shifts then loads latest nibble into low order end // when decoding, it is necessary to reverse the order here. for (int j=packedSymsPerStorageUnit-1; j >= 0; j--) { symbolCache[symIndex + j] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); currStorageUnit = (byte) (currStorageUnit>>4); } symIndex += packedSymsPerStorageUnit; storageUnitIndex++; } /* // unrolled version byte currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[1] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[0] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[3] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[2] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[5] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[4] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[7] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[6] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[9] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[8] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[11] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[10] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[13] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[12] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); currStorageUnit = packedSymbolArray[storageUnitIndex++]; symbolCache[15] = alfaIndex.symbolForIndex((int)(currStorageUnit & 0x000F)); symbolCache[14] = alfaIndex.symbolForIndex((int)((currStorageUnit>>4) & 0x000F)); */ } currCacheIndex = cacheIndex; } return symbolCache[cacheOffset]; } /** * returns the byte array backing the SymbolList. * (can be written out and stored). */ public byte [] getArray() { return packedSymbolArray; } }
src/org/biojava/bio/symbol/PackedDnaSymbolList.java
initial version by David Huen. Requires FullDNAAlphabetIndex.java too git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@1700 7c6358e6-4a41-0410-a743-a5b2a554c398
src/org/biojava/bio/symbol/PackedDnaSymbolList.java
initial version by David Huen. Requires FullDNAAlphabetIndex.java too
Java
lgpl-2.1
error: pathspec 'src/java/com/threerings/util/StreamableHashIntMap.java' did not match any file(s) known to git
f0628cfeac946ca1bf5aec27186357416fdde1fe
1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: StreamableHashIntMap.java,v 1.1 2003/02/18 03:01:16 mdb Exp $ package com.threerings.util; import java.io.IOException; import java.util.Iterator; import com.samskivert.util.HashIntMap; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; /** * A {@link HashIntMap} extension that can be streamed. The keys and * values in the map must also be of streamable types. * * @see Streamable */ public class StreamableHashIntMap extends HashIntMap implements Streamable { /** * Constructs an empty hash int map with the specified number of hash * buckets. */ public StreamableHashIntMap (int buckets, float loadFactor) { super(buckets, loadFactor); } /** * Constructs an empty hash int map with the default number of hash * buckets. */ public StreamableHashIntMap () { super(); } /** * Writes our custom streamable fields. */ public void writeObject (ObjectOutputStream out) throws IOException { int ecount = size(); out.writeInt(ecount); Iterator iter = keySet().iterator(); while (iter.hasNext()) { int key = ((Integer)iter.next()).intValue(); out.writeInt(key); out.writeObject(get(key)); } } /** * Reads our custom streamable fields. */ public void readObject (ObjectInputStream in) throws IOException, ClassNotFoundException { int ecount = in.readInt(); for (int ii = 0; ii < ecount; ii++) { int key = in.readInt(); put(key, in.readObject()); } } }
src/java/com/threerings/util/StreamableHashIntMap.java
A streamable hash int map; whee! git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2283 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/util/StreamableHashIntMap.java
A streamable hash int map; whee!
Java
lgpl-2.1
error: pathspec 'src/test/org/jdesktop/swingx/treetable/TreeTableModelIssues.java' did not match any file(s) known to git
9658aa7ac13eb5a6b75170cde446aee94e019a2a
1
trejkaz/swingx,trejkaz/swingx,tmyroadctfig/swingx,krichter722/swingx,krichter722/swingx
/* * Created on 13.12.2005 * */ package org.jdesktop.swingx.treetable; import java.util.logging.Logger; import junit.framework.TestCase; public class TreeTableModelIssues extends TestCase { private static final Logger LOG = Logger .getLogger(TreeTableModelIssues.class.getName()); /** * Issue #??-swingx: TreeTableModel impl break type contract for * hierarchical column. * * Expected contract (non-doc'ed but common sense...) * * <pre> <code> * * Object value = model.getValueAt(node, column); * assert((value == null) || * (model.getColumnClass(column).isAssignableFrom(value.getClass()))) * * </code> </pre> * * Here: FileSystemModel. * */ public void testFileSystemTTM() { TreeTableModel model = new FileSystemModel(); assertColumnClassAssignableFromValue(model); } /** * loops through all model columns to test type contract. * * * @param model the model to test. */ private void assertColumnClassAssignableFromValue(TreeTableModel model) { for (int i = 0; i < model.getColumnCount(); i++) { Class clazz = model.getColumnClass(i); Object value = model.getValueAt(model.getRoot(), i); if (value != null) { assertTrue("column class must be assignable to value class at column " + i + "\n" + "columnClass = " + model.getColumnClass(i) + "\n" + "valueClass = " + value.getClass() , clazz.isAssignableFrom(value.getClass())); } else { LOG.info("column " + i + " not testable - value == null"); } } } }
src/test/org/jdesktop/swingx/treetable/TreeTableModelIssues.java
Issue number: #218-swingx TreeTableModel impl break type contract added test TreeTableModelIssues to expose git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@662 1312f61e-266d-0410-97fa-c3b71232c9ac
src/test/org/jdesktop/swingx/treetable/TreeTableModelIssues.java
Issue number: #218-swingx
Java
lgpl-2.1
error: pathspec 'LGPL/CommonSoftware/acsalarmidl/ws/src/alma/acs/alarmsystem/acsimpl/AcsAlarmSystem.java' did not match any file(s) known to git
26de175a4f9f477118e67d22b79f9ff193de65a5
1
ACS-Community/ACS,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,csrg-utfsm/acscb,csrg-utfsm/acscb,csrg-utfsm/acscb,ACS-Community/ACS,jbarriosc/ACSUFRO,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO
/* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2009 * Copyright by ESO (in the framework of the ALMA collaboration), * All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ package alma.acs.alarmsystem.acsimpl; import java.util.logging.Logger; import alma.acs.logging.AcsLogLevel; import alma.alarmsystem.AlarmServicePOA; import alma.acs.alarmsystem.corbaservice.AlarmSystemCorbaServer; public class AcsAlarmSystem extends AlarmServicePOA { /** * The CORBA server */ private final AlarmSystemCorbaServer corbaServer; /** * Set to <code>true</code> if the alarm service has been shut down */ private volatile boolean closed=false; /** * The logger */ private final Logger logger; /** * A class to terminate the alarm service asynchronously. * <P> * The alarm service is stopped by calling the shutdown IDL method. * But inside such a method, the ORB can't be closed. * This class shuts down the servant outside of the ORB thread. * * @author acaproni * */ public class AcsComponentTerminator implements Runnable { public void run() { corbaServer.shutdown(); logger.log(AcsLogLevel.DEBUG,"See you soon :-)"); } } /** * Constructor */ public AcsAlarmSystem(AlarmSystemCorbaServer corbaServer) throws Exception { if (corbaServer==null) { throw new Exception("The CORBA server can't be null"); } this.corbaServer=corbaServer; logger=corbaServer.getLogger(); } /** * Return the type of alarm system * * @return always <code>true</code> */ public boolean isACSAlarmService() { return true; } /** * Shutdown the alarm service */ public synchronized void shutdown() { if (closed) { return; } closed=true; logger.log(AcsLogLevel.DEBUG,"Shutting down"); Thread t = new Thread(new AcsComponentTerminator(),"LaserComponentTerminator"); t.start(); } }
LGPL/CommonSoftware/acsalarmidl/ws/src/alma/acs/alarmsystem/acsimpl/AcsAlarmSystem.java
Moved here from laser-core and customized ACS alarm service implementation git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@111252 523d945c-050c-4681-91ec-863ad3bb968a
LGPL/CommonSoftware/acsalarmidl/ws/src/alma/acs/alarmsystem/acsimpl/AcsAlarmSystem.java
Moved here from laser-core and customized ACS alarm service implementation
Java
lgpl-2.1
error: pathspec 'languagetool-dev/src/main/java/org/languagetool/dev/bigdata/ConfusionSetFileFormatter.java' did not match any file(s) known to git
6ed3062bf16c934dacfe39924d87f33e64432648
1
languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2020 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.bigdata; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ConfusionSetFileFormatter { public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + ConfusionSetFileFormatter.class.getSimpleName() + " <confusion_set.txt>"); System.exit(1); } List<String> lines = Files.readAllLines(Paths.get(args[0])); for (String line : lines) { System.out.println(reformat(line)); } } private static String reformat(String s) { Pattern pattern = Pattern.compile(";\\s*\\d+"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { int spaceStart = matcher.end(); int spaceEnd = s.indexOf('#', 2); if (spaceStart > 0 && spaceEnd > 0) { String spaces = StringUtils.repeat(" ", 52-spaceStart); return s.substring(0, spaceStart+1) + spaces + s.substring(spaceEnd); } } return s; } }
languagetool-dev/src/main/java/org/languagetool/dev/bigdata/ConfusionSetFileFormatter.java
simple script to reformat confusion_sets.txt
languagetool-dev/src/main/java/org/languagetool/dev/bigdata/ConfusionSetFileFormatter.java
simple script to reformat confusion_sets.txt
Java
apache-2.0
d4f23d21bd7b0e533d697d3c198c84b065618eef
0
TheRealRasu/arx,kbabioch/arx,RaffaelBild/arx,kentoa/arx,jgaupp/arx,RaffaelBild/arx,bitraten/arx,TheRealRasu/arx,kentoa/arx,tijanat/arx,arx-deidentifier/arx,bitraten/arx,kbabioch/arx,COWYARD/arx,tijanat/arx,fstahnke/arx,fstahnke/arx,jgaupp/arx,COWYARD/arx,arx-deidentifier/arx
/* * ARX: Efficient, Stable and Optimal Data Anonymization * Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.deidentifier.arx.test; import java.io.IOException; import org.deidentifier.arx.ARXAnonymizer; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.AttributeType; import org.deidentifier.arx.AttributeType.Hierarchy; import org.deidentifier.arx.Data; import org.deidentifier.arx.criteria.KAnonymity; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * A test case for illegal arguments * * @author Prasser, Kohlmayer */ public class TestIllegalArguments extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void testEmptyDatasetWithAttributeDefinition() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = Data.create(); data.getDefinition() .setAttributeType("age", AttributeType.IDENTIFYING_ATTRIBUTE); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyDatasetWithoutAttributeDefinition() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = Data.create(); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(data, config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyDefinition() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyHierarchy() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = provider.getData(); data.getDefinition().setAttributeType("age", Hierarchy.create()); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testHistorySize() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setHistorySize(-1); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testInvalidHierarchies() throws IOException { provider.createWrongDataDefinition(); final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString("*"); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeNegative() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(-1)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeTooLarge() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(8)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeZero() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(0)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersEqualsOne() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersNegative() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(-0.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersTooLarge() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMetric() { try { final ARXConfiguration config = ARXConfiguration.create(); config.setMetric(null); } catch (final NullPointerException e) { return; } Assert.fail(); } @Test public void testMissingHierarchyValue() throws IOException { provider.createDataDefinitionMissing(); final Data data = provider.getData(); final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString("*"); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(0d); anonymizer.anonymize(data, config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testNullHierarchy() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = provider.getData(); data.getDefinition().setAttributeType("age", null); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(data, config); } catch (final NullPointerException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeNegative() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(-1); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeTooLarge() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(1.01d); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeZero() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(0); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSuppressionString() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString(null); } catch (final NullPointerException e) { return; } Assert.fail(); } }
src/test/org/deidentifier/arx/test/TestIllegalArguments.java
/* * ARX: Efficient, Stable and Optimal Data Anonymization * Copyright (C) 2012 - 2014 Florian Kohlmayer, Fabian Prasser * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.deidentifier.arx.test; import java.io.IOException; import org.deidentifier.arx.ARXAnonymizer; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.AttributeType; import org.deidentifier.arx.AttributeType.Hierarchy; import org.deidentifier.arx.Data; import org.deidentifier.arx.criteria.KAnonymity; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * A test case for illegal arguments * * @author Prasser, Kohlmayer */ public class TestIllegalArguments extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void testEmptyDatasetWithAttributeDefinition() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = Data.create(); data.getDefinition() .setAttributeType("age", AttributeType.IDENTIFYING_ATTRIBUTE); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyDatasetWithoutAttributeDefinition() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = Data.create(); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(data, config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyDefinition() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testEmptyHierarchy() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = provider.getData(); data.getDefinition().setAttributeType("age", Hierarchy.create()); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testHistorySize() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setHistorySize(-1); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testInvalidHierarchies() throws IOException { provider.createWrongDataDefinition(); final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString("*"); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeNegative() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(-1)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeTooLarge() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(8)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testKRangeZero() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(0)); config.setMaxOutliers(0d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersEqualsOne() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersNegative() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(-0.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMaxOutliersTooLarge() throws IOException { final ARXAnonymizer anonymizer = new ARXAnonymizer(); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(provider.getData(), config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testMetric() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final ARXConfiguration config = ARXConfiguration.create(); config.setMetric(null); } catch (final NullPointerException e) { return; } Assert.fail(); } @Test public void testMissingHierarchyValue() throws IOException { provider.createDataDefinitionMissing(); final Data data = provider.getData(); final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString("*"); try { final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(0d); anonymizer.anonymize(data, config); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testNullHierarchy() throws IOException { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); final Data data = provider.getData(); data.getDefinition().setAttributeType("age", null); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(2)); config.setMaxOutliers(1.2d); anonymizer.anonymize(data, config); } catch (final NullPointerException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeNegative() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(-1); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeTooLarge() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(1.01d); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSnapshotSizeZero() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setMaximumSnapshotSizeDataset(0); } catch (final IllegalArgumentException e) { return; } Assert.fail(); } @Test public void testSuppressionString() { try { final ARXAnonymizer anonymizer = new ARXAnonymizer(); anonymizer.setSuppressionString(null); } catch (final NullPointerException e) { return; } Assert.fail(); } }
Cleanups
src/test/org/deidentifier/arx/test/TestIllegalArguments.java
Cleanups
Java
apache-2.0
98372d8c65da69272093d0879059667cd40489f4
0
lemib/maps-app-android,kubaszostak/maps-app-android,shellygill/maps-app-android,Esri/maps-app-android
/* Copyright 1995-2014 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For additional information, contact: * Environmental Systems Research Institute, Inc. * Attn: Contracts Dept * 380 New York Street * Redlands, California, USA 92373 * * email: contracts@esri.com * */ package com.esri.android.mapsapp; import java.util.ArrayList; import java.util.List; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.esri.android.mapsapp.account.AccountManager; import com.esri.android.mapsapp.account.SignInActivity; /** * Entry point into the Maps App. */ public class MapsAppActivity extends Activity { private static final String TAG = MapsAppActivity.class.getSimpleName(); DrawerLayout mDrawerLayout; ContentBrowserFragment mBrowseFragment; /** * The FrameLayout that hosts the main content of the activity, such as the MapView */ FrameLayout mContentFrame; /** * The list of menu items in the navigation drawer */ private ListView mDrawerList; private final List<DrawerItem> mDrawerItems = new ArrayList<DrawerItem>(); /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps_app_activity); setupDrawer(); } @Override protected void onResume() { super.onResume(); setView(); updateDrawer(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // first check if the drawer toggle button was selected boolean handled = mDrawerToggle.onOptionsItemSelected(item); if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } /** * Initializes the navigation drawer. */ private void setupDrawer() { mDrawerLayout = (DrawerLayout) findViewById(R.id.maps_app_activity_drawer_layout); mContentFrame = (FrameLayout) findViewById(R.id.maps_app_activity_content_frame); mDrawerList = (ListView) findViewById(R.id.maps_app_activity_left_drawer); // Set the list's click listener mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); updateDrawer(); } private void setView() { if (AccountManager.getInstance().isSignedIn()) { // we are signed in to a portal - show the content browser to choose a map showContentBrowser(); } else { // show the default map showMap(null, null); } } /** * Opens the content browser that shows the user's maps. */ private void showContentBrowser() { FragmentManager fragmentManager = getFragmentManager(); Fragment browseFragment = fragmentManager.findFragmentByTag(ContentBrowserFragment.TAG); if (browseFragment == null) { browseFragment = new ContentBrowserFragment(); } if (!browseFragment.isVisible()) { FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.maps_app_activity_content_frame, browseFragment, ContentBrowserFragment.TAG); transaction.addToBackStack(null); transaction.commit(); invalidateOptionsMenu(); // reload the options menu } mDrawerLayout.closeDrawers(); } /** * Opens the map represented by the specified portal item or if null, opens a default map. */ public void showMap(String portalItemId, String basemapPortalItemId) { // remove existing MapFragment explicitly, simply replacing it can cause the app to freeze when switching basemaps FragmentTransaction transaction = null; FragmentManager fragmentManager = getFragmentManager(); Fragment currentMapFragment = fragmentManager.findFragmentByTag(MapFragment.TAG); if (currentMapFragment != null) { transaction = fragmentManager.beginTransaction(); transaction.remove(currentMapFragment); transaction.commit(); } MapFragment mapFragment = MapFragment.newInstance(portalItemId, basemapPortalItemId); transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.maps_app_activity_content_frame, mapFragment, MapFragment.TAG); // transaction.addToBackStack(null); transaction.commit(); invalidateOptionsMenu(); // reload the options menu } private void showSignInActivity() { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); mDrawerLayout.closeDrawers(); } /** * Resets the app to "signed out" state. */ private void signOut() { AccountManager.getInstance().setPortal(null); setView(); updateDrawer(); mDrawerLayout.closeDrawers(); } /** * Updates the navigation drawer items. */ private void updateDrawer() { mDrawerItems.clear(); DrawerItem item = null; if (AccountManager.getInstance().isSignedIn()) { // Sign Out item = new DrawerItem(getString(R.string.sign_out), new DrawerItem.OnClickListener() { @Override public void onClick() { signOut(); } }); mDrawerItems.add(item); // My Maps item = new DrawerItem(getString(R.string.my_maps), new DrawerItem.OnClickListener() { @Override public void onClick() { showContentBrowser(); } }); mDrawerItems.add(item); } else { item = new DrawerItem(getString(R.string.sign_in), new DrawerItem.OnClickListener() { @Override public void onClick() { showSignInActivity(); } }); mDrawerItems.add(item); } BaseAdapter adapter = (BaseAdapter) mDrawerList.getAdapter(); if (adapter == null) { adapter = new DrawerItemListAdapter(); mDrawerList.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } } /** * Handles selection of items in the navigation drawer. */ private class DrawerItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerItems.get(position).onClicked(); } } /** * Populates the navigation drawer list with items. */ private class DrawerItemListAdapter extends BaseAdapter { @Override public int getCount() { return mDrawerItems.size(); } @Override public Object getItem(int position) { return mDrawerItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = getLayoutInflater().inflate(R.layout.drawer_item_layout, null); } DrawerItem drawerItem = (DrawerItem) getItem(position); TextView textView = (TextView) view; textView.setText(drawerItem.getTitle()); return view; } } }
maps-app/src/com/esri/android/mapsapp/MapsAppActivity.java
/* Copyright 1995-2014 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For additional information, contact: * Environmental Systems Research Institute, Inc. * Attn: Contracts Dept * 380 New York Street * Redlands, California, USA 92373 * * email: contracts@esri.com * */ package com.esri.android.mapsapp; import java.util.ArrayList; import java.util.List; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.esri.android.mapsapp.account.AccountManager; import com.esri.android.mapsapp.account.SignInActivity; /** * Entry point into the Maps App. */ public class MapsAppActivity extends Activity { private static final String TAG = MapsAppActivity.class.getSimpleName(); DrawerLayout mDrawerLayout; ContentBrowserFragment mBrowseFragment; /** * The FrameLayout that hosts the main content of the activity, such as the MapView */ FrameLayout mContentFrame; /** * The list of menu items in the navigation drawer */ private ListView mDrawerList; private final List<DrawerItem> mDrawerItems = new ArrayList<DrawerItem>(); /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps_app_activity); setupDrawer(); } @Override protected void onResume() { super.onResume(); setView(); updateDrawer(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // first check if the drawer toggle button was selected boolean handled = mDrawerToggle.onOptionsItemSelected(item); if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } /** * Initializes the navigation drawer. */ private void setupDrawer() { mDrawerLayout = (DrawerLayout) findViewById(R.id.maps_app_activity_drawer_layout); mContentFrame = (FrameLayout) findViewById(R.id.maps_app_activity_content_frame); mDrawerList = (ListView) findViewById(R.id.maps_app_activity_left_drawer); // Set the list's click listener mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); // calls onPrepareOptionsMenu() } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); updateDrawer(); } private void setView() { if (AccountManager.getInstance().isSignedIn()) { // we are signed in to a portal - show the content browser to choose a map showContentBrowser(); } else { // show the default map showMap(null, null); } } /** * Opens the content browser that shows the user's maps. */ private void showContentBrowser() { ContentBrowserFragment browseFragment = new ContentBrowserFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.maps_app_activity_content_frame, browseFragment, ContentBrowserFragment.TAG); transaction.commit(); invalidateOptionsMenu(); // reload the options menu } /** * Opens the map represented by the specified portal item or if null, opens a default map. */ public void showMap(String portalItemId, String basemapPortalItemId) { // remove existing MapFragment explicitly, simply replacing it can cause the app to freeze when switching basemaps FragmentTransaction transaction = null; FragmentManager fragmentManager = getFragmentManager(); Fragment currentMapFragment = fragmentManager.findFragmentByTag(MapFragment.TAG); if (currentMapFragment != null) { transaction = fragmentManager.beginTransaction(); transaction.remove(currentMapFragment); transaction.commit(); } MapFragment mapFragment = MapFragment.newInstance(portalItemId, basemapPortalItemId); transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.maps_app_activity_content_frame, mapFragment, MapFragment.TAG); // transaction.addToBackStack(null); transaction.commit(); invalidateOptionsMenu(); // reload the options menu } private void showSignInActivity() { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); mDrawerLayout.closeDrawers(); } /** * Resets the app to "signed out" state. */ private void signOut() { AccountManager.getInstance().setPortal(null); setView(); updateDrawer(); mDrawerLayout.closeDrawers(); } /** * Updates the navigation drawer items. */ private void updateDrawer() { mDrawerItems.clear(); DrawerItem item = null; if (AccountManager.getInstance().isSignedIn()) { item = new DrawerItem(getString(R.string.sign_out), new DrawerItem.OnClickListener() { @Override public void onClick() { signOut(); } }); } else { item = new DrawerItem(getString(R.string.sign_in), new DrawerItem.OnClickListener() { @Override public void onClick() { showSignInActivity(); } }); } mDrawerItems.add(item); BaseAdapter adapter = (BaseAdapter) mDrawerList.getAdapter(); if (adapter == null) { adapter = new DrawerItemListAdapter(); mDrawerList.setAdapter(adapter); } else { adapter.notifyDataSetChanged(); } } /** * Handles selection of items in the navigation drawer. */ private class DrawerItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mDrawerItems.get(position).onClicked(); } } /** * Populates the navigation drawer list with items. */ private class DrawerItemListAdapter extends BaseAdapter { @Override public int getCount() { return mDrawerItems.size(); } @Override public Object getItem(int position) { return mDrawerItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = getLayoutInflater().inflate(R.layout.drawer_item_layout, null); } DrawerItem drawerItem = (DrawerItem) getItem(position); TextView textView = (TextView) view; textView.setText(drawerItem.getTitle()); return view; } } }
added My Maps item to navigation drawer
maps-app/src/com/esri/android/mapsapp/MapsAppActivity.java
added My Maps item to navigation drawer
Java
apache-2.0
9127b874244c77d32fda5c1ff0826ec7a5647d21
0
soygul/nbusy-android,nbusy/nbusy-android
package com.nbusy.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * An activity representing a list of Messages. This activity has different presentations for handset and tablet-size devices. On * handsets, the activity presents a list of items, which when touched, lead to a {@link MessageDetailActivity} representing * item details. On tablets, the activity presents the list of items and item details side-by-side using two vertical panes. * <p/> * The activity makes heavy use of fragments. The list of items is a {@link MessageListFragment} and the item details * (if present) is a {@link MessageDetailFragment}. * <p/> * This activity also implements the required {@link MessageListFragment.Callbacks} interface to listen for item selections. */ public class MessageListActivity extends Activity implements MessageListFragment.Callbacks { private static final String TAG = "MessageListActivity"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_REG_ID = "registration_id"; GoogleCloudMessaging gcm; String SENDER_ID = "218602439235"; String regId; AtomicInteger msgId = new AtomicInteger(); // whether or not the activity is in two-pane mode, i.e. running on a tablet device private boolean mTwoPane; /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } @Override protected void onCreate(Bundle savedInstanceState) { if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_message_list); if (findViewById(R.id.message_detail_container) != null) { // the detail container view will be present only in the large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the activity should be in two-pane mode mTwoPane = true; // in two-pane mode, list items should be given the 'activated' state when touched ((MessageListFragment) getFragmentManager() .findFragmentById(R.id.message_list)) .setActivateOnItemClick(true); } // GCM registration gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getApplicationContext()); if (regId.isEmpty()) { registerInBackground(); } sendGcmMessage("just testing from Android simulator"); } /** * Callback method from {@link MessageListFragment.Callbacks} indicating that the item with the given ID was selected. */ @Override public void onItemSelected(String id) { if (mTwoPane) { // in two-pane mode, show the detail view in this activity by adding or replacing the detail fragment using a fragment transaction Bundle arguments = new Bundle(); arguments.putString(MessageDetailFragment.ARG_ITEM_ID, id); MessageDetailFragment fragment = new MessageDetailFragment(); fragment.setArguments(arguments); getFragmentManager() .beginTransaction() .replace(R.id.message_detail_container, fragment) .commit(); } else { // in single-pane mode, simply start the detail activity for the selected item ID Intent detailIntent = new Intent(this, MessageDetailActivity.class); detailIntent.putExtra(MessageDetailFragment.ARG_ITEM_ID, id); startActivity(detailIntent); } } /** * Gets the current registration ID for application on GCM service, if there is one. If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "GCM registration not found."); return ""; } // check if app was updated; if so, it must clear the registration ID since the existing regID is not guaranteed to work with // the new app version int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed. GCM registration will be refreshed."); return ""; } Log.i(TAG, "GCM registration id found: " + registrationId); return registrationId; } /** * Registers the application with GCM servers asynchronously. * Stores the registration ID and the app versionCode in the application's shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); } regId = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regId; // you should send the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send messages to your app sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send upstream messages to a server that echo back the message // using the 'from' address in the message. // persist the regID - no need to register again storeRegistrationId(getApplicationContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // if there is an error, don't just keep trying to register // require the user to click a button again, or perform exponential back-off } Log.i(TAG, msg); return msg; } @Override protected void onPostExecute(String msg) { Log.i(TAG, msg); } }.execute(null, null, null); } /** * Stores the registration ID and the app versionCode in the application's {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.apply(); } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // this sample app persists the registration ID in shared preferences, but how you store the regID in your app is up to you return getSharedPreferences(MessageListActivity.class.getSimpleName(), Context.MODE_PRIVATE); } private void sendRegistrationIdToBackend() { sendGcmMessage(regId); } private void sendGcmMessage(final String message) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("test_message_from_device", message); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent upstream GCM message to the backend: " + message; } catch (IOException ex) { msg = "Error while sending upstream GCM message to the backend:" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { Log.i(TAG, msg); } }.execute(null, null, null); } }
app/src/main/java/com/nbusy/app/MessageListActivity.java
package com.nbusy.app; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * An activity representing a list of Messages. This activity has different presentations for handset and tablet-size devices. On * handsets, the activity presents a list of items, which when touched, lead to a {@link MessageDetailActivity} representing * item details. On tablets, the activity presents the list of items and item details side-by-side using two vertical panes. * <p/> * The activity makes heavy use of fragments. The list of items is a {@link MessageListFragment} and the item details * (if present) is a {@link MessageDetailFragment}. * <p/> * This activity also implements the required {@link MessageListFragment.Callbacks} interface to listen for item selections. */ public class MessageListActivity extends Activity implements MessageListFragment.Callbacks { private static final String TAG = "MessageListActivity"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_REG_ID = "registration_id"; GoogleCloudMessaging gcm; String SENDER_ID = "218602439235"; String regId; AtomicInteger msgId = new AtomicInteger(); // whether or not the activity is in two-pane mode, i.e. running on a tablet device private boolean mTwoPane; /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } @Override protected void onCreate(Bundle savedInstanceState) { if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_message_list); if (findViewById(R.id.message_detail_container) != null) { // the detail container view will be present only in the large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the activity should be in two-pane mode mTwoPane = true; // in two-pane mode, list items should be given the 'activated' state when touched ((MessageListFragment) getFragmentManager() .findFragmentById(R.id.message_list)) .setActivateOnItemClick(true); } // GCM registration gcm = GoogleCloudMessaging.getInstance(this); regId = getRegistrationId(getApplicationContext()); if (regId.isEmpty()) { registerInBackground(); } sendRegistrationIdToBackend(); // todo: remove this! } /** * Callback method from {@link MessageListFragment.Callbacks} indicating that the item with the given ID was selected. */ @Override public void onItemSelected(String id) { if (mTwoPane) { // in two-pane mode, show the detail view in this activity by adding or replacing the detail fragment using a fragment transaction Bundle arguments = new Bundle(); arguments.putString(MessageDetailFragment.ARG_ITEM_ID, id); MessageDetailFragment fragment = new MessageDetailFragment(); fragment.setArguments(arguments); getFragmentManager() .beginTransaction() .replace(R.id.message_detail_container, fragment) .commit(); } else { // in single-pane mode, simply start the detail activity for the selected item ID Intent detailIntent = new Intent(this, MessageDetailActivity.class); detailIntent.putExtra(MessageDetailFragment.ARG_ITEM_ID, id); startActivity(detailIntent); } } /** * Gets the current registration ID for application on GCM service, if there is one. If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "GCM registration not found."); return ""; } // check if app was updated; if so, it must clear the registration ID since the existing regID is not guaranteed to work with // the new app version int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed. GCM registration will be refreshed."); return ""; } Log.i(TAG, "GCM registration id found: " + registrationId); return registrationId; } /** * Registers the application with GCM servers asynchronously. * Stores the registration ID and the app versionCode in the application's shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); } regId = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regId; // you should send the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send messages to your app sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send upstream messages to a server that echo back the message // using the 'from' address in the message. // persist the regID - no need to register again storeRegistrationId(getApplicationContext(), regId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // if there is an error, don't just keep trying to register // require the user to click a button again, or perform exponential back-off } Log.i(TAG, msg); return msg; } @Override protected void onPostExecute(String msg) { Log.i(TAG, msg); } }.execute(null, null, null); } /** * Stores the registration ID and the app versionCode in the application's {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.apply(); } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // this sample app persists the registration ID in shared preferences, but how you store the regID in your app is up to you return getSharedPreferences(MessageListActivity.class.getSimpleName(), Context.MODE_PRIVATE); } private void sendRegistrationIdToBackend() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", regId); // send access token here as regId is 'from' field in <message> data.putString("my_action", "com.nbusy.app.MessageListActivity"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent GCM registration ID to the backend."; } catch (IOException ex) { msg = "Error while sending GCM registration ID to the backend :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { Log.i(TAG, msg); } }.execute(null, null, null); } }
tidyup
app/src/main/java/com/nbusy/app/MessageListActivity.java
tidyup
Java
apache-2.0
f295829d13c3a6020d8effe8f1ddef0ee8ce1709
0
cuba-platform/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.web.toolkit.ui.client.combobox; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.Widget; import com.vaadin.client.ui.ShortcutActionHandler; import com.vaadin.client.ui.VFilterSelect; import java.util.Iterator; import java.util.LinkedList; public class CubaComboBoxWidget extends VFilterSelect implements ShortcutActionHandler.ShortcutActionHandlerOwner, HasEnabled { private static final String READONLY_STYLE_SUFFIX = "readonly"; private static final String PROMPT_STYLE = "prompt"; private static final String CUBA_DISABLED_OR_READONLY = "c-disabled-or-readonly"; private static final String CUBA_EMPTY_VALUE = "c-empty-value"; protected ShortcutActionHandler shortcutHandler; protected boolean enabled = true; public CubaComboBoxWidget() { // handle shortcuts DOM.sinkEvents(getElement(), Event.ONKEYDOWN); } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); final int type = DOM.eventGetType(event); if (type == Event.ONKEYDOWN && shortcutHandler != null) { shortcutHandler.handleKeyboardEvent(event); } } @Override public void onKeyUp(KeyUpEvent event) { if (enabled && !readonly) { switch (event.getNativeKeyCode()) { case KeyCodes.KEY_ENTER: case KeyCodes.KEY_TAB: case KeyCodes.KEY_SHIFT: case KeyCodes.KEY_CTRL: case KeyCodes.KEY_ALT: case KeyCodes.KEY_DOWN: case KeyCodes.KEY_UP: case KeyCodes.KEY_PAGEDOWN: case KeyCodes.KEY_PAGEUP: case KeyCodes.KEY_ESCAPE: // NOP break; default: // special case for "clear" shortcut action if (event.isShiftKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_DELETE) { suggestionPopup.hide(); } else { // do not show options popup if we handle shortcut action if (!event.isControlKeyDown() && !event.isAltKeyDown()) { super.onKeyUp(event); } } break; } } } @Override public void setPromptingOff(String text) { // copied from com.vaadin.client.ui.VFilterSelect.setPromptingOff // condition operator and calling method were s if (prompting) { prompting = false; removeStyleDependentName(PROMPT_STYLE); } setTextboxText(text); } public void setShortcutActionHandler(ShortcutActionHandler handler) { this.shortcutHandler = handler; } @Override public ShortcutActionHandler getShortcutActionHandler() { return shortcutHandler; } @Override public void add(Widget w) { } @Override public void setTextboxText(String text) { super.setTextboxText(text); if ("".equals(text) || text == null) { addStyleName(CUBA_EMPTY_VALUE); } else { if (getStyleName().contains(PROMPT_STYLE)) { addStyleName(CUBA_EMPTY_VALUE); } else { removeStyleName(CUBA_EMPTY_VALUE); } } } @Override public void clear() { } @Override public Iterator<Widget> iterator() { return new LinkedList<Widget>().iterator(); } @Override public boolean remove(Widget w) { return false; } @Override public boolean isEnabled() { return enabled; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; refreshEnabledOrReadonly(); if (getStyleName().contains(CUBA_EMPTY_VALUE)) { setPromptingOn(); } } protected boolean isReadonly() { return getStyleName().contains(getStylePrimaryName() + "-" + READONLY_STYLE_SUFFIX); } protected void refreshEnabledOrReadonly() { if (!isEnabled() || isReadonly()) { addStyleName(CUBA_DISABLED_OR_READONLY); } else { removeStyleName(CUBA_DISABLED_OR_READONLY); } } @Override public void onBlur(BlurEvent event) { super.onBlur(event); if (!readonly && !"".equals(inputPrompt) && ("".equals(selectedOptionKey) || null == selectedOptionKey)) { setPromptingOn(); } } @Override protected boolean isDoSelectedItemActionOnBlur() { return super.isDoSelectedItemActionOnBlur() // We need to create a new item if suggestionPopup is closed // by clicking outside the component && suggestionPopup.isJustClosed(); } }
modules/web-toolkit/src/com/haulmont/cuba/web/toolkit/ui/client/combobox/CubaComboBoxWidget.java
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.web.toolkit.ui.client.combobox; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.HasEnabled; import com.google.gwt.user.client.ui.Widget; import com.vaadin.client.ui.ShortcutActionHandler; import com.vaadin.client.ui.VFilterSelect; import java.util.Iterator; import java.util.LinkedList; public class CubaComboBoxWidget extends VFilterSelect implements ShortcutActionHandler.ShortcutActionHandlerOwner, HasEnabled { private static final String READONLY_STYLE_SUFFIX = "readonly"; private static final String PROMPT_STYLE = "prompt"; private static final String CUBA_DISABLED_OR_READONLY = "c-disabled-or-readonly"; private static final String CUBA_EMPTY_VALUE = "c-empty-value"; protected ShortcutActionHandler shortcutHandler; protected boolean enabled = true; public CubaComboBoxWidget() { // handle shortcuts DOM.sinkEvents(getElement(), Event.ONKEYDOWN); } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); final int type = DOM.eventGetType(event); if (type == Event.ONKEYDOWN && shortcutHandler != null) { shortcutHandler.handleKeyboardEvent(event); } } @Override public void onKeyUp(KeyUpEvent event) { if (enabled && !readonly) { switch (event.getNativeKeyCode()) { case KeyCodes.KEY_ENTER: case KeyCodes.KEY_TAB: case KeyCodes.KEY_SHIFT: case KeyCodes.KEY_CTRL: case KeyCodes.KEY_ALT: case KeyCodes.KEY_DOWN: case KeyCodes.KEY_UP: case KeyCodes.KEY_PAGEDOWN: case KeyCodes.KEY_PAGEUP: case KeyCodes.KEY_ESCAPE: // NOP break; default: // special case for "clear" shortcut action if (event.isShiftKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_DELETE) { suggestionPopup.hide(); } else { // do not show options popup if we handle shortcut action if (!event.isControlKeyDown() && !event.isAltKeyDown()) { super.onKeyUp(event); } } break; } } } @Override public void setPromptingOff(String text) { // copied from com.vaadin.client.ui.VFilterSelect.setPromptingOff // condition operator and calling method were s if (prompting) { prompting = false; removeStyleDependentName(PROMPT_STYLE); } setTextboxText(text); } public void setShortcutActionHandler(ShortcutActionHandler handler) { this.shortcutHandler = handler; } @Override public ShortcutActionHandler getShortcutActionHandler() { return shortcutHandler; } @Override public void add(Widget w) { } @Override public void setTextboxText(String text) { super.setTextboxText(text); if ("".equals(text) || text == null) { addStyleName(CUBA_EMPTY_VALUE); } else { if (getStyleName().contains(PROMPT_STYLE)) { addStyleName(CUBA_EMPTY_VALUE); } else { removeStyleName(CUBA_EMPTY_VALUE); } } } @Override public void clear() { } @Override public Iterator<Widget> iterator() { return new LinkedList<Widget>().iterator(); } @Override public boolean remove(Widget w) { return false; } @Override public boolean isEnabled() { return enabled; } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; refreshEnabledOrReadonly(); if (getStyleName().contains(CUBA_EMPTY_VALUE)) { setPromptingOn(); } } protected boolean isReadonly() { return getStyleName().contains(getStylePrimaryName() + "-" + READONLY_STYLE_SUFFIX); } protected void refreshEnabledOrReadonly() { if (!isEnabled() || isReadonly()) { addStyleName(CUBA_DISABLED_OR_READONLY); } else { removeStyleName(CUBA_DISABLED_OR_READONLY); } } @Override public void onBlur(BlurEvent event) { super.onBlur(event); if (!readonly && !"".equals(inputPrompt) && ("".equals(selectedOptionKey) || null == selectedOptionKey)) { setPromptingOn(); } } @Override protected boolean isDoSelectedItemActionOnBlur() { return super.isDoSelectedItemActionOnBlur() && suggestionPopup.isAttached(); } }
PL-10434 NewOptionHandler on LookupField is not fired when focus changed through mouse click
modules/web-toolkit/src/com/haulmont/cuba/web/toolkit/ui/client/combobox/CubaComboBoxWidget.java
PL-10434 NewOptionHandler on LookupField is not fired when focus changed through mouse click
Java
apache-2.0
111056e4e88749612c9ecf9cb9552a9ca822486b
0
salguarnieri/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,vladmm/intellij-community,FHannes/intellij-community,petteyg/intellij-community,allotria/intellij-community,samthor/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,amith01994/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,slisson/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,fitermay/intellij-community,izonder/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,holmes/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,da1z/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,caot/intellij-community,samthor/intellij-community,youdonghai/intellij-community,slisson/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,adedayo/intellij-community,samthor/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,izonder/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,clumsy/intellij-community,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,holmes/intellij-community,diorcety/intellij-community,slisson/intellij-community,semonte/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,holmes/intellij-community,apixandru/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,asedunov/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,da1z/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,diorcety/intellij-community,jagguli/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,apixandru/intellij-community,adedayo/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,da1z/intellij-community,dslomov/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,kool79/intellij-community,clumsy/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,kdwink/intellij-community,hurricup/intellij-community,signed/intellij-community,semonte/intellij-community,fnouama/intellij-community,allotria/intellij-community,da1z/intellij-community,gnuhub/intellij-community,allotria/intellij-community,nicolargo/intellij-community,samthor/intellij-community,kdwink/intellij-community,kool79/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,slisson/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,robovm/robovm-studio,hurricup/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,retomerz/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,holmes/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,kool79/intellij-community,supersven/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,slisson/intellij-community,ryano144/intellij-community,adedayo/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,samthor/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,supersven/intellij-community,supersven/intellij-community,jagguli/intellij-community,izonder/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,signed/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,amith01994/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,allotria/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,allotria/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,signed/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,holmes/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,samthor/intellij-community,supersven/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,signed/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,clumsy/intellij-community,diorcety/intellij-community,semonte/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,allotria/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,SerCeMan/intellij-community,jagguli/intellij-community,ibinti/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,semonte/intellij-community,xfournet/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,da1z/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,caot/intellij-community,allotria/intellij-community,xfournet/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,signed/intellij-community,holmes/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,holmes/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,caot/intellij-community,supersven/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,robovm/robovm-studio,ibinti/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,ibinti/intellij-community,izonder/intellij-community,kool79/intellij-community,apixandru/intellij-community,asedunov/intellij-community,caot/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,allotria/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,kool79/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,retomerz/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,signed/intellij-community,vladmm/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,kool79/intellij-community,caot/intellij-community,da1z/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,caot/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,slisson/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,semonte/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,vvv1559/intellij-community,signed/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,fitermay/intellij-community,robovm/robovm-studio,xfournet/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,slisson/intellij-community,dslomov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,kool79/intellij-community,apixandru/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,asedunov/intellij-community,samthor/intellij-community,allotria/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,fnouama/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,FHannes/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,caot/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fitermay/intellij-community,petteyg/intellij-community,holmes/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,izonder/intellij-community,hurricup/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,asedunov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,caot/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,ryano144/intellij-community,FHannes/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,da1z/intellij-community,hurricup/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,izonder/intellij-community,izonder/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,apixandru/intellij-community,dslomov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,FHannes/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,fitermay/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,da1z/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,samthor/intellij-community,vladmm/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,kdwink/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,semonte/intellij-community,clumsy/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,signed/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,blademainer/intellij-community,allotria/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,asedunov/intellij-community,slisson/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,holmes/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,caot/intellij-community,caot/intellij-community,ryano144/intellij-community,Lekanich/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.coverage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import org.jetbrains.jps.model.java.JavaSourceRootType; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author ven */ public class PackageAnnotator { private static final Logger LOG = Logger.getInstance("#" + PackageAnnotator.class.getName()); private static final String DEFAULT_CONSTRUCTOR_NAME_SIGNATURE = "<init>()V"; private final PsiPackage myPackage; private final Project myProject; private final PsiManager myManager; private final CoverageDataManager myCoverageManager; public PackageAnnotator(final PsiPackage aPackage) { myPackage = aPackage; myProject = myPackage.getProject(); myManager = PsiManager.getInstance(myProject); myCoverageManager = CoverageDataManager.getInstance(myProject); } public interface Annotator { void annotateSourceDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotateTestDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo, boolean flatten); void annotateClass(String classQualifiedName, ClassCoverageInfo classCoverageInfo); } public static abstract class SummaryCoverageInfo { public int totalClassCount; public int coveredClassCount; public int totalMethodCount; public int coveredMethodCount; public int totalLineCount; public abstract int getCoveredLineCount(); } public static class ClassCoverageInfo extends SummaryCoverageInfo { public int fullyCoveredLineCount; public int partiallyCoveredLineCount; public ClassCoverageInfo() { totalClassCount = 1; } @Override public int getCoveredLineCount() { return fullyCoveredLineCount + partiallyCoveredLineCount; } } public static class PackageCoverageInfo extends SummaryCoverageInfo { public int coveredLineCount; @Override public int getCoveredLineCount() { return coveredLineCount; } public void append(SummaryCoverageInfo info) { totalClassCount += info.totalClassCount; totalLineCount += info.totalLineCount; coveredClassCount += info.coveredClassCount; coveredLineCount += info.getCoveredLineCount(); coveredMethodCount += info.coveredMethodCount; totalMethodCount += info.totalMethodCount; } } public static class DirCoverageInfo extends PackageCoverageInfo { public VirtualFile sourceRoot; public DirCoverageInfo(VirtualFile sourceRoot) { this.sourceRoot = sourceRoot; } } //get read lock myself when needed public void annotate(final CoverageSuitesBundle suite, Annotator annotator) { final ProjectData data = suite.getCoverageData(); if (data == null) return; final String qualifiedName = myPackage.getQualifiedName(); boolean filtered = false; for (CoverageSuite coverageSuite : suite.getSuites()) { if (((JavaCoverageSuite)coverageSuite).isPackageFiltered(qualifiedName)) { filtered = true; break; } } if (!filtered) return; final GlobalSearchScope scope = suite.getSearchScope(myProject); final Module[] modules = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Module[]>() { public Module[] compute() { return ModuleManager.getInstance(myProject).getModules(); } }); if (modules == null) return; Map<String, PackageCoverageInfo> packageCoverageMap = new HashMap<String, PackageCoverageInfo>(); Map<String, PackageCoverageInfo> flattenPackageCoverageMap = new HashMap<String, PackageCoverageInfo>(); for (final Module module : modules) { if (!scope.isSearchInModuleContent(module)) continue; final String rootPackageVMName = qualifiedName.replaceAll("\\.", "/"); final VirtualFile output = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { return CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); } }); if (output != null) { File outputRoot = findRelativeFile(rootPackageVMName, output); if (outputRoot.exists()) { collectCoverageInformation(outputRoot, packageCoverageMap, flattenPackageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), false); } } if (suite.isTrackTestFolders()) { final VirtualFile testPackageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { return CompilerModuleExtension.getInstance(module).getCompilerOutputPathForTests(); } }); if (testPackageRoot != null) { final File outputRoot = findRelativeFile(rootPackageVMName, testPackageRoot); if (outputRoot.exists()) { collectCoverageInformation(outputRoot, packageCoverageMap, flattenPackageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), true); } } } } for (Map.Entry<String, PackageCoverageInfo> entry : packageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info); } for (Map.Entry<String, PackageCoverageInfo> entry : flattenPackageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info, true); } } private static File findRelativeFile(String rootPackageVMName, VirtualFile output) { File outputRoot = VfsUtilCore.virtualToIoFile(output); outputRoot = rootPackageVMName.length() > 0 ? new File(outputRoot, FileUtil.toSystemDependentName(rootPackageVMName)) : outputRoot; return outputRoot; } public void annotateFilteredClass(PsiClass psiClass, CoverageSuitesBundle bundle, Annotator annotator) { final ProjectData data = bundle.getCoverageData(); if (data == null) return; final Module module = ModuleUtil.findModuleForPsiElement(psiClass); if (module != null) { final boolean isInTests = ProjectRootManager.getInstance(module.getProject()).getFileIndex() .isInTestSourceContent(psiClass.getContainingFile().getVirtualFile()); final CompilerModuleExtension moduleExtension = CompilerModuleExtension.getInstance(module); final VirtualFile outputPath = isInTests ? moduleExtension.getCompilerOutputPathForTests() : moduleExtension.getCompilerOutputPath(); if (outputPath != null) { final String qualifiedName = psiClass.getQualifiedName(); if (qualifiedName == null) return; final String packageVMName = StringUtil.getPackageName(qualifiedName).replace('.', '/'); final File packageRoot = findRelativeFile(packageVMName, outputPath); if (packageRoot != null && packageRoot.exists()) { Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); final File[] files = packageRoot.listFiles(); if (files != null) { for (File child : files) { if (isClassFile(child)) { final String childName = getClassName(child); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); if (toplevelClassSrcFQName.equals(qualifiedName)) { collectClassCoverageInformation(child, psiClass, new PackageCoverageInfo(), data, toplevelClassCoverage, classFqVMName.replace("/", "."), toplevelClassSrcFQName); } } } } for (ClassCoverageInfo coverageInfo : toplevelClassCoverage.values()) { annotator.annotateClass(qualifiedName, coverageInfo); } } } } } @Nullable private DirCoverageInfo[] collectCoverageInformation(final File packageOutputRoot, final Map<String, PackageCoverageInfo> packageCoverageMap, Map<String, PackageCoverageInfo> flattenPackageCoverageMap, final ProjectData projectInfo, final String packageVMName, final Annotator annotator, final Module module, final boolean trackTestFolders, final boolean isTestHierarchy) { final List<DirCoverageInfo> dirs = new ArrayList<DirCoverageInfo>(); final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (ContentEntry contentEntry : contentEntries) { for (SourceFolder folder : contentEntry.getSourceFolders(isTestHierarchy ? JavaSourceRootType.TEST_SOURCE : JavaSourceRootType.SOURCE)) { final VirtualFile file = folder.getFile(); if (file == null) continue; final String prefix = folder.getPackagePrefix().replaceAll("\\.", "/"); final VirtualFile relativeSrcRoot = file.findFileByRelativePath(StringUtil.trimStart(packageVMName, prefix)); dirs.add(new DirCoverageInfo(relativeSrcRoot)); } } final PackageCoverageInfo classWithoutSourceCoverageInfo = new PackageCoverageInfo(); final File[] children = packageOutputRoot.listFiles(); if (children == null) return null; Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); for (File child : children) { if (child.isDirectory()) { final String childName = child.getName(); final String childPackageVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final DirCoverageInfo[] childCoverageInfo = collectCoverageInformation(child, packageCoverageMap, flattenPackageCoverageMap, projectInfo, childPackageVMName, annotator, module, trackTestFolders, isTestHierarchy); if (childCoverageInfo != null) { for (int i = 0; i < childCoverageInfo.length; i++) { DirCoverageInfo coverageInfo = childCoverageInfo[i]; final DirCoverageInfo parentDir = dirs.get(i); parentDir.totalClassCount += coverageInfo.totalClassCount; parentDir.coveredClassCount += coverageInfo.coveredClassCount; parentDir.totalLineCount += coverageInfo.totalLineCount; parentDir.coveredLineCount += coverageInfo.coveredLineCount; parentDir.totalMethodCount += coverageInfo.totalMethodCount; parentDir.coveredMethodCount += coverageInfo.coveredMethodCount; } } } else { if (isClassFile(child)) { final String childName = getClassName(child); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); final Ref<VirtualFile> containingFileRef = new Ref<VirtualFile>(); final Ref<PsiClass> psiClassRef = new Ref<PsiClass>(); final Boolean isInSource = DumbService.getInstance(myProject).runReadActionInSmartMode(new Computable<Boolean>() { public Boolean compute() { if (myProject.isDisposed()) return null; final PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(toplevelClassSrcFQName, GlobalSearchScope.moduleScope(module)); if (aClass == null || !aClass.isValid()) return Boolean.FALSE; psiClassRef.set(aClass); containingFileRef.set(aClass.getNavigationElement().getContainingFile().getVirtualFile()); if (containingFileRef.isNull()) { LOG.info("No virtual file found for: " + aClass); return null; } final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); return fileIndex.isUnderSourceRootOfType(containingFileRef.get(), JavaModuleSourceRootTypes.SOURCES) && (trackTestFolders || !fileIndex.isInTestSourceContent(containingFileRef.get())); } }); PackageCoverageInfo coverageInfoForClass = null; String classCoverageKey = classFqVMName.replace('/', '.'); boolean ignoreClass = false; for (JavaCoverageEngineExtension extension : JavaCoverageEngineExtension.EP_NAME.getExtensions()) { if (extension.ignoreCoverageForClass(myCoverageManager.getCurrentSuitesBundle(), child)) { ignoreClass = true; break; } if (extension.keepCoverageInfoForClassWithoutSource(myCoverageManager.getCurrentSuitesBundle(), child)) { coverageInfoForClass = classWithoutSourceCoverageInfo; break; } } if (ignoreClass) { continue; } if (coverageInfoForClass == null && isInSource != null && isInSource.booleanValue()) { for (DirCoverageInfo dirCoverageInfo : dirs) { if (dirCoverageInfo.sourceRoot != null && VfsUtil.isAncestor(dirCoverageInfo.sourceRoot, containingFileRef.get(), false)) { coverageInfoForClass = dirCoverageInfo; classCoverageKey = toplevelClassSrcFQName; break; } } } if (coverageInfoForClass != null) { collectClassCoverageInformation(child, psiClassRef.get(), coverageInfoForClass, projectInfo, toplevelClassCoverage, classFqVMName.replace("/", "."), classCoverageKey); } } } } for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final String toplevelClassName = entry.getKey(); final ClassCoverageInfo coverageInfo = entry.getValue(); annotator.annotateClass(toplevelClassName, coverageInfo); } PackageCoverageInfo flattenPackageCoverageInfo = getOrCreateCoverageInfo(flattenPackageCoverageMap, packageVMName); for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final ClassCoverageInfo coverageInfo = entry.getValue(); flattenPackageCoverageInfo.append(coverageInfo); } PackageCoverageInfo packageCoverageInfo = getOrCreateCoverageInfo(packageCoverageMap, packageVMName); for (DirCoverageInfo dir : dirs) { packageCoverageInfo.append(dir); if (isTestHierarchy) { annotator.annotateTestDirectory(dir.sourceRoot, dir, module); } else { annotator.annotateSourceDirectory(dir.sourceRoot, dir, module); } } packageCoverageInfo.append(classWithoutSourceCoverageInfo); return dirs.toArray(new DirCoverageInfo[dirs.size()]); } private static boolean isClassFile(File classFile) { return classFile.getName().endsWith(".class"); } private static String getClassName(File classFile) { return StringUtil.trimEnd(classFile.getName(), ".class"); } private static PackageCoverageInfo getOrCreateCoverageInfo(final Map<String, PackageCoverageInfo> packageCoverageMap, final String packageVMName) { PackageCoverageInfo coverageInfo = packageCoverageMap.get(packageVMName); if (coverageInfo == null) { coverageInfo = new PackageCoverageInfo(); packageCoverageMap.put(packageVMName, coverageInfo); } return coverageInfo; } private void collectClassCoverageInformation(final File classFile, @Nullable final PsiClass psiClass, final PackageCoverageInfo packageCoverageInfo, final ProjectData projectInfo, final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String className, final String toplevelClassSrcFQName) { final ClassCoverageInfo toplevelClassCoverageInfo = new ClassCoverageInfo(); final ClassData classData = projectInfo.getClassData(className); if (classData != null && classData.getLines() != null) { final Object[] lines = classData.getLines(); for (Object l : lines) { if (l instanceof LineData) { final LineData lineData = (LineData)l; if (lineData.getStatus() == LineCoverage.FULL) { toplevelClassCoverageInfo.fullyCoveredLineCount++; } else if (lineData.getStatus() == LineCoverage.PARTIAL) { toplevelClassCoverageInfo.partiallyCoveredLineCount++; } toplevelClassCoverageInfo.totalLineCount++; packageCoverageInfo.totalLineCount++; } } boolean touchedClass = false; final Collection methodSigs = classData.getMethodSigs(); for (final Object nameAndSig : methodSigs) { if (isGeneratedDefaultConstructor(psiClass, (String)nameAndSig)) { continue; } final int covered = classData.getStatus((String)nameAndSig); if (covered != LineCoverage.NONE) { toplevelClassCoverageInfo.coveredMethodCount++; touchedClass = true; } toplevelClassCoverageInfo.totalMethodCount++; } if (!methodSigs.isEmpty()) { if (touchedClass) { packageCoverageInfo.coveredClassCount++; } packageCoverageInfo.totalClassCount++; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; packageCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; packageCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; } else { LOG.debug("Did not find any method signatures in " + classFile.getName()); return; } } else { if (!collectNonCoveredClassInfo(classFile, psiClass, toplevelClassCoverageInfo, packageCoverageInfo)) { LOG.debug("Did not collect non-covered class info for " + classFile.getName()); return; } } ClassCoverageInfo classCoverageInfo = getOrCreateClassCoverageInfo(toplevelClassCoverage, toplevelClassSrcFQName); LOG.debug("Adding coverage of " + classFile.getName() + " to top-level class " + toplevelClassSrcFQName); classCoverageInfo.totalLineCount += toplevelClassCoverageInfo.totalLineCount; classCoverageInfo.fullyCoveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; classCoverageInfo.partiallyCoveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; classCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; classCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; if (toplevelClassCoverageInfo.coveredMethodCount > 0) { classCoverageInfo.coveredClassCount++; } } /** * Checks if the method is a default constructor generated by the compiler. Such constructors are not marked as synthetic * in the bytecode, so we need to look at the PSI to see if the class defines such a constructor. */ public static boolean isGeneratedDefaultConstructor(@Nullable final PsiClass aClass, String nameAndSig) { if (DEFAULT_CONSTRUCTOR_NAME_SIGNATURE.equals(nameAndSig)) { return hasGeneratedConstructor(aClass); } return false; } private static boolean hasGeneratedConstructor(@Nullable final PsiClass aClass) { if (aClass == null) { return false; } return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return aClass.getConstructors().length == 0; } }); } private static ClassCoverageInfo getOrCreateClassCoverageInfo(final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String sourceToplevelFQName) { ClassCoverageInfo toplevelClassCoverageInfo = toplevelClassCoverage.get(sourceToplevelFQName); if (toplevelClassCoverageInfo == null) { toplevelClassCoverageInfo = new ClassCoverageInfo(); toplevelClassCoverage.put(sourceToplevelFQName, toplevelClassCoverageInfo); } else { toplevelClassCoverageInfo.totalClassCount++; } return toplevelClassCoverageInfo; } private static String getSourceToplevelFQName(String classFQVMName) { final int index = classFQVMName.indexOf('$'); if (index > 0) classFQVMName = classFQVMName.substring(0, index); if (classFQVMName.startsWith("/")) classFQVMName = classFQVMName.substring(1); return classFQVMName.replaceAll("/", "."); } /** * Return true if there is executable code in the class */ private boolean collectNonCoveredClassInfo(final File classFile, @Nullable PsiClass psiClass, final ClassCoverageInfo classCoverageInfo, final PackageCoverageInfo packageCoverageInfo) { final byte[] content = myCoverageManager.doInReadActionIfProjectOpen(new Computable<byte[]>() { public byte[] compute() { try { return FileUtil.loadFileBytes(classFile); } catch (IOException e) { return null; } } }); final CoverageSuitesBundle coverageSuite = CoverageDataManager.getInstance(myProject).getCurrentSuitesBundle(); if (coverageSuite == null) return false; return SourceLineCounterUtil .collectNonCoveredClassInfo(classCoverageInfo, packageCoverageInfo, content, coverageSuite.isTracingEnabled(), psiClass); } }
plugins/coverage/src/com/intellij/coverage/PackageAnnotator.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.coverage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.rt.coverage.data.ClassData; import com.intellij.rt.coverage.data.LineCoverage; import com.intellij.rt.coverage.data.LineData; import com.intellij.rt.coverage.data.ProjectData; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; import org.jetbrains.jps.model.java.JavaSourceRootType; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; /** * @author ven */ public class PackageAnnotator { private static final Logger LOG = Logger.getInstance("#" + PackageAnnotator.class.getName()); private static final String DEFAULT_CONSTRUCTOR_NAME_SIGNATURE = "<init>()V"; private final PsiPackage myPackage; private final Project myProject; private final PsiManager myManager; private final CoverageDataManager myCoverageManager; public PackageAnnotator(final PsiPackage aPackage) { myPackage = aPackage; myProject = myPackage.getProject(); myManager = PsiManager.getInstance(myProject); myCoverageManager = CoverageDataManager.getInstance(myProject); } public interface Annotator { void annotateSourceDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotateTestDirectory(VirtualFile virtualFile, PackageCoverageInfo packageCoverageInfo, Module module); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo); void annotatePackage(String packageQualifiedName, PackageCoverageInfo packageCoverageInfo, boolean flatten); void annotateClass(String classQualifiedName, ClassCoverageInfo classCoverageInfo); } public static abstract class SummaryCoverageInfo { public int totalClassCount; public int coveredClassCount; public int totalMethodCount; public int coveredMethodCount; public int totalLineCount; public abstract int getCoveredLineCount(); } public static class ClassCoverageInfo extends SummaryCoverageInfo { public int fullyCoveredLineCount; public int partiallyCoveredLineCount; public ClassCoverageInfo() { totalClassCount = 1; } @Override public int getCoveredLineCount() { return fullyCoveredLineCount + partiallyCoveredLineCount; } } public static class PackageCoverageInfo extends SummaryCoverageInfo { public int coveredLineCount; @Override public int getCoveredLineCount() { return coveredLineCount; } public void append(SummaryCoverageInfo info) { totalClassCount += info.totalClassCount; totalLineCount += info.totalLineCount; coveredClassCount += info.coveredClassCount; coveredLineCount += info.getCoveredLineCount(); coveredMethodCount += info.coveredMethodCount; totalMethodCount += info.totalMethodCount; } } public static class DirCoverageInfo extends PackageCoverageInfo { public VirtualFile sourceRoot; public DirCoverageInfo(VirtualFile sourceRoot) { this.sourceRoot = sourceRoot; } } //get read lock myself when needed public void annotate(final CoverageSuitesBundle suite, Annotator annotator) { final ProjectData data = suite.getCoverageData(); if (data == null) return; final String qualifiedName = myPackage.getQualifiedName(); boolean filtered = false; for (CoverageSuite coverageSuite : suite.getSuites()) { if (((JavaCoverageSuite)coverageSuite).isPackageFiltered(qualifiedName)) { filtered = true; break; } } if (!filtered) return; final GlobalSearchScope scope = suite.getSearchScope(myProject); final Module[] modules = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Module[]>() { public Module[] compute() { return ModuleManager.getInstance(myProject).getModules(); } }); if (modules == null) return; Map<String, PackageCoverageInfo> packageCoverageMap = new HashMap<String, PackageCoverageInfo>(); Map<String, PackageCoverageInfo> flattenPackageCoverageMap = new HashMap<String, PackageCoverageInfo>(); for (final Module module : modules) { if (!scope.isSearchInModuleContent(module)) continue; final String rootPackageVMName = qualifiedName.replaceAll("\\.", "/"); final VirtualFile output = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { return CompilerModuleExtension.getInstance(module).getCompilerOutputPath(); } }); if (output != null) { File outputRoot = findRelativeFile(rootPackageVMName, output); if (outputRoot.exists()) { collectCoverageInformation(outputRoot, packageCoverageMap, flattenPackageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), false); } } if (suite.isTrackTestFolders()) { final VirtualFile testPackageRoot = myCoverageManager.doInReadActionIfProjectOpen(new Computable<VirtualFile>() { @Nullable public VirtualFile compute() { return CompilerModuleExtension.getInstance(module).getCompilerOutputPathForTests(); } }); if (testPackageRoot != null) { final File outputRoot = findRelativeFile(rootPackageVMName, testPackageRoot); if (outputRoot.exists()) { collectCoverageInformation(outputRoot, packageCoverageMap, flattenPackageCoverageMap, data, rootPackageVMName, annotator, module, suite.isTrackTestFolders(), true); } } } } for (Map.Entry<String, PackageCoverageInfo> entry : packageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info); } for (Map.Entry<String, PackageCoverageInfo> entry : flattenPackageCoverageMap.entrySet()) { final String packageFQName = entry.getKey().replaceAll("/", "."); final PackageCoverageInfo info = entry.getValue(); annotator.annotatePackage(packageFQName, info, true); } } private static File findRelativeFile(String rootPackageVMName, VirtualFile output) { File outputRoot = VfsUtilCore.virtualToIoFile(output); outputRoot = rootPackageVMName.length() > 0 ? new File(outputRoot, FileUtil.toSystemDependentName(rootPackageVMName)) : outputRoot; return outputRoot; } public void annotateFilteredClass(PsiClass psiClass, CoverageSuitesBundle bundle, Annotator annotator) { final ProjectData data = bundle.getCoverageData(); if (data == null) return; final Module module = ModuleUtil.findModuleForPsiElement(psiClass); if (module != null) { final boolean isInTests = ProjectRootManager.getInstance(module.getProject()).getFileIndex() .isInTestSourceContent(psiClass.getContainingFile().getVirtualFile()); final CompilerModuleExtension moduleExtension = CompilerModuleExtension.getInstance(module); final VirtualFile outputPath = isInTests ? moduleExtension.getCompilerOutputPathForTests() : moduleExtension.getCompilerOutputPath(); if (outputPath != null) { final String qualifiedName = psiClass.getQualifiedName(); if (qualifiedName == null) return; final String packageVMName = StringUtil.getPackageName(qualifiedName).replace('.', '/'); final File packageRoot = findRelativeFile(packageVMName, outputPath); if (packageRoot != null && packageRoot.exists()) { Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); final File[] files = packageRoot.listFiles(); if (files != null) { for (File child : files) { if (isClassFile(child)) { final String childName = getClassName(child); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); if (toplevelClassSrcFQName.equals(qualifiedName)) { collectClassCoverageInformation(child, psiClass, new PackageCoverageInfo(), data, toplevelClassCoverage, classFqVMName.replace("/", "."), toplevelClassSrcFQName); } } } } for (ClassCoverageInfo coverageInfo : toplevelClassCoverage.values()) { annotator.annotateClass(qualifiedName, coverageInfo); } } } } } @Nullable private DirCoverageInfo[] collectCoverageInformation(final File packageOutputRoot, final Map<String, PackageCoverageInfo> packageCoverageMap, Map<String, PackageCoverageInfo> flattenPackageCoverageMap, final ProjectData projectInfo, final String packageVMName, final Annotator annotator, final Module module, final boolean trackTestFolders, final boolean isTestHierarchy) { final List<DirCoverageInfo> dirs = new ArrayList<DirCoverageInfo>(); final ContentEntry[] contentEntries = ModuleRootManager.getInstance(module).getContentEntries(); for (ContentEntry contentEntry : contentEntries) { for (SourceFolder folder : contentEntry.getSourceFolders(isTestHierarchy ? JavaSourceRootType.TEST_SOURCE : JavaSourceRootType.SOURCE)) { final VirtualFile file = folder.getFile(); if (file == null) continue; final String prefix = folder.getPackagePrefix().replaceAll("\\.", "/"); final VirtualFile relativeSrcRoot = file.findFileByRelativePath(StringUtil.trimStart(packageVMName, prefix)); dirs.add(new DirCoverageInfo(relativeSrcRoot)); } } final PackageCoverageInfo classWithoutSourceCoverageInfo = new PackageCoverageInfo(); final File[] children = packageOutputRoot.listFiles(); if (children == null) return null; Map<String, ClassCoverageInfo> toplevelClassCoverage = new HashMap<String, ClassCoverageInfo>(); for (File child : children) { if (child.isDirectory()) { final String childName = child.getName(); final String childPackageVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final DirCoverageInfo[] childCoverageInfo = collectCoverageInformation(child, packageCoverageMap, flattenPackageCoverageMap, projectInfo, childPackageVMName, annotator, module, trackTestFolders, isTestHierarchy); if (childCoverageInfo != null) { for (int i = 0; i < childCoverageInfo.length; i++) { DirCoverageInfo coverageInfo = childCoverageInfo[i]; final DirCoverageInfo parentDir = dirs.get(i); parentDir.totalClassCount += coverageInfo.totalClassCount; parentDir.coveredClassCount += coverageInfo.coveredClassCount; parentDir.totalLineCount += coverageInfo.totalLineCount; parentDir.coveredLineCount += coverageInfo.coveredLineCount; parentDir.totalMethodCount += coverageInfo.totalMethodCount; parentDir.coveredMethodCount += coverageInfo.coveredMethodCount; } } } else { if (isClassFile(child)) { final String childName = getClassName(child); final String classFqVMName = packageVMName.length() > 0 ? packageVMName + "/" + childName : childName; final String toplevelClassSrcFQName = getSourceToplevelFQName(classFqVMName); final Ref<VirtualFile> containingFileRef = new Ref<VirtualFile>(); final Ref<PsiClass> psiClassRef = new Ref<PsiClass>(); final Boolean isInSource = myCoverageManager.doInReadActionIfProjectOpen(new Computable<Boolean>() { public Boolean compute() { final PsiClass aClass = JavaPsiFacade.getInstance(myManager.getProject()).findClass(toplevelClassSrcFQName, GlobalSearchScope.moduleScope(module)); if (aClass == null || !aClass.isValid()) return Boolean.FALSE; psiClassRef.set(aClass); containingFileRef.set(aClass.getNavigationElement().getContainingFile().getVirtualFile()); if (containingFileRef.isNull()) { LOG.info("No virtual file found for: " + aClass); return null; } final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex(); return fileIndex.isUnderSourceRootOfType(containingFileRef.get(), JavaModuleSourceRootTypes.SOURCES) && (trackTestFolders || !fileIndex.isInTestSourceContent(containingFileRef.get())); } }); PackageCoverageInfo coverageInfoForClass = null; String classCoverageKey = classFqVMName.replace('/', '.'); boolean ignoreClass = false; for (JavaCoverageEngineExtension extension : JavaCoverageEngineExtension.EP_NAME.getExtensions()) { if (extension.ignoreCoverageForClass(myCoverageManager.getCurrentSuitesBundle(), child)) { ignoreClass = true; break; } if (extension.keepCoverageInfoForClassWithoutSource(myCoverageManager.getCurrentSuitesBundle(), child)) { coverageInfoForClass = classWithoutSourceCoverageInfo; break; } } if (ignoreClass) { continue; } if (coverageInfoForClass == null && isInSource != null && isInSource.booleanValue()) { for (DirCoverageInfo dirCoverageInfo : dirs) { if (dirCoverageInfo.sourceRoot != null && VfsUtil.isAncestor(dirCoverageInfo.sourceRoot, containingFileRef.get(), false)) { coverageInfoForClass = dirCoverageInfo; classCoverageKey = toplevelClassSrcFQName; break; } } } if (coverageInfoForClass != null) { collectClassCoverageInformation(child, psiClassRef.get(), coverageInfoForClass, projectInfo, toplevelClassCoverage, classFqVMName.replace("/", "."), classCoverageKey); } } } } for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final String toplevelClassName = entry.getKey(); final ClassCoverageInfo coverageInfo = entry.getValue(); annotator.annotateClass(toplevelClassName, coverageInfo); } PackageCoverageInfo flattenPackageCoverageInfo = getOrCreateCoverageInfo(flattenPackageCoverageMap, packageVMName); for (Map.Entry<String, ClassCoverageInfo> entry : toplevelClassCoverage.entrySet()) { final ClassCoverageInfo coverageInfo = entry.getValue(); flattenPackageCoverageInfo.append(coverageInfo); } PackageCoverageInfo packageCoverageInfo = getOrCreateCoverageInfo(packageCoverageMap, packageVMName); for (DirCoverageInfo dir : dirs) { packageCoverageInfo.append(dir); if (isTestHierarchy) { annotator.annotateTestDirectory(dir.sourceRoot, dir, module); } else { annotator.annotateSourceDirectory(dir.sourceRoot, dir, module); } } packageCoverageInfo.append(classWithoutSourceCoverageInfo); return dirs.toArray(new DirCoverageInfo[dirs.size()]); } private static boolean isClassFile(File classFile) { return classFile.getName().endsWith(".class"); } private static String getClassName(File classFile) { return StringUtil.trimEnd(classFile.getName(), ".class"); } private static PackageCoverageInfo getOrCreateCoverageInfo(final Map<String, PackageCoverageInfo> packageCoverageMap, final String packageVMName) { PackageCoverageInfo coverageInfo = packageCoverageMap.get(packageVMName); if (coverageInfo == null) { coverageInfo = new PackageCoverageInfo(); packageCoverageMap.put(packageVMName, coverageInfo); } return coverageInfo; } private void collectClassCoverageInformation(final File classFile, @Nullable final PsiClass psiClass, final PackageCoverageInfo packageCoverageInfo, final ProjectData projectInfo, final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String className, final String toplevelClassSrcFQName) { final ClassCoverageInfo toplevelClassCoverageInfo = new ClassCoverageInfo(); final ClassData classData = projectInfo.getClassData(className); if (classData != null && classData.getLines() != null) { final Object[] lines = classData.getLines(); for (Object l : lines) { if (l instanceof LineData) { final LineData lineData = (LineData)l; if (lineData.getStatus() == LineCoverage.FULL) { toplevelClassCoverageInfo.fullyCoveredLineCount++; } else if (lineData.getStatus() == LineCoverage.PARTIAL) { toplevelClassCoverageInfo.partiallyCoveredLineCount++; } toplevelClassCoverageInfo.totalLineCount++; packageCoverageInfo.totalLineCount++; } } boolean touchedClass = false; final Collection methodSigs = classData.getMethodSigs(); for (final Object nameAndSig : methodSigs) { if (isGeneratedDefaultConstructor(psiClass, (String)nameAndSig)) { continue; } final int covered = classData.getStatus((String)nameAndSig); if (covered != LineCoverage.NONE) { toplevelClassCoverageInfo.coveredMethodCount++; touchedClass = true; } toplevelClassCoverageInfo.totalMethodCount++; } if (!methodSigs.isEmpty()) { if (touchedClass) { packageCoverageInfo.coveredClassCount++; } packageCoverageInfo.totalClassCount++; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; packageCoverageInfo.coveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; packageCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; packageCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; } else { LOG.debug("Did not find any method signatures in " + classFile.getName()); return; } } else { if (!collectNonCoveredClassInfo(classFile, psiClass, toplevelClassCoverageInfo, packageCoverageInfo)) { LOG.debug("Did not collect non-covered class info for " + classFile.getName()); return; } } ClassCoverageInfo classCoverageInfo = getOrCreateClassCoverageInfo(toplevelClassCoverage, toplevelClassSrcFQName); LOG.debug("Adding coverage of " + classFile.getName() + " to top-level class " + toplevelClassSrcFQName); classCoverageInfo.totalLineCount += toplevelClassCoverageInfo.totalLineCount; classCoverageInfo.fullyCoveredLineCount += toplevelClassCoverageInfo.fullyCoveredLineCount; classCoverageInfo.partiallyCoveredLineCount += toplevelClassCoverageInfo.partiallyCoveredLineCount; classCoverageInfo.totalMethodCount += toplevelClassCoverageInfo.totalMethodCount; classCoverageInfo.coveredMethodCount += toplevelClassCoverageInfo.coveredMethodCount; if (toplevelClassCoverageInfo.coveredMethodCount > 0) { classCoverageInfo.coveredClassCount++; } } /** * Checks if the method is a default constructor generated by the compiler. Such constructors are not marked as synthetic * in the bytecode, so we need to look at the PSI to see if the class defines such a constructor. */ public static boolean isGeneratedDefaultConstructor(@Nullable final PsiClass aClass, String nameAndSig) { if (DEFAULT_CONSTRUCTOR_NAME_SIGNATURE.equals(nameAndSig)) { return hasGeneratedConstructor(aClass); } return false; } private static boolean hasGeneratedConstructor(@Nullable final PsiClass aClass) { if (aClass == null) { return false; } return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() { public Boolean compute() { return aClass.getConstructors().length == 0; } }); } private static ClassCoverageInfo getOrCreateClassCoverageInfo(final Map<String, ClassCoverageInfo> toplevelClassCoverage, final String sourceToplevelFQName) { ClassCoverageInfo toplevelClassCoverageInfo = toplevelClassCoverage.get(sourceToplevelFQName); if (toplevelClassCoverageInfo == null) { toplevelClassCoverageInfo = new ClassCoverageInfo(); toplevelClassCoverage.put(sourceToplevelFQName, toplevelClassCoverageInfo); } else { toplevelClassCoverageInfo.totalClassCount++; } return toplevelClassCoverageInfo; } private static String getSourceToplevelFQName(String classFQVMName) { final int index = classFQVMName.indexOf('$'); if (index > 0) classFQVMName = classFQVMName.substring(0, index); if (classFQVMName.startsWith("/")) classFQVMName = classFQVMName.substring(1); return classFQVMName.replaceAll("/", "."); } /** * Return true if there is executable code in the class */ private boolean collectNonCoveredClassInfo(final File classFile, @Nullable PsiClass psiClass, final ClassCoverageInfo classCoverageInfo, final PackageCoverageInfo packageCoverageInfo) { final byte[] content = myCoverageManager.doInReadActionIfProjectOpen(new Computable<byte[]>() { public byte[] compute() { try { return FileUtil.loadFileBytes(classFile); } catch (IOException e) { return null; } } }); final CoverageSuitesBundle coverageSuite = CoverageDataManager.getInstance(myProject).getCurrentSuitesBundle(); if (coverageSuite == null) return false; return SourceLineCounterUtil .collectNonCoveredClassInfo(classCoverageInfo, packageCoverageInfo, content, coverageSuite.isTracingEnabled(), psiClass); } }
run coverage findClass in smart mode (EA-66153 - INRE)
plugins/coverage/src/com/intellij/coverage/PackageAnnotator.java
run coverage findClass in smart mode (EA-66153 - INRE)
Java
apache-2.0
120191aaa133317548e4bc1f4efbcc39c94c007c
0
ThiagoGarciaAlves/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,FHannes/intellij-community,apixandru/intellij-community,fitermay/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,semonte/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,fitermay/intellij-community,xfournet/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,fitermay/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,signed/intellij-community,da1z/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,xfournet/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,semonte/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,xfournet/intellij-community,asedunov/intellij-community,semonte/intellij-community,hurricup/intellij-community,apixandru/intellij-community,da1z/intellij-community,allotria/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,signed/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,youdonghai/intellij-community,signed/intellij-community,allotria/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,apixandru/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,allotria/intellij-community,asedunov/intellij-community,da1z/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,xfournet/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,semonte/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,FHannes/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,hurricup/intellij-community,allotria/intellij-community,FHannes/intellij-community,da1z/intellij-community,vvv1559/intellij-community,apixandru/intellij-community
package com.jetbrains.edu.learning.stepic; import com.intellij.ide.AppLifecycleListener; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Alarm; import com.intellij.util.text.DateFormatUtil; import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; import org.jetbrains.annotations.NotNull; import java.util.List; public class EduStepicUpdater { private static final long CHECK_INTERVAL = DateFormatUtil.DAY; private final Runnable myCheckRunnable = () -> updateCourseList().doWhenDone(() -> queueNextCheck(CHECK_INTERVAL)); private final Alarm myCheckForUpdatesAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); public EduStepicUpdater(@NotNull Application application) { scheduleCourseListUpdate(application); } public void scheduleCourseListUpdate(Application application) { if (!checkNeeded()) { return; } application.getMessageBus().connect(application).subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() { @Override public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) { long timeToNextCheck = StepicUpdateSettings.getInstance().getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis(); if (timeToNextCheck <= 0) { myCheckRunnable.run(); } else { queueNextCheck(timeToNextCheck); } } }); } private static ActionCallback updateCourseList() { ActionCallback callback = new ActionCallback(); ApplicationManager.getApplication().executeOnPooledThread(() -> { final List<CourseInfo> courses = EduStepicConnector.getCourses(); final List<CourseInfo> cachedCourses = StudyProjectGenerator.getCoursesFromCache(); StudyProjectGenerator.flushCache(courses); StepicUpdateSettings.getInstance().setLastTimeChecked(System.currentTimeMillis()); courses.removeAll(cachedCourses); if (!courses.isEmpty() && !cachedCourses.isEmpty()) { final String message; final String title; if (courses.size() == 1) { message = courses.get(0).getName(); title = "New course available"; } else { title = "New courses available"; message = StringUtil.join(courses, CourseInfo::getName, ", "); } final Notification notification = new Notification("New.course", title, message, NotificationType.INFORMATION); notification.notify(null); } }); return callback; } private void queueNextCheck(long interval) { myCheckForUpdatesAlarm.addRequest(myCheckRunnable, interval); } private static boolean checkNeeded() { final List<CourseInfo> courses = StudyProjectGenerator.getCoursesFromCache(); long timeToNextCheck = StepicUpdateSettings.getInstance().getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis(); return courses.isEmpty() || timeToNextCheck <= 0; } }
python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicUpdater.java
package com.jetbrains.edu.learning.stepic; import com.intellij.ide.AppLifecycleListener; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Alarm; import com.intellij.util.text.DateFormatUtil; import com.jetbrains.edu.learning.courseGeneration.StudyProjectGenerator; import org.jetbrains.annotations.NotNull; import java.util.List; public class EduStepicUpdater { private static final long CHECK_INTERVAL = DateFormatUtil.DAY; private final Runnable myCheckRunnable = () -> updateCourseList().doWhenDone(() -> queueNextCheck(CHECK_INTERVAL)); private final Alarm myCheckForUpdatesAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); public EduStepicUpdater(@NotNull Application application) { scheduleCourseListUpdate(application); } public void scheduleCourseListUpdate(Application application) { if (!checkNeeded()) { return; } application.getMessageBus().connect(application).subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener.Adapter() { @Override public void appFrameCreated(String[] commandLineArgs, @NotNull Ref<Boolean> willOpenProject) { long timeToNextCheck = StepicUpdateSettings.getInstance().getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis(); if (timeToNextCheck <= 0) { myCheckRunnable.run(); } else { queueNextCheck(timeToNextCheck); } } }); } private static ActionCallback updateCourseList() { ActionCallback callback = new ActionCallback(); ApplicationManager.getApplication().executeOnPooledThread(() -> { final List<CourseInfo> courses = EduStepicConnector.getCourses(); final List<CourseInfo> cachedCourses = StudyProjectGenerator.getCoursesFromCache(); StudyProjectGenerator.flushCache(courses); StepicUpdateSettings.getInstance().setLastTimeChecked(System.currentTimeMillis()); courses.removeAll(cachedCourses); if (!courses.isEmpty()) { final String message; final String title; if (courses.size() == 1) { message = courses.get(0).getName(); title = "New course available"; } else { title = "New courses available"; message = StringUtil.join(courses, CourseInfo::getName, ", "); } final Notification notification = new Notification("New.course", title, message, NotificationType.INFORMATION); notification.notify(null); } }); return callback; } private void queueNextCheck(long interval) { myCheckForUpdatesAlarm.addRequest(myCheckRunnable, interval); } private static boolean checkNeeded() { final List<CourseInfo> courses = StudyProjectGenerator.getCoursesFromCache(); long timeToNextCheck = StepicUpdateSettings.getInstance().getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis(); return courses.isEmpty() || timeToNextCheck <= 0; } }
remove notification about courses on application setup
python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicUpdater.java
remove notification about courses on application setup
Java
apache-2.0
7219072c8e8efbc34507fbb63ef12f21f97a2c51
0
caot/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,supersven/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,slisson/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,ryano144/intellij-community,caot/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,samthor/intellij-community,ibinti/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,xfournet/intellij-community,signed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,ibinti/intellij-community,adedayo/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,hurricup/intellij-community,apixandru/intellij-community,FHannes/intellij-community,xfournet/intellij-community,signed/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,petteyg/intellij-community,clumsy/intellij-community,xfournet/intellij-community,izonder/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,samthor/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,signed/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,caot/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,da1z/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fitermay/intellij-community,kdwink/intellij-community,hurricup/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,signed/intellij-community,FHannes/intellij-community,supersven/intellij-community,ibinti/intellij-community,apixandru/intellij-community,fnouama/intellij-community,apixandru/intellij-community,supersven/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,allotria/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,slisson/intellij-community,blademainer/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,allotria/intellij-community,holmes/intellij-community,fnouama/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,caot/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,allotria/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,caot/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,fnouama/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kool79/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,signed/intellij-community,izonder/intellij-community,allotria/intellij-community,vladmm/intellij-community,hurricup/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,clumsy/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,asedunov/intellij-community,blademainer/intellij-community,da1z/intellij-community,petteyg/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,kool79/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,caot/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,da1z/intellij-community,samthor/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,signed/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ryano144/intellij-community,xfournet/intellij-community,adedayo/intellij-community,signed/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,caot/intellij-community,da1z/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,asedunov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,caot/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ibinti/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,signed/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,allotria/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,slisson/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,signed/intellij-community,dslomov/intellij-community,xfournet/intellij-community,allotria/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,semonte/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,kool79/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ibinti/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,semonte/intellij-community,semonte/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,allotria/intellij-community,retomerz/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,da1z/intellij-community,amith01994/intellij-community,kdwink/intellij-community,semonte/intellij-community,samthor/intellij-community,gnuhub/intellij-community,allotria/intellij-community,da1z/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,vladmm/intellij-community,caot/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,apixandru/intellij-community,supersven/intellij-community,asedunov/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,izonder/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,da1z/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,caot/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,kdwink/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,da1z/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,semonte/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,amith01994/intellij-community,adedayo/intellij-community,robovm/robovm-studio,supersven/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,holmes/intellij-community,adedayo/intellij-community,allotria/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,caot/intellij-community,supersven/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,semonte/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,signed/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,adedayo/intellij-community,hurricup/intellij-community,slisson/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,samthor/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,adedayo/intellij-community,blademainer/intellij-community,ryano144/intellij-community,dslomov/intellij-community,apixandru/intellij-community,signed/intellij-community,Lekanich/intellij-community,supersven/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,holmes/intellij-community,caot/intellij-community,slisson/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,kool79/intellij-community,izonder/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,hurricup/intellij-community,kdwink/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,apixandru/intellij-community,kool79/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,izonder/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,jagguli/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,FHannes/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,signed/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,samthor/intellij-community,petteyg/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,diorcety/intellij-community,holmes/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,robovm/robovm-studio,slisson/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,signed/intellij-community,slisson/intellij-community,vladmm/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.actions; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.TestFrameworkRunningModel; import com.intellij.execution.testframework.TestTreeView; import com.intellij.execution.testframework.TestTreeViewAction; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NonNls; import java.awt.*; import java.util.ArrayList; import java.util.List; public class ViewAssertEqualsDiffAction extends AnAction implements TestTreeViewAction { @NonNls public static final String ACTION_ID = "openAssertEqualsDiff"; public void actionPerformed(final AnActionEvent e) { if (!openDiff(e.getDataContext())) { final Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT); Messages.showInfoMessage(component, "Comparison error was not found", "No Comparison Data Found"); } } public static boolean openDiff(DataContext context) { final AbstractTestProxy testProxy = AbstractTestProxy.DATA_KEY.getData(context); if (testProxy != null) { final AbstractTestProxy.AssertEqualsDiffViewerProvider diffViewerProvider = testProxy.getDiffViewerProvider(); if (diffViewerProvider != null) { final Project project = CommonDataKeys.PROJECT.getData(context); if (diffViewerProvider instanceof AbstractTestProxy.AssertEqualsMultiDiffViewProvider) { final TestFrameworkRunningModel runningModel = TestTreeView.MODEL_DATA_KEY.getData(context); final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers = collectAvailableProviders(runningModel); final MyAssertEqualsDiffChain diffChain = providers.size() > 1 ? new MyAssertEqualsDiffChain(providers, (AbstractTestProxy.AssertEqualsMultiDiffViewProvider)diffViewerProvider) : null; ((AbstractTestProxy.AssertEqualsMultiDiffViewProvider)diffViewerProvider).openMultiDiff(project, diffChain); } else { diffViewerProvider.openDiff(project); } return true; } } return false; } private static List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> collectAvailableProviders(TestFrameworkRunningModel model) { final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers = new ArrayList<AbstractTestProxy.AssertEqualsMultiDiffViewProvider>(); if (model != null) { final AbstractTestProxy root = model.getRoot(); final List<? extends AbstractTestProxy> allTests = root.getAllTests(); for (AbstractTestProxy test : allTests) { if (test.isLeaf()) { final AbstractTestProxy.AssertEqualsDiffViewerProvider provider = test.getDiffViewerProvider(); if (provider instanceof AbstractTestProxy.AssertEqualsMultiDiffViewProvider) { providers.add((AbstractTestProxy.AssertEqualsMultiDiffViewProvider)provider); } } } } return providers; } public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); final boolean enabled; final DataContext dataContext = e.getDataContext(); if (CommonDataKeys.PROJECT.getData(dataContext) == null) { enabled = false; } else { final AbstractTestProxy test = AbstractTestProxy.DATA_KEY.getData(dataContext); if (test != null) { if (test.isLeaf()) { enabled = test.getDiffViewerProvider() != null; } else if (test.isDefect()) { enabled = true; } else { enabled = false; } } else { enabled = false; } } presentation.setEnabled(enabled); presentation.setVisible(enabled); } private static class MyAssertEqualsDiffChain implements AbstractTestProxy.AssertEqualsDiffChain { private final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> myProviders; private AbstractTestProxy.AssertEqualsMultiDiffViewProvider myProvider; public MyAssertEqualsDiffChain(List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers, AbstractTestProxy.AssertEqualsMultiDiffViewProvider provider) { myProviders = providers; myProvider = provider; } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getPrevious() { final int prevIdx = (myProviders.size() + myProviders.indexOf(myProvider) - 1) % myProviders.size(); return myProviders.get(prevIdx); } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getCurrent() { return myProvider; } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getNext() { final int nextIdx = (myProviders.indexOf(myProvider) + 1) % myProviders.size(); return myProviders.get(nextIdx); } @Override public void setCurrent(AbstractTestProxy.AssertEqualsMultiDiffViewProvider provider) { myProvider = provider; } } }
platform/testRunner/src/com/intellij/execution/testframework/actions/ViewAssertEqualsDiffAction.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.testframework.actions; import com.intellij.execution.testframework.AbstractTestProxy; import com.intellij.execution.testframework.TestFrameworkRunningModel; import com.intellij.execution.testframework.TestTreeView; import com.intellij.execution.testframework.TestTreeViewAction; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NonNls; import java.awt.*; import java.util.ArrayList; import java.util.List; public class ViewAssertEqualsDiffAction extends AnAction implements TestTreeViewAction { @NonNls public static final String ACTION_ID = "openAssertEqualsDiff"; public void actionPerformed(final AnActionEvent e) { if (!openDiff(e.getDataContext())) { final Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT); Messages.showInfoMessage(component, "Comparison error was not found", "No Comparison Data Found"); } } public static boolean openDiff(DataContext context) { final AbstractTestProxy testProxy = AbstractTestProxy.DATA_KEY.getData(context); if (testProxy != null) { final AbstractTestProxy.AssertEqualsDiffViewerProvider diffViewerProvider = testProxy.getDiffViewerProvider(); if (diffViewerProvider != null) { final Project project = CommonDataKeys.PROJECT.getData(context); if (diffViewerProvider instanceof AbstractTestProxy.AssertEqualsMultiDiffViewProvider) { final TestFrameworkRunningModel runningModel = TestTreeView.MODEL_DATA_KEY.getData(context); final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers = collectAvailableProviders(runningModel); final MyAssertEqualsDiffChain diffChain = providers.size() > 1 ? new MyAssertEqualsDiffChain(providers, (AbstractTestProxy.AssertEqualsMultiDiffViewProvider)diffViewerProvider) : null; ((AbstractTestProxy.AssertEqualsMultiDiffViewProvider)diffViewerProvider).openMultiDiff(project, diffChain); } else { diffViewerProvider.openDiff(project); } return true; } } return false; } private static List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> collectAvailableProviders(TestFrameworkRunningModel model) { final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers = new ArrayList<AbstractTestProxy.AssertEqualsMultiDiffViewProvider>(); if (model != null) { final AbstractTestProxy root = model.getRoot(); final List<? extends AbstractTestProxy> allTests = root.getAllTests(); for (AbstractTestProxy test : allTests) { final AbstractTestProxy.AssertEqualsDiffViewerProvider provider = test.getDiffViewerProvider(); if (provider instanceof AbstractTestProxy.AssertEqualsMultiDiffViewProvider) { providers.add((AbstractTestProxy.AssertEqualsMultiDiffViewProvider)provider); } } } return providers; } public void update(final AnActionEvent e) { final Presentation presentation = e.getPresentation(); final boolean enabled; final DataContext dataContext = e.getDataContext(); if (CommonDataKeys.PROJECT.getData(dataContext) == null) { enabled = false; } else { final AbstractTestProxy test = AbstractTestProxy.DATA_KEY.getData(dataContext); if (test != null) { if (test.isLeaf()) { enabled = test.getDiffViewerProvider() != null; } else if (test.isDefect()) { enabled = true; } else { enabled = false; } } else { enabled = false; } } presentation.setEnabled(enabled); presentation.setVisible(enabled); } private static class MyAssertEqualsDiffChain implements AbstractTestProxy.AssertEqualsDiffChain { private final List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> myProviders; private AbstractTestProxy.AssertEqualsMultiDiffViewProvider myProvider; public MyAssertEqualsDiffChain(List<AbstractTestProxy.AssertEqualsMultiDiffViewProvider> providers, AbstractTestProxy.AssertEqualsMultiDiffViewProvider provider) { myProviders = providers; myProvider = provider; } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getPrevious() { final int prevIdx = (myProviders.size() + myProviders.indexOf(myProvider) - 1) % myProviders.size(); return myProviders.get(prevIdx); } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getCurrent() { return myProvider; } @Override public AbstractTestProxy.AssertEqualsMultiDiffViewProvider getNext() { final int nextIdx = (myProviders.indexOf(myProvider) + 1) % myProviders.size(); return myProviders.get(nextIdx); } @Override public void setCurrent(AbstractTestProxy.AssertEqualsMultiDiffViewProvider provider) { myProvider = provider; } } }
tests diff: ensure that only providers from leafs are collected, so the same provider appears only one in view
platform/testRunner/src/com/intellij/execution/testframework/actions/ViewAssertEqualsDiffAction.java
tests diff: ensure that only providers from leafs are collected, so the same provider appears only one in view
Java
apache-2.0
8f66939714ed8e73aed50720118415d2f265da25
0
vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,Martinfx/yodaqa,Martinfx/yodaqa,Martinfx/yodaqa,Martinfx/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa,vineetk1/yodaqa
package cz.brmlab.yodaqa; import cz.brmlab.yodaqa.analysis.question.QuestionAnalysisAE; import cz.brmlab.yodaqa.flow.MultiCASPipeline; import cz.brmlab.yodaqa.flow.asb.ParallelEngineFactory; import cz.brmlab.yodaqa.io.collection.JSONQuestionReader; import cz.brmlab.yodaqa.io.collection.TSVQuestionReader; import cz.brmlab.yodaqa.io.debug.QuestionPrinter; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.collection.CollectionReaderDescription; import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription; import static org.apache.uima.fit.factory.CollectionReaderFactory.createReaderDescription; /** * Simplified pipeline to print QuestionAnalysis results */ public class QuestionDump { public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: QuestionDump INPUT.TSV OUTPUT.json"); System.err.println("Outputs the result of QuestionAnalysis"); System.exit(1); } /* CollectionReaderDescription reader = createReaderDescription( TSVQuestionReader.class, TSVQuestionReader.PARAM_TSVFILE, args[0], TSVQuestionReader.PARAM_LANGUAGE, "en"); */ CollectionReaderDescription reader = createReaderDescription( JSONQuestionReader.class, JSONQuestionReader.PARAM_JSONFILE, args[0], JSONQuestionReader.PARAM_LANGUAGE, "en"); AnalysisEngineDescription pipeline = QuestionAnalysisAE.createEngineDescription(); AnalysisEngineDescription printer = createEngineDescription( QuestionPrinter.class, QuestionPrinter.PARAM_JSONFILE, args[1], ParallelEngineFactory.PARAM_NO_MULTIPROCESSING, 1); // ParallelEngineFactory.registerFactory(); // comment out for a linear single-thread flow /* XXX: Later, we will want to create an actual flow * to support scaleout. */ MultiCASPipeline.runPipeline(reader, pipeline, printer); } }
src/main/java/cz/brmlab/yodaqa/QuestionDump.java
package cz.brmlab.yodaqa; import cz.brmlab.yodaqa.analysis.question.QuestionAnalysisAE; import cz.brmlab.yodaqa.flow.MultiCASPipeline; import cz.brmlab.yodaqa.flow.asb.ParallelEngineFactory; import cz.brmlab.yodaqa.io.collection.TSVQuestionReader; import cz.brmlab.yodaqa.io.debug.QuestionPrinter; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.collection.CollectionReaderDescription; import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription; import static org.apache.uima.fit.factory.CollectionReaderFactory.createReaderDescription; /** * Simplified pipeline to print QuestionAnalysis results */ public class QuestionDump { public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: QuestionDump INPUT.TSV OUTPUT.json"); System.err.println("Outputs the result of QuestionAnalysis"); System.exit(1); } CollectionReaderDescription reader = createReaderDescription( TSVQuestionReader.class, TSVQuestionReader.PARAM_TSVFILE, args[0], TSVQuestionReader.PARAM_LANGUAGE, "en"); AnalysisEngineDescription pipeline = QuestionAnalysisAE.createEngineDescription(); AnalysisEngineDescription printer = createEngineDescription( QuestionPrinter.class, QuestionPrinter.PARAM_JSONFILE, args[1], ParallelEngineFactory.PARAM_NO_MULTIPROCESSING, 1); // ParallelEngineFactory.registerFactory(); // comment out for a linear single-thread flow /* XXX: Later, we will want to create an actual flow * to support scaleout. */ MultiCASPipeline.runPipeline(reader, pipeline, printer); } }
questiondump reads json instead of tsv
src/main/java/cz/brmlab/yodaqa/QuestionDump.java
questiondump reads json instead of tsv
Java
apache-2.0
3c9e508762e6e0d7de096e9b5dc15bdae4a3ea39
0
ananthc/apex-malhar,yogidevendra/apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,apache/incubator-apex-malhar,prasannapramod/apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,yogidevendra/incubator-apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,skekre98/apex-mlhr,apache/incubator-apex-malhar,trusli/apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,DataTorrent/Megh,PramodSSImmaneni/apex-malhar,yogidevendra/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,trusli/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,ilganeli/incubator-apex-malhar,ilganeli/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,siyuanh/incubator-apex-malhar,vrozov/incubator-apex-malhar,patilvikram/apex-malhar,tushargosavi/incubator-apex-malhar,tweise/incubator-apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,ilganeli/incubator-apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,siyuanh/apex-malhar,prasannapramod/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,prasannapramod/apex-malhar,apache/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,sandeep-n/incubator-apex-malhar,vrozov/apex-malhar,siyuanh/apex-malhar,trusli/apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,trusli/apex-malhar,skekre98/apex-mlhr,tweise/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chinmaykolhatkar/apex-malhar,ananthc/apex-malhar,chinmaykolhatkar/apex-malhar,siyuanh/incubator-apex-malhar,siyuanh/apex-malhar,trusli/apex-malhar,ananthc/apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,patilvikram/apex-malhar,patilvikram/apex-malhar,skekre98/apex-mlhr,ilganeli/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,chandnisingh/apex-malhar,tweise/apex-malhar,chinmaykolhatkar/apex-malhar,tushargosavi/incubator-apex-malhar,tweise/apex-malhar,apache/incubator-apex-malhar,tweise/apex-malhar,vrozov/apex-malhar,yogidevendra/apex-malhar,skekre98/apex-mlhr,siyuanh/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,tweise/incubator-apex-malhar,siyuanh/incubator-apex-malhar,vrozov/apex-malhar,davidyan74/apex-malhar,yogidevendra/apex-malhar,yogidevendra/apex-malhar,patilvikram/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,siyuanh/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,tweise/incubator-apex-malhar,davidyan74/apex-malhar,ananthc/apex-malhar,brightchen/apex-malhar,vrozov/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,tweise/incubator-apex-malhar,tweise/incubator-apex-malhar,siyuanh/apex-malhar,apache/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,vrozov/apex-malhar,vrozov/apex-malhar,brightchen/apex-malhar,patilvikram/apex-malhar,yogidevendra/incubator-apex-malhar,prasannapramod/apex-malhar,tushargosavi/incubator-apex-malhar,ilganeli/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,apache/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,ilganeli/incubator-apex-malhar,davidyan74/apex-malhar,trusli/apex-malhar,yogidevendra/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/incubator-apex-malhar,chandnisingh/apex-malhar,brightchen/apex-malhar,PramodSSImmaneni/apex-malhar,tweise/apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,DataTorrent/Megh,DataTorrent/incubator-apex-malhar,siyuanh/apex-malhar,brightchen/apex-malhar,prasannapramod/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,ilganeli/incubator-apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,tweise/incubator-apex-malhar,vrozov/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,davidyan74/apex-malhar,skekre98/apex-mlhr,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,yogidevendra/incubator-apex-malhar,chandnisingh/apex-malhar
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. * */ /** * <b>com.malhartech.lib.math</b> is a library of arithmetic modules for reuse<p> * <br> * <br>The modules are<br> * <b>{@link com.malhartech.lib.math.ArithmeticMargin}</b>: For every window computes margins of sums of values of a key in two streams<br> * <b>{@link com.malhartech.lib.math.ArithmeticQuotient}</b>: For every window computes quotient of sum of values of a key in two streams<br> * <b>{@link com.malhartech.lib.math.ArithmeticSum}</b>: For every window adds all the values of a key in a stream. For string values users can choose to appends with a delimiter<br> * <b>{@link com.malhartech.lib.math.SearchInvertIndex}</b>: Takes in a stream via input port "data". Inverts the index and sends out the tuple on output port "index"<p> * <b>{@link com.malhartech.lib.math.UniqueCounter}</b>: Counts payloads and send unique count for each on end of window<br> * <br> * */ package com.malhartech.lib.math;
library/src/main/java/com/malhartech/lib/math/package-info.java
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. * */ /** * <b>com.malhartech.lib.math</b> is a library of arithmetic modules for reuse<p> * <br> * <br>The modules are<br> * <b>{@link com.malhartech.lib.math.ArithmeticMargin}</b>: For every window computes margins of sums of values of a key in two streams<br> * <b>{@link com.malhartech.lib.math.ArithmeticQuotient}</b>: For every window computes quotient of sum of values of a key in two streams<br> * <b>{@link com.malhartech.lib.math.ArithmeticSum}</b>: For every window adds all the values of a key in a stream. For string values users can choose to appends with a delimiter<br> * <br> * */ package com.malhartech.lib.math;
Added more info
library/src/main/java/com/malhartech/lib/math/package-info.java
Added more info
Java
apache-2.0
error: pathspec 'share/classes/mjava/lang/MString.java' did not match any file(s) known to git
4259f361745e79eecc7011957f26372d9dc3a56f
1
EndlessCheng/OpenJDK-7u4-analysis,EndlessCheng/OpenJDK-7u4-analysis
package mjava.lang; public final class MString { /** 我们需要一个存储空间 */ private final char[] value; /** 保存字符串长度,一经初始化便不会改变 */ private final int count; public MString() { // http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.newarray this.value = new char[0]; this.count = 0; } public MString(char[] value) { this.value = value; // Java有专门的指令arraylength来获取数组的长度 // 见http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.arraylength int size = value.length; this.count = size; } }
share/classes/mjava/lang/MString.java
Create MString.java 实现MString类的构造方法。
share/classes/mjava/lang/MString.java
Create MString.java
Java
apache-2.0
error: pathspec 'src/test/java/core/genome/GenomeTest.java' did not match any file(s) known to git
cacd86e659f108768a8301357b748f176691229e
1
ProgrammingLife2016/PL4-2016
package core.genome; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Test suite for the Genome class. * * @author Niels Warnars */ public class GenomeTest { Genome g; @Before public void setUp() { g = new Genome(); } /** * Test case for the get/setAge methods. */ @Test public void testSetAge() { g.setAge(42); assertEquals(42, g.getAge()); } /** * Test case for the get/setSex methods. */ @Test public void testSetSex() { g.setSex("test"); assertEquals("test", g.getSex()); } /** * Test case for the get/setHiv methods. */ @Test public void testSetHivBool() { g.setHiv(true); assertTrue(g.isHiv()); } /** * Test case for the get/setHiv methods. */ @Test public void testSetHivString() { g.setHiv("Positive"); assertTrue(g.isHiv()); g.setHiv("Negative"); assertFalse(g.isHiv()); } /** * Test case for the get/setCohort methods. */ @Test public void testSetCohort() { g.setCohort("test"); assertEquals("test", g.getCohort()); } /** * Test case for the get/setStudyDistrict methods. */ @Test public void testSetStudyDistrict() { g.setStudyDistrict("test"); assertEquals("test", g.getStudyDistrict()); } /** * Test case for the get/setSpecimenType methods. */ @Test public void testSetSpecimenType() { g.setSpecimenType("test"); assertEquals("test", g.getSpecimenType()); } /** * Test case for the get/setSmearStatus methods. */ @Test public void testSetSmearStatus() { g.setSmearStatus("test"); assertEquals("test", g.getSmearStatus()); } /** * Test case for the get/setIsolation methods. */ @Test public void testSetIsolation() { g.setIsolation("test"); assertEquals("test", g.getIsolation()); } /** * Test case for the get/setPhenoDST methods. */ @Test public void testSetPhenoDST() { g.setPhenoDST("test"); assertEquals("test", g.getPhenoDST()); } /** * Test case for the get/setCapreomycin methods. */ @Test public void testSetCapreomycin() { g.setCapreomycin("test"); assertEquals("test", g.getCapreomycin()); } /** * Test case for the get/setEthambutol methods. */ @Test public void testSetEthambutol() { g.setEthambutol("test"); assertEquals("test", g.getEthambutol()); } /** * Test case for the get/setEthionamide methods. */ @Test public void testSetEthionamide() { g.setEthionamide("test"); assertEquals("test", g.getEthionamide()); } /** * Test case for the get/setIsoniazid methods. */ @Test public void testSetIsoniazid() { g.setIsoniazid("test"); assertEquals("test", g.getIsoniazid()); } /** * Test case for the get/setKanamycin methods. */ @Test public void testSetKanamycin() { g.setKanamycin("test"); assertEquals("test", g.getKanamycin()); } /** * Test case for the get/setPyrazinamide methods. */ @Test public void testSetPyrazinamide() { g.setPyrazinamide("test"); assertEquals("test", g.getPyrazinamide()); } /** * Test case for the get/setOfloxacin methods. */ @Test public void testSetOfloxacin() { g.setOfloxacin("test"); assertEquals("test", g.getOfloxacin()); } /** * Test case for the get/setRifampin methods. */ @Test public void testSetRifampin() { g.setRifampin("test"); assertEquals("test", g.getRifampin()); } /** * Test case for the get/setStreptomycin methods. */ @Test public void testSetStreptomycin() { g.setStreptomycin("test"); assertEquals("test", g.getStreptomycin()); } /** * Test case for the get/setSpoligotype methods. */ @Test public void testSetSpoligotype() { g.setSpoligotype("test"); assertEquals("test", g.getSpoligotype()); } /** * Test case for the get/setGenoDST methods. */ @Test public void testSetGenoDST() { g.setGenoDST("test"); assertEquals("test", g.getGenoDST()); } /** * Test case for the get/setLineage methods. */ @Test public void testSetLineage() { g.setLineage(42); assertEquals(42, g.getLineage()); } /** * Test case for the get/setTf methods. */ @Test public void testSetTf() { g.setTf("test"); assertEquals("test", g.getTf()); } }
src/test/java/core/genome/GenomeTest.java
Added test cases for the Genome class.
src/test/java/core/genome/GenomeTest.java
Added test cases for the Genome class.
Java
apache-2.0
error: pathspec 'Java/JUnit/00_Test_Normal/HolaMundoTest.java' did not match any file(s) known to git
247d66c72f970e19a57d80de3ce283a18c6b487e
1
CarlosIribarren/Ejemplos-Examples,CarlosIribarren/Ejemplos-Examples,CarlosIribarren/Ejemplos-Examples,CarlosIribarren/Ejemplos-Examples,CarlosIribarren/Ejemplos-Examples,CarlosIribarren/Ejemplos-Examples
package net.izfe.g210.hgfzergabidea.modelos.modelo048.ejercicio2014.core.beans; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class HolaMundoTest { @Test public void testMethod() { //Test normal } @Test(timeout=100) public void testMethodWithTimeOut() { //Test normal con time out. } @Before public void methodBefore() { //Se ejecuta despues de ejecutar cada test. } @After public void methodAfter() { //Se ejecuta antes de ejecutar cada test. } @BeforeClass public static void methodBeforeClass() { //Se ejecuta Antes de inicializar la clase } @AfterClass public static void methodAfterClass() { //Se ejecuta Despues de finalizar la clase } }
Java/JUnit/00_Test_Normal/HolaMundoTest.java
Añadido ejemplo de HolaMundo para JUNit.
Java/JUnit/00_Test_Normal/HolaMundoTest.java
Añadido ejemplo de HolaMundo para JUNit.
Java
apache-2.0
error: pathspec 'test/com/opera/core/systems/OperaActionTest.java' did not match any file(s) known to git
804be11f485c8a1151757bc96cdb74836117dd68
1
operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver
package com.opera.core.systems; import org.junit.Assert; import org.junit.Test; public class OperaActionTest extends TestBase { @Test(expected=org.openqa.selenium.WebDriverException.class) public void testDoesntExist() throws Exception { driver.operaAction("this action does exist"); } // FIXME does not fail @Test public void testMissingParam() throws Exception { driver.operaAction("Set preference"); } // FIXME does not fail @Test public void testExtraParam() throws Exception { driver.operaAction("Go to end", "an", "extra", "param"); } /* * The tests below test the commonly used Opera actions */ @Test public void testGo() throws Exception { driver.operaAction("Go", fixture("test.html")); Assert.assertEquals(fixture("test.html"), driver.getCurrentUrl()); } @Test public void testCase() throws Exception { driver.operaAction("GO", fixture("keys.html")); Assert.assertEquals(fixture("keys.html"), driver.getCurrentUrl()); driver.operaAction("go", fixture("javascript.html")); Assert.assertEquals(fixture("javascript.html"), driver.getCurrentUrl()); } @Test public void testNavigateUp() throws Exception { getFixture("two_input_fields.html"); driver.findElementByName("two").click(); driver.operaAction("Navigate up"); driver.key("enter"); driver.type("hello"); Assert.assertEquals("hello", driver.findElementByName("one").getValue()); } @Test public void testNavigateDown() throws Exception { getFixture("two_input_fields.html"); driver.findElementByName("one").click(); driver.operaAction("Navigate down"); driver.key("enter"); driver.type("hello"); Assert.assertEquals("hello", driver.findElementByName("two").getValue()); } @Test public void testNavigateRight() throws Exception { getFixture("test.html"); driver.findElementById("radio_little").click(); driver.operaAction("Navigate right"); driver.key("enter"); Assert.assertEquals(true, ((OperaWebElement) driver.findElementById("radio_some")).isSelected() ); } @Test public void testNavigateLeft() throws Exception { getFixture("test.html"); driver.findElementById("radio_little").click(); driver.operaAction("Navigate left"); driver.key("enter"); driver.type("hello"); Assert.assertEquals("hello", driver.findElementById("input_email").getValue()); } }
test/com/opera/core/systems/OperaActionTest.java
Add tests for operaAction
test/com/opera/core/systems/OperaActionTest.java
Add tests for operaAction
Java
apache-2.0
error: pathspec 'src/org/netmelody/cii/monitor/JobStatusScanner.java' did not match any file(s) known to git
7fee91029f91278da08baa79406e8615caba1006
1
MaltheFriisberg/CiEyeWork,MaltheFriisberg/CiEyeWork,MaltheFriisberg/CiEyeWork,netmelody/ci-eye,MaltheFriisberg/CiEyeWork,MaltheFriisberg/CIE,netmelody/ci-eye,MaltheFriisberg/CIE,netmelody/ci-eye,MaltheFriisberg/CIE,netmelody/ci-eye,MaltheFriisberg/CIE
package org.netmelody.cii.monitor; public final class JobStatusScanner { }
src/org/netmelody/cii/monitor/JobStatusScanner.java
add scanner
src/org/netmelody/cii/monitor/JobStatusScanner.java
add scanner
Java
apache-2.0
error: pathspec 'chapter_003/Find/src/main/java/ru/nivanov/Param.java' did not match any file(s) known to git
543cfca1c037ce1c827be1a709fb7a94dddf97f6
1
Piterski72/Java-a-to-z,Piterski72/Java-a-to-z,Piterski72/Java-a-to-z
package ru.nivanov; /** * Created by Nikolay Ivanov on 20.02.2017. */ class Param { private static final int THREE = 3; private static final int FOUR = 4; private static final int FIVE = 5; private static final int SIX = 6; private final String[] value; /** * Constructor for param. * @param value is input data from command line */ Param(String[] value) { this.value = value; } /** * Get dir name. * @return directory name */ String getDirName() { return this.value[1]; } /** * Get file name or mask. * @return .. */ String getFileName() { return this.value[THREE]; } /** * Get log file name. * @return .. */ String getLogName() { return this.value[SIX]; } /** * Get -d key. * @return .. */ String getDparam() { return this.value[0]; } /** * Get -n key. * @return .. */ String getNparam() { return this.value[2]; } /** * Get -m or -f or -r key. * @return .. */ String getMFRparam() { return this.value[FOUR]; } /** * Get -o key. * @return .. */ String getOparam() { return this.value[FIVE]; } /** * Get all values. * @return .. */ private String[] getAllparams() { return this.value; } }
chapter_003/Find/src/main/java/ru/nivanov/Param.java
restored afted system crash
chapter_003/Find/src/main/java/ru/nivanov/Param.java
restored afted system crash
Java
apache-2.0
error: pathspec 'src/main/java/io/reactivex/subjects/ReplaySubject.java' did not match any file(s) known to git
1c1839a125043839e61d30dc6dee262139943709
1
akarnokd/RxJava,NiteshKant/RxJava,AttwellBrian/RxJava,artem-zinnatullin/RxJava,spoon-bot/RxJava,reactivex/rxjava,ReactiveX/RxJava,AttwellBrian/RxJava,NiteshKant/RxJava,ReactiveX/RxJava,artem-zinnatullin/RxJava,spoon-bot/RxJava,reactivex/rxjava,benjchristensen/RxJava,akarnokd/RxJava
/** * Copyright 2015 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.subjects; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.*; import org.reactivestreams.*; import io.reactivex.Scheduler; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; /** * Replays events to Subscribers. * * <p>This Subject respects the backpressure behavior of its Subscribers (individually). * * @param <T> the value type */ public final class ReplaySubject<T> extends Subject<T, T> { public static <T> ReplaySubject<T> create() { return create(16); } public static <T> ReplaySubject<T> create(int capacityHint) { if (capacityHint <= 0) { throw new IllegalArgumentException("capacityHint > 0 required but it was " + capacityHint); } ReplayBuffer<T> buffer = new UnboundedReplayBuffer<>(capacityHint); return createWithBuffer(buffer); } public static <T> ReplaySubject<T> createWithSize(int size) { if (size <= 0) { throw new IllegalArgumentException("size > 0 required but it was " + size); } SizeBoundReplayBuffer<T> buffer = new SizeBoundReplayBuffer<>(size); return createWithBuffer(buffer); } public static <T> ReplaySubject<T> createWithTime(long maxAge, TimeUnit unit) { return createWithTime(maxAge, unit, Schedulers.trampoline()); } public static <T> ReplaySubject<T> createWithTime(long maxAge, TimeUnit unit, Scheduler scheduler) { return createWithTimeAndSize(maxAge, unit, scheduler, Integer.MAX_VALUE); } public static <T> ReplaySubject<T> createWithTimeAndSize(long maxAge, TimeUnit unit, Scheduler scheduler, int size) { Objects.requireNonNull(unit); Objects.requireNonNull(scheduler); if (size <= 0) { throw new IllegalArgumentException("size > 0 required but it was " + size); } SizeAndTimeBoundReplayBuffer<T> buffer = new SizeAndTimeBoundReplayBuffer<>(size, maxAge, unit, scheduler); return createWithBuffer(buffer); } static <T> ReplaySubject<T> createWithBuffer(ReplayBuffer<T> buffer) { State<T> state = new State<>(buffer); return new ReplaySubject<>(state); } final State<T> state; protected ReplaySubject(State<T> state) { super(state); this.state = state; } @Override public void onSubscribe(Subscription s) { state.onSubscribe(s); } @Override public void onNext(T t) { state.onNext(t); } @Override public void onError(Throwable t) { state.onError(t); } @Override public void onComplete() { state.onComplete(); } @Override public boolean hasSubscribers() { return state.subscribers.length != 0; } @Override public Throwable getThrowable() { Object o = state.get(); if (NotificationLite.isError(o)) { return NotificationLite.getError(o); } return null; } @Override public T getValue() { return state.buffer.getValue(); } @Override public T[] getValues(T[] array) { return state.buffer.getValues(array); } @Override public boolean hasComplete() { Object o = state.get(); return NotificationLite.isComplete(o); } @Override public boolean hasThrowable() { Object o = state.get(); return NotificationLite.isError(o); } @Override public boolean hasValue() { return state.buffer.size() != 0; } static final class State<T> extends AtomicReference<Object> implements Publisher<T>, Subscriber<T> { /** */ private static final long serialVersionUID = -4673197222000219014L; final ReplayBuffer<T> buffer; boolean done; volatile ReplaySubscription<T>[] subscribers; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater<State, ReplaySubscription[]> SUBSCRIBERS = AtomicReferenceFieldUpdater.newUpdater(State.class, ReplaySubscription[].class, "subscribers"); @SuppressWarnings("rawtypes") static final ReplaySubscription[] EMPTY = new ReplaySubscription[0]; @SuppressWarnings("rawtypes") static final ReplaySubscription[] TERMINATED = new ReplaySubscription[0]; public State(ReplayBuffer<T> buffer) { this.buffer = buffer; SUBSCRIBERS.lazySet(this, EMPTY); } @Override public void subscribe(Subscriber<? super T> s) { ReplaySubscription<T> rs = new ReplaySubscription<>(s, this); s.onSubscribe(rs); if (!rs.cancelled) { if (add(rs)) { if (rs.cancelled) { remove(rs); } } } } public boolean add(ReplaySubscription<T> rs) { for (;;) { ReplaySubscription<T>[] a = subscribers; if (a == TERMINATED) { return false; } int len = a.length; @SuppressWarnings("unchecked") ReplaySubscription<T>[] b = new ReplaySubscription[len + 1]; System.arraycopy(a, 0, b, 0, len); b[len] = rs; if (SUBSCRIBERS.compareAndSet(this, a, b)) { return true; } } } @SuppressWarnings("unchecked") public void remove(ReplaySubscription<T> rs) { for (;;) { ReplaySubscription<T>[] a = subscribers; if (a == TERMINATED || a == EMPTY) { return; } int len = a.length; int j = -1; for (int i = 0; i < len; i++) { if (a[i] == rs) { j = i; break; } } if (j < 0) { return; } ReplaySubscription<T>[] b; if (len == 1) { b = EMPTY; } else { b = new ReplaySubscription[len - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, len - j - 1); } if (SUBSCRIBERS.compareAndSet(this, a, b)) { return; } } } @SuppressWarnings("unchecked") public ReplaySubscription<T>[] terminate(Object terminalValue) { if (compareAndSet(null, terminalValue)) { return SUBSCRIBERS.getAndSet(this, TERMINATED); } return TERMINATED; } @Override public void onSubscribe(Subscription s) { if (done) { s.cancel(); return; } s.request(Long.MAX_VALUE); } @Override public void onNext(T t) { if (done) { return; } ReplayBuffer<T> b = buffer; b.add(t); for (ReplaySubscription<T> rs : subscribers) { b.replay(rs); } } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } done = true; Object o = NotificationLite.error(t); ReplayBuffer<T> b = buffer; b.addFinal(o); for (ReplaySubscription<T> rs : terminate(o)) { b.replay(rs); } } @Override public void onComplete() { if (done) { return; } done = true; Object o = NotificationLite.complete(); ReplayBuffer<T> b = buffer; b.addFinal(o); for (ReplaySubscription<T> rs : terminate(o)) { b.replay(rs); } } } interface ReplayBuffer<T> { void add(T value); void addFinal(Object notificationLite); void replay(ReplaySubscription<T> rs); int size(); T getValue(); T[] getValues(T[] array); } static final class ReplaySubscription<T> extends AtomicInteger implements Subscription { /** */ private static final long serialVersionUID = 466549804534799122L; final Subscriber<? super T> actual; final State<T> state; Object index; volatile long requested; @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<ReplaySubscription> REQUESTED = AtomicLongFieldUpdater.newUpdater(ReplaySubscription.class, "requested"); volatile boolean cancelled; public ReplaySubscription(Subscriber<? super T> actual, State<T> state) { this.actual = actual; this.state = state; } @Override public void request(long n) { if (SubscriptionHelper.validateRequest(n)) { return; } BackpressureHelper.add(REQUESTED, this, n); state.buffer.replay(this); } @Override public void cancel() { if (!cancelled) { cancelled = true; state.remove(this); } } } static final class UnboundedReplayBuffer<T> implements ReplayBuffer<T> { final List<Object> buffer; volatile boolean done; volatile int size; public UnboundedReplayBuffer(int capacityHint) { this.buffer = new ArrayList<>(capacityHint); } @Override public void add(T value) { buffer.add(value); size++; } @Override public void addFinal(Object notificationLite) { buffer.add(notificationLite); size++; done = true; } @Override @SuppressWarnings("unchecked") public T getValue() { int s = size; if (s != 0) { List<Object> b = buffer; Object o = b.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { if (s == 1) { return null; } return (T)b.get(s - 2); } return (T)o; } return null; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { int s = size; if (s == 0) { if (array.length != 0) { array[0] = null; } return array; } List<Object> b = buffer; Object o = b.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { s--; if (s == 0) { if (array.length != 0) { array[0] = null; } return array; } } if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } for (int i = 0; i < s; i++) { array[i] = (T)b.get(i); } if (array.length > s) { array[s] = null; } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplaySubscription<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final List<Object> b = buffer; final Subscriber<? super T> a = rs.actual; int index = (Integer)rs.index; for (;;) { if (rs.cancelled) { rs.index = null; return; } int s = size; long r = rs.requested; boolean unbounded = r == Long.MAX_VALUE; long e = 0; while (s != index) { if (rs.cancelled) { rs.index = null; return; } Object o = b.get(index); if (done) { if (index + 1 == s) { s = size; if (index + 1 == s) { if (NotificationLite.isComplete(o)) { a.onComplete(); } else { a.onError(NotificationLite.getError(o)); } rs.index = null; rs.cancelled = true; return; } } } if (r == 0) { r = rs.requested; if (r == 0) { break; } } a.onNext((T)o); r--; e--; index++; } if (!unbounded) { r = ReplaySubscription.REQUESTED.addAndGet(rs, e); } if (index != size && r != 0L) { continue; } rs.index = index; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { int s = size; if (s != 0) { Object o = buffer.get(s - 1); if (NotificationLite.isComplete(o) || NotificationLite.isError(o)) { return s - 1; } return s; } return 0; } } static final class Node<T> extends AtomicReference<Node<T>> { /** */ private static final long serialVersionUID = 6404226426336033100L; final T value; public Node(T value) { this.value = value; } } abstract static class BoundedReplayBuffer<T> implements ReplayBuffer<T> { int size; volatile Node<Object> head; Node<Object> tail; volatile boolean done; public BoundedReplayBuffer() { Node<Object> h = new Node<>(null); this.tail = h; this.head = h; } @Override public void add(T value) { Object o = enter(value); Node<Object> n = new Node<>(o); Node<Object> t = tail; tail = n; size++; t.lazySet(n); // releases both the tail and size trim(); } @Override public void addFinal(Object notificationLite) { Object o = enter(notificationLite); Node<Object> n = new Node<>(o); Node<Object> t = tail; tail = n; size++; t.lazySet(n); // releases both the tail and size trimFinal(); done = true; } abstract Object enter(Object value); abstract Object leave(Object value); abstract void trim(); abstract void trimFinal(); @Override @SuppressWarnings("unchecked") public T getValue() { Node<Object> prev = null; Node<Object> h = head; for (;;) { Node<Object> next = h.get(); if (next == null) { break; } prev = h; h = next; } Object v = h.value; if (v == null) { return null; } v = leave(v); if (NotificationLite.isComplete(v) || NotificationLite.isError(v)) { return (T)leave(prev.value); } return (T)v; } @Override @SuppressWarnings("unchecked") public T[] getValues(T[] array) { Node<Object> h = head; int s = size(); if (s == 0) { if (array.length != 0) { array[0] = null; } } else { if (array.length < s) { array = (T[])Array.newInstance(array.getClass().getComponentType(), s); } int i = 0; while (i != s) { Node<Object> next = h.get(); array[i] = (T)leave(next.value); i++; h = next; } } return array; } @Override @SuppressWarnings("unchecked") public void replay(ReplaySubscription<T> rs) { if (rs.getAndIncrement() != 0) { return; } int missed = 1; final Subscriber<? super T> a = rs.actual; Node<Object> index = (Node<Object>)rs.index; if (index == null) { index = head; } for (;;) { if (rs.cancelled) { rs.index = null; return; } long r = rs.requested; boolean unbounded = r == Long.MAX_VALUE; long e = 0; for (;;) { if (rs.cancelled) { rs.index = null; return; } Node<Object> n = index.get(); if (n == null) { break; } Object o = leave(n.value); if (done) { if (n.get() == null) { if (NotificationLite.isComplete(o)) { a.onComplete(); } else { a.onError(NotificationLite.getError(o)); } rs.index = null; rs.cancelled = true; return; } } if (r == 0) { r = rs.requested; if (r == 0) { break; } } a.onNext((T)o); r--; e--; index = n; } if (!unbounded) { r = ReplaySubscription.REQUESTED.addAndGet(rs, e); } if (index.get() != null && r != 0L) { continue; } rs.index = index; missed = rs.addAndGet(-missed); if (missed == 0) { break; } } } @Override public int size() { int s = 0; Node<Object> h = head; while (s != Integer.MAX_VALUE) { Node<Object> next = h.get(); if (next == null) { break; } s++; h = next; } return s; } } static final class SizeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> { final int maxSize; public SizeBoundReplayBuffer(int maxSize) { this.maxSize = maxSize; } @Override Object enter(Object value) { return value; } @Override Object leave(Object value) { return value; } @Override void trim() { if (size > maxSize) { Node<Object> h = head; head = h.get(); } } @Override void trimFinal() { // do nothing } } static final class SizeAndTimeBoundReplayBuffer<T> extends BoundedReplayBuffer<T> { final int maxSize; final long maxAge; final TimeUnit unit; final Scheduler scheduler; public SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) { this.maxSize = maxSize; this.maxAge = maxAge; this.unit = unit; this.scheduler = scheduler; } @Override Object enter(Object value) { return new Timed<>(value, scheduler.now(unit), unit); } @Override Object leave(Object value) { return ((Timed<?>)value).value(); } @Override void trim() { if (size > maxSize) { Node<Object> h = head; head = h.get(); } trimFinal(); } @Override void trimFinal() { long limit = scheduler.now(unit) - maxAge; Node<Object> h = head; for (;;) { Node<Object> next = h.get(); if (next == null) { head = h; break; } Timed<?> t = (Timed<?>)next.value; if (t.time() > limit) { head = next; break; } h = next; } } } }
src/main/java/io/reactivex/subjects/ReplaySubject.java
ReplaySubject Has full backpressure support (replays as many elements as requested).
src/main/java/io/reactivex/subjects/ReplaySubject.java
ReplaySubject
Java
apache-2.0
error: pathspec 'com/planet_ink/coffee_mud/Abilities/Druid/Chant_Grapevine.java' did not match any file(s) known to git
2120e20782bbcc21804cbc7a41761d4bcfa21119
1
sfunk1x/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Abilities.Druid; public class Chant_Grapevine { }
com/planet_ink/coffee_mud/Abilities/Druid/Chant_Grapevine.java
git-svn-id: svn://192.168.1.10/public/CoffeeMud@2336 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Abilities/Druid/Chant_Grapevine.java
Java
apache-2.0
error: pathspec 'src/test/java/com/mediamath/terminalone/ReportingMockTest.java' did not match any file(s) known to git
8a46441baefeaef114f572e3afe8d77108aa3052
1
MediaMath/t1-java,MediaMath/t1-java
package com.mediamath.terminalone; import static org.junit.Assert.assertNotNull; import java.io.InputStream; import java.util.Properties; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.mediamath.terminalone.exceptions.ClientException; import com.mediamath.terminalone.exceptions.ParseException; import com.mediamath.terminalone.functional.PostFunctionalTestIT; import com.mediamath.terminalone.models.JsonResponse; import com.mediamath.terminalone.models.T1User; @RunWith(MockitoJUnitRunner.class) public class ReportingMockTest { private static final String META = "{\"reports\":{\"app_transparency\":{\"Description\":\"Standard performance metrics broken out by App ID. Non-app inventory shown as N/A app_id\",\"Name\":\"App Transparency Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/app_transparency\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/app_transparency/meta\",\"Version\":1},\"audience_index\":{\"Description\":\"Special index metrics for comparing your ads' viewers to 3rd party segments. Broken out by audience name, as well as standard dimensions down to campaign and strategy. Currently available in one interval: last 14 days.\",\"Name\":\"Audience Index Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/audience_index\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/audience_index/meta\",\"Version\":1},\"audience_index_pixel\":{\"Description\":\"Special index metrics for comparing your site visitors to 3rd party segments. Broken out by audience name and pixel. Currently available in one interval: last 14 days.\",\"Name\":\"Audience Index Pixel Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/audience_index_pixel\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/audience_index_pixel/meta\",\"Version\":1},\"contextual_insights\":{\"Description\":\"Standard performance metrics broken out by contextual categories that strategies are targeting\",\"Name\":\"Contextual Insights\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/contextual_insights\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/contextual_insights/meta\",\"Version\":1},\"data_pixel_loads\":{\"Description\":\"Loads and Uniques metrics for data pixels, broken out by referrer and referrer rank, available by day.\",\"Name\":\"Data Pixel Loads Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/data_pixel_loads\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/data_pixel_loads/meta\",\"Version\":1},\"day_part\":{\"Description\":\"Standard performance metrics broken out by time of day and day of week. Available in standard intervals.\",\"Name\":\"Day Part Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/day_part\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/day_part/meta\",\"Version\":2},\"device_technology\":{\"Description\":\"Standard performance metrics broken out by technology dimensions including browser, operating system, and connection type. Available in custom date ranges or intervals with the option to aggregate by day, week, or month.\",\"Name\":\"Device Technology Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/device_technology\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/device_technology/meta\",\"Version\":1},\"event_pixel_loads\":{\"Description\":\"Loads and Uniques metrics for event pixels, broken out by referrer and referrer rank, available by day.\",\"Name\":\"Event Pixel Loads Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/event_pixel_loads\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/event_pixel_loads/meta\",\"Version\":1},\"geo\":{\"Description\":\"Standard performance metrics broken out by geographic dimensions including country, region, and metro area. Available in standard intervals.\",\"Name\":\"Geo Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/geo\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/geo/meta\",\"Version\":2},\"hyperlocal\":{\"Description\":\"Standard performance metrics broken out by Hyperlocal Targeting objects created via third party.\",\"Name\":\"Hyperlocal Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/hyperlocal\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/hyperlocal/meta\",\"Version\":1},\"performance\":{\"Description\":\"Standard performance metrics in campaign currency and broken out by our widest array of dimensions. Available in custom date ranges or intervals with the option to aggregate by day, week, or month.\",\"Name\":\"Performance Report in Campaign Currency\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/performance\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/performance/meta\",\"Version\":1},\"postal_code\":{\"Description\":\"Standard performance metrics broken out by postal code. Only includes data for strategies that targeted or anti-targeted postal codes. Available in custom date ranges or intervals with the option to aggregate by day, week, or month.\",\"Name\":\"Postal Code Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/postal_code\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/postal_code/meta\",\"Version\":1},\"pulse\":{\"Description\":\"Standard performance metrics broken out by standard dimensions, available in precise time windows - down to the hour - with the option to aggregate by hour or day.\",\"Name\":\"Pulse Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/pulse\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/pulse/meta\",\"Version\":1},\"reach_frequency\":{\"Description\":\"Basic performance metrics as well as the uniques metric, broken out by frequency of ad exposure. Available in standard intervals.\",\"Name\":\"Reach and Frequency Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/reach_frequency\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/reach_frequency/meta\",\"Version\":1},\"site_transparency\":{\"Description\":\"Standard performance metrics broken out by the domain of the inventory. Available in standard intervals.\",\"Name\":\"Site Transparency Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/site_transparency\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/site_transparency/meta\",\"Version\":2},\"video\":{\"Description\":\"Video-specific metrics such as completion rate, skips, and fullscreens broken out by a wide array of dimensions. Available in custom date-ranges or intervals with the option to aggregate by day, week, or month.\",\"Name\":\"Video Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/video\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/video/meta\",\"Version\":1},\"watermark\":{\"Description\":\"Watermark metrics show how many impressions and how much spend went towards the brain's learning activities. Viewable by campaign and strategy dimensions and available by day.\",\"Name\":\"Watermark Report in US Dollars\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/watermark\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/watermark/meta\",\"Version\":1},\"win_loss\":{\"Description\":\"Metrics describe the auction before a win or even a bid has taken place. Broken out by strategy, exchange, and deal dimensions and available by hour.\",\"Name\":\"Win/Loss Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/win_loss\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/win_loss/meta\",\"Version\":2},\"win_loss_creative\":{\"Description\":\"Metrics describe the auction before a win has taken place. Broken out by creative dimensions and available by hour.\",\"Name\":\"Win/Loss Creative Report\",\"URI_Data\":\"https://api.mediamath.com/reporting/v1/std/win_loss_creative\",\"URI_Meta\":\"https://api.mediamath.com/reporting/v1/std/win_loss_creative/meta\",\"Version\":1}}}"; private static final String RESPONSEMETA = null; private static Properties testConfig = new Properties(); private static String LOGIN = null; @Mock Connection connectionmock; @InjectMocks TerminalOne t1 = new TerminalOne(); @Mock Response response; @BeforeClass public static void init() throws Exception { InputStream input = PostFunctionalTestIT.class.getClassLoader().getResourceAsStream("mocktest.properties"); testConfig.load(input); LOGIN = testConfig.getProperty("t1.mock.loginResponse"); } @After public final void tearDown() throws InterruptedException { Thread.sleep(5000); } @SuppressWarnings("unchecked") @Test public void testGetMeta() throws ClientException { Mockito.when(connectionmock.post(Mockito.anyString(), Mockito.any(Form.class), Mockito.any(T1User.class))).thenReturn(response); Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(LOGIN, META); Mockito.when(connectionmock.get(Mockito.anyString(), Mockito.any(T1User.class))).thenReturn(META); //login and get the reports. t1.authenticate("abc", "xyz", "adfadslfadkfakjf"); JsonResponse<?> response = t1.getMeta(); assertNotNull(response.getData()); } @SuppressWarnings("unchecked") @Test public void testReportsMeta() throws ClientException { Mockito.when(connectionmock.post(Mockito.anyString(), Mockito.any(Form.class), Mockito.any(T1User.class))).thenReturn(response); Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(LOGIN, RESPONSEMETA); Mockito.when(connectionmock.get(Mockito.anyString(), Mockito.any(T1User.class))).thenReturn(RESPONSEMETA); } }
src/test/java/com/mediamath/terminalone/ReportingMockTest.java
Response Mock Test initial commit.
src/test/java/com/mediamath/terminalone/ReportingMockTest.java
Response Mock Test initial commit.
Java
apache-2.0
error: pathspec 'src/main/java/org/jamesframework/core/search/cache/MoveCache.java' did not match any file(s) known to git
07868a6407533cb316f6e36deed78cd09d822cfc
1
hdbeukel/james-core,hdbeukel/james-core
// Copyright 2014 Herman De Beukelaer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.jamesframework.core.search.cache; import org.jamesframework.core.problems.Problem; import org.jamesframework.core.search.neigh.Move; /** * Interface of a cache that records validity (see {@link Problem#rejectSolution(Solution)}) and * evaluations (see {@link Problem#evaluate(Solution)}) of neighbours obtained by applying moves * to the current solution in a neighbourhood search. Whenever a move is validated and evaluated, the * computed values may be offered to the cache. They can be retrieved later, when the same move is * validated or evaluated again for the same current solution, if these value are still contained * in the cache at that time. * <p> * In general, there is no guarantee that cached values will still be available at any later * point in time. Every cache implementation may handle cache requests in a specific way, and may * store a different number and/or specific selection of values. The only guarantee is that if a * value is retrieved from the cache, it will be correct. * <p> * When the current solution of a neighbourhood search is modified, any move cache used by this * search should be cleared using {@link #clear()}, as then it is no longer valid. * <p> * Note that when using a cache implementation that stores multiple values, it may be beneficial * to override {@link Object#equals(Object)} and {@link Object#hashCode()} in the moves generated * by the applied neighbourhood, to increase the number of cache hits. * * @author Herman De Beukelaer <herman.debeukelaer@ugent.be> */ public interface MoveCache { /** * Request to cache the evaluation (see {@link Problem#evaluate(Solution)}) of the neighbouring * solution which is obtained by applying the given move to the current solution. The specific cache * implementation may decide whether to store the given value and/or discard previously cached values. * * @param move move applied to the current solution * @param evaluation evaluation of the obtained neighbour */ public void cacheMoveEvaluation(Move<?> move, double evaluation); /** * Retrieve the cached evaluation (see {@link Problem#evaluate(Solution)}) of the neighbouring * solution which is obtained by applying the given move to the current solution, if available. * If this evaluation is not (or no longer) available in the cache, <code>null</code> is returned. * Else, the returned value is guaranteed to be correct. * * @param move move applied to the current solution * @return evaluation of the obtained neighbour, <code>null</code> if not available in the cache */ public Double getCachedMoveEvaluation(Move<?> move); /** * Request to cache rejection (see {@link Problem#rejectSolution(Solution)}) of the neighbouring * solution which is obtained by applying the given move to the current solution. The specific cache * implementation may decide whether to store the given value and/or discard previously cached values. * * @param move move applied to the current solution * @param isRejected indicates whether the obtained neighbour is rejected */ public void cacheMoveRejection(Move<?> move, boolean isRejected); /** * Retrieve cached rejection (see {@link Problem#evaluate(Solution)}) of the neighbouring * solution which is obtained by applying the given move to the current solution, if available. * If this evaluation is not (or no longer) available in the cache, <code>null</code> is returned. * Else, <code>true</code> is returned if the obtained neighbour is rejected, and <code>false</code> * is returned in case of a valid neighbour. * * @param move move applied to the current solution * @return <code>true</code> if obtained neighbour is rejected, <code>null</code> if not available in the cache */ public Boolean getCachedMoveRejection(Move<?> move); /** * Clears all cached values. This method should at least be called whenever the current solution * has been modified, as then the cached values are no longer valid. */ public void clear(); }
src/main/java/org/jamesframework/core/search/cache/MoveCache.java
implemented move cache interface
src/main/java/org/jamesframework/core/search/cache/MoveCache.java
implemented move cache interface
Java
apache-2.0
error: pathspec 'apptbook_cmdLine/src/main/java/edu/pdx/cs410J/markum2/Project4.java' did not match any file(s) known to git
bd5f0b11d84192d69e51694fdccbe5a246e9db9f
1
mmattwan/CS410J
package edu.pdx.cs410J.markum2; import edu.pdx.cs410J.ParserException; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; /** * The main class for the client side of CS410J appointment book Project 4. * * @author Markus Mattwandel * @version 2016.07.27 */ public class Project4 { // The AppointmentBook the project will work on public static edu.pdx.cs410J.markum2.AppointmentBook newAppointmentBook = new edu.pdx.cs410J.markum2.AppointmentBook(); /** * Prints README */ private static void printReadme() { System.out.println("\n\nCS410J Project 4"); System.out.println("Author: Markus Mattwandel\n"); System.out.println("This program implements a REST client-server appointment book service.\n"); System.out.println("The following options are supported:"); System.out.println(" -host hostname\t name of host computer on which server is running"); System.out.println(" -port port\t\t port on which the server is listening"); System.out.println(" -search\t\t specifies that appointments should be searched for"); System.out.println(" -print\t\t prints a description of the new appointment"); System.out.println(" -README\t\t to print this message and exits"); System.out.println("Options can be specified in any order but must precede appointment information.\n"); System.out.println("Appointments must adhere to the following format in the order indicated:"); System.out.println(" owner:\t\t the owner of the appointment book"); System.out.println(" description:\t\t the description of the appointment"); System.out.println(" beginDateTime:\t the beginning date and meridiem time (separated by a blank)"); System.out.println(" beginTimeTime:\t the ending date and meridiem time (separated by a blank)"); System.out.println("Time can have 1 or 2 digits for hour, but must have 2 digits for minutes."); System.out.println("Date can have 1 or 2 digits for month and day, but must have 4 digits for year."); System.out.println("owner and description can use double quotes to span multiple words."); System.out.println("If -search is specified, dscription is not required.\n"); System.out.println("An appointment must always be specified.\n"); } /** * main for Project 4. Parses command line, processes options, ... * * @param args command line arguments */ public static void main(String[] args) { Boolean hostOption = Boolean.FALSE; // set if -host specified in cmdLine String hostName = ""; // name of host Boolean portOption = Boolean.FALSE; // set if -port specified in cmdLine Integer portNumber=0; // port number Boolean searchOption = Boolean.FALSE; // set if -search specified in cmdLine Date startSearchDate; // search start dateTime Date endSearchDate; // search end dateTime Boolean printOption = Boolean.FALSE; // set if -print specified in cmdLine Boolean readmeOption = Boolean.FALSE; // set if -README specified in cmdLine Integer optCnt = 0; // number of options found // no args is an error if (args.length==0) { System.err.println("Missing command line arguments"); System.exit(1); } // find all -options for (int i=0; i<args.length; i++) { // an arg preceded with a dash is an option if (args[i].substring(0,1).contains("-")) { // count #options found optCnt++; // check for valid options switch (args[i]) { case "-host": // verify that a hostName is specified after -host, exit if not if (i == args.length - 1) { System.err.println("No arguments after -host"); System.exit(1); } // verify that no options follow directly after -host, exit if not if (args[i + 1].contains("-")) { System.err.println("No hostName specified after -host"); System.exit(1); } // Set hostName option and save hostName name hostOption = Boolean.TRUE; optCnt++; // hostName is also an option to count! hostName = args[i + 1]; break; case "-port": // verify that something is specified after -port, exit if not if (i == args.length - 1) { System.err.println("No arguments after -port"); System.exit(1); } // verify that no options follow directly after -port, exit if not if (args[i + 1].contains("-")) { System.err.println("No port number specified after -port"); System.exit(1); } // verify that port is an integer try { portNumber = Integer.parseInt(args[i + 1]); } catch (NumberFormatException ex) { System.err.println("Port \"" + args[i + 1] + "\" must be an integer"); System.exit(1); } // Set hostName option portOption = Boolean.TRUE; optCnt++; // portNumber is also an option to count! break; case "-search": searchOption = Boolean.TRUE; break; case "-print": printOption = Boolean.TRUE; break; case "-README": readmeOption = Boolean.TRUE; break; // Any other options are invalid and signal and default: System.err.println("Invalid option found: " + args[i]); System.exit(1); } } } /* System.out.println("hostOption is: "+hostOption); System.out.println("hostName is: "+hostName); System.out.println("portOption is: "+portOption); System.out.println("portNumber is: "+portNumber); System.out.println("searchOption is: "+searchOption); System.out.println("printOption is: "+printOption); System.out.println("readmeOption is: "+readmeOption); System.out.println("optCnt is: "+optCnt); System.out.println("totalArgsCnt is: "+args.length); */ // print README and exit if -README found if (readmeOption) { printReadme(); System.exit(0); } // -port and -host must be specified if (!portOption || !hostOption) { System.err.println("-host hostName and -port portNumber must be specified"); System.exit(1); } // it takes exactly 8 args after the options to specify an appointment: // or 7 args if -search is specified // add that to optCnt to verify and exit it wrong amount if ( (optCnt+8 != args.length && !searchOption) || (optCnt+7 != args.length && searchOption ) ) { System.err.println("Invalid number of appointment arguments"); System.exit(1); } // cmdLine good: start processing! // Extract new appointment details from args String beginDate = args[args.length-6], beginTime = args[args.length-5], beginTimeMeridiem = args[args.length-4]; String endDate = args[args.length-3], endTime = args[args.length-2], endTimeMeridiem = args[args.length-1]; String owner, description = ""; if (searchOption) owner = args[args.length - 7]; else { owner = args[args.length - 8]; description = args[args.length - 7]; } // convert command line dates to Date class, flagging and exiting on bad dates Date beginDateTime = null, endDateTime = null ; DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); try { beginDateTime = df.parse(beginDate+" "+beginTime+" "+beginTimeMeridiem); } catch (ParseException ex) { System.err.println("Bad beginning Date and time: "+beginDate+" "+beginTime+" "+beginTimeMeridiem); System.exit(1); } try { endDateTime = df.parse(endDate+" "+endTime+" "+endTimeMeridiem); } catch (ParseException ex) { System.err.println("Bad ending date and time: "+endDate+" "+endTime+" "+endTimeMeridiem); System.exit(1); } /* System.out.println("owner = "+owner); System.out.println("description = "+description); System.out.println("beginDate = "+beginDate); System.out.println("beginTime = "+beginTime); System.out.println("beginTimeMeridiem = "+beginTimeMeridiem); System.out.println("beginDateTime = "+beginDateTime); System.out.println("endDate = "+endDate); System.out.println("endTime = "+endTime); System.out.println("endTimeMeridiem = "+endTimeMeridiem); System.out.println("endDateTime = "+endDateTime); */ /* // if -textFile specified, read appointments from file and add them to AppointmentBook if (textFileOption) { try { TextParser parser = new TextParser(textFileName,owner); edu.pdx.cs410J.markum2.AppointmentBook book = parser.parse(); } catch (FileNotFoundException ex) { // catch exception, but do nothing which creates an empty file as specified } // catch parser exceptions and exit if true catch (ParserException ex) { System.err.println("** " + ex.getMessage()); System.exit(1); } } // Construct new Appointment from cmdLine args and add it to AppointmentBook Appointment newAppointment = new Appointment(owner, description, beginDateTime, endDateTime); newAppointmentBook.addAppointment(newAppointment); // if -textFile specified, write all appointments back out if (textFileOption) { try { TextDumper dumper = new TextDumper(textFileName); dumper.dump(newAppointmentBook); } catch (IOException ex) { System.err.println("** " + ex.getMessage()); System.exit(1); } } // if -prettyPrint specified, print out AppointmentBook in pretty format if (prettyFileOption) { try { TextDumper dumper = new TextDumper(prettyFileName); dumper.prettyPrint(newAppointmentBook, prettyFileName); } catch (IOException ex) { System.err.println("** " + ex.getMessage()); System.exit(1); } } // if -print specified, print out cmdLine appointment added if (printOption) if (textFileOption) System.out.println("Added to "+textFileName+": "+newAppointment.toString()); else System.out.println("Read: "+newAppointment.toString()); */ // if you've made it this far, exit with Success System.exit(0); } }
apptbook_cmdLine/src/main/java/edu/pdx/cs410J/markum2/Project4.java
Porject4 cmdLine parsing completed.
apptbook_cmdLine/src/main/java/edu/pdx/cs410J/markum2/Project4.java
Porject4 cmdLine parsing completed.
Java
apache-2.0
error: pathspec 'src/main/java/org/apdplat/word/segmentation/impl/MaxNgramScore.java' did not match any file(s) known to git
cd524af42b43fac0d640197e2677f5ced0438920
1
ysc/word,ysc/word
/** * * APDPlat - Application Product Development Platform * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.apdplat.word.segmentation.impl; import org.apdplat.word.corpus.Bigram; import org.apdplat.word.recognition.RecognitionTool; import org.apdplat.word.segmentation.Segmentation; import org.apdplat.word.segmentation.Word; import java.util.*; /** * 最大Ngram分值算法 * Dictionary-based max ngram score segmentation algorithm * 最大N元模型分值算法是指从切分结果里面选择切分出来的词的ngram分值最大的结果 * 利用ngram给切分结果计算分值 * 接着按分值从大到小排序 * 然后选择第一个结果 * 如果所有切分结果都没有ngram分值 * 则算法退化为 最少词数算法(org.apdplat.word.segmentation.impl.MinimalWordCount) * @author 杨尚川 */ public class MaxNgramScore extends AbstractSegmentation{ @Override public List<Word> segImpl(String text) { //文本长度 final int textLen = text.length(); //开始虚拟节点,注意值的长度只能为1 Node start = new Node("S", 0); //首节点为0,用ngram分值作为路径 //求最长路径也就是求最大分值 start.score = 0F; //结束虚拟节点 Node end = new Node("END", textLen+1); //以文本中每一个字的位置(从1开始)作为二维数组的横坐标 //以每一个字开始所能切分出来的所有的词的顺序作为纵坐标(从0开始) Node[][] dag = new Node[textLen+2][0]; dag[0] = new Node[] { start }; dag[textLen+1] = new Node[] { end }; for(int i=0; i<textLen; i++){ dag[i+1] = fullSeg(text, i); } dumpDAG(dag); //标注路径 boolean hasNGramScore = false; int following = 0; Node node = null; for (int i = 0; i < dag.length - 1; i++) { for (int j = 0; j < dag[i].length; j++) { node = dag[i][j]; following = node.getFollowing(); for (int k = 0; k < dag[following].length; k++) { boolean result = dag[following][k].setPrevious(node); if(result){ hasNGramScore = true; } } } } if(!hasNGramScore){ if(LOGGER.isDebugEnabled()){ LOGGER.debug("所有切分结果都没有ngram分值,算法退化为 最少词数算法"); } //重置所有节点的分数 for (int i = 0; i < dag.length; i++) { for (int j = 0; j < dag[i].length; j++) { dag[i][j].setScore(null); } } //首节点分值为1,每两个词之间的距离都为1 //求最短路径也就是求最少词数 start.score = 1F; for (int i = 0; i < dag.length - 1; i++) { for (int j = 0; j < dag[i].length; j++) { node = dag[i][j]; following = node.getFollowing(); for (int k = 0; k < dag[following].length; k++) { dag[following][k].setPrevious(node, 1); } } } } dumpShortestPath(dag); return toWords(end); } /** * 反向遍历生成分词结果 * @param node 结束虚拟节点 * @return 分词结果 */ private List<Word> toWords(Node node){ Stack<String> stack = new Stack<>(); while ((node = node.getPrevious()) != null) { if(!"S".equals(node.getText())) { stack.push(node.getText()); } } int len = stack.size(); List<Word> list = new ArrayList<>(len); for(int i=0; i<len; i++){ list.add(new Word(stack.pop())); } return list; } /** * 获取以某个字符开始的小于截取长度的所有词 * @param text 文本 * @param start 起始字符索引 * @return 所有符合要求的词 */ private Node[] fullSeg(final String text, final int start) { List<Node> result = new LinkedList<>(); //增加单字词 result.add(new Node(text.substring(start, start + 1), start+1)); //文本长度 final int textLen = text.length(); //剩下文本长度 int len = textLen - start; //最大截取长度 int interceptLength = getInterceptLength(); if(len > interceptLength){ len = interceptLength; } while(len > 1){ if(getDictionary().contains(text, start, len) || RecognitionTool.recog(text, start, len)){ result.add(new Node(text.substring(start, start + len), start+1)); } len--; } return result.toArray(new Node[0]); } /** * 输出有向无环图的最佳路径 * @param dag */ private void dumpShortestPath(Node[][] dag){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("有向无环图的最佳路径:"); for (Node[] nodes : dag) { StringBuilder line = new StringBuilder(); for (Node node : nodes) { line.append("【") .append(node.getText()) .append("(").append(node.getScore()).append(")") .append("<-").append(node.getPrevious()==null?"":node.getPrevious().getText()) .append("】\t"); } LOGGER.debug(line.toString()); } } } /** * 输出有向无环图的结构 * @param dag */ private void dumpDAG(Node[][] dag){ if(LOGGER.isDebugEnabled()) { LOGGER.debug("有向无环图:"); for (int i=0; i<dag.length-1; i++) { Node[] nodes = dag[i]; StringBuilder line = new StringBuilder(); for (Node node : nodes) { int following = node.getFollowing(); StringBuilder followingNodeTexts = new StringBuilder(); for (int k = 0; k < dag[following].length; k++) { String followingNodeText = dag[following][k].getText(); followingNodeTexts.append("(").append(followingNodeText).append(")"); } line.append("【") .append(node.getText()) .append("->").append(followingNodeTexts.toString()) .append("】\t"); } LOGGER.debug(line.toString()); } } } /** * 有向无环图 的 图节点 */ private static class Node { private String text; private Node previous; private int offset; private Float score; public Node(String text, int offset) { this.text = text; this.offset = offset; } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } public Node getPrevious() { return previous; } /** * 求最大ngram分值 * @param previous 前一个节点 * @return 前一个节点到当前节点的分值是否大于0 */ public boolean setPrevious(Node previous) { float score = Bigram.getScore(previous.getText(), this.getText()); if (this.score == null) { this.score = previous.score + score; this.previous = previous; } else if (previous.score + score > this.score) { //发现更大的ngram分值 this.score = previous.score + score; this.previous = previous; } //要知道是不是所有切分结果都没有ngram分值 if(score>0){ return true; } return false; } /** * 求最短路径 * @param previous 前一个节点 * @param distance 前一个节点到当前节点的距离 */ public void setPrevious(Node previous, int distance) { if (this.score == null) { this.score = previous.score + distance; this.previous = previous; } else if (previous.score + distance < this.score) { //发现更短的路径 this.score = previous.score + distance; this.previous = previous; } } public int getFollowing() { return this.offset + text.length(); } @Override public String toString() { return "Node{" + "text='" + text + '\'' + ", previous=" + previous + ", offset=" + offset + ", score=" + score + '}'; } } public static void main(String[] args){ Segmentation segmentation = new MaxNgramScore(); if(args !=null && args.length > 0){ System.out.println(segmentation.seg(Arrays.asList(args).toString())); return; } System.out.println(segmentation.seg("独立自主和平等互利的原则")); System.out.println(segmentation.seg("我爱杨尚川")); } }
src/main/java/org/apdplat/word/segmentation/impl/MaxNgramScore.java
最大Ngram分值算法
src/main/java/org/apdplat/word/segmentation/impl/MaxNgramScore.java
最大Ngram分值算法
Java
apache-2.0
error: pathspec 'ASS.UI.Common/src/com/ass/ui/Adaptor/ContentFragmentPagerAdapter.java' did not match any file(s) known to git
7f1d62fb0b11336d13ca85825acc23a37555e8c0
1
c6supper/ASS.UI.COMMON
package com.ass.ui.Adaptor; import java.util.List; import com.ass.ui.Fragment.ContentFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.ListFragment; public class ContentFragmentPagerAdapter extends FragmentPagerAdapter { private ListFragment mFragList; public ContentFragmentPagerAdapter(FragmentManager fm) { super(fm); } public ContentFragmentPagerAdapter(FragmentManager fm,ListFragment list) { super(fm); this.mFragList = list; } @Override public Fragment getItem(int arg0) { return ContentFragment.newInstance(mFragList.get(arg0)); } @Override public int getCount() { return mFragList.size(); } @Override public CharSequence getPageTitle(int position) { // TODO Auto-generated method stub return mFragList.get(position).getTitle(); } }
ASS.UI.Common/src/com/ass/ui/Adaptor/ContentFragmentPagerAdapter.java
daily change Signed-off-by: c6supper <1bfc85538de62147e56d985f73e79abd765b1488@hotmail.com>
ASS.UI.Common/src/com/ass/ui/Adaptor/ContentFragmentPagerAdapter.java
daily change
Java
apache-2.0
error: pathspec 'graphdb/src/test/java/com/tinkerpop/blueprints/impls/orient/SimplePropertyLinkTest.java' did not match any file(s) known to git
2930ee742312511780eb453022416cf08255dcbf
1
orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb
package com.tinkerpop.blueprints.impls.orient; import com.orientechnologies.orient.core.db.record.OIdentifiable; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * Created by tglman on 28/04/16. */ public class SimplePropertyLinkTest { @Test public void testSimplePropertyLink() { OrientGraph graph = new OrientGraph("memory:" + SimplePropertyLinkTest.class.getSimpleName()); OrientVertex v1 = graph.addVertex(null); OrientVertex v2 = graph.addVertex(null); v1.setProperty("link", v2); v1.save(); v2.save(); graph.commit(); graph.getRawGraph().getLocalCache().clear(); assertTrue(((OIdentifiable) graph.getVertex(v1.getIdentity()).getProperty("link")).getIdentity().isPersistent()); } }
graphdb/src/test/java/com/tinkerpop/blueprints/impls/orient/SimplePropertyLinkTest.java
add test for missing vertex link save, issue #5355
graphdb/src/test/java/com/tinkerpop/blueprints/impls/orient/SimplePropertyLinkTest.java
add test for missing vertex link save, issue #5355
Java
apache-2.0
error: pathspec 'uberfire-workbench/uberfire-workbench-client/src/main/java/org/uberfire/client/workbench/panels/UFFlowPanel.java' did not match any file(s) known to git
c40a0cee2dfd374b78524a562ae771dce2fb8edc
1
psiroky/uberfire,porcelli-forks/uberfire,dgutierr/uberfire,mbiarnes/uberfire,mbarkley/uberfire,karreiro/uberfire,paulovmr/uberfire,qmx/uberfire,baldimir/uberfire,ederign/uberfire,wmedvede/uberfire,psiroky/uberfire,paulovmr/uberfire,cristianonicolai/uberfire,uberfire/uberfire,mbiarnes/uberfire,Salaboy/uberfire,cristianonicolai/uberfire,ederign/uberfire,dgutierr/uberfire,psiroky/uberfire,wmedvede/uberfire,uberfire/uberfire,cristianonicolai/uberfire,paulovmr/uberfire,kiereleaseuser/uberfire,mbiarnes/uberfire,dgutierr/uberfire,dgutierr/uberfire,porcelli-forks/uberfire,karreiro/uberfire,kiereleaseuser/uberfire,karreiro/uberfire,cristianonicolai/uberfire,uberfire/uberfire,kiereleaseuser/uberfire,qmx/uberfire,Salaboy/uberfire,qmx/uberfire,Salaboy/uberfire,ederign/uberfire,mbarkley/uberfire,baldimir/uberfire,baldimir/uberfire,qmx/uberfire,wmedvede/uberfire,psiroky/uberfire,porcelli-forks/uberfire,karreiro/uberfire,paulovmr/uberfire,mbarkley/uberfire,kiereleaseuser/uberfire,Salaboy/uberfire,baldimir/uberfire,ederign/uberfire,mbarkley/uberfire,wmedvede/uberfire,paulovmr/uberfire,uberfire/uberfire,mbiarnes/uberfire,porcelli-forks/uberfire
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.uberfire.client.workbench.panels; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.ui.FlowPanel; public class UFFlowPanel extends FlowPanel { /** * Creates a panel with relative positioning that fills its nearest relative or absolute positioned parent. */ public UFFlowPanel() { getElement().getStyle().setPosition( Position.RELATIVE ); getElement().getStyle().setWidth( 100, Unit.PCT ); getElement().getStyle().setHeight( 100, Unit.PCT ); } /** * Creates a panel with relative positioning that has the given fixed height in pixels, and fills the width of its * nearest relative or absolute positioned parent. */ public UFFlowPanel( int height ) { getElement().getStyle().setPosition( Position.RELATIVE ); getElement().getStyle().setWidth( 100, Unit.PCT ); getElement().getStyle().setHeight( height, Unit.PX ); } /** * Creates a panel with relative positioning that has the given fixed width and height in pixels. */ public UFFlowPanel( int width, int height ) { getElement().getStyle().setPosition( Position.RELATIVE ); getElement().getStyle().setWidth( width, Unit.PX ); getElement().getStyle().setHeight( height, Unit.PX ); } }
uberfire-workbench/uberfire-workbench-client/src/main/java/org/uberfire/client/workbench/panels/UFFlowPanel.java
Special Flow Panel (with height) required by tutorial and templated perspectives. This is related with: https://issues.jboss.org/browse/UF-185. This panel used to live as default in our archetype
uberfire-workbench/uberfire-workbench-client/src/main/java/org/uberfire/client/workbench/panels/UFFlowPanel.java
Special Flow Panel (with height) required by tutorial and templated perspectives. This is related with: https://issues.jboss.org/browse/UF-185. This panel used to live as default in our archetype
Java
bsd-3-clause
98f46bac9f181d9fc936b655a94b93634ad4288d
0
ojacobson/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,mdiggory/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,mdiggory/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo
package org.dspace.app.xmlui.aspect.submission.submit; import org.dspace.app.util.Util; import org.dspace.app.xmlui.aspect.submission.AbstractStep; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.authorize.AuthorizeException; import org.dspace.content.*; import org.dspace.core.ConfigurationManager; import org.dspace.handle.HandleManager; import org.dspace.services.ConfigurationService; import org.dspace.submit.AbstractProcessingStep; import org.dspace.workflow.DryadWorkflowUtils; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowRequirementsManager; import org.xml.sax.SAXException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.ArrayList; import java.util.UUID; /** * User: kevin (kevin at atmire.com) * Date: 8-jun-2010 * Time: 11:54:39 * Page that displays an overview of a publication & it's datasets * On this page you can edit your publication or dataset(s) * You can delete dataset(s) * You can finish up the submission */ public class OverviewStep extends AbstractStep { private static final Message T_MAIN_HEAD = message("xmlui.Submission.submit.OverviewStep.head"); private static final Message T_MAIN_HELP = message("xmlui.Submission.submit.OverviewStep.help"); private static final Message T_STEPS_HEAD_1 = message("xmlui.Submission.submit.OverviewStep.steps.1"); private static final Message T_STEPS_HEAD_2 = message("xmlui.Submission.submit.OverviewStep.steps.2"); private static final Message T_STEPS_HEAD_3 = message("xmlui.Submission.submit.OverviewStep.steps.3"); private static final Message T_STEPS_HEAD_4 = message("xmlui.Submission.submit.OverviewStep.steps.4"); private static final Message T_FINALIZE_HELP = message("xmlui.Submission.submit.OverviewStep.finalize.help"); private static final Message T_FINALIZE_BUTTON = message("xmlui.Submission.submit.OverviewStep.button.finalize"); private static final Message T_ERROR_ALL_FILES = message("xmlui.Submission.submit.OverviewStep.error.finalize.all-files"); private static final Message T_ERROR_ONE_FILE = message("xmlui.Submission.submit.OverviewStep.error.finalize.one-file"); private static final Message T_BUTTON_PUBLICATION_DELETE = message("xmlui.Submission.submit.OverviewStep.button.delete-datapackage"); private static final Message T_BUTTON_PUBLICATION_EDIT = message("xmlui.Submission.submit.OverviewStep.button.edit-datapackage"); private static final Message T_BUTTON_DATAFILE_ADD = message("xmlui.Submission.submit.OverviewStep.button.add-datafile"); private static final Message T_BUTTON_DATAFILE_EDIT = message("xmlui.Submission.submit.OverviewStep.button.datafile.edit"); private static final Message T_BUTTON_DATAFILE_DELETE = message("xmlui.Submission.submit.OverviewStep.button.datafile.delete"); private static final Message T_BUTTON_DATAFILE_CONTINUE = message("xmlui.Submission.submit.OverviewStep.button.datafile.continue"); private static final Message T_STEPS_HEAD_GENBANK = message("xmlui.Submission.submit.OverviewStep.headgenbank"); private static final Message T_GENBANK_HELP = message("xmlui.Submission.submit.OverviewStep.genbankhelp"); private static final Message T_GENBANK_BUTTON = message("xmlui.Submission.submit.OverviewStep.button.genbank"); @Override public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Collection collection = submission.getCollection(); String actionURL = contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId() + ".continue"; Division mainDiv = body.addDivision("submit-completed-dataset", actionURL, Division.METHOD_POST, "primary submission"); Division helpDivision = mainDiv.addDivision("submit-help"); helpDivision.setHead(T_MAIN_HEAD); helpDivision.addPara(T_MAIN_HELP); Division actionsDiv = mainDiv.addDivision("submit-completed-overview"); org.dspace.content.Item publication = DryadWorkflowUtils.getDataPackage(context, submission.getItem()); if(publication == null) publication = submission.getItem(); //First of all add all the publication info { Division pubDiv = actionsDiv.addDivision("puboverviewdivision", "odd subdiv"); pubDiv.addPara("pub-label", "bold").addContent(T_STEPS_HEAD_1); //TODO: expand this ! pubDiv.addPara().addXref(HandleManager.resolveToURL(context, publication.getHandle()), publication.getName()); //add an edit button for the publication (if we aren't archived) if(!publication.isArchived()){ Para actionsPara = pubDiv.addPara(); actionsPara.addButton("submit_edit_publication").setValue(T_BUTTON_PUBLICATION_EDIT); if((submission instanceof WorkspaceItem)){ WorkspaceItem pubWsItem = WorkspaceItem.findByItemId(context, publication.getID()); actionsPara.addButton("submit_delete_datapack_" + pubWsItem.getID()).setValue(T_BUTTON_PUBLICATION_DELETE); } if(submission instanceof WorkflowItem){ //For a curator add an edit metadata button actionsPara.addButton("submit_edit_metadata_" + submission.getID()).setValue(message("xmlui.Submission.Submissions.OverviewStep.edit-metadata-pub")); } } } //A boolean set to true if we have dataset that is not fully submitted, BUT has been linked to the publication boolean submissionNotFinished = false; boolean noDatasets = false; org.dspace.content.Item[] datasets = DryadWorkflowUtils.getDataFiles(context, publication); //Second add info & edit/delete buttons for all our data files { Division dataDiv = actionsDiv.addDivision("dataoverviewdivision", "even subdiv"); //First of all add the current one ! dataDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_2); List dataSetList = dataDiv.addList("datasets"); if(datasets.length == 0) noDatasets = true; if(publication.isArchived()){ //Add the current dataset, since our publication is archived this will probally be the only one ! submissionNotFinished = renderDatasetItem(submissionNotFinished, dataSetList, submission.getItem(), (WorkspaceItem) submission); } for (org.dspace.content.Item dataset : datasets) { //Our current item has already been added InProgressSubmission wsDataset; if(submissionInfo.getSubmissionItem() instanceof WorkspaceItem) wsDataset = WorkspaceItem.findByItemId(context, dataset.getID()); else wsDataset = WorkflowItem.findByItemId(context, dataset.getID()); //Only add stuff IF we have a workspaceitem if(wsDataset != null){ submissionNotFinished = renderDatasetItem(submissionNotFinished, dataSetList, dataset, wsDataset); } } Item addDataFileItem = dataSetList.addItem(); addDataFileItem.addButton("submit_adddataset").setValue(T_BUTTON_DATAFILE_ADD); } //Thirdly add the the upload data files to external repos (this is optional) // Commented out because there is a bug somewhere in this code -- Clicking the checkbox for TreeBASE upload causes the Tomcat server to crash! /* { if(submission instanceof WorkspaceItem){ java.util.List<Bitstream> toUploadFiles = new ArrayList<Bitstream>(); for (org.dspace.content.Item dataset : datasets) { Bundle[] orignalBundles = dataset.getBundles("ORIGINAL"); if(orignalBundles != null){ for (Bundle bundle : orignalBundles) { if(bundle != null){ Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { toUploadFiles.add(bit); } } } } } if(0 < toUploadFiles.size()){ Division uploadDiv = actionsDiv.addDivision("uploadexternaldivision", "odd subdiv"); uploadDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_3); List fileList = uploadDiv.addList("upload-external-list"); for (Bitstream bitstream : toUploadFiles) { org.dspace.content.Item item = bitstream.getBundles()[0].getItems()[0]; Item externalItem = fileList.addItem(); externalItem.addCheckBox("export_item").addOption(false, item.getHandle(), ""); String identifier; if (item.getHandle() != null) identifier = "handle/"+item.getHandle(); else if (item != null) identifier = "item/"+item.getID(); else identifier = "id/"+bitstream.getID(); String url = contextPath + "/bitstream/"+identifier+"/"; // If we can put the pretty name of the bitstream on the end of the URL try { if (bitstream.getName() != null) url += Util.encodeBitstreamName(bitstream.getName(), "UTF-8"); } catch (UnsupportedEncodingException uee) { // just ignore it, we don't have to have a pretty // name on the end of the url because the sequence id will // locate it. However it means that links in this file might // not work.... } url += "?sequence="+bitstream.getSequenceID(); externalItem.addXref(url, bitstream.getName()); Select repoSelect = externalItem.addSelect("repo_name_" + item.getHandle()); for(String repo : DCRepositoryFile.repoConfigLocations) repoSelect.addOption(repo, repo); } } } } */ // Add GenBank button // Division genBankDiv = actionsDiv.addDivision("genbankdivision", "odd subdiv"); // if(submission instanceof WorkspaceItem){ // genBankDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_GENBANK); // genBankDiv.addPara().addContent(T_GENBANK_HELP); // // String token = generateTokenAndAddToMetadata(); // // String url= ConfigurationManager.getProperty("genbank.url") + "/?tool=genbank&dryadID=" + publication.getMetadata("dc.identifier")[0].value + "&ticket=" + token; // genBankDiv.addPara().addHidden("genbank_url").setValue(url); // genBankDiv.addPara().addButton("submit_genbank").setValue(T_GENBANK_BUTTON); // } //Lastly add the finalize submission button { Division finDiv = actionsDiv.addDivision("finalizedivision", (submission instanceof WorkspaceItem ? "even" : "odd") + " subdiv"); if(submission instanceof WorkspaceItem){ finDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_4); finDiv.addPara().addContent(T_FINALIZE_HELP); Button finishButton = finDiv.addPara().addButton(AbstractProcessingStep.NEXT_BUTTON); finishButton.setValue(T_FINALIZE_BUTTON); if(submissionNotFinished || noDatasets){ finishButton.setDisabled(true); if(submissionNotFinished) finishButton.addError(T_ERROR_ALL_FILES); else finishButton.addError(T_ERROR_ONE_FILE); } } else { // finDiv.addPara().addButton("submit_cancel").setValue(message("xmlui.general.return")); } } } private String generateTokenAndAddToMetadata() throws SQLException, AuthorizeException { String randomKey = null; DCValue[] values = submission.getItem().getMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA + ".genbank.token"); if(values!=null && values.length > 0){ randomKey = values[0].value; } else{ UUID uuid = UUID.randomUUID(); submission.getItem().addMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, "genbank", "token", null, uuid.toString()); submission.getItem().update(); randomKey = uuid.toString(); } return randomKey; } private boolean renderDatasetItem(boolean submissionNotFinished, List dataSetList, org.dspace.content.Item dataset, InProgressSubmission wsDataset) throws WingException, SQLException { Item dataItem = dataSetList.addItem(); String datasetTitle = wsDataset.getItem().getName(); if(datasetTitle == null) datasetTitle = "Untitled"; dataItem.addXref(HandleManager.resolveToURL(context, dataset.getHandle()), datasetTitle); Button editButton = dataItem.addButton("submit_edit_dataset_" + wsDataset.getID()); //To determine which name our button is getting check if we are through submission with this if(dataset.getMetadata("internal", "workflow", "submitted", org.dspace.content.Item.ANY).length == 0 && (wsDataset instanceof WorkspaceItem)){ editButton.setValue(T_BUTTON_DATAFILE_CONTINUE); submissionNotFinished = true; } else editButton.setValue(T_BUTTON_DATAFILE_EDIT); if(wsDataset instanceof WorkflowItem){ dataItem.addButton("submit_edit_metadata_" + wsDataset.getID()).setValue(message("xmlui.Submission.Submissions.OverviewStep.edit-metadata-dataset")); } dataItem.addButton("submit_delete_dataset_" + wsDataset.getID()).setValue(T_BUTTON_DATAFILE_DELETE); return submissionNotFinished; } }
dspace/modules/xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/OverviewStep.java
package org.dspace.app.xmlui.aspect.submission.submit; import org.dspace.app.util.Util; import org.dspace.app.xmlui.aspect.submission.AbstractStep; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.*; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.authorize.AuthorizeException; import org.dspace.content.*; import org.dspace.core.ConfigurationManager; import org.dspace.handle.HandleManager; import org.dspace.services.ConfigurationService; import org.dspace.submit.AbstractProcessingStep; import org.dspace.workflow.DryadWorkflowUtils; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowRequirementsManager; import org.xml.sax.SAXException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.ArrayList; import java.util.UUID; /** * User: kevin (kevin at atmire.com) * Date: 8-jun-2010 * Time: 11:54:39 * Page that displays an overview of a publication & it's datasets * On this page you can edit your publication or dataset(s) * You can delete dataset(s) * You can finish up the submission */ public class OverviewStep extends AbstractStep { private static final Message T_MAIN_HEAD = message("xmlui.Submission.submit.OverviewStep.head"); private static final Message T_MAIN_HELP = message("xmlui.Submission.submit.OverviewStep.help"); private static final Message T_STEPS_HEAD_1 = message("xmlui.Submission.submit.OverviewStep.steps.1"); private static final Message T_STEPS_HEAD_2 = message("xmlui.Submission.submit.OverviewStep.steps.2"); private static final Message T_STEPS_HEAD_3 = message("xmlui.Submission.submit.OverviewStep.steps.3"); private static final Message T_STEPS_HEAD_4 = message("xmlui.Submission.submit.OverviewStep.steps.4"); private static final Message T_FINALIZE_HELP = message("xmlui.Submission.submit.OverviewStep.finalize.help"); private static final Message T_FINALIZE_BUTTON = message("xmlui.Submission.submit.OverviewStep.button.finalize"); private static final Message T_ERROR_ALL_FILES = message("xmlui.Submission.submit.OverviewStep.error.finalize.all-files"); private static final Message T_ERROR_ONE_FILE = message("xmlui.Submission.submit.OverviewStep.error.finalize.one-file"); private static final Message T_BUTTON_PUBLICATION_DELETE = message("xmlui.Submission.submit.OverviewStep.button.delete-datapackage"); private static final Message T_BUTTON_PUBLICATION_EDIT = message("xmlui.Submission.submit.OverviewStep.button.edit-datapackage"); private static final Message T_BUTTON_DATAFILE_ADD = message("xmlui.Submission.submit.OverviewStep.button.add-datafile"); private static final Message T_BUTTON_DATAFILE_EDIT = message("xmlui.Submission.submit.OverviewStep.button.datafile.edit"); private static final Message T_BUTTON_DATAFILE_DELETE = message("xmlui.Submission.submit.OverviewStep.button.datafile.delete"); private static final Message T_BUTTON_DATAFILE_CONTINUE = message("xmlui.Submission.submit.OverviewStep.button.datafile.continue"); private static final Message T_STEPS_HEAD_GENBANK = message("xmlui.Submission.submit.OverviewStep.headgenbank"); private static final Message T_GENBANK_HELP = message("xmlui.Submission.submit.OverviewStep.genbankhelp"); private static final Message T_GENBANK_BUTTON = message("xmlui.Submission.submit.OverviewStep.button.genbank"); @Override public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { Collection collection = submission.getCollection(); String actionURL = contextPath + "/handle/" + collection.getHandle() + "/submit/" + knot.getId() + ".continue"; Division mainDiv = body.addInteractiveDivision("submit-completed-dataset", actionURL, Division.METHOD_POST, "primary submission"); Division helpDivision = mainDiv.addDivision("submit-help"); helpDivision.setHead(T_MAIN_HEAD); helpDivision.addPara(T_MAIN_HELP); Division actionsDiv = mainDiv.addDivision("submit-completed-overview"); org.dspace.content.Item publication = DryadWorkflowUtils.getDataPackage(context, submission.getItem()); if(publication == null) publication = submission.getItem(); //First of all add all the publication info { Division pubDiv = actionsDiv.addDivision("puboverviewdivision", "odd subdiv"); pubDiv.addPara("pub-label", "bold").addContent(T_STEPS_HEAD_1); //TODO: expand this ! pubDiv.addPara().addXref(HandleManager.resolveToURL(context, publication.getHandle()), publication.getName()); //add an edit button for the publication (if we aren't archived) if(!publication.isArchived()){ Para actionsPara = pubDiv.addPara(); actionsPara.addButton("submit_edit_publication").setValue(T_BUTTON_PUBLICATION_EDIT); if((submission instanceof WorkspaceItem)){ WorkspaceItem pubWsItem = WorkspaceItem.findByItemId(context, publication.getID()); actionsPara.addButton("submit_delete_datapack_" + pubWsItem.getID()).setValue(T_BUTTON_PUBLICATION_DELETE); } if(submission instanceof WorkflowItem){ //For a curator add an edit metadata button actionsPara.addButton("submit_edit_metadata_" + submission.getID()).setValue(message("xmlui.Submission.Submissions.OverviewStep.edit-metadata-pub")); } } } //A boolean set to true if we have dataset that is not fully submitted, BUT has been linked to the publication boolean submissionNotFinished = false; boolean noDatasets = false; org.dspace.content.Item[] datasets = DryadWorkflowUtils.getDataFiles(context, publication); //Second add info & edit/delete buttons for all our data files { Division dataDiv = actionsDiv.addDivision("dataoverviewdivision", "even subdiv"); //First of all add the current one ! dataDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_2); List dataSetList = dataDiv.addList("datasets"); if(datasets.length == 0) noDatasets = true; if(publication.isArchived()){ //Add the current dataset, since our publication is archived this will probally be the only one ! submissionNotFinished = renderDatasetItem(submissionNotFinished, dataSetList, submission.getItem(), (WorkspaceItem) submission); } for (org.dspace.content.Item dataset : datasets) { //Our current item has already been added InProgressSubmission wsDataset; if(submissionInfo.getSubmissionItem() instanceof WorkspaceItem) wsDataset = WorkspaceItem.findByItemId(context, dataset.getID()); else wsDataset = WorkflowItem.findByItemId(context, dataset.getID()); //Only add stuff IF we have a workspaceitem if(wsDataset != null){ submissionNotFinished = renderDatasetItem(submissionNotFinished, dataSetList, dataset, wsDataset); } } Item addDataFileItem = dataSetList.addItem(); addDataFileItem.addButton("submit_adddataset").setValue(T_BUTTON_DATAFILE_ADD); } //Thirdly add the the upload data files to external repos (this is optional) // Commented out because there is a bug somewhere in this code -- Clicking the checkbox for TreeBASE upload causes the Tomcat server to crash! /* { if(submission instanceof WorkspaceItem){ java.util.List<Bitstream> toUploadFiles = new ArrayList<Bitstream>(); for (org.dspace.content.Item dataset : datasets) { Bundle[] orignalBundles = dataset.getBundles("ORIGINAL"); if(orignalBundles != null){ for (Bundle bundle : orignalBundles) { if(bundle != null){ Bitstream[] bits = bundle.getBitstreams(); for (Bitstream bit : bits) { toUploadFiles.add(bit); } } } } } if(0 < toUploadFiles.size()){ Division uploadDiv = actionsDiv.addDivision("uploadexternaldivision", "odd subdiv"); uploadDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_3); List fileList = uploadDiv.addList("upload-external-list"); for (Bitstream bitstream : toUploadFiles) { org.dspace.content.Item item = bitstream.getBundles()[0].getItems()[0]; Item externalItem = fileList.addItem(); externalItem.addCheckBox("export_item").addOption(false, item.getHandle(), ""); String identifier; if (item.getHandle() != null) identifier = "handle/"+item.getHandle(); else if (item != null) identifier = "item/"+item.getID(); else identifier = "id/"+bitstream.getID(); String url = contextPath + "/bitstream/"+identifier+"/"; // If we can put the pretty name of the bitstream on the end of the URL try { if (bitstream.getName() != null) url += Util.encodeBitstreamName(bitstream.getName(), "UTF-8"); } catch (UnsupportedEncodingException uee) { // just ignore it, we don't have to have a pretty // name on the end of the url because the sequence id will // locate it. However it means that links in this file might // not work.... } url += "?sequence="+bitstream.getSequenceID(); externalItem.addXref(url, bitstream.getName()); Select repoSelect = externalItem.addSelect("repo_name_" + item.getHandle()); for(String repo : DCRepositoryFile.repoConfigLocations) repoSelect.addOption(repo, repo); } } } } */ // Add GenBank button // Division genBankDiv = actionsDiv.addDivision("genbankdivision", "odd subdiv"); // if(submission instanceof WorkspaceItem){ // genBankDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_GENBANK); // genBankDiv.addPara().addContent(T_GENBANK_HELP); // // String token = generateTokenAndAddToMetadata(); // // String url= ConfigurationManager.getProperty("genbank.url") + "/?tool=genbank&dryadID=" + publication.getMetadata("dc.identifier")[0].value + "&ticket=" + token; // genBankDiv.addPara().addHidden("genbank_url").setValue(url); // genBankDiv.addPara().addButton("submit_genbank").setValue(T_GENBANK_BUTTON); // } //Lastly add the finalize submission button { Division finDiv = actionsDiv.addDivision("finalizedivision", (submission instanceof WorkspaceItem ? "even" : "odd") + " subdiv"); if(submission instanceof WorkspaceItem){ finDiv.addPara("data-label", "bold").addContent(T_STEPS_HEAD_4); finDiv.addPara().addContent(T_FINALIZE_HELP); Button finishButton = finDiv.addPara().addButton(AbstractProcessingStep.NEXT_BUTTON); finishButton.setValue(T_FINALIZE_BUTTON); if(submissionNotFinished || noDatasets){ finishButton.setDisabled(true); if(submissionNotFinished) finishButton.addError(T_ERROR_ALL_FILES); else finishButton.addError(T_ERROR_ONE_FILE); } } else { // finDiv.addPara().addButton("submit_cancel").setValue(message("xmlui.general.return")); } } } private String generateTokenAndAddToMetadata() throws SQLException, AuthorizeException { String randomKey = null; DCValue[] values = submission.getItem().getMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA + ".genbank.token"); if(values!=null && values.length > 0){ randomKey = values[0].value; } else{ UUID uuid = UUID.randomUUID(); submission.getItem().addMetadata(WorkflowRequirementsManager.WORKFLOW_SCHEMA, "genbank", "token", null, uuid.toString()); submission.getItem().update(); randomKey = uuid.toString(); } return randomKey; } private boolean renderDatasetItem(boolean submissionNotFinished, List dataSetList, org.dspace.content.Item dataset, InProgressSubmission wsDataset) throws WingException, SQLException { Item dataItem = dataSetList.addItem(); String datasetTitle = wsDataset.getItem().getName(); if(datasetTitle == null) datasetTitle = "Untitled"; dataItem.addXref(HandleManager.resolveToURL(context, dataset.getHandle()), datasetTitle); Button editButton = dataItem.addButton("submit_edit_dataset_" + wsDataset.getID()); //To determine which name our button is getting check if we are through submission with this if(dataset.getMetadata("internal", "workflow", "submitted", org.dspace.content.Item.ANY).length == 0 && (wsDataset instanceof WorkspaceItem)){ editButton.setValue(T_BUTTON_DATAFILE_CONTINUE); submissionNotFinished = true; } else editButton.setValue(T_BUTTON_DATAFILE_EDIT); if(wsDataset instanceof WorkflowItem){ dataItem.addButton("submit_edit_metadata_" + wsDataset.getID()).setValue(message("xmlui.Submission.Submissions.OverviewStep.edit-metadata-dataset")); } dataItem.addButton("submit_delete_dataset_" + wsDataset.getID()).setValue(T_BUTTON_DATAFILE_DELETE); return submissionNotFinished; } }
Crude fix for nested boxes in Submission Overview page
dspace/modules/xmlui/src/main/java/org/dspace/app/xmlui/aspect/submission/submit/OverviewStep.java
Crude fix for nested boxes in Submission Overview page
Java
bsd-3-clause
error: pathspec 'src/com/vmware/vim25/mo/samples/QueryEvent.java' did not match any file(s) known to git
59215a2081aaa8a9ee3b90d9ed65dd85591cb915
1
omar-infinio/yavijava,yavijava/yavijava-samples,n4ybn/yavijava,yavijava/yavijava,vThinkBeyondVM/yavijava-samples,michaelrice/yavijava,vmware-serengeti/yavijava-samples,hubertverstraete/yavijava,vmware-serengeti/yavijava-samples,yavijava/yavijava-samples
/*================================================================================ Copyright (c) 2008 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25.mo.samples; import java.net.URL; import com.vmware.vim25.Event; import com.vmware.vim25.EventFilterSpec; import com.vmware.vim25.mo.EventHistoryCollector; import com.vmware.vim25.mo.EventManager; import com.vmware.vim25.mo.ServiceInstance; import com.vmware.vim25.mo.util.CommandLineParser; import com.vmware.vim25.mo.util.OptionSpec; /** * This sample shows you how to get filtered events from VC * * @author Tom Elliott (twelliott - telliott@vmware.com) * */ public class QueryEvent { private static void usage() { System.err.println("Usage: QueryEvent server username password"); } public static void main(String[] args) throws Exception { if (args.length != 3) { usage(); return; } String urlStr = args[0]; String username = args[1]; String password = args[2]; System.out.println("Connecting to " + urlStr + " as " + username); ServiceInstance si = new ServiceInstance(new URL(urlStr), username, password, true); System.out.println("info---" + si.getAboutInfo().getFullName()); // Displays all the Events with Full Formatted message try { EventManager _eventManager = si.getEventManager(); EventFilterSpec eventFilter = new EventFilterSpec(); EventHistoryCollector history = _eventManager .createCollectorForEvents(eventFilter); Event[] events = history.getLastPage(); System.out.println("Events In the latestPage are : "); for (int i = 0; i < events.length; i++) { Event anEvent = events[i]; System.out.println("Event: " + anEvent.getClass().getName() + " FullFormattedMessage: " + anEvent.getFullFormattedMessage()); } } catch (Exception e) { System.out.println("Caught Exception : " + " Name : " + e.getClass().getName() + " Message : " + e.getMessage() + " Trace : "); e.printStackTrace(); } si.getServerConnection().logout(); } }
src/com/vmware/vim25/mo/samples/QueryEvent.java
Add Tom's new sample code
src/com/vmware/vim25/mo/samples/QueryEvent.java
Add Tom's new sample code
Java
bsd-3-clause
error: pathspec 'src/main/java/com/game30/javagl/buffers/GLBufferType.java' did not match any file(s) known to git
b0817d184cec9818beb6b52ff81f4caac57120e5
1
game-30/javagl
package com.game30.javagl.buffers; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL15; /** * An enumeration of the different primitive types which an OpenGL buffer can store. * * <p />This is sort of a hack class that gets around the restrictive nature of the LWJGL methods which only allow * specific types of {@link Buffer}s to be passed to the buffer write and read methods. Each enumeration value contains * the behavior corresponding to the specific buffer type it represents. * * @author Brian Norman * @version 1.0.0-SNAPSHOT * @since 1.0.0 */ public enum GLBufferType { /** * Byte primitive buffer type corresponding to the {@link ByteBuffer}. */ Byte() { @Override int getByteShift() { return 0; } @Override ByteBuffer readFromBuffer(GLBufferTarget target, long offset, int length) { ByteBuffer data = BufferUtils.createByteBuffer(length); GL15.glGetBufferSubData(target.glInt(), offset, data); return data; } @Override void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage) { GL15.glBufferData(target.glInt(), (ByteBuffer) data, usage.glInt()); } }, /** * Short primitive buffer type corresponding to the {@link ShortBuffer}. */ Short() { @Override int getByteShift() { return 1; } @Override ShortBuffer readFromBuffer(GLBufferTarget target, long offset, int length) { ShortBuffer data = BufferUtils.createShortBuffer(length); GL15.glGetBufferSubData(target.glInt(), offset, data); return data; } @Override void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage) { GL15.glBufferData(target.glInt(), (ShortBuffer) data, usage.glInt()); } }, /** * Integer primitive buffer type corresponding to the {@link IntBuffer}. */ Integer() { @Override int getByteShift() { return 2; } @Override IntBuffer readFromBuffer(GLBufferTarget target, long offset, int length) { IntBuffer data = BufferUtils.createIntBuffer(length); GL15.glGetBufferSubData(target.glInt(), offset, data); return data; } @Override void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage) { GL15.glBufferData(target.glInt(), (IntBuffer) data, usage.glInt()); } }, /** * Float primitive buffer type corresponding to the {@link FloatBuffer}. */ Float() { @Override int getByteShift() { return 2; } @Override FloatBuffer readFromBuffer(GLBufferTarget target, long offset, int length) { FloatBuffer data = BufferUtils.createFloatBuffer(length); GL15.glGetBufferSubData(target.glInt(), offset, data); return data; } @Override void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage) { GL15.glBufferData(target.glInt(), (FloatBuffer) data, usage.glInt()); } }, /** * Double primitive buffer type corresponding to the {@link DoubleBuffer}. */ Double() { @Override int getByteShift() { return 3; } @Override DoubleBuffer readFromBuffer(GLBufferTarget target, long offset, int length) { DoubleBuffer data = BufferUtils.createDoubleBuffer(length); GL15.glGetBufferSubData(target.glInt(), offset, data); return data; } @Override void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage) { GL15.glBufferData(target.glInt(), (DoubleBuffer) data, usage.glInt()); } }, // End of enumeration ; /** * Returns the buffer primitive type of the specified buffer. * * @param buffer the buffer data. * @return buffer primitive type. * @throws GLBufferException when there is no match to a buffer primitive type. */ public static GLBufferType getType(Buffer buffer) { if (ByteBuffer.class.isInstance(buffer)) { return GLBufferType.Byte; } else if (FloatBuffer.class.isInstance(buffer)) { return GLBufferType.Float; } else if (IntBuffer.class.isInstance(buffer)) { return GLBufferType.Integer; } else if (DoubleBuffer.class.isInstance(buffer)) { return GLBufferType.Double; } else if (Short.class.isInstance(buffer)) { return GLBufferType.Short; } else { throw new GLBufferException("Specified buffer [" + buffer + "] is not a supported OpenGL buffer type"); } } /** * Returns the byte shift value of the buffer primitive type. This is the value used to shift the number of * elements to either convert to or from the number of byte elements. * * @return byte shift value. */ abstract int getByteShift(); /** * Converts the specified size of the buffer primitive type to the size of the buffer if it were bytes. * * @param size the size of the buffer. * @return the size of the byte buffer. */ int toByteSize(int size) { return size << getByteShift(); } /** * Converts the specified size of a byte buffer to the size of the buffer if it were of the primitive type. * * @param byteSize the size of the byte buffer. * @return the size of the primitive type buffer. */ int fromByteSize(int byteSize) { return byteSize >> getByteShift(); } /** * Reads the buffer bound to the specified target starting from the specified offset and for the specified length. * * @param target buffer target to read. * @param offset offset to start reading. * @param length length to read. * @return the data read from the bound buffer. */ abstract Buffer readFromBuffer(GLBufferTarget target, long offset, int length); /** * Writes the specified buffer data too the buffer bound to the specified target with the specified usage pattern. * * @param target buffer target to write. * @param data data to write to the bound buffer. * @param usage usage pattern to set on the bound buffer. */ abstract void writeToBuffer(GLBufferTarget target, Buffer data, GLBufferUsage usage); }
src/main/java/com/game30/javagl/buffers/GLBufferType.java
New enumeration for buffer primitive types LWJGL only allows certain types of data to be loaded into OpenGL buffers. These take the form of different methods to require different types of Java Buffers. This enumeration abstracts each of those specific methods to an enumeration value. It's sort of a hack and should be discussed some more. Later.
src/main/java/com/game30/javagl/buffers/GLBufferType.java
New enumeration for buffer primitive types
Java
mit
96d98239079fc3bb8f705ec4a46d95fd68c36ef7
0
CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main
package seedu.ezdo.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.ezdo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.ezdo.model.todo.DueDate.MESSAGE_DUEDATE_CONSTRAINTS; import static seedu.ezdo.model.todo.Priority.MESSAGE_PRIORITY_CONSTRAINTS; import static seedu.ezdo.model.todo.StartDate.MESSAGE_STARTDATE_CONSTRAINTS; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.ezdo.commons.core.EventsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.ui.JumpToListRequestEvent; import seedu.ezdo.commons.events.ui.ShowHelpRequestEvent; import seedu.ezdo.logic.commands.AddCommand; import seedu.ezdo.logic.commands.ClearCommand; import seedu.ezdo.logic.commands.Command; import seedu.ezdo.logic.commands.CommandResult; import seedu.ezdo.logic.commands.DeleteCommand; import seedu.ezdo.logic.commands.ExitCommand; import seedu.ezdo.logic.commands.FindCommand; import seedu.ezdo.logic.commands.HelpCommand; import seedu.ezdo.logic.commands.ListCommand; import seedu.ezdo.logic.commands.SelectCommand; import seedu.ezdo.logic.commands.exceptions.CommandException; import seedu.ezdo.model.EzDo; import seedu.ezdo.model.Model; import seedu.ezdo.model.ModelManager; import seedu.ezdo.model.ReadOnlyEzDo; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.tag.UniqueTagList; import seedu.ezdo.model.todo.DueDate; import seedu.ezdo.model.todo.Name; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyTask; import seedu.ezdo.model.todo.StartDate; import seedu.ezdo.model.todo.Task; import seedu.ezdo.storage.StorageManager; public class LogicManagerTest { /** * See https://github.com/junit-team/junit4/wiki/rules#temporaryfolder-rule */ @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyEzDo latestSavedEzDo; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(EzDoChangedEvent ezce) { latestSavedEzDo = new EzDo(ezce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempEzDoFile = saveFolder.getRoot().getPath() + "TempEzDo.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempEzDoFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedEzDo = new EzDo(model.getEzDo()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'ezDo' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyEzDo expectedEzDo, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedEzDo, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'ezDo' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { EzDo expectedEzDo = new EzDo(model.getEzDo()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedEzDo, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal ezDo data are same as those in the {@code expectedEzDo} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedEzDo} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyEzDo expectedEzDo, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedEzDo, model.getEzDo()); assertEquals(expectedEzDo, latestSavedEzDo); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new EzDo(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new EzDo(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new EzDo(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { assertCommandFailure("add Valid Name p/1" + ", todo d/s23/03/2017", MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 " + "s/abcd d/24/04/2017", MESSAGE_STARTDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 " + "s/12/12/2013 d/999", MESSAGE_DUEDATE_CONSTRAINTS); } @Test public void execute_add_invalidPersonData() { assertCommandFailure("add []\\[;] p/3 s/30/03/1999 d/31/05/1999 t/invalidName", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add Valid Name p/not_numbers s/01/08/1998 d/11/08/1998 t/invalidPriority", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Name p/2 s/Invalid_Start.Date d/11/08/1998 t/invalidStartDate", StartDate.MESSAGE_STARTDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 s/01/08/1998 d/invalid_DueDate. t/invalidDueDate", DueDate.MESSAGE_DUEDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 s/01/01/1990 d/01/03/1990 t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); EzDo expectedEZ = new EzDo(); expectedEZ.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedEZ, expectedEZ.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal ezDo // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); EzDo expectedEZ = helper.generateEzDo(2); List<? extends ReadOnlyTask> expectedList = expectedEZ.getTaskList(); // prepare ezDo state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedEZ, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new EzDo()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); EzDo expectedEZ = helper.generateEzDo(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedEZ, expectedEZ.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); EzDo expectedEZ = helper.generateEzDo(threeTasks); expectedEZ.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedEZ, expectedEZ.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { private Task adam() throws Exception { Name name = new Name("Adam Brown"); Priority privatePriority = new Priority("1"); StartDate privateStartDate = new StartDate("3/3/2017"); DueDate privateDueDate = new DueDate("16/06/2016"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, privatePriority, privateStartDate, privateDueDate, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ private Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new Priority("1"), new StartDate("01/01/2000"), new DueDate("07/07/2007"), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ private String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" p/").append(p.getPriority()); cmd.append(" s/").append(p.getStartDate()); cmd.append(" d/").append(p.getDueDate()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an EzDo with auto-generated tasks. */ private EzDo generateEzDo(int numGenerated) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, numGenerated); return ezDo; } /** * Generates an EzDo based on the list of Tasks given. */ private EzDo generateEzDo(List<Task> tasks) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, tasks); return ezDo; } /** * Adds auto-generated Task objects to the given EzDo * @param ezDo The EzDo to which the Tasks will be added */ private void addToEzDo(EzDo ezDo, int numGenerated) throws Exception { addToEzDo(ezDo, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given EzDo */ private void addToEzDo(EzDo ezDo, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { ezDo.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ private void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ private void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ private List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } private List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ private Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new Priority("1"), new StartDate("1/1/2017"), new DueDate("09/09/2009"), new UniqueTagList(new Tag("tag")) ); } } }
src/test/java/seedu/ezdo/logic/LogicManagerTest.java
package seedu.ezdo.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.ezdo.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.ezdo.model.todo.DueDate.MESSAGE_DUEDATE_CONSTRAINTS; import static seedu.ezdo.model.todo.Priority.MESSAGE_PRIORITY_CONSTRAINTS; import static seedu.ezdo.model.todo.StartDate.MESSAGE_STARTDATE_CONSTRAINTS; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.ezdo.commons.core.EventsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.ui.JumpToListRequestEvent; import seedu.ezdo.commons.events.ui.ShowHelpRequestEvent; import seedu.ezdo.logic.commands.AddCommand; import seedu.ezdo.logic.commands.ClearCommand; import seedu.ezdo.logic.commands.Command; import seedu.ezdo.logic.commands.CommandResult; import seedu.ezdo.logic.commands.DeleteCommand; import seedu.ezdo.logic.commands.ExitCommand; import seedu.ezdo.logic.commands.FindCommand; import seedu.ezdo.logic.commands.HelpCommand; import seedu.ezdo.logic.commands.ListCommand; import seedu.ezdo.logic.commands.SelectCommand; import seedu.ezdo.logic.commands.exceptions.CommandException; import seedu.ezdo.model.EzDo; import seedu.ezdo.model.Model; import seedu.ezdo.model.ModelManager; import seedu.ezdo.model.ReadOnlyEzDo; import seedu.ezdo.model.tag.Tag; import seedu.ezdo.model.tag.UniqueTagList; import seedu.ezdo.model.todo.DueDate; import seedu.ezdo.model.todo.Name; import seedu.ezdo.model.todo.Priority; import seedu.ezdo.model.todo.ReadOnlyTask; import seedu.ezdo.model.todo.StartDate; import seedu.ezdo.model.todo.Task; import seedu.ezdo.storage.StorageManager; public class LogicManagerTest { /** * See https://github.com/junit-team/junit4/wiki/rules#temporaryfolder-rule */ @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyEzDo latestSavedEzDo; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(EzDoChangedEvent ezce) { latestSavedEzDo = new EzDo(ezce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempEzDoFile = saveFolder.getRoot().getPath() + "TempEzDo.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempEzDoFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedEzDo = new EzDo(model.getEzDo()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'ezDo' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyEzDo expectedEzDo, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedEzDo, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'ezDo' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyEzDo, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { EzDo expectedEzDo = new EzDo(model.getEzDo()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedEzDo, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal ezDo data are same as those in the {@code expectedEzDo} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedEzDo} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyEzDo expectedEzDo, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedEzDo, model.getEzDo()); assertEquals(expectedEzDo, latestSavedEzDo); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new EzDo(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new EzDo(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new EzDo(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { assertCommandFailure("add Valid Name p/1" + ", todo d/s23/03/2017", MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 " + "s/abcd d/24/04/2017", MESSAGE_STARTDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 " + "s/12/12/2013 d/999", MESSAGE_DUEDATE_CONSTRAINTS); } @Test public void execute_add_invalidPersonData() { assertCommandFailure("add []\\[;] p/3 s/30/03/1999 d/31/05/1999 t/invalidName", Name.MESSAGE_NAME_CONSTRAINTS) assertCommandFailure("add Valid Name p/not_numbers s/01/08/1998 d/11/08/1998 t/invalidPriority", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add Valid Name p/2 s/Invalid_Start.Date d/11/08/1998 t/invalidStartDate", StartDate.MESSAGE_STARTDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 s/01/08/1998 d/invalid_DueDate. t/invalidDueDate", DueDate.MESSAGE_DUEDATE_CONSTRAINTS); assertCommandFailure("add Valid Name p/1 s/01/01/1990 d/01/03/1990 t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); EzDo expectedEZ = new EzDo(); expectedEZ.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedEZ, expectedEZ.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal ezDo // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); EzDo expectedEZ = helper.generateEzDo(2); List<? extends ReadOnlyTask> expectedList = expectedEZ.getTaskList(); // prepare ezDo state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedEZ, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new EzDo()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); EzDo expectedEZ = helper.generateEzDo(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedEZ, expectedEZ.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); EzDo expectedEZ = helper.generateEzDo(threeTasks); expectedEZ.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedEZ, expectedEZ.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); EzDo expectedEZ = helper.generateEzDo(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedEZ, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { private Task adam() throws Exception { Name name = new Name("Adam Brown"); Priority privatePriority = new Priority("1"); StartDate privateStartDate = new StartDate("3/3/2017"); DueDate privateDueDate = new DueDate("16/06/2016"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, privatePriority, privateStartDate, privateDueDate, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ private Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new Priority("1"), new StartDate("01/01/2000"), new DueDate("07/07/2007"), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ private String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" p/").append(p.getPriority()); cmd.append(" s/").append(p.getStartDate()); cmd.append(" d/").append(p.getDueDate()); UniqueTagList tags = p.getTags(); for (Tag t: tags) { cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an EzDo with auto-generated tasks. */ private EzDo generateEzDo(int numGenerated) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, numGenerated); return ezDo; } /** * Generates an EzDo based on the list of Tasks given. */ private EzDo generateEzDo(List<Task> tasks) throws Exception { EzDo ezDo = new EzDo(); addToEzDo(ezDo, tasks); return ezDo; } /** * Adds auto-generated Task objects to the given EzDo * @param ezDo The EzDo to which the Tasks will be added */ private void addToEzDo(EzDo ezDo, int numGenerated) throws Exception { addToEzDo(ezDo, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given EzDo */ private void addToEzDo(EzDo ezDo, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { ezDo.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ private void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ private void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task p: tasksToAdd) { model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ private List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } private List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ private Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new Priority("1"), new StartDate("1/1/2017"), new DueDate("09/09/2009"), new UniqueTagList(new Tag("tag")) ); } } }
Fix typo - missing semicolon
src/test/java/seedu/ezdo/logic/LogicManagerTest.java
Fix typo - missing semicolon
Java
mit
d911c350c897d0585b582384e7f3bb1b4ac7126f
0
hkamran/ServiceRecorder
package com.hkamran.mocking; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.CharsetUtil; import io.netty.util.internal.StringUtil; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringEscapeUtils; import org.json.JSONObject; import com.hkamran.mocking.Filter.State; import com.hkamran.mocking.util.Formatter; /** * This class represents the HTTP response that the client has gotten. * * @author Hooman Kamran */ public class Response { private Map<String, String> headers = new HashMap<String, String>(); private String protocol; private Integer status; private String content; private State state; private Integer id = -1; private Integer parent = -1; public Response(FullHttpResponse res, State state) { FullHttpResponse resCopy = (FullHttpResponse) res.copy(); resCopy.retain(); this.content = parseContent(resCopy); this.protocol = resCopy.getProtocolVersion().toString(); this.status = resCopy.getStatus().code(); copyHeaders(resCopy); this.state = state; } private void copyHeaders(FullHttpResponse resCopy) { for (Entry<String, String> entry : resCopy.headers()) { String key = entry.getKey(); String value = entry.getValue(); if (key.equalsIgnoreCase("Content-Length")) { Integer length = content.length(); value = length.toString(); } if (value == null) { value = ""; } headers.put(key, value); } } public Response(Map<String, String> headers, String content, String protocol, Integer status, State state) { this.headers = headers; this.content = content; this.protocol = protocol; this.status = status; this.state = state; } private String parseContent(FullHttpResponse res) { ByteBufInputStream bufInputStream = new ByteBufInputStream(res.content().copy()); StringBuilder content = new StringBuilder(); try { while (bufInputStream.available() > 0) { content.append((char) bufInputStream.readByte()); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return Formatter.format(content.toString()); } public Response clone() { return new Response(getHeaders(), getContent(), getProtocol(), getStatus(), getState()); } public State getState() { return state; } public String getContent() { return content; } public Integer getStatus() { return this.status; } public String getProtocol() { return this.protocol; } public void setId(Integer id) { this.id = id; } public int getId() { return this.id; } public void setContent(String content) { this.content = content; } public void setStatus(Integer status) { this.status = status; } public void setProtocol(HttpVersion version) { this.protocol = version.toString(); } public void setState(State state) { this.state = state; } public void setProtocol(String version) { this.protocol = version; } public void setParent(Integer hashCode) { this.parent = hashCode; } public Integer getParent() { return parent; } public Map<String, String> getHeaders() { return headers; } // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // String content = toString(); // int charValue = 0; // for (char c : content.toCharArray()) { // charValue += c; // } // result = prime * result + charValue; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Response other = (Response) obj; // if (res == null) { // if (other.res != null) // return false; // } else if (!toString().equalsIgnoreCase(other.toString())) { // return false; // } // return true; // } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("Response" + StringUtil.NEWLINE); buf.append(" Status: " + getStatus().toString() + StringUtil.NEWLINE); buf.append(" Protocol: " + getProtocol() + StringUtil.NEWLINE); buf.append(" Headers: " + headers.toString() + StringUtil.NEWLINE); buf.append(" Content: " + StringUtil.NEWLINE); buf.append(StringEscapeUtils.unescapeJava(getContent()) + StringUtil.NEWLINE); return buf.toString(); } public JSONObject toJSON() { JSONObject responseJSON = new JSONObject(); responseJSON.put("status", getStatus()); responseJSON.put("protocol", getProtocol()); responseJSON.put("content", getContent()); responseJSON.put("headers", getHeaders()); responseJSON.put("hashCode", hashCode()); responseJSON.put("id", id); responseJSON.put("state", getState()); responseJSON.put("parent", parent); return responseJSON; } public static Response parseJSON(String source) { JSONObject json = new JSONObject(source); Integer status = json.getInt("status"); String protocol = json.getString("protocol"); String content = json.getString("content"); Integer id = json.getInt("id"); State state = State.valueOf(json.getString("state")); Integer parent = json.getInt("parent"); JSONObject headersJSON = json.getJSONObject("headers"); Map<String, String> headers = new HashMap<String, String>(); for (Object key : headersJSON.keySet()) { headers.put(key.toString(), headersJSON.getString(key.toString())); } Response response = new Response(headers, content, protocol, status, state); response.setParent(parent); response.setId(id); return response; } public HttpResponse getHTTPObject() { HttpVersion version = HttpVersion.valueOf(protocol); HttpResponseStatus status = HttpResponseStatus.valueOf(this.status); ByteBuf content = Unpooled.copiedBuffer(this.content, CharsetUtil.UTF_8); DefaultFullHttpResponse response = new DefaultFullHttpResponse(version, status, content); HttpHeaders headers = response.headers(); if (!headers.contains(HttpHeaders.Names.CONNECTION)) { headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); } for (String key : this.headers.keySet()) { headers.set(key, this.headers.get(key)); } return response; } }
src/main/java/com/hkamran/mocking/Response.java
package com.hkamran.mocking; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.internal.StringUtil; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringEscapeUtils; import org.json.JSONObject; import com.hkamran.mocking.Filter.State; import com.hkamran.mocking.util.Formatter; /** * This class represents the HTTP response that the client has gotten. * * @author Hooman Kamran */ public class Response { private Map<String, String> headers = new HashMap<String, String>(); private String protocol; private Integer status; private String content; private State state; private Integer id = -1; private Integer parent = -1; public Response(FullHttpResponse res, State state) { FullHttpResponse resCopy = (FullHttpResponse) res.copy(); resCopy.retain(); this.content = parseContent(resCopy); this.protocol = resCopy.getProtocolVersion().toString(); this.status = resCopy.getStatus().code(); copyHeaders(resCopy); this.state = state; } private void copyHeaders(FullHttpResponse resCopy) { for (Entry<String, String> entry : resCopy.headers()) { String key = entry.getKey(); String value = entry.getValue(); if (key.equalsIgnoreCase("Content-Length")) { Integer length = content.length(); value = length.toString(); } if (value == null) { value = ""; } headers.put(key, value); } } public Response(Map<String, String> headers, String content, String protocol, Integer status, State state) { this.headers = headers; this.content = content; this.protocol = protocol; this.status = status; this.state = state; } private String parseContent(FullHttpResponse res) { ByteBufInputStream bufInputStream = new ByteBufInputStream(res.content().copy()); StringBuilder content = new StringBuilder(); try { while (bufInputStream.available() > 0) { content.append((char) bufInputStream.readByte()); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return Formatter.format(content.toString()); } public Response clone() { return new Response(getHeaders(), getContent(), getProtocol(), getStatus(), getState()); } public State getState() { return state; } public String getContent() { return content; } public Integer getStatus() { return this.status; } public String getProtocol() { return this.protocol; } public void setId(Integer id) { this.id = id; } public int getId() { return this.id; } public void setContent(String content) { this.content = content; } public void setStatus(Integer status) { this.status = status; } public void setProtocol(HttpVersion version) { this.protocol = version.toString(); } public void setState(State state) { this.state = state; } public void setProtocol(String version) { this.protocol = version; } public void setParent(Integer hashCode) { this.parent = hashCode; } public Integer getParent() { return parent; } public Map<String, String> getHeaders() { return headers; } // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // String content = toString(); // int charValue = 0; // for (char c : content.toCharArray()) { // charValue += c; // } // result = prime * result + charValue; // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Response other = (Response) obj; // if (res == null) { // if (other.res != null) // return false; // } else if (!toString().equalsIgnoreCase(other.toString())) { // return false; // } // return true; // } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("Response" + StringUtil.NEWLINE); buf.append(" Status: " + getStatus().toString() + StringUtil.NEWLINE); buf.append(" Protocol: " + getProtocol() + StringUtil.NEWLINE); buf.append(" Headers: " + headers.toString() + StringUtil.NEWLINE); buf.append(" Content: " + StringUtil.NEWLINE); buf.append(StringEscapeUtils.unescapeJava(getContent()) + StringUtil.NEWLINE); return buf.toString(); } public JSONObject toJSON() { JSONObject responseJSON = new JSONObject(); responseJSON.put("status", getStatus()); responseJSON.put("protocol", getProtocol()); responseJSON.put("content", getContent()); responseJSON.put("headers", getHeaders()); responseJSON.put("hashCode", hashCode()); responseJSON.put("id", id); responseJSON.put("state", getState()); responseJSON.put("parent", parent); return responseJSON; } public static Response parseJSON(String source) { JSONObject json = new JSONObject(source); Integer status = json.getInt("status"); String protocol = json.getString("protocol"); String content = json.getString("content"); Integer id = json.getInt("id"); State state = State.valueOf(json.getString("state")); Integer parent = json.getInt("parent"); JSONObject headersJSON = json.getJSONObject("headers"); Map<String, String> headers = new HashMap<String, String>(); for (Object key : headersJSON.keySet()) { headers.put(key.toString(), headersJSON.getString(key.toString())); } Response response = new Response(headers, content, protocol, status, state); response.setParent(parent); response.setId(id); return response; } public HttpResponse getHTTPObject() { HttpVersion version = HttpVersion.valueOf(protocol); HttpResponseStatus status = HttpResponseStatus.valueOf(this.status); ByteBuf content = Unpooled.wrappedBuffer(this.content.getBytes()); DefaultFullHttpResponse response = new DefaultFullHttpResponse(version, status, content); HttpHeaders headers = response.headers(); for (String key : this.headers.keySet()) { headers.set(key, this.headers.get(key)); } return response; } }
Bizarre bug with littleproxy where HTTPResponse is not seen as !isChunked
src/main/java/com/hkamran/mocking/Response.java
Bizarre bug with littleproxy where HTTPResponse is not seen as !isChunked
Java
mit
9d76546ed55831ad2a97f247a9b5db352f7e6171
0
siarhei-luskanau/android-iot-doorbell
package siarhei.luskanau.iot.doorbell.companion.images; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.List; import javax.inject.Inject; import io.reactivex.Observable; import siarhei.luskanau.iot.doorbell.DomainConstants; import siarhei.luskanau.iot.doorbell.ImageEntry; import siarhei.luskanau.iot.doorbell.companion.BaseComponentActivity; import siarhei.luskanau.iot.doorbell.companion.R; import siarhei.luskanau.iot.doorbell.companion.dagger.component.ActivityComponent; import siarhei.luskanau.iot.doorbell.companion.dagger.component.DaggerActivityComponent; import siarhei.luskanau.iot.doorbell.presenter.images.ImagesPresenter; import siarhei.luskanau.iot.doorbell.presenter.images.ImagesView; public class ImagesActivity extends BaseComponentActivity implements ImagesView { @Inject protected ImagesPresenter imagesPresenter; private String deviceId; private RecyclerView recyclerView; private ImageEntryAdapter adapter; public static Intent buildIntent(Context context, String deviceId) { return new Intent(context, ImagesActivity.class).putExtra(DomainConstants.DEVICE_ID, deviceId); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_images); deviceId = getIntent().getStringExtra(DomainConstants.DEVICE_ID); getSupportActionBar().setTitle(deviceId); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new ImageEntryAdapter(); recyclerView.setAdapter(adapter); this.initializeInjector(); imagesPresenter.setView(this); imagesPresenter.listenDoorbell(deviceId); } private void initializeInjector() { ActivityComponent activityComponent = DaggerActivityComponent.builder() .applicationComponent(getApplicationComponent()) .activityModule(getActivityModule()) .build(); activityComponent.inject(this); } @Override protected void onDestroy() { super.onDestroy(); imagesPresenter.destroy(); } @Override public void onImageListUpdated(List<ImageEntry> list) { if (list != null) { list = Observable.fromIterable(list) .toSortedList((imageEntry1, imageEntry2) -> imageEntry2.getTimestamp().compareTo(imageEntry1.getTimestamp())) .blockingGet(); } adapter.setData(list); } @Override public void showErrorMessage(CharSequence errorMessage) { Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show(); } }
app_companion/src/main/java/siarhei/luskanau/iot/doorbell/companion/images/ImagesActivity.java
package siarhei.luskanau.iot.doorbell.companion.images; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.List; import javax.inject.Inject; import siarhei.luskanau.iot.doorbell.DomainConstants; import siarhei.luskanau.iot.doorbell.ImageEntry; import siarhei.luskanau.iot.doorbell.companion.BaseComponentActivity; import siarhei.luskanau.iot.doorbell.companion.R; import siarhei.luskanau.iot.doorbell.companion.dagger.component.ActivityComponent; import siarhei.luskanau.iot.doorbell.companion.dagger.component.DaggerActivityComponent; import siarhei.luskanau.iot.doorbell.presenter.images.ImagesPresenter; import siarhei.luskanau.iot.doorbell.presenter.images.ImagesView; public class ImagesActivity extends BaseComponentActivity implements ImagesView { @Inject protected ImagesPresenter imagesPresenter; private String deviceId; private RecyclerView recyclerView; private ImageEntryAdapter adapter; public static Intent buildIntent(Context context, String deviceId) { return new Intent(context, ImagesActivity.class).putExtra(DomainConstants.DEVICE_ID, deviceId); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_images); deviceId = getIntent().getStringExtra(DomainConstants.DEVICE_ID); getSupportActionBar().setTitle(deviceId); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true)); adapter = new ImageEntryAdapter(); recyclerView.setAdapter(adapter); this.initializeInjector(); imagesPresenter.setView(this); imagesPresenter.listenDoorbell(deviceId); } private void initializeInjector() { ActivityComponent activityComponent = DaggerActivityComponent.builder() .applicationComponent(getApplicationComponent()) .activityModule(getActivityModule()) .build(); activityComponent.inject(this); } @Override protected void onDestroy() { super.onDestroy(); imagesPresenter.destroy(); } @Override public void onImageListUpdated(List<ImageEntry> list) { adapter.setData(list); } @Override public void showErrorMessage(CharSequence errorMessage) { Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show(); } }
sorted images by timestamp
app_companion/src/main/java/siarhei/luskanau/iot/doorbell/companion/images/ImagesActivity.java
sorted images by timestamp
Java
epl-1.0
bfab03f766ab973cd3fda5e44ee073d47be2fed1
0
trajano/openid-connect,trajano/openid-connect
package net.trajano.openidconnect.token; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.json.JsonObject; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import net.trajano.openidconnect.core.Scope; @XmlAccessorType(XmlAccessType.NONE) public class TokenResponse implements Serializable { public static final String BEARER = "Bearer"; /** * */ private static final long serialVersionUID = 5216911835177655318L; /** * REQUIRED. The access token issued by the authorization server. */ @XmlElement(name = "access_token", required = true) private String accessToken; /** * RECOMMENDED. The lifetime in seconds of the access token. For example, * the value "3600" denotes that the access token will expire in one hour * from the time the response was generated. If omitted, the authorization * server SHOULD provide the expiration time via other means or document the * default value. */ @XmlElement(name = "expires_in", required = false) private int expiresIn; @XmlElement(name = "refresh_token") private String refreshToken; /** * OPTIONAL, if identical to the scope requested by the client; otherwise, * REQUIRED. The scope of the access token as described by Section 3.3. */ @XmlElement(name = "scope") private String scope; /** * <p> * REQUIRED. The type of the token issued as described in Section 7.1. Value * is case insensitive. * </p> * <p> * The OAuth 2.0 token_type response parameter value MUST be Bearer, as * specified in OAuth 2.0 Bearer Token Usage [RFC6750], unless another Token * Type has been negotiated with the Client. Servers SHOULD support the * Bearer Token Type; use of other Token Types is outside the scope of this * specification. * </p> */ @XmlElement(name = "token_type", required = true) private String tokenType = BEARER; /** * Constructs TokenResponse. * * @param tokenResponse */ public TokenResponse() { } /** * Constructs TokenResponse. * * @param tokenResponse */ public TokenResponse(final JsonObject tokenResponse) { accessToken = tokenResponse.getString("access_token"); expiresIn = tokenResponse.getInt("expires_in"); if (tokenResponse.containsKey("refresh_token")) { refreshToken = tokenResponse.getString("refresh_token"); } if (tokenResponse.containsKey("scope")) { scope = tokenResponse.getString("scope"); } tokenType = tokenResponse.getString("token_type", BEARER); } public String getAccessToken() { return accessToken; } public int getExpiresIn() { return expiresIn; } public String getRefreshToken() { return refreshToken; } public String getScope() { return scope; } @XmlTransient public Set<Scope> getScopes() { final Set<Scope> scopes = new HashSet<>(); for (final String scopePart : scope.split("\\s")) { scopes.add(Scope.valueOf(scopePart)); } return scopes; } public String getTokenType() { return tokenType; } public void setAccessToken(final String accessToken) { this.accessToken = accessToken; } public void setExpiresIn(final int expiresIn) { this.expiresIn = expiresIn; } public void setRefreshToken(final String refreshToken) { this.refreshToken = refreshToken; } public void setScope(final String scope) { this.scope = scope; } public void setScopes(final Set<Scope> scopes) { final StringBuilder b = new StringBuilder(); final Iterator<Scope> i = scopes.iterator(); b.append(i.next()); while (i.hasNext()) { b.append(' '); b.append(i.next()); } scope = b.toString(); } public void setTokenType(final String tokenType) { this.tokenType = tokenType; } }
openid-connect-core/src/main/java/net/trajano/openidconnect/token/TokenResponse.java
package net.trajano.openidconnect.token; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.json.JsonObject; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import net.trajano.openidconnect.core.Scope; @XmlAccessorType(XmlAccessType.NONE) public class TokenResponse implements Serializable { public static final String BEARER = "Bearer"; /** * */ private static final long serialVersionUID = 5216911835177655318L; /** * REQUIRED. The access token issued by the authorization server. */ @XmlElement(name = "access_token", required = true) private String accessToken; /** * RECOMMENDED. The lifetime in seconds of the access token. For example, * the value "3600" denotes that the access token will expire in one hour * from the time the response was generated. If omitted, the authorization * server SHOULD provide the expiration time via other means or document the * default value. */ @XmlElement(name = "expires_in", required = false) private int expiresIn; @XmlElement(name = "refresh_token") private String refreshToken; /** * OPTIONAL, if identical to the scope requested by the client; otherwise, * REQUIRED. The scope of the access token as described by Section 3.3. */ @XmlElement(name = "scope") private String scope; /** * <p> * REQUIRED. The type of the token issued as described in Section 7.1. Value * is case insensitive. * </p> * <p> * The OAuth 2.0 token_type response parameter value MUST be Bearer, as * specified in OAuth 2.0 Bearer Token Usage [RFC6750], unless another Token * Type has been negotiated with the Client. Servers SHOULD support the * Bearer Token Type; use of other Token Types is outside the scope of this * specification. * </p> */ @XmlElement(name = "token_type", required = true) private String tokenType = BEARER; /** * Constructs TokenResponse. * * @param tokenResponse */ public TokenResponse() { } /** * Constructs TokenResponse. * * @param tokenResponse */ public TokenResponse(final JsonObject tokenResponse) { accessToken = tokenResponse.getString("access_token"); expiresIn = tokenResponse.getInt("expires_in"); refreshToken = tokenResponse.getString("refresh_token"); scope = tokenResponse.getString("scope"); tokenType = tokenResponse.getString("token_type", BEARER); } public String getAccessToken() { return accessToken; } public int getExpiresIn() { return expiresIn; } public String getRefreshToken() { return refreshToken; } public String getScope() { return scope; } @XmlTransient public Set<Scope> getScopes() { final Set<Scope> scopes = new HashSet<>(); for (final String scopePart : scope.split("\\s")) { scopes.add(Scope.valueOf(scopePart)); } return scopes; } public String getTokenType() { return tokenType; } public void setAccessToken(final String accessToken) { this.accessToken = accessToken; } public void setExpiresIn(final int expiresIn) { this.expiresIn = expiresIn; } public void setRefreshToken(final String refreshToken) { this.refreshToken = refreshToken; } public void setScope(final String scope) { this.scope = scope; } public void setScopes(final Set<Scope> scopes) { final StringBuilder b = new StringBuilder(); final Iterator<Scope> i = scopes.iterator(); b.append(i.next()); while (i.hasNext()) { b.append(' '); b.append(i.next()); } scope = b.toString(); } public void setTokenType(final String tokenType) { this.tokenType = tokenType; } }
Added extra check for Heroku testing
openid-connect-core/src/main/java/net/trajano/openidconnect/token/TokenResponse.java
Added extra check for Heroku testing
Java
lgpl-2.1
21fb8c0c2cf5da4bb076cb14716fda2d9ef63c48
0
sewe/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Project.java * * Created on March 30, 2003, 2:22 PM */ package edu.umd.cs.findbugs; import static edu.umd.cs.findbugs.xml.XMLOutputUtil.writeElementList; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import javax.annotation.Nullable; import org.dom4j.DocumentException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.ba.URLClassPath; import edu.umd.cs.findbugs.charsets.UTF8; import edu.umd.cs.findbugs.cloud.CloudPlugin; import edu.umd.cs.findbugs.config.UserPreferences; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; import edu.umd.cs.findbugs.xml.XMLWriteable; /** * A project in the GUI. This consists of some number of Jar files to analyze * for bugs, and optionally * <p/> * <ul> * <li>some number of source directories, for locating the program's source code * <li>some number of auxiliary classpath entries, for locating classes * referenced by the program which the user doesn't want to analyze * <li>some number of boolean options * </ul> * * @author David Hovemeyer */ public class Project implements XMLWriteable { private static final boolean DEBUG = SystemProperties.getBoolean("findbugs.project.debug"); private final List<File> currentWorkingDirectoryList; private String projectName; /** * List of jars/directories to analyze */ private List<String> analysisTargets; /** * The list of source directories. */ private List<String> srcDirList; /** * The list of auxiliary classpath entries. */ private List<String> auxClasspathEntryList; /** * Flag to indicate that this Project has been modified. */ private boolean isModified; private String cloudId; private UserPreferences configuration; /** key is plugin id */ private final Map<String,Boolean> enabledPlugins; public boolean getPluginStatus(Plugin plugin) { Boolean b = enabledPlugins.get(plugin.getPluginId()); if (b != null) { return b; } return plugin.isGloballyEnabled(); } public void setPluginStatus(String pluginId, boolean enabled) { enabledPlugins.put(pluginId, enabled); Plugin plugin = Plugin.getByPluginId(pluginId); if(plugin == null) { return; } if (isDefaultInitialPluginState(plugin, enabled)) { enabledPlugins.remove(plugin.getPluginId()); } } public UserPreferences getConfiguration() { return configuration; } /** * @param configuration The configuration to set, nuon null */ public void setConfiguration(UserPreferences configuration) { this.configuration = configuration; } /** * @return Returns the cloudId. */ public @CheckForNull String getCloudId() { return cloudId; } /** * @param cloudId * The cloudId to set. */ public void setCloudId(@Nullable String cloudId) { if (cloudId != null && cloudId.indexOf('.') == -1) { Map<String, CloudPlugin> registeredClouds = DetectorFactoryCollection.instance().getRegisteredClouds(); String check = "." + cloudId; int count = 0; String result = cloudId; for(String name : registeredClouds.keySet()) if (name.endsWith(check)) { count++; result = name; } if (count == 1) cloudId = result; } this.cloudId = cloudId; } private Properties cloudProperties = new Properties(); /** * @return Returns the cloudProperties. */ public Properties getCloudProperties() { return cloudProperties; } /** * @param cloudProperties * The cloudProperties to set. */ public void setCloudProperties(Properties cloudProperties) { this.cloudProperties = cloudProperties; } /** * Constant used to name anonymous projects. */ public static final String UNNAMED_PROJECT = "<<unnamed project>>"; private long timestampForAnalyzedClasses = 0L; private IGuiCallback guiCallback; @NonNull private Filter suppressionFilter = new Filter(); private SourceFinder sourceFinder; /** * Create an anonymous project. */ public Project() { enabledPlugins = new HashMap<String,Boolean>(); configuration = UserPreferences.createDefaultUserPreferences(); analysisTargets = new LinkedList<String>(); srcDirList = new LinkedList<String>(); auxClasspathEntryList = new LinkedList<String>(); isModified = false; currentWorkingDirectoryList = new ArrayList<File>(); } /** * Return an exact copy of this Project. */ public Project duplicate() { Project dup = new Project(); dup.currentWorkingDirectoryList.addAll(this.currentWorkingDirectoryList); dup.projectName = this.projectName; dup.analysisTargets.addAll(this.analysisTargets); dup.srcDirList.addAll(this.srcDirList); dup.auxClasspathEntryList.addAll(this.auxClasspathEntryList); dup.timestampForAnalyzedClasses = timestampForAnalyzedClasses; dup.guiCallback = guiCallback; dup.cloudId = cloudId; dup.cloudProperties.putAll(cloudProperties); return dup; } public SourceFinder getSourceFinder() { if (sourceFinder == null) { sourceFinder = new SourceFinder(this); } return sourceFinder; } public boolean isGuiAvaliable() { return guiCallback != null; } /** * add information from project2 to this project */ public void add(Project project2) { analysisTargets = appendWithoutDuplicates(analysisTargets, project2.analysisTargets); srcDirList = appendWithoutDuplicates(srcDirList, project2.srcDirList); auxClasspathEntryList = appendWithoutDuplicates(auxClasspathEntryList, project2.auxClasspathEntryList); } public static <T> List<T> appendWithoutDuplicates(List<T> lst1, List<T> lst2) { LinkedHashSet<T> joined = new LinkedHashSet<T>(lst1); joined.addAll(lst2); return new ArrayList<T>(joined); } public void setCurrentWorkingDirectory(File f) { if (f != null) addWorkingDir(f.toString()); } /** * Return whether or not this Project has unsaved modifications. */ public boolean isModified() { return isModified; } /** * Set whether or not this Project has unsaved modifications. */ public void setModified(boolean isModified) { this.isModified = isModified; } /** * Add a file to the project. * * @param fileName * the file to add * @return true if the file was added, or false if the file was already * present */ public boolean addFile(String fileName) { return addToListInternal(analysisTargets, makeAbsoluteCWD(fileName)); } /** * Add a source directory to the project. * * @param dirName * the directory to add * @return true if the source directory was added, or false if the source * directory was already present */ public boolean addSourceDir(String dirName) { boolean isNew = false; for (String dir : makeAbsoluteCwdCandidates(dirName)) { isNew = addToListInternal(srcDirList, dir) || isNew; } sourceFinder = new SourceFinder(this); return isNew; } /** * Add a working directory to the project. * * @param dirName * the directory to add * @return true if the working directory was added, or false if the working * directory was already present */ public boolean addWorkingDir(String dirName) { if (dirName == null) throw new NullPointerException(); return addToListInternal(currentWorkingDirectoryList, new File(dirName)); } /** * Get the number of files in the project. * * @return the number of files in the project */ public int getFileCount() { return analysisTargets.size(); } /** * Get the given file in the list of project files. * * @param num * the number of the file in the list of project files * @return the name of the file */ public String getFile(int num) { return analysisTargets.get(num); } /** * Remove file at the given index in the list of project files * * @param num * index of the file to remove in the list of project files */ public void removeFile(int num) { analysisTargets.remove(num); isModified = true; } /** * Get the list of files, directories, and zip files in the project. */ public List<String> getFileList() { return analysisTargets; } /** * Get the number of source directories in the project. * * @return the number of source directories in the project */ public int getNumSourceDirs() { return srcDirList.size(); } /** * Get the given source directory. * * @param num * the number of the source directory * @return the source directory */ public String getSourceDir(int num) { return srcDirList.get(num); } /** * Remove source directory at given index. * * @param num * index of the source directory to remove */ public void removeSourceDir(int num) { srcDirList.remove(num); sourceFinder = new SourceFinder(this); isModified = true; } /** * Get project files as an array of Strings. */ public String[] getFileArray() { return analysisTargets.toArray(new String[analysisTargets.size()]); } /** * Get source dirs as an array of Strings. */ public String[] getSourceDirArray() { return srcDirList.toArray(new String[srcDirList.size()]); } /** * Get the source dir list. */ public List<String> getSourceDirList() { return srcDirList; } /** * Add an auxiliary classpath entry * * @param auxClasspathEntry * the entry * @return true if the entry was added successfully, or false if the given * entry is already in the list */ public boolean addAuxClasspathEntry(String auxClasspathEntry) { return addToListInternal(auxClasspathEntryList, makeAbsoluteCWD(auxClasspathEntry)); } /** * Get the number of auxiliary classpath entries. */ public int getNumAuxClasspathEntries() { return auxClasspathEntryList.size(); } /** * Get the n'th auxiliary classpath entry. */ public String getAuxClasspathEntry(int n) { return auxClasspathEntryList.get(n); } /** * Remove the n'th auxiliary classpath entry. */ public void removeAuxClasspathEntry(int n) { auxClasspathEntryList.remove(n); isModified = true; } /** * Return the list of aux classpath entries. */ public List<String> getAuxClasspathEntryList() { return auxClasspathEntryList; } /** * Worklist item for finding implicit classpath entries. */ private static class WorkListItem { private final URL url; /** * Constructor. * * @param url * the URL of the Jar or Zip file */ public WorkListItem(URL url) { this.url = url; } /** * Get URL of Jar/Zip file. */ public URL getURL() { return this.url; } } /** * Worklist for finding implicit classpath entries. */ private static class WorkList { private final LinkedList<WorkListItem> itemList; private final HashSet<String> addedSet; /** * Constructor. Creates an empty worklist. */ public WorkList() { this.itemList = new LinkedList<WorkListItem>(); this.addedSet = new HashSet<String>(); } /** * Create a URL from a filename specified in the project file. */ public URL createURL(String fileName) throws MalformedURLException { String protocol = URLClassPath.getURLProtocol(fileName); if (protocol == null) { fileName = "file:" + fileName; } return new URL(fileName); } /** * Create a URL of a file relative to another URL. */ public URL createRelativeURL(URL base, String fileName) throws MalformedURLException { return new URL(base, fileName); } /** * Add a worklist item. * * @param item * the WorkListItem representing a zip/jar file to be * examined * @return true if the item was added, false if not (because it was * examined already) */ public boolean add(WorkListItem item) { if (DEBUG) { System.out.println("Adding " + item.getURL().toString()); } if (!addedSet.add(item.getURL().toString())) { if (DEBUG) { System.out.println("\t==> Already processed"); } return false; } itemList.add(item); return true; } /** * Return whether or not the worklist is empty. */ public boolean isEmpty() { return itemList.isEmpty(); } /** * Get the next item in the worklist. */ public WorkListItem getNextItem() { return itemList.removeFirst(); } } /** * Return the list of implicit classpath entries. The implicit classpath is * computed from the closure of the set of jar files that are referenced by * the <code>"Class-Path"</code> attribute of the manifest of the any jar * file that is part of this project or by the <code>"Class-Path"</code> * attribute of any directly or indirectly referenced jar. The referenced * jar files that exist are the list of implicit classpath entries. * * @deprecated FindBugs2 and ClassPathBuilder take care of this * automatically */ @Deprecated public List<String> getImplicitClasspathEntryList() { final LinkedList<String> implicitClasspath = new LinkedList<String>(); WorkList workList = new WorkList(); // Prime the worklist by adding the zip/jar files // in the project. for (String fileName : analysisTargets) { try { URL url = workList.createURL(fileName); WorkListItem item = new WorkListItem(url); workList.add(item); } catch (MalformedURLException ignore) { // Ignore } } // Scan recursively. while (!workList.isEmpty()) { WorkListItem item = workList.getNextItem(); processComponentJar(item.getURL(), workList, implicitClasspath); } return implicitClasspath; } /** * Examine the manifest of a single zip/jar file for implicit classapth * entries. * * @param jarFileURL * URL of the zip/jar file * @param workList * worklist of zip/jar files to examine * @param implicitClasspath * list of implicit classpath entries found */ private void processComponentJar(URL jarFileURL, WorkList workList, List<String> implicitClasspath) { if (DEBUG) { System.out.println("Processing " + jarFileURL.toString()); } if (!jarFileURL.toString().endsWith(".zip") && !jarFileURL.toString().endsWith(".jar")) { return; } try { URL manifestURL = new URL("jar:" + jarFileURL.toString() + "!/META-INF/MANIFEST.MF"); InputStream in = null; try { in = manifestURL.openStream(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] fileList = classPath.split("\\s+"); for (String jarFile : fileList) { URL referencedURL = workList.createRelativeURL(jarFileURL, jarFile); if (workList.add(new WorkListItem(referencedURL))) { implicitClasspath.add(referencedURL.toString()); if (DEBUG) { System.out.println("Implicit jar: " + referencedURL.toString()); } } } } } finally { if (in != null) { in.close(); } } } catch (IOException ignore) { // Ignore } } private static final String OPTIONS_KEY = "[Options]"; private static final String JAR_FILES_KEY = "[Jar files]"; private static final String SRC_DIRS_KEY = "[Source dirs]"; private static final String AUX_CLASSPATH_ENTRIES_KEY = "[Aux classpath entries]"; // Option keys public static final String RELATIVE_PATHS = "relative_paths"; /** * Save the project to an output file. * * @param outputFile * name of output file * @param useRelativePaths * true if the project should be written using only relative * paths * @param relativeBase * if useRelativePaths is true, this file is taken as the base * directory in terms of which all files should be made relative * @throws IOException * if an error occurs while writing */ @Deprecated public void write(String outputFile, boolean useRelativePaths, String relativeBase) throws IOException { PrintWriter writer = UTF8.printWriter(outputFile); try { writer.println(JAR_FILES_KEY); for (String jarFile : analysisTargets) { if (useRelativePaths) { jarFile = convertToRelative(jarFile, relativeBase); } writer.println(jarFile); } writer.println(SRC_DIRS_KEY); for (String srcDir : srcDirList) { if (useRelativePaths) { srcDir = convertToRelative(srcDir, relativeBase); } writer.println(srcDir); } writer.println(AUX_CLASSPATH_ENTRIES_KEY); for (String auxClasspathEntry : auxClasspathEntryList) { if (useRelativePaths) { auxClasspathEntry = convertToRelative(auxClasspathEntry, relativeBase); } writer.println(auxClasspathEntry); } if (useRelativePaths) { writer.println(OPTIONS_KEY); writer.println(RELATIVE_PATHS + "=true"); } } finally { writer.close(); } // Project successfully saved isModified = false; } public static Project readXML(File f) throws IOException, DocumentException, SAXException { InputStream in = new BufferedInputStream(new FileInputStream(f)); Project project = new Project(); try { String tag = Util.getXMLType(in); SAXBugCollectionHandler handler; if (tag.equals("Project")) { handler = new SAXBugCollectionHandler(project, f); } else if (tag.equals("BugCollection")) { SortedBugCollection bugs = new SortedBugCollection(project); handler = new SAXBugCollectionHandler(bugs, f); } else { throw new IOException("Can't load a project from a " + tag + " file"); } XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } finally { in.close(); } // Presumably, project is now up-to-date project.setModified(false); return project; } public void writeXML(File f) throws IOException { OutputStream out = new FileOutputStream(f); XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput, f); } finally { xmlOutput.finish(); } } /** * Read Project from named file. * * @param argument * command line argument containing project file name * @return the Project * @throws IOException */ public static Project readProject(String argument) throws IOException { String projectFileName = argument; File projectFile = new File(projectFileName); if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) { try { return Project.readXML(projectFile); } catch (DocumentException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } catch (SAXException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } } throw new IllegalArgumentException("Can't read project from " + argument); } /** * Read a line from a BufferedReader, ignoring blank lines and comments. */ private static String getLine(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith("#")) { break; } } return line; } /** * Convert to a string in a nice (displayable) format. */ @Override public String toString() { if (projectName != null) { return projectName; } return UNNAMED_PROJECT; } /** * Transform a user-entered filename into a proper filename, by adding the * ".fb" file extension if it isn't already present. */ public static String transformFilename(String fileName) { if (!fileName.endsWith(".fb")) { fileName = fileName + ".fb"; } return fileName; } static final String JAR_ELEMENT_NAME = "Jar"; static final String AUX_CLASSPATH_ENTRY_ELEMENT_NAME = "AuxClasspathEntry"; static final String SRC_DIR_ELEMENT_NAME = "SrcDir"; static final String WRK_DIR_ELEMENT_NAME = "WrkDir"; static final String FILENAME_ATTRIBUTE_NAME = "filename"; static final String PROJECTNAME_ATTRIBUTE_NAME = "projectName"; static final String CLOUD_ELEMENT_NAME = "Cloud"; static final String CLOUD_ID_ATTRIBUTE_NAME = "id"; static final String CLOUD_PROPERTY_ELEMENT_NAME = "Property"; static final String PLUGIN_ELEMENT_NAME = "Plugin"; static final String PLUGIN_ID_ATTRIBUTE_NAME = "id"; static final String PLUGIN_STATUS_ELEMENT_NAME = "enabled"; public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, null); } public void writeXML(XMLOutput xmlOutput, @CheckForNull File destination) throws IOException { { XMLAttributeList attributeList = new XMLAttributeList(); if (getProjectName() != null) { attributeList = attributeList.addAttribute(PROJECTNAME_ATTRIBUTE_NAME, getProjectName()); } xmlOutput.openTag(BugCollection.PROJECT_ELEMENT_NAME, attributeList); } if (destination != null) { String base = destination.getParent(); writeElementList(xmlOutput, JAR_ELEMENT_NAME, convertToRelative(analysisTargets, base)); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, convertToRelative(auxClasspathEntryList, base)); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, convertToRelative(srcDirList, base)); List<String> cwdStrings = new ArrayList<String>(); for (File file : currentWorkingDirectoryList) cwdStrings.add(file.getPath()); XMLOutputUtil.writeElementList(xmlOutput, WRK_DIR_ELEMENT_NAME, convertToRelative(cwdStrings, base)); } else { // TODO to allow relative paths: refactor the code which uses null // file arguments writeElementList(xmlOutput, JAR_ELEMENT_NAME, analysisTargets); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, auxClasspathEntryList); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, srcDirList); XMLOutputUtil.writeFileList(xmlOutput, WRK_DIR_ELEMENT_NAME, currentWorkingDirectoryList); } if (suppressionFilter != null && !suppressionFilter.isEmpty()) { xmlOutput.openTag("SuppressionFilter"); suppressionFilter.writeBodyAsXML(xmlOutput); xmlOutput.closeTag("SuppressionFilter"); } for(Map.Entry<String, Boolean> e : enabledPlugins.entrySet()) { String pluginId = e.getKey(); Boolean enabled = e.getValue(); Plugin plugin = Plugin.getByPluginId(pluginId); if (plugin == null || isDefaultInitialPluginState(plugin, enabled)) { continue; } XMLAttributeList pluginAttributeList = new XMLAttributeList(); pluginAttributeList.addAttribute(PLUGIN_ID_ATTRIBUTE_NAME, plugin.getPluginId()); pluginAttributeList.addAttribute(PLUGIN_STATUS_ELEMENT_NAME, enabled.toString()); xmlOutput.openCloseTag(PLUGIN_ELEMENT_NAME, pluginAttributeList); } if (cloudId != null) { xmlOutput.startTag(CLOUD_ELEMENT_NAME); xmlOutput.addAttribute(CLOUD_ID_ATTRIBUTE_NAME, cloudId); xmlOutput.stopTag(false); for (Map.Entry e : cloudProperties.entrySet()) { xmlOutput.startTag(CLOUD_PROPERTY_ELEMENT_NAME); xmlOutput.addAttribute("key", e.getKey().toString()); xmlOutput.stopTag(false); Object value = e.getValue(); xmlOutput.writeText(value.toString()); xmlOutput.closeTag(CLOUD_PROPERTY_ELEMENT_NAME); } xmlOutput.closeTag(CLOUD_ELEMENT_NAME); } xmlOutput.closeTag(BugCollection.PROJECT_ELEMENT_NAME); } private boolean isDefaultInitialPluginState(Plugin plugin, Boolean enabled) { return plugin.isInitialPlugin() && enabled == plugin.isGloballyEnabled() && plugin.isEnabledByDefault() == plugin.isGloballyEnabled(); } /** * Hack for whether files are case insensitive. For now, we'll assume that * Windows is the only case insensitive OS. (OpenVMS users, feel free to * submit a patch :-) */ private static final boolean FILE_IGNORE_CASE = SystemProperties.getProperty("os.name", "unknown").startsWith("Windows"); private Iterable<String> convertToRelative(List<String> paths, String base) { List<String> newList = new ArrayList<String>(paths.size()); for (String path : paths) { newList.add(convertToRelative(path, base)); } return newList; } /** * Converts a full path to a relative path if possible * * @param srcFile * path to convert * @return the converted filename */ private String convertToRelative(String srcFile, String base) { String slash = SystemProperties.getProperty("file.separator"); if (FILE_IGNORE_CASE) { srcFile = srcFile.toLowerCase(); base = base.toLowerCase(); } if (base.equals(srcFile)) { return "."; } if (!base.endsWith(slash)) { base = base + slash; } if (base.length() <= srcFile.length()) { String root = srcFile.substring(0, base.length()); if (root.equals(base)) { // Strip off the base directory, make relative return "." + SystemProperties.getProperty("file.separator") + srcFile.substring(base.length()); } } // See if we can build a relative path above the base using .. notation int slashPos = srcFile.indexOf(slash); int branchPoint; if (slashPos >= 0) { String subPath = srcFile.substring(0, slashPos); if ((subPath.length() == 0) || base.startsWith(subPath)) { branchPoint = slashPos + 1; slashPos = srcFile.indexOf(slash, branchPoint); while (slashPos >= 0) { subPath = srcFile.substring(0, slashPos); if (base.startsWith(subPath)) { branchPoint = slashPos + 1; } else { break; } slashPos = srcFile.indexOf(slash, branchPoint); } int slashCount = 0; slashPos = base.indexOf(slash, branchPoint); while (slashPos >= 0) { slashCount++; slashPos = base.indexOf(slash, slashPos + 1); } StringBuilder path = new StringBuilder(); String upDir = ".." + slash; for (int i = 0; i < slashCount; i++) { path.append(upDir); } path.append(srcFile.substring(branchPoint)); return path.toString(); } } return srcFile; } /** * Converts a relative path to an absolute path if possible. * * @param fileName * path to convert * @return the converted filename */ private String convertToAbsolute(String fileName) throws IOException { // At present relative paths are only calculated if the fileName is // below the project file. This need not be the case, and we could use // .. // syntax to move up the tree. (To Be Added) File file = new File(fileName); if (!file.isAbsolute()) { for (File cwd : currentWorkingDirectoryList) { File test = new File(cwd, fileName); if (test.canRead()) return test.getAbsolutePath(); } return file.getAbsolutePath(); } return fileName; } /** * Make the given filename absolute relative to the current working * directory. */ private String makeAbsoluteCWD(String fileName) { List<String> candidates = makeAbsoluteCwdCandidates(fileName); return candidates.get(0); } /** * Make the given filename absolute relative to the current working * directory candidates. * * If the given filename exists in more than one of the working directories, * a list of these existing absolute paths is returned. * * The returned list is guaranteed to be non-empty. The returned paths might * exist or not exist and might be relative or absolute. * * @return A list of at least one candidate path for the given filename. */ private List<String> makeAbsoluteCwdCandidates(String fileName) { List<String> candidates = new ArrayList<String>(); boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { candidates.add(fileName); return candidates; } if (new File(fileName).isAbsolute()) { candidates.add(fileName); return candidates; } for (File currentWorkingDirectory : currentWorkingDirectoryList) { File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { candidates.add(relativeToCurrent.toString()); } } if (candidates.isEmpty()) { candidates.add(fileName); } return candidates; } /** * Add a value to given list, making the Project modified if the value is * not already present in the list. * * @param list * the list * @param value * the value to be added * @return true if the value was not already present in the list, false * otherwise */ private <T> boolean addToListInternal(Collection<T> list, T value) { if (!list.contains(value)) { list.add(value); isModified = true; return true; } else { return false; } } /** * Make the given list of pathnames absolute relative to the absolute path * of the project file. */ private void makeListAbsoluteProject(List<String> list) throws IOException { List<String> replace = new LinkedList<String>(); for (String fileName : list) { fileName = convertToAbsolute(fileName); replace.add(fileName); } list.clear(); list.addAll(replace); } /** * @param timestamp * The timestamp to set. */ public void setTimestamp(long timestamp) { this.timestampForAnalyzedClasses = timestamp; } public void addTimestamp(long timestamp) { if (this.timestampForAnalyzedClasses < timestamp && FindBugs.validTimestamp(timestamp)) { this.timestampForAnalyzedClasses = timestamp; } } /** * @return Returns the timestamp. */ public long getTimestamp() { return timestampForAnalyzedClasses; } /** * @param projectName * The projectName to set. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return Returns the projectName. */ public String getProjectName() { return projectName; } /** * @param suppressionFilter * The suppressionFilter to set. */ public void setSuppressionFilter(Filter suppressionFilter) { this.suppressionFilter = suppressionFilter; } /** * @return Returns the suppressionFilter. */ public Filter getSuppressionFilter() { if (suppressionFilter == null) { suppressionFilter = new Filter(); } return suppressionFilter; } public void setGuiCallback(IGuiCallback guiCallback) { this.guiCallback = guiCallback; } public IGuiCallback getGuiCallback() { if (guiCallback == null) guiCallback = new CommandLineUiCallback(); return guiCallback; } /** * @return */ public Iterable<String> getResolvedSourcePaths() { List<String> result = new ArrayList<String>(); for (String s : srcDirList) { boolean hasProtocol = (URLClassPath.getURLProtocol(s) != null); if (hasProtocol) { result.add(s); continue; } File f = new File(s); if (f.isAbsolute() || currentWorkingDirectoryList.isEmpty()) { if (f.canRead()) result.add(s); continue; } for (File d : currentWorkingDirectoryList) if (d.canRead() && d.isDirectory()) { File a = new File(d, s); if (a.canRead()) result.add(a.getAbsolutePath()); } } return result; } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/Project.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Project.java * * Created on March 30, 2003, 2:22 PM */ package edu.umd.cs.findbugs; import static edu.umd.cs.findbugs.xml.XMLOutputUtil.writeElementList; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import javax.annotation.Nullable; import org.dom4j.DocumentException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.SourceFinder; import edu.umd.cs.findbugs.ba.URLClassPath; import edu.umd.cs.findbugs.charsets.UTF8; import edu.umd.cs.findbugs.cloud.CloudPlugin; import edu.umd.cs.findbugs.config.UserPreferences; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; import edu.umd.cs.findbugs.xml.XMLOutputUtil; import edu.umd.cs.findbugs.xml.XMLWriteable; /** * A project in the GUI. This consists of some number of Jar files to analyze * for bugs, and optionally * <p/> * <ul> * <li>some number of source directories, for locating the program's source code * <li>some number of auxiliary classpath entries, for locating classes * referenced by the program which the user doesn't want to analyze * <li>some number of boolean options * </ul> * * @author David Hovemeyer */ public class Project implements XMLWriteable { private static final boolean DEBUG = SystemProperties.getBoolean("findbugs.project.debug"); private final List<File> currentWorkingDirectoryList; private String projectName; /** * List of jars/directories to analyze */ private List<String> analysisTargets; /** * The list of source directories. */ private List<String> srcDirList; /** * The list of auxiliary classpath entries. */ private List<String> auxClasspathEntryList; /** * Flag to indicate that this Project has been modified. */ private boolean isModified; private String cloudId; private UserPreferences configuration; /** key is plugin id */ private final Map<String,Boolean> enabledPlugins; public boolean getPluginStatus(Plugin plugin) { Boolean b = enabledPlugins.get(plugin.getPluginId()); if (b != null) { return b; } return plugin.isGloballyEnabled(); } public void setPluginStatus(String pluginId, boolean enabled) { enabledPlugins.put(pluginId, enabled); Plugin plugin = Plugin.getByPluginId(pluginId); if(plugin == null) { return; } if (isDefaultInitialPluginState(plugin, enabled)) { enabledPlugins.remove(plugin.getPluginId()); } } public UserPreferences getConfiguration() { return configuration; } /** * @param configuration The configuration to set, nuon null */ public void setConfiguration(UserPreferences configuration) { this.configuration = configuration; } /** * @return Returns the cloudId. */ public @CheckForNull String getCloudId() { return cloudId; } /** * @param cloudId * The cloudId to set. */ public void setCloudId(@Nullable String cloudId) { if (cloudId != null && cloudId.indexOf('.') == -1) { Map<String, CloudPlugin> registeredClouds = DetectorFactoryCollection.instance().getRegisteredClouds(); String check = "." + cloudId; int count = 0; String result = cloudId; for(String name : registeredClouds.keySet()) if (name.endsWith(check)) { count++; result = name; } if (count == 1) cloudId = result; } this.cloudId = cloudId; } private Properties cloudProperties = new Properties(); /** * @return Returns the cloudProperties. */ public Properties getCloudProperties() { return cloudProperties; } /** * @param cloudProperties * The cloudProperties to set. */ public void setCloudProperties(Properties cloudProperties) { this.cloudProperties = cloudProperties; } /** * Constant used to name anonymous projects. */ public static final String UNNAMED_PROJECT = "<<unnamed project>>"; private long timestampForAnalyzedClasses = 0L; private IGuiCallback guiCallback; @NonNull private Filter suppressionFilter = new Filter(); private SourceFinder sourceFinder; /** * Create an anonymous project. */ public Project() { enabledPlugins = new HashMap<String,Boolean>(); configuration = UserPreferences.createDefaultUserPreferences(); analysisTargets = new LinkedList<String>(); srcDirList = new LinkedList<String>(); auxClasspathEntryList = new LinkedList<String>(); isModified = false; currentWorkingDirectoryList = new ArrayList<File>(); } /** * Return an exact copy of this Project. */ public Project duplicate() { Project dup = new Project(); dup.currentWorkingDirectoryList.addAll(this.currentWorkingDirectoryList); dup.projectName = this.projectName; dup.analysisTargets.addAll(this.analysisTargets); dup.srcDirList.addAll(this.srcDirList); dup.auxClasspathEntryList.addAll(this.auxClasspathEntryList); dup.timestampForAnalyzedClasses = timestampForAnalyzedClasses; dup.guiCallback = guiCallback; dup.cloudId = cloudId; dup.cloudProperties.putAll(cloudProperties); return dup; } public SourceFinder getSourceFinder() { if (sourceFinder == null) { sourceFinder = new SourceFinder(this); } return sourceFinder; } public boolean isGuiAvaliable() { return guiCallback != null; } /** * add information from project2 to this project */ public void add(Project project2) { analysisTargets = appendWithoutDuplicates(analysisTargets, project2.analysisTargets); srcDirList = appendWithoutDuplicates(srcDirList, project2.srcDirList); auxClasspathEntryList = appendWithoutDuplicates(auxClasspathEntryList, project2.auxClasspathEntryList); } public static <T> List<T> appendWithoutDuplicates(List<T> lst1, List<T> lst2) { LinkedHashSet<T> joined = new LinkedHashSet<T>(lst1); joined.addAll(lst2); return new ArrayList<T>(joined); } public void setCurrentWorkingDirectory(File f) { if (f != null) addWorkingDir(f.toString()); } /** * Return whether or not this Project has unsaved modifications. */ public boolean isModified() { return isModified; } /** * Set whether or not this Project has unsaved modifications. */ public void setModified(boolean isModified) { this.isModified = isModified; } /** * Add a file to the project. * * @param fileName * the file to add * @return true if the file was added, or false if the file was already * present */ public boolean addFile(String fileName) { return addToListInternal(analysisTargets, makeAbsoluteCWD(fileName)); } /** * Add a source directory to the project. * * @param dirName * the directory to add * @return true if the source directory was added, or false if the source * directory was already present */ public boolean addSourceDir(String dirName) { boolean isNew = false; for (String dir : makeAbsoluteCwdCandidates(dirName)) { isNew = addToListInternal(srcDirList, dir) || isNew; } sourceFinder = new SourceFinder(this); return isNew; } /** * Add a working directory to the project. * * @param dirName * the directory to add * @return true if the working directory was added, or false if the working * directory was already present */ public boolean addWorkingDir(String dirName) { if (dirName == null) throw new NullPointerException(); return addToListInternal(currentWorkingDirectoryList, new File(dirName)); } /** * Get the number of files in the project. * * @return the number of files in the project */ public int getFileCount() { return analysisTargets.size(); } /** * Get the given file in the list of project files. * * @param num * the number of the file in the list of project files * @return the name of the file */ public String getFile(int num) { return analysisTargets.get(num); } /** * Remove file at the given index in the list of project files * * @param num * index of the file to remove in the list of project files */ public void removeFile(int num) { analysisTargets.remove(num); isModified = true; } /** * Get the list of files, directories, and zip files in the project. */ public List<String> getFileList() { return analysisTargets; } /** * Get the number of source directories in the project. * * @return the number of source directories in the project */ public int getNumSourceDirs() { return srcDirList.size(); } /** * Get the given source directory. * * @param num * the number of the source directory * @return the source directory */ public String getSourceDir(int num) { return srcDirList.get(num); } /** * Remove source directory at given index. * * @param num * index of the source directory to remove */ public void removeSourceDir(int num) { srcDirList.remove(num); sourceFinder = new SourceFinder(this); isModified = true; } /** * Get project files as an array of Strings. */ public String[] getFileArray() { return analysisTargets.toArray(new String[analysisTargets.size()]); } /** * Get source dirs as an array of Strings. */ public String[] getSourceDirArray() { return srcDirList.toArray(new String[srcDirList.size()]); } /** * Get the source dir list. */ public List<String> getSourceDirList() { return srcDirList; } /** * Add an auxiliary classpath entry * * @param auxClasspathEntry * the entry * @return true if the entry was added successfully, or false if the given * entry is already in the list */ public boolean addAuxClasspathEntry(String auxClasspathEntry) { return addToListInternal(auxClasspathEntryList, makeAbsoluteCWD(auxClasspathEntry)); } /** * Get the number of auxiliary classpath entries. */ public int getNumAuxClasspathEntries() { return auxClasspathEntryList.size(); } /** * Get the n'th auxiliary classpath entry. */ public String getAuxClasspathEntry(int n) { return auxClasspathEntryList.get(n); } /** * Remove the n'th auxiliary classpath entry. */ public void removeAuxClasspathEntry(int n) { auxClasspathEntryList.remove(n); isModified = true; } /** * Return the list of aux classpath entries. */ public List<String> getAuxClasspathEntryList() { return auxClasspathEntryList; } /** * Worklist item for finding implicit classpath entries. */ private static class WorkListItem { private final URL url; /** * Constructor. * * @param url * the URL of the Jar or Zip file */ public WorkListItem(URL url) { this.url = url; } /** * Get URL of Jar/Zip file. */ public URL getURL() { return this.url; } } /** * Worklist for finding implicit classpath entries. */ private static class WorkList { private final LinkedList<WorkListItem> itemList; private final HashSet<String> addedSet; /** * Constructor. Creates an empty worklist. */ public WorkList() { this.itemList = new LinkedList<WorkListItem>(); this.addedSet = new HashSet<String>(); } /** * Create a URL from a filename specified in the project file. */ public URL createURL(String fileName) throws MalformedURLException { String protocol = URLClassPath.getURLProtocol(fileName); if (protocol == null) { fileName = "file:" + fileName; } return new URL(fileName); } /** * Create a URL of a file relative to another URL. */ public URL createRelativeURL(URL base, String fileName) throws MalformedURLException { return new URL(base, fileName); } /** * Add a worklist item. * * @param item * the WorkListItem representing a zip/jar file to be * examined * @return true if the item was added, false if not (because it was * examined already) */ public boolean add(WorkListItem item) { if (DEBUG) { System.out.println("Adding " + item.getURL().toString()); } if (!addedSet.add(item.getURL().toString())) { if (DEBUG) { System.out.println("\t==> Already processed"); } return false; } itemList.add(item); return true; } /** * Return whether or not the worklist is empty. */ public boolean isEmpty() { return itemList.isEmpty(); } /** * Get the next item in the worklist. */ public WorkListItem getNextItem() { return itemList.removeFirst(); } } /** * Return the list of implicit classpath entries. The implicit classpath is * computed from the closure of the set of jar files that are referenced by * the <code>"Class-Path"</code> attribute of the manifest of the any jar * file that is part of this project or by the <code>"Class-Path"</code> * attribute of any directly or indirectly referenced jar. The referenced * jar files that exist are the list of implicit classpath entries. * * @deprecated FindBugs2 and ClassPathBuilder take care of this * automatically */ @Deprecated public List<String> getImplicitClasspathEntryList() { final LinkedList<String> implicitClasspath = new LinkedList<String>(); WorkList workList = new WorkList(); // Prime the worklist by adding the zip/jar files // in the project. for (String fileName : analysisTargets) { try { URL url = workList.createURL(fileName); WorkListItem item = new WorkListItem(url); workList.add(item); } catch (MalformedURLException ignore) { // Ignore } } // Scan recursively. while (!workList.isEmpty()) { WorkListItem item = workList.getNextItem(); processComponentJar(item.getURL(), workList, implicitClasspath); } return implicitClasspath; } /** * Examine the manifest of a single zip/jar file for implicit classapth * entries. * * @param jarFileURL * URL of the zip/jar file * @param workList * worklist of zip/jar files to examine * @param implicitClasspath * list of implicit classpath entries found */ private void processComponentJar(URL jarFileURL, WorkList workList, List<String> implicitClasspath) { if (DEBUG) { System.out.println("Processing " + jarFileURL.toString()); } if (!jarFileURL.toString().endsWith(".zip") && !jarFileURL.toString().endsWith(".jar")) { return; } try { URL manifestURL = new URL("jar:" + jarFileURL.toString() + "!/META-INF/MANIFEST.MF"); InputStream in = null; try { in = manifestURL.openStream(); Manifest manifest = new Manifest(in); Attributes mainAttrs = manifest.getMainAttributes(); String classPath = mainAttrs.getValue("Class-Path"); if (classPath != null) { String[] fileList = classPath.split("\\s+"); for (String jarFile : fileList) { URL referencedURL = workList.createRelativeURL(jarFileURL, jarFile); if (workList.add(new WorkListItem(referencedURL))) { implicitClasspath.add(referencedURL.toString()); if (DEBUG) { System.out.println("Implicit jar: " + referencedURL.toString()); } } } } } finally { if (in != null) { in.close(); } } } catch (IOException ignore) { // Ignore } } private static final String OPTIONS_KEY = "[Options]"; private static final String JAR_FILES_KEY = "[Jar files]"; private static final String SRC_DIRS_KEY = "[Source dirs]"; private static final String AUX_CLASSPATH_ENTRIES_KEY = "[Aux classpath entries]"; // Option keys public static final String RELATIVE_PATHS = "relative_paths"; /** * Save the project to an output file. * * @param outputFile * name of output file * @param useRelativePaths * true if the project should be written using only relative * paths * @param relativeBase * if useRelativePaths is true, this file is taken as the base * directory in terms of which all files should be made relative * @throws IOException * if an error occurs while writing */ @Deprecated public void write(String outputFile, boolean useRelativePaths, String relativeBase) throws IOException { PrintWriter writer = UTF8.printWriter(outputFile); try { writer.println(JAR_FILES_KEY); for (String jarFile : analysisTargets) { if (useRelativePaths) { jarFile = convertToRelative(jarFile, relativeBase); } writer.println(jarFile); } writer.println(SRC_DIRS_KEY); for (String srcDir : srcDirList) { if (useRelativePaths) { srcDir = convertToRelative(srcDir, relativeBase); } writer.println(srcDir); } writer.println(AUX_CLASSPATH_ENTRIES_KEY); for (String auxClasspathEntry : auxClasspathEntryList) { if (useRelativePaths) { auxClasspathEntry = convertToRelative(auxClasspathEntry, relativeBase); } writer.println(auxClasspathEntry); } if (useRelativePaths) { writer.println(OPTIONS_KEY); writer.println(RELATIVE_PATHS + "=true"); } } finally { writer.close(); } // Project successfully saved isModified = false; } public static Project readXML(File f) throws IOException, DocumentException, SAXException { InputStream in = new BufferedInputStream(new FileInputStream(f)); Project project = new Project(); try { String tag = Util.getXMLType(in); SAXBugCollectionHandler handler; if (tag.equals("Project")) { handler = new SAXBugCollectionHandler(project, f); } else if (tag.equals("BugCollection")) { SortedBugCollection bugs = new SortedBugCollection(project); handler = new SAXBugCollectionHandler(bugs, f); } else { throw new IOException("Can't load a project from a " + tag + " file"); } XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(handler); xr.setErrorHandler(handler); Reader reader = Util.getReader(in); xr.parse(new InputSource(reader)); } finally { in.close(); } // Presumably, project is now up-to-date project.setModified(false); return project; } public void writeXML(File f) throws IOException { OutputStream out = new FileOutputStream(f); XMLOutput xmlOutput = new OutputStreamXMLOutput(out); try { writeXML(xmlOutput, f); } finally { xmlOutput.finish(); } } /** * Read Project from named file. * * @param argument * command line argument containing project file name * @return the Project * @throws IOException */ public static Project readProject(String argument) throws IOException { String projectFileName = argument; File projectFile = new File(projectFileName); if (projectFileName.endsWith(".xml") || projectFileName.endsWith(".fbp")) { try { return Project.readXML(projectFile); } catch (DocumentException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } catch (SAXException e) { IOException ioe = new IOException("Couldn't read saved FindBugs project"); ioe.initCause(e); throw ioe; } } throw new IllegalArgumentException("Can't read project from " + argument); } /** * Read a line from a BufferedReader, ignoring blank lines and comments. */ private static String getLine(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith("#")) { break; } } return line; } /** * Convert to a string in a nice (displayable) format. */ @Override public String toString() { if (projectName != null) { return projectName; } return UNNAMED_PROJECT; } /** * Transform a user-entered filename into a proper filename, by adding the * ".fb" file extension if it isn't already present. */ public static String transformFilename(String fileName) { if (!fileName.endsWith(".fb")) { fileName = fileName + ".fb"; } return fileName; } static final String JAR_ELEMENT_NAME = "Jar"; static final String AUX_CLASSPATH_ENTRY_ELEMENT_NAME = "AuxClasspathEntry"; static final String SRC_DIR_ELEMENT_NAME = "SrcDir"; static final String WRK_DIR_ELEMENT_NAME = "WrkDir"; static final String FILENAME_ATTRIBUTE_NAME = "filename"; static final String PROJECTNAME_ATTRIBUTE_NAME = "projectName"; static final String CLOUD_ELEMENT_NAME = "Cloud"; static final String CLOUD_ID_ATTRIBUTE_NAME = "id"; static final String CLOUD_PROPERTY_ELEMENT_NAME = "Property"; static final String PLUGIN_ELEMENT_NAME = "Plugin"; static final String PLUGIN_ID_ATTRIBUTE_NAME = "id"; static final String PLUGIN_STATUS_ELEMENT_NAME = "enabled"; public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, null); } public void writeXML(XMLOutput xmlOutput, @CheckForNull File destination) throws IOException { { XMLAttributeList attributeList = new XMLAttributeList(); if (getProjectName() != null) { attributeList = attributeList.addAttribute(PROJECTNAME_ATTRIBUTE_NAME, getProjectName()); } xmlOutput.openTag(BugCollection.PROJECT_ELEMENT_NAME, attributeList); } if (destination != null) { String base = destination.getParent(); writeElementList(xmlOutput, JAR_ELEMENT_NAME, convertToRelative(analysisTargets, base)); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, convertToRelative(auxClasspathEntryList, base)); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, convertToRelative(srcDirList, base)); List<String> cwdStrings = new ArrayList<String>(); for (File file : currentWorkingDirectoryList) cwdStrings.add(file.getPath()); XMLOutputUtil.writeElementList(xmlOutput, WRK_DIR_ELEMENT_NAME, convertToRelative(cwdStrings, base)); } else { // TODO to allow relative paths: refactor the code which uses null // file arguments writeElementList(xmlOutput, JAR_ELEMENT_NAME, analysisTargets); writeElementList(xmlOutput, AUX_CLASSPATH_ENTRY_ELEMENT_NAME, auxClasspathEntryList); writeElementList(xmlOutput, SRC_DIR_ELEMENT_NAME, srcDirList); XMLOutputUtil.writeFileList(xmlOutput, WRK_DIR_ELEMENT_NAME, currentWorkingDirectoryList); } if (suppressionFilter != null && !suppressionFilter.isEmpty()) { xmlOutput.openTag("SuppressionFilter"); suppressionFilter.writeBodyAsXML(xmlOutput); xmlOutput.closeTag("SuppressionFilter"); } for(Map.Entry<String, Boolean> e : enabledPlugins.entrySet()) { String pluginId = e.getKey(); Boolean enabled = e.getValue(); Plugin plugin = Plugin.getByPluginId(pluginId); if (plugin == null || isDefaultInitialPluginState(plugin, enabled)) { continue; } XMLAttributeList pluginAttributeList = new XMLAttributeList(); pluginAttributeList.addAttribute(PLUGIN_ID_ATTRIBUTE_NAME, plugin.getPluginId()); pluginAttributeList.addAttribute(PLUGIN_STATUS_ELEMENT_NAME, enabled.toString()); xmlOutput.openCloseTag(PLUGIN_ELEMENT_NAME, pluginAttributeList); } if (cloudId != null) { xmlOutput.startTag(CLOUD_ELEMENT_NAME); xmlOutput.addAttribute(CLOUD_ID_ATTRIBUTE_NAME, cloudId); xmlOutput.stopTag(false); for (Map.Entry e : cloudProperties.entrySet()) { xmlOutput.startTag(CLOUD_PROPERTY_ELEMENT_NAME); xmlOutput.addAttribute("key", e.getKey().toString()); xmlOutput.stopTag(false); Object value = e.getValue(); xmlOutput.writeText(value.toString()); xmlOutput.closeTag(CLOUD_PROPERTY_ELEMENT_NAME); } xmlOutput.closeTag(CLOUD_ELEMENT_NAME); } xmlOutput.closeTag(BugCollection.PROJECT_ELEMENT_NAME); } private boolean isDefaultInitialPluginState(Plugin plugin, Boolean enabled) { return plugin.isInitialPlugin() && enabled == plugin.isGloballyEnabled() && plugin.isEnabledByDefault() == plugin.isGloballyEnabled(); } /** * Hack for whether files are case insensitive. For now, we'll assume that * Windows is the only case insensitive OS. (OpenVMS users, feel free to * submit a patch :-) */ private static final boolean FILE_IGNORE_CASE = SystemProperties.getProperty("os.name", "unknown").startsWith("Windows"); private Iterable<String> convertToRelative(List<String> paths, String base) { List<String> newList = new ArrayList<String>(paths.size()); for (String path : paths) { newList.add(convertToRelative(path, base)); } return newList; } /** * Converts a full path to a relative path if possible * * @param srcFile * path to convert * @return the converted filename */ private String convertToRelative(String srcFile, String base) { String slash = SystemProperties.getProperty("file.separator"); if (FILE_IGNORE_CASE) { srcFile = srcFile.toLowerCase(); base = base.toLowerCase(); } if (base.equals(srcFile)) { return "."; } if (!base.endsWith(slash)) { base = base + slash; } if (base.length() <= srcFile.length()) { String root = srcFile.substring(0, base.length()); if (root.equals(base)) { // Strip off the base directory, make relative return "." + SystemProperties.getProperty("file.separator") + srcFile.substring(base.length()); } } // See if we can build a relative path above the base using .. notation int slashPos = srcFile.indexOf(slash); int branchPoint; if (slashPos >= 0) { String subPath = srcFile.substring(0, slashPos); if ((subPath.length() == 0) || base.startsWith(subPath)) { branchPoint = slashPos + 1; slashPos = srcFile.indexOf(slash, branchPoint); while (slashPos >= 0) { subPath = srcFile.substring(0, slashPos); if (base.startsWith(subPath)) { branchPoint = slashPos + 1; } else { break; } slashPos = srcFile.indexOf(slash, branchPoint); } int slashCount = 0; slashPos = base.indexOf(slash, branchPoint); while (slashPos >= 0) { slashCount++; slashPos = base.indexOf(slash, slashPos + 1); } StringBuilder path = new StringBuilder(); String upDir = ".." + slash; for (int i = 0; i < slashCount; i++) { path.append(upDir); } path.append(srcFile.substring(branchPoint)); return path.toString(); } } return srcFile; } /** * Converts a relative path to an absolute path if possible. * * @param fileName * path to convert * @return the converted filename */ private String convertToAbsolute(String fileName) throws IOException { // At present relative paths are only calculated if the fileName is // below the project file. This need not be the case, and we could use // .. // syntax to move up the tree. (To Be Added) File file = new File(fileName); if (!file.isAbsolute()) { for (File cwd : currentWorkingDirectoryList) { File test = new File(cwd, fileName); if (test.canRead()) return test.getAbsolutePath(); } return file.getAbsolutePath(); } return fileName; } /** * Make the given filename absolute relative to the current working * directory. */ private String makeAbsoluteCWD(String fileName) { List<String> candidates = makeAbsoluteCwdCandidates(fileName); return candidates.get(0); } /** * Make the given filename absolute relative to the current working * directory candidates. * * If the given filename exists in more than one of the working directories, * a list of these existing absolute paths is returned. * * The returned list is guaranteed to be non-empty. The returned paths might * exist or not exist and might be relative or absolute. * * @return A list of at least one candidate path for the given filename. */ private List<String> makeAbsoluteCwdCandidates(String fileName) { List<String> candidates = new ArrayList<String>(); boolean hasProtocol = (URLClassPath.getURLProtocol(fileName) != null); if (hasProtocol) { candidates.add(fileName); return candidates; } if (new File(fileName).isAbsolute()) { candidates.add(fileName); return candidates; } for (File currentWorkingDirectory : currentWorkingDirectoryList) { File relativeToCurrent = new File(currentWorkingDirectory, fileName); if (relativeToCurrent.exists()) { candidates.add(relativeToCurrent.toString()); } } if (candidates.isEmpty()) { candidates.add(fileName); } return candidates; } /** * Add a value to given list, making the Project modified if the value is * not already present in the list. * * @param list * the list * @param value * the value to be added * @return true if the value was not already present in the list, false * otherwise */ private <T> boolean addToListInternal(Collection<T> list, T value) { if (!list.contains(value)) { list.add(value); isModified = true; return true; } else { return false; } } /** * Make the given list of pathnames absolute relative to the absolute path * of the project file. */ private void makeListAbsoluteProject(List<String> list) throws IOException { List<String> replace = new LinkedList<String>(); for (String fileName : list) { fileName = convertToAbsolute(fileName); replace.add(fileName); } list.clear(); list.addAll(replace); } /** * @param timestamp * The timestamp to set. */ public void setTimestamp(long timestamp) { this.timestampForAnalyzedClasses = timestamp; } public void addTimestamp(long timestamp) { if (this.timestampForAnalyzedClasses < timestamp && FindBugs.validTimestamp(timestamp)) { this.timestampForAnalyzedClasses = timestamp; } } /** * @return Returns the timestamp. */ public long getTimestamp() { return timestampForAnalyzedClasses; } /** * @param projectName * The projectName to set. */ public void setProjectName(String projectName) { this.projectName = projectName; } /** * @return Returns the projectName. */ public String getProjectName() { return projectName; } /** * @param suppressionFilter * The suppressionFilter to set. */ public void setSuppressionFilter(Filter suppressionFilter) { this.suppressionFilter = suppressionFilter; } /** * @return Returns the suppressionFilter. */ public Filter getSuppressionFilter() { if (suppressionFilter == null) { suppressionFilter = new Filter(); } return suppressionFilter; } public void setGuiCallback(IGuiCallback guiCallback) { this.guiCallback = guiCallback; } public IGuiCallback getGuiCallback() { if (guiCallback == null) guiCallback = new CommandLineUiCallback(); return guiCallback; } /** * @return */ public Iterable<String> getResolvedSourcePaths() { List<String> result = new ArrayList<String>(); for (String s : srcDirList) { boolean hasProtocol = (URLClassPath.getURLProtocol(s) != null); if (hasProtocol) { result.add(s); continue; } File f = new File(s); if (f.isAbsolute() || currentWorkingDirectoryList.isEmpty()) { if (f.canRead()) result.add(s); continue; } for (File d : currentWorkingDirectoryList) if (d.canRead() && d.isDirectory()) { File a = new File(d, s); if (a.canRead()) result.add(a.getAbsolutePath()); } } return result; } } // vim:ts=4
remove blank lines git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@13372 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/Project.java
remove blank lines
Java
apache-2.0
5fe9992f4e0c2c43f54dad621e5b07c18f87fb34
0
escidoc-ng/escidoc-ng,escidoc-ng/escidoc-ng,escidoc-ng/escidoc-ng
/* * Copyright 2014 FIZ Karlsruhe * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ROLE_ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.objecthunter.larch.service.backend.weedfs; import java.io.File; import java.io.IOException; import java.nio.file.FileSystemNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import net.objecthunter.larch.helpers.InputStreamLoggerTask; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; /** * Helper class for starting and monitoring a WeedFs Master node process */ public class WeedFsMaster { private static final Logger log = LoggerFactory.getLogger(WeedFsMaster.class); @Autowired Environment env; private Process masterProcess; private InputStreamLoggerTask loggerTask; @PostConstruct public void init() { if (env.getProperty("blobstore.weedfs.master.enabled") != null && !Boolean.parseBoolean(env.getProperty("blobstore.weedfs.master.enabled"))) { // no weedfs master node is needed return; } /* check if the master dir exists and create if neccessary */ final File dir = new File(env.getProperty("blobstore.weedfs.master.dir")); if (!dir.exists()) { log.info("creating WeedFS master directory at " + dir.getAbsolutePath()); if (!dir.mkdir()) { throw new IllegalArgumentException( "Unable to create master directory. Please check the configuration"); } } if (!dir.canRead() || !dir.canWrite()) { log.error("Unable to create master directory. The application was not initialiazed correctly"); throw new IllegalArgumentException("Unable to use master directory. Please check the configuration"); } if (env.getProperty("blobstore.weedfs.binary") == null) { throw new IllegalArgumentException("The WeedFs Binary path has to be set"); } final File binary = new File(env.getProperty("blobstore.weedfs.binary")); if (!binary.exists()) { throw new IllegalArgumentException(new FileSystemNotFoundException( "The weedfs binary can not be found at " + binary.getAbsolutePath())); } if (!binary.canExecute()) { throw new IllegalArgumentException("The weedfs binary at " + binary.getAbsolutePath() + " can not be executed"); } try { List<String> command = new ArrayList<String> (){{ add(env.getProperty("blobstore.weedfs.binary")); add("master"); add("-mdir=" + env.getProperty("blobstore.weedfs.master.dir")); add("-port=" + env.getProperty("blobstore.weedfs.master.port")); add("-ip=" + env.getProperty("blobstore.weedfs.master.public")); }}; if (StringUtils.isNotBlank(env.getProperty("blobstore.weedfs.master.peers"))) { command.add("-peers=" + env.getProperty("blobstore.weedfs.master.peers")); } log.info("Starting weedfs master with command '" + String.join(" ", command) + "'"); masterProcess = new ProcessBuilder(command) .redirectErrorStream(true) .redirectInput(ProcessBuilder.Redirect.PIPE) .start(); final Executor executor = Executors.newSingleThreadExecutor(); if (!masterProcess.isAlive()) { throw new IOException("WeedFS Master could not be started! Exitcode " + masterProcess.exitValue()); } else { log.info("WeedFs master is running"); executor.execute(new InputStreamLoggerTask(masterProcess.getInputStream())); } } catch (IOException e) { e.printStackTrace(); } } public boolean isAvailable() { final File binary = new File(env.getProperty("blobstore.weedfs.binary")); return binary.exists() && binary.canExecute(); } public boolean isAlive() { return (masterProcess != null) && masterProcess.isAlive(); } @PreDestroy public void shutdown() { log.info("shutting down WeedFS master"); if (this.masterProcess != null && this.masterProcess.isAlive()) { this.masterProcess.destroy(); } } }
larch-server/src/main/java/net/objecthunter/larch/service/backend/weedfs/WeedFsMaster.java
/* * Copyright 2014 FIZ Karlsruhe * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ROLE_ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.objecthunter.larch.service.backend.weedfs; import java.io.File; import java.io.IOException; import java.nio.file.FileSystemNotFoundException; import java.util.Arrays; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import net.objecthunter.larch.helpers.InputStreamLoggerTask; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; /** * Helper class for starting and monitoring a WeedFs Master node process */ public class WeedFsMaster { private static final Logger log = LoggerFactory.getLogger(WeedFsMaster.class); @Autowired Environment env; private Process masterProcess; private InputStreamLoggerTask loggerTask; @PostConstruct public void init() { if (env.getProperty("blobstore.weedfs.master.enabled") != null && !Boolean.parseBoolean(env.getProperty("blobstore.weedfs.master.enabled"))) { // no weedfs master node is needed return; } /* check if the master dir exists and create if neccessary */ final File dir = new File(env.getProperty("blobstore.weedfs.master.dir")); if (!dir.exists()) { log.info("creating WeedFS master directory at " + dir.getAbsolutePath()); if (!dir.mkdir()) { throw new IllegalArgumentException( "Unable to create master directory. Please check the configuration"); } } if (!dir.canRead() || !dir.canWrite()) { log.error("Unable to create master directory. The application was not initialiazed correctly"); throw new IllegalArgumentException("Unable to use master directory. Please check the configuration"); } if (env.getProperty("blobstore.weedfs.binary") == null) { throw new IllegalArgumentException("The WeedFs Binary path has to be set"); } final File binary = new File(env.getProperty("blobstore.weedfs.binary")); if (!binary.exists()) { throw new IllegalArgumentException(new FileSystemNotFoundException( "The weedfs binary can not be found at " + binary.getAbsolutePath())); } if (!binary.canExecute()) { throw new IllegalArgumentException("The weedfs binary at " + binary.getAbsolutePath() + " can not be executed"); } try { List<String> command = Arrays.asList( env.getProperty("blobstore.weedfs.binary"), "master", "-mdir=" + env.getProperty("blobstore.weedfs.master.dir"), "-port=" + env.getProperty("blobstore.weedfs.master.port"), "-ip=" + env.getProperty("blobstore.weedfs.master.public") ); if (StringUtils.isNotBlank(env.getProperty("blobstore.weedfs.master.peers"))) { command.add("-peers=" + env.getProperty("blobstore.weedfs.master.peers")); } log.info("Starting weedfs master with command '" + String.join(" ", command) + "'"); masterProcess = new ProcessBuilder(command) .redirectErrorStream(true) .redirectInput(ProcessBuilder.Redirect.PIPE) .start(); final Executor executor = Executors.newSingleThreadExecutor(); if (!masterProcess.isAlive()) { throw new IOException("WeedFS Master could not be started! Exitcode " + masterProcess.exitValue()); } else { log.info("WeedFs master is running"); executor.execute(new InputStreamLoggerTask(masterProcess.getInputStream())); } } catch (IOException e) { e.printStackTrace(); } } public boolean isAvailable() { final File binary = new File(env.getProperty("blobstore.weedfs.binary")); return binary.exists() && binary.canExecute(); } public boolean isAlive() { return (masterProcess != null) && masterProcess.isAlive(); } @PreDestroy public void shutdown() { log.info("shutting down WeedFS master"); if (this.masterProcess != null && this.masterProcess.isAlive()) { this.masterProcess.destroy(); } } }
add possibility to define peers to weedfs
larch-server/src/main/java/net/objecthunter/larch/service/backend/weedfs/WeedFsMaster.java
add possibility to define peers to weedfs
Java
apache-2.0
e8d5993fe88e08f0b9b0c751e17d7ad440156a6d
0
anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.index.property; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashSet; import java.util.Set; import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.spi.query.Cursor; import org.apache.jackrabbit.oak.spi.query.Cursors; import org.apache.jackrabbit.oak.spi.query.Filter; import org.apache.jackrabbit.oak.spi.query.Filter.PropertyRestriction; import org.apache.jackrabbit.oak.spi.query.QueryIndex; import org.apache.jackrabbit.oak.spi.state.NodeState; import com.google.common.base.Charsets; import com.google.common.collect.Iterables; /** * Provides a QueryIndex that does lookups against a property index * * <p> * To define a property index on a subtree you have to add an <code>oak:index</code> node. * <br> * Next (as a child node) follows the index definition node that: * <ul> * <li>must be of type <code>oak:queryIndexDefinition</code></li> * <li>must have the <code>type</code> property set to <b><code>property</code></b></li> * <li>contains the <code>propertyNames</code> property that indicates what property will be stored in the index</li> * </ul> * </p> * <p> * Optionally you can specify * <ul> * <li> a uniqueness constraint on a property index by setting the <code>unique</code> flag to <code>true</code></li> * <li> that the property index only applies to a certain node type by setting the <code>declaringNodeTypes</code> property</li> * </ul> * </p> * <p> * Notes: * <ul> * <li> <code>propertyNames</code> can be a list of properties, and it is optional.in case it is missing, the node name will be used as a property name reference value</li> * <li> <code>reindex</code> is a property that when set to <code>true</code>, triggers a full content reindex.</li> * </ul> * </p> * * <pre> * <code> * { * NodeBuilder index = root.child("oak:index"); * index.child("uuid") * .setProperty("jcr:primaryType", "oak:queryIndexDefinition", Type.NAME) * .setProperty("type", "property") * .setProperty("propertyNames", "jcr:uuid") * .setProperty("declaringNodeTypes", "mix:referenceable") * .setProperty("unique", true) * .setProperty("reindex", true); * } * </code> * </pre> * * @see QueryIndex * @see PropertyIndexLookup */ class PropertyIndex implements QueryIndex { // TODO the max string length should be removed, or made configurable private static final int MAX_STRING_LENGTH = 100; /** * name used when the indexed value is an empty string */ private static final String EMPTY_TOKEN = ":"; static Set<String> encode(PropertyValue value) { if (value == null) { return null; } Set<String> values = new HashSet<String>(); for (String v : value.getValue(Type.STRINGS)) { try { if (v.length() > MAX_STRING_LENGTH) { v = v.substring(0, MAX_STRING_LENGTH); } if (v.isEmpty()) { v = EMPTY_TOKEN; } else { v = URLEncoder.encode(v, Charsets.UTF_8.name()); } values.add(v); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is unsupported", e); } } return values; } //--------------------------------------------------------< QueryIndex >-- @Override public String getIndexName() { return "property"; } @Override public double getCost(Filter filter, NodeState root) { PropertyIndexLookup lookup = new PropertyIndexLookup(root); for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { // "[property] = $value" return lookup.getCost(filter, propertyName, pr.first); } else if (pr.list != null) { double cost = 0; for (PropertyValue p : pr.list) { cost += lookup.getCost(filter, propertyName, p); } return cost; } else { // processed as "[property] is not null" return lookup.getCost(filter, propertyName, null); } } } // not an appropriate index return Double.POSITIVE_INFINITY; } @Override public Cursor query(Filter filter, NodeState root) { Iterable<String> paths = null; PropertyIndexLookup lookup = new PropertyIndexLookup(root); int depth = 1; for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); depth = PathUtils.getDepth(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { // equality if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { // "[property] = $value" paths = lookup.query(filter, propertyName, pr.first); break; } else if (pr.list != null) { for (PropertyValue pv : pr.list) { Iterable<String> p = lookup.query(filter, propertyName, pv); if (paths == null) { paths = p; } else { paths = Iterables.concat(paths, p); } } break; } else { // processed as "[property] is not null" paths = lookup.query(filter, propertyName, null); break; } } } if (paths == null) { throw new IllegalStateException("Property index is used even when no index is available for filter " + filter); } Cursor c = Cursors.newPathCursor(paths); if (depth > 1) { c = Cursors.newAncestorCursor(c, depth - 1); } return c; } @Override public String getPlan(Filter filter, NodeState root) { StringBuilder buff = new StringBuilder("property"); StringBuilder notIndexed = new StringBuilder(); PropertyIndexLookup lookup = new PropertyIndexLookup(root); for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { buff.append(' ').append(propertyName).append('=').append(pr.first); } else { buff.append(' ').append(propertyName); } } else if (pr.list != null) { buff.append(' ').append(propertyName).append(" IN("); int i = 0; for (PropertyValue pv : pr.list) { if (i++ > 0) { buff.append(", "); } buff.append(pv); } buff.append(')'); } else { notIndexed.append(' ').append(propertyName); if (!pr.toString().isEmpty()) { notIndexed.append(':').append(pr); } } } if (notIndexed.length() > 0) { buff.append(" (").append(notIndexed.toString().trim()).append(")"); } return buff.toString(); } }
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.index.property; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashSet; import java.util.Set; import org.apache.jackrabbit.oak.api.PropertyValue; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.spi.query.Cursor; import org.apache.jackrabbit.oak.spi.query.Cursors; import org.apache.jackrabbit.oak.spi.query.Filter; import org.apache.jackrabbit.oak.spi.query.Filter.PropertyRestriction; import org.apache.jackrabbit.oak.spi.query.QueryIndex; import org.apache.jackrabbit.oak.spi.state.NodeState; import com.google.common.base.Charsets; /** * Provides a QueryIndex that does lookups against a property index * * <p> * To define a property index on a subtree you have to add an <code>oak:index</code> node. * <br> * Next (as a child node) follows the index definition node that: * <ul> * <li>must be of type <code>oak:queryIndexDefinition</code></li> * <li>must have the <code>type</code> property set to <b><code>property</code></b></li> * <li>contains the <code>propertyNames</code> property that indicates what property will be stored in the index</li> * </ul> * </p> * <p> * Optionally you can specify * <ul> * <li> a uniqueness constraint on a property index by setting the <code>unique</code> flag to <code>true</code></li> * <li> that the property index only applies to a certain node type by setting the <code>declaringNodeTypes</code> property</li> * </ul> * </p> * <p> * Notes: * <ul> * <li> <code>propertyNames</code> can be a list of properties, and it is optional.in case it is missing, the node name will be used as a property name reference value</li> * <li> <code>reindex</code> is a property that when set to <code>true</code>, triggers a full content reindex.</li> * </ul> * </p> * * <pre> * <code> * { * NodeBuilder index = root.child("oak:index"); * index.child("uuid") * .setProperty("jcr:primaryType", "oak:queryIndexDefinition", Type.NAME) * .setProperty("type", "property") * .setProperty("propertyNames", "jcr:uuid") * .setProperty("declaringNodeTypes", "mix:referenceable") * .setProperty("unique", true) * .setProperty("reindex", true); * } * </code> * </pre> * * @see QueryIndex * @see PropertyIndexLookup */ class PropertyIndex implements QueryIndex { // TODO the max string length should be removed, or made configurable private static final int MAX_STRING_LENGTH = 100; /** * name used when the indexed value is an empty string */ private static final String EMPTY_TOKEN = ":"; static Set<String> encode(PropertyValue value) { if (value == null) { return null; } Set<String> values = new HashSet<String>(); for (String v : value.getValue(Type.STRINGS)) { try { if (v.length() > MAX_STRING_LENGTH) { v = v.substring(0, MAX_STRING_LENGTH); } if (v.isEmpty()) { v = EMPTY_TOKEN; } else { v = URLEncoder.encode(v, Charsets.UTF_8.name()); } values.add(v); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is unsupported", e); } } return values; } //--------------------------------------------------------< QueryIndex >-- @Override public String getIndexName() { return "property"; } @Override public double getCost(Filter filter, NodeState root) { PropertyIndexLookup lookup = new PropertyIndexLookup(root); for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { // "[property] = $value" return lookup.getCost(filter, propertyName, pr.first); } else { // processed as "[property] is not null" return lookup.getCost(filter, propertyName, null); } } } // not an appropriate index return Double.POSITIVE_INFINITY; } @Override public Cursor query(Filter filter, NodeState root) { Iterable<String> paths = null; PropertyIndexLookup lookup = new PropertyIndexLookup(root); int depth = 1; for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); depth = PathUtils.getDepth(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { // equality if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { // "[property] = $value" paths = lookup.query(filter, propertyName, pr.first); break; } else { // processed as "[property] is not null" paths = lookup.query(filter, propertyName, null); break; } } } if (paths == null) { throw new IllegalStateException("Property index is used even when no index is available for filter " + filter); } Cursor c = Cursors.newPathCursor(paths); if (depth > 1) { c = Cursors.newAncestorCursor(c, depth - 1); } return c; } @Override public String getPlan(Filter filter, NodeState root) { StringBuilder buff = new StringBuilder("property"); StringBuilder notIndexed = new StringBuilder(); PropertyIndexLookup lookup = new PropertyIndexLookup(root); for (PropertyRestriction pr : filter.getPropertyRestrictions()) { String propertyName = PathUtils.getName(pr.propertyName); // TODO support indexes on a path // currently, only indexes on the root node are supported if (lookup.isIndexed(propertyName, "/", filter)) { if (pr.firstIncluding && pr.lastIncluding && pr.first != null && pr.first.equals(pr.last)) { buff.append(' ').append(propertyName).append('=').append(pr.first); } else { buff.append(' ').append(propertyName); } } else { notIndexed.append(' ').append(propertyName); if (!pr.toString().isEmpty()) { notIndexed.append(':').append(pr); } } } if (notIndexed.length() > 0) { buff.append(" (").append(notIndexed.toString().trim()).append(")"); } return buff.toString(); } }
OAK-882 Query: support conditions of type "property in(value1, value2)" git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1496970 13f79535-47bb-0310-9956-ffa450edef68
oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/index/property/PropertyIndex.java
OAK-882 Query: support conditions of type "property in(value1, value2)"
Java
apache-2.0
48e9df3722e9eac786cd207472dfe77e1ef4da3e
0
jeffpc/voldemort,birendraa/voldemort,dallasmarlow/voldemort,HB-SI/voldemort,squarY/voldemort,stotch/voldemort,voldemort/voldemort,voldemort/voldemort,squarY/voldemort,arunthirupathi/voldemort,jwlent55/voldemort,gnb/voldemort,medallia/voldemort,rickbw/voldemort,mabh/voldemort,FelixGV/voldemort,FelixGV/voldemort,jeffpc/voldemort,jwlent55/voldemort,bitti/voldemort,mabh/voldemort,arunthirupathi/voldemort,PratikDeshpande/voldemort,gnb/voldemort,arunthirupathi/voldemort,PratikDeshpande/voldemort,rickbw/voldemort,jwlent55/voldemort,rickbw/voldemort,bhasudha/voldemort,FelixGV/voldemort,squarY/voldemort,squarY/voldemort,jeffpc/voldemort,bhasudha/voldemort,dallasmarlow/voldemort,arunthirupathi/voldemort,voldemort/voldemort,stotch/voldemort,stotch/voldemort,LeoYao/voldemort,LeoYao/voldemort,bhasudha/voldemort,rickbw/voldemort,FelixGV/voldemort,birendraa/voldemort,gnb/voldemort,jwlent55/voldemort,cshaxu/voldemort,PratikDeshpande/voldemort,HB-SI/voldemort,bitti/voldemort,jalkjaer/voldemort,null-exception/voldemort,HB-SI/voldemort,jeffpc/voldemort,mabh/voldemort,FelixGV/voldemort,gnb/voldemort,rickbw/voldemort,FelixGV/voldemort,birendraa/voldemort,stotch/voldemort,bitti/voldemort,birendraa/voldemort,bhasudha/voldemort,medallia/voldemort,mabh/voldemort,bitti/voldemort,LeoYao/voldemort,PratikDeshpande/voldemort,birendraa/voldemort,cshaxu/voldemort,squarY/voldemort,bitti/voldemort,squarY/voldemort,mabh/voldemort,birendraa/voldemort,voldemort/voldemort,HB-SI/voldemort,squarY/voldemort,gnb/voldemort,medallia/voldemort,medallia/voldemort,PratikDeshpande/voldemort,jwlent55/voldemort,rickbw/voldemort,stotch/voldemort,null-exception/voldemort,null-exception/voldemort,LeoYao/voldemort,medallia/voldemort,jalkjaer/voldemort,bhasudha/voldemort,cshaxu/voldemort,dallasmarlow/voldemort,arunthirupathi/voldemort,bitti/voldemort,jalkjaer/voldemort,jalkjaer/voldemort,null-exception/voldemort,LeoYao/voldemort,PratikDeshpande/voldemort,HB-SI/voldemort,jeffpc/voldemort,jeffpc/voldemort,cshaxu/voldemort,bitti/voldemort,medallia/voldemort,stotch/voldemort,voldemort/voldemort,jalkjaer/voldemort,dallasmarlow/voldemort,LeoYao/voldemort,dallasmarlow/voldemort,bhasudha/voldemort,HB-SI/voldemort,voldemort/voldemort,gnb/voldemort,jalkjaer/voldemort,dallasmarlow/voldemort,cshaxu/voldemort,null-exception/voldemort,null-exception/voldemort,jalkjaer/voldemort,jwlent55/voldemort,FelixGV/voldemort,voldemort/voldemort,arunthirupathi/voldemort,arunthirupathi/voldemort,mabh/voldemort,cshaxu/voldemort
/* * Copyright 2008-2009 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.client.protocol.admin; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.client.protocol.RequestFormatType; import voldemort.client.protocol.pb.ProtoUtils; import voldemort.client.protocol.pb.VAdminProto; import voldemort.cluster.Node; import voldemort.routing.RoutingStrategy; import voldemort.routing.RoutingStrategyFactory; import voldemort.store.StoreDefinition; import voldemort.store.socket.SocketDestination; import voldemort.utils.ByteArray; import voldemort.utils.EventThrottler; import voldemort.utils.Pair; import voldemort.versioning.Versioned; /** * * @author anagpal * * The streaming API allows for send events into voldemort stores in the * async fashion. All the partition and replication logic will be taken * care of internally. * * The users is expected to provide two callbacks, one for performing * period checkpoints and one for recovering the streaming process from * the last checkpoint. * * NOTE: The API is not thread safe, since if multiple threads use this * API we cannot make any guarantees about correctness of the * checkpointing mechanism. * * Right now we expect this to used by a single thread per data source * */ public class StreamingClient { private static final Logger logger = Logger.getLogger(StreamingClient.class); @SuppressWarnings("rawtypes") private Callable checkpointCallback = null; @SuppressWarnings("rawtypes") private Callable recoveryCallback = null; private boolean allowMerge = false; private SocketPool streamingSocketPool; List<StoreDefinition> remoteStoreDefs; protected RoutingStrategy routingStrategy; boolean newBatch; boolean cleanedUp = false; boolean isMultiSession; ExecutorService streamingresults; // Every batch size we commit private static int CHECKPOINT_COMMIT_SIZE; // TODO // provide knobs to tune this private static int TIME_COMMIT_SIZE = 30; // we have to throttle to a certain qps private static int THROTTLE_QPS; private int entriesProcessed; // In case a Recovery callback fails we got to stop it from getting any // worse // so we mark the session as bad and dont take any more requests private static boolean MARKED_BAD = false; protected EventThrottler throttler; AdminClient adminClient; AdminClientConfig adminClientConfig; String bootstrapURL; // Data structures for the streaming maps from Pair<Store, Node Id> to // Resource private HashMap<String, RoutingStrategy> storeToRoutingStrategy; private HashMap<Pair<String, Integer>, Boolean> nodeIdStoreInitialized; private HashMap<Pair<String, Integer>, SocketDestination> nodeIdStoreToSocketRequest; private HashMap<Pair<String, Integer>, DataOutputStream> nodeIdStoreToOutputStreamRequest; private HashMap<Pair<String, Integer>, DataInputStream> nodeIdStoreToInputStreamRequest; private HashMap<Pair<String, Integer>, SocketAndStreams> nodeIdStoreToSocketAndStreams; private List<String> storeNames; private List<Node> nodesToStream; private List<Integer> blackListedNodes; private final static int MAX_STORES_PER_SESSION = 100; // use this as a guard against race conditions due to a sperate timer based // checkpointer thread which flushes data to the V server final ReentrantLock commitActionLock = new ReentrantLock(); Calendar calendar = Calendar.getInstance(); public StreamingClient(StreamingClientConfig config) { this.bootstrapURL = config.getBootstrapURL(); CHECKPOINT_COMMIT_SIZE = config.getBatchSize(); THROTTLE_QPS = config.getThrottleQPS(); } public void updateThrottleLimit(int throttleQPS) { THROTTLE_QPS = throttleQPS; this.throttler = new EventThrottler(THROTTLE_QPS); } /** ** * @param store - the name of the store to be streamed to * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. **/ @SuppressWarnings({ "rawtypes", "unchecked" }) public void initStreamingSession(String store, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge) { // internally call initsessions with a single store List<String> stores = new ArrayList(); stores.add(store); initStreamingSessions(stores, checkpointCallback, recoveryCallback, allowMerge); } /** * A Streaming Put call ** * @param key - The key * * @param value - The value **/ @SuppressWarnings({}) public void streamingPut(ByteArray key, Versioned<byte[]> value) { if(MARKED_BAD) { logger.error("Cannot stream more entries since Recovery Callback Failed!"); throw new VoldemortException("Cannot stream more entries since Recovery Callback Failed!"); } for(String store: storeNames) { streamingPut(key, value, store); } } /** ** * @param resetCheckpointCallback - the callback that allows for the user to * clean up the checkpoint at the end of the streaming session so a * new session could, if necessary, start from 0 position. **/ @SuppressWarnings({ "rawtypes" }) public synchronized void closeStreamingSession(Callable resetCheckpointCallback) { closeStreamingSessions(resetCheckpointCallback); } /** * Close the streaming session Flush all n/w buffers and call the commit * callback **/ @SuppressWarnings({}) public synchronized void closeStreamingSession() { closeStreamingSessions(); } private void close(Socket socket) { try { socket.close(); } catch(IOException e) { logger.warn("Failed to close socket"); } } @Override protected void finalize() { if(!cleanedUp) { cleanupSessions(); } } /** ** * @param stores - the list of name of the stores to be streamed to * * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. **/ @SuppressWarnings({ "rawtypes" }) public void initStreamingSessions(List<String> stores, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge) { initStreamingSessions(stores, checkpointCallback, recoveryCallback, allowMerge, null); } /** ** * @param stores - the list of name of the stores to be streamed to * * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. * * @param blackListedNodes - the list of Nodes not to stream to; we can * probably recover them later from the replicas **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public void initStreamingSessions(List<String> stores, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge, List<Integer> blackListedNodes) { logger.info("Initializing a streaming session"); adminClientConfig = new AdminClientConfig(); adminClient = new AdminClient(bootstrapURL, adminClientConfig); this.checkpointCallback = checkpointCallback; this.recoveryCallback = recoveryCallback; this.allowMerge = allowMerge; streamingresults = Executors.newFixedThreadPool(3); entriesProcessed = 0; newBatch = true; isMultiSession = true; storeNames = new ArrayList(); this.throttler = new EventThrottler(THROTTLE_QPS); TimeUnit unit = TimeUnit.SECONDS; Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes(); nodesToStream = new ArrayList(); if(blackListedNodes != null && blackListedNodes.size() > 0) { this.blackListedNodes = blackListedNodes; } for(Node node: nodesInCluster) { if(blackListedNodes != null && blackListedNodes.size() > 0) { if(!blackListedNodes.contains(node.getId())) { nodesToStream.add(node); } } else nodesToStream.add(node); } // socket pool streamingSocketPool = new SocketPool(adminClient.getAdminClientCluster().getNumberOfNodes() * MAX_STORES_PER_SESSION, (int) unit.toMillis(adminClientConfig.getAdminConnectionTimeoutSec()), (int) unit.toMillis(adminClientConfig.getAdminSocketTimeoutSec()), adminClientConfig.getAdminSocketBufferSize(), adminClientConfig.getAdminSocketKeepAlive()); nodeIdStoreToSocketRequest = new HashMap(); nodeIdStoreToOutputStreamRequest = new HashMap(); nodeIdStoreToInputStreamRequest = new HashMap(); nodeIdStoreInitialized = new HashMap(); storeToRoutingStrategy = new HashMap(); nodeIdStoreToSocketAndStreams = new HashMap(); for(String store: stores) { addStoreToSession(store); } } /** * Add another store destination to an existing streaming session * * * @param store: the name of the store to stream to */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void addStoreToSession(String store) { storeNames.add(store); for(Node node: nodesToStream) { SocketDestination destination = new SocketDestination(node.getHost(), node.getAdminPort(), RequestFormatType.ADMIN_PROTOCOL_BUFFERS); SocketAndStreams sands = streamingSocketPool.checkout(destination); try { DataOutputStream outputStream = sands.getOutputStream(); DataInputStream inputStream = sands.getInputStream(); nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination); nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream); nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream); nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands); nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId()) .getValue(); } catch(Exception e) { close(sands.getSocket()); streamingSocketPool.checkin(destination, sands); throw new VoldemortException(e); } } boolean foundStore = false; for(StoreDefinition remoteStoreDef: remoteStoreDefs) { if(remoteStoreDef.getName().equals(store)) { RoutingStrategyFactory factory = new RoutingStrategyFactory(); RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef, adminClient.getAdminClientCluster()); storeToRoutingStrategy.put(store, storeRoutingStrategy); foundStore = true; break; } } if(!foundStore) { logger.error("Store Name not found on the cluster"); throw new VoldemortException("Store Name not found on the cluster"); } } /** * Remove a list of stores from the session * * First commit all entries for these stores and then cleanup resources * * @param storeNameToRemove List of stores to be removed from the current * streaming session * **/ @SuppressWarnings({}) public void removeStoreFromSession(List<String> storeNameToRemove) { logger.info("closing the Streaming session for a few stores"); commitToVoldemort(storeNameToRemove); cleanupSessions(storeNameToRemove); } /** ** * @param key - The key * * @param value - The value * * @param storeName takes an additional store name as a parameter * * If a store is added mid way through a streaming session we do not * play catchup and entries that were processed earlier during the * session will not be applied for the store. * **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public void streamingPut(ByteArray key, Versioned<byte[]> value, String storeName) { commitActionLock.lock(); // If store does not exist in the stores list // add it and checkout a socket if(!storeNames.contains(storeName)) { addStoreToSession(storeName); } if(MARKED_BAD) { logger.error("Cannot stream more entries since Recovery Callback Failed!"); throw new VoldemortException("Cannot stream more entries since Recovery Callback Failed! You Need to restart the session"); } List<Node> nodeList = storeToRoutingStrategy.get(storeName).routeRequest(key.get()); // sent the k/v pair to the nodes for(Node node: nodeList) { if(blackListedNodes != null && blackListedNodes.size() > 0) { if(blackListedNodes.contains(node.getId())) continue; } // if node! in blacklistednodes VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder() .setKey(ProtoUtils.encodeBytes(key)) .setVersioned(ProtoUtils.encodeVersioned(value)) .build(); VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder() .setStore(storeName) .setPartitionEntry(partitionEntry); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(storeName, node.getId())); try { if(nodeIdStoreInitialized.get(new Pair(storeName, node.getId()))) { ProtoUtils.writeMessage(outputStream, updateRequest.build()); } else { ProtoUtils.writeMessage(outputStream, VAdminProto.VoldemortAdminRequest.newBuilder() .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES) .setUpdatePartitionEntries(updateRequest) .build()); outputStream.flush(); nodeIdStoreInitialized.put(new Pair(storeName, node.getId()), true); } entriesProcessed++; } catch(IOException e) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } e.printStackTrace(); } } int secondsTime = calendar.get(Calendar.SECOND); if(entriesProcessed == CHECKPOINT_COMMIT_SIZE || secondsTime % TIME_COMMIT_SIZE == 0) { entriesProcessed = 0; commitToVoldemort(); } throttler.maybeThrottle(1); commitActionLock.unlock(); } /** * Flush the network buffer and write all entries to the server Wait for an * ack from the server This is a blocking call. It is invoked on every * Commit batch size of entries It is also called on the close session call */ public synchronized void commitToVoldemort() { entriesProcessed = 0; commitToVoldemort(storeNames); } /** * Flush the network buffer and write all entries to the serve. then wait * for an ack from the server. This is a blocking call. It is invoked on * every Commit batch size of entries, It is also called on the close * session call * * @param storeNameToCommit List of stores to be flushed and committed * */ @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { commitActionLock.lock(); logger.info("Trying to commit to Voldemort"); for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); outputStream.flush(); DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } } else { logger.info("Commit successful"); logger.info("calling checkpoint callback"); Future future = streamingresults.submit(checkpointCallback); try { future.get(); } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!"); e1.printStackTrace(); } catch(ExecutionException e1) { logger.warn("Checkpoint callback failed!"); e1.printStackTrace(); } } } catch(IOException e) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } e.printStackTrace(); } } } commitActionLock.unlock(); } /** ** * @param resetCheckpointCallback - the callback that allows for the user to * clean up the checkpoint at the end of the streaming session so a * new session could, if necessary, start from 0 position. **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public synchronized void closeStreamingSessions(Callable resetCheckpointCallback) { closeStreamingSessions(); Future future = streamingresults.submit(resetCheckpointCallback); try { future.get(); } catch(InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch(ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * Close the streaming session Flush all n/w buffers and call the commit * callback **/ @SuppressWarnings({}) public synchronized void closeStreamingSessions() { logger.info("closing the Streaming session"); commitToVoldemort(); cleanupSessions(); } /** * Helper method to Close all open socket connections and checkin back to * the pool */ private void cleanupSessions() { cleanupSessions(storeNames); } /** * Helper method to Close all open socket connections and checkin back to * the pool * * @param storeNameToCleanUp List of stores to be cleanedup from the current * streaming session */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void cleanupSessions(List<String> storeNamesToCleanUp) { commitActionLock.lock(); logger.info("Performing cleanup"); for(String store: storeNamesToCleanUp) { for(Node node: nodesToStream) { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, node.getId())); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, node.getId())); streamingSocketPool.checkin(destination, sands); } } cleanedUp = true; commitActionLock.unlock(); } }
src/java/voldemort/client/protocol/admin/StreamingClient.java
/* * Copyright 2008-2009 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package voldemort.client.protocol.admin; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.client.protocol.RequestFormatType; import voldemort.client.protocol.pb.ProtoUtils; import voldemort.client.protocol.pb.VAdminProto; import voldemort.cluster.Node; import voldemort.routing.RoutingStrategy; import voldemort.routing.RoutingStrategyFactory; import voldemort.store.StoreDefinition; import voldemort.store.socket.SocketDestination; import voldemort.utils.ByteArray; import voldemort.utils.EventThrottler; import voldemort.utils.Pair; import voldemort.versioning.Versioned; /** * * @author anagpal * * The streaming API allows for send events into voldemort stores in the * async fashion. All the partition and replication logic will be taken * care of internally. * * The users is expected to provide two callbacks, one for performing * period checkpoints and one for recovering the streaming process from * the last checkpoint. * * NOTE: The API is not thread safe, since if multiple threads use this * API we cannot make any guarantees about correctness of the * checkpointing mechanism. * * Right now we expect this to used by a single thread per data source * */ public class StreamingClient { private static final Logger logger = Logger.getLogger(StreamingClient.class); @SuppressWarnings("rawtypes") private Callable checkpointCallback = null; @SuppressWarnings("rawtypes") private Callable recoveryCallback = null; private boolean allowMerge = false; private SocketPool streamingSocketPool; List<StoreDefinition> remoteStoreDefs; protected RoutingStrategy routingStrategy; boolean newBatch; boolean cleanedUp = false; boolean isMultiSession; ExecutorService streamingresults; // Every batch size we commit private static int CHECKPOINT_COMMIT_SIZE; // TODO // provide knobs to tune this private static int TIME_COMMIT_SIZE = 30; // we have to throttle to a certain qps private static int THROTTLE_QPS; private int entriesProcessed; // In case a Recovery callback fails we got to stop it from getting any // worse // so we mark the session as bad and dont take any more requests private static boolean MARKED_BAD = false; protected EventThrottler throttler; AdminClient adminClient; AdminClientConfig adminClientConfig; String bootstrapURL; // Data structures for the streaming maps from Pair<Store, Node Id> to // Resource private HashMap<String, RoutingStrategy> storeToRoutingStrategy; private HashMap<Pair<String, Integer>, Boolean> nodeIdStoreInitialized; private HashMap<Pair<String, Integer>, SocketDestination> nodeIdStoreToSocketRequest; private HashMap<Pair<String, Integer>, DataOutputStream> nodeIdStoreToOutputStreamRequest; private HashMap<Pair<String, Integer>, DataInputStream> nodeIdStoreToInputStreamRequest; private HashMap<Pair<String, Integer>, SocketAndStreams> nodeIdStoreToSocketAndStreams; private List<String> storeNames; private List<Node> nodesToStream; private List<Integer> blackListedNodes; private final static int MAX_STORES_PER_SESSION = 100; Calendar calendar = Calendar.getInstance(); public StreamingClient(StreamingClientConfig config) { this.bootstrapURL = config.getBootstrapURL(); CHECKPOINT_COMMIT_SIZE = config.getBatchSize(); THROTTLE_QPS = config.getThrottleQPS(); } public void updateThrottleLimit(int throttleQPS) { THROTTLE_QPS = throttleQPS; this.throttler = new EventThrottler(THROTTLE_QPS); } /** ** * @param store - the name of the store to be streamed to * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. **/ @SuppressWarnings({ "rawtypes", "unchecked" }) public void initStreamingSession(String store, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge) { // internally call initsessions with a single store List<String> stores = new ArrayList(); stores.add(store); initStreamingSessions(stores, checkpointCallback, recoveryCallback, allowMerge); } /** * A Streaming Put call ** * @param key - The key * * @param value - The value **/ @SuppressWarnings({}) public void streamingPut(ByteArray key, Versioned<byte[]> value) { if(MARKED_BAD) { logger.error("Cannot stream more entries since Recovery Callback Failed!"); throw new VoldemortException("Cannot stream more entries since Recovery Callback Failed!"); } for(String store: storeNames) { streamingPut(key, value, store); } } /** ** * @param resetCheckpointCallback - the callback that allows for the user to * clean up the checkpoint at the end of the streaming session so a * new session could, if necessary, start from 0 position. **/ @SuppressWarnings({ "rawtypes" }) public synchronized void closeStreamingSession(Callable resetCheckpointCallback) { closeStreamingSessions(resetCheckpointCallback); } /** * Close the streaming session Flush all n/w buffers and call the commit * callback **/ @SuppressWarnings({}) public synchronized void closeStreamingSession() { closeStreamingSessions(); } private void close(Socket socket) { try { socket.close(); } catch(IOException e) { logger.warn("Failed to close socket"); } } @Override protected void finalize() { if(!cleanedUp) { cleanupSessions(); } } /** ** * @param stores - the list of name of the stores to be streamed to * * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. **/ @SuppressWarnings({ "rawtypes" }) public void initStreamingSessions(List<String> stores, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge) { initStreamingSessions(stores, checkpointCallback, recoveryCallback, allowMerge, null); } /** ** * @param stores - the list of name of the stores to be streamed to * * * @param checkpointCallback - the callback that allows for the user to * record the progress, up to the last event delivered. This callable * would be invoked every so often internally. * * @param recoveryCallback - the callback that allows the user to rewind the * upstream to the position recorded by the last complete call on * checkpointCallback whenever an exception occurs during the * streaming session. * * @param allowMerge - whether to allow for the streaming event to be merged * with online writes. If not, all online writes since the completion * of the last streaming session will be lost at the end of the * current streaming session. * * @param blackListedNodes - the list of Nodes not to stream to; we can * probably recover them later from the replicas **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public void initStreamingSessions(List<String> stores, Callable checkpointCallback, Callable recoveryCallback, boolean allowMerge, List<Integer> blackListedNodes) { logger.info("Initializing a streaming session"); adminClientConfig = new AdminClientConfig(); adminClient = new AdminClient(bootstrapURL, adminClientConfig); this.checkpointCallback = checkpointCallback; this.recoveryCallback = recoveryCallback; this.allowMerge = allowMerge; streamingresults = Executors.newFixedThreadPool(3); entriesProcessed = 0; newBatch = true; isMultiSession = true; storeNames = new ArrayList(); this.throttler = new EventThrottler(THROTTLE_QPS); TimeUnit unit = TimeUnit.SECONDS; Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes(); nodesToStream = new ArrayList(); if(blackListedNodes != null && blackListedNodes.size() > 0) { this.blackListedNodes = blackListedNodes; } for(Node node: nodesInCluster) { if(blackListedNodes != null && blackListedNodes.size() > 0) { if(!blackListedNodes.contains(node.getId())) { nodesToStream.add(node); } } else nodesToStream.add(node); } // socket pool streamingSocketPool = new SocketPool(adminClient.getAdminClientCluster().getNumberOfNodes() * MAX_STORES_PER_SESSION, (int) unit.toMillis(adminClientConfig.getAdminConnectionTimeoutSec()), (int) unit.toMillis(adminClientConfig.getAdminSocketTimeoutSec()), adminClientConfig.getAdminSocketBufferSize(), adminClientConfig.getAdminSocketKeepAlive()); nodeIdStoreToSocketRequest = new HashMap(); nodeIdStoreToOutputStreamRequest = new HashMap(); nodeIdStoreToInputStreamRequest = new HashMap(); nodeIdStoreInitialized = new HashMap(); storeToRoutingStrategy = new HashMap(); nodeIdStoreToSocketAndStreams = new HashMap(); for(String store: stores) { addStoreToSession(store); } } /** * Add another store destination to an existing streaming session * * * @param store: the name of the store to stream to */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void addStoreToSession(String store) { storeNames.add(store); for(Node node: nodesToStream) { SocketDestination destination = new SocketDestination(node.getHost(), node.getAdminPort(), RequestFormatType.ADMIN_PROTOCOL_BUFFERS); SocketAndStreams sands = streamingSocketPool.checkout(destination); try { DataOutputStream outputStream = sands.getOutputStream(); DataInputStream inputStream = sands.getInputStream(); nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination); nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream); nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream); nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands); nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId()) .getValue(); } catch(Exception e) { close(sands.getSocket()); streamingSocketPool.checkin(destination, sands); throw new VoldemortException(e); } } boolean foundStore = false; for(StoreDefinition remoteStoreDef: remoteStoreDefs) { if(remoteStoreDef.getName().equals(store)) { RoutingStrategyFactory factory = new RoutingStrategyFactory(); RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef, adminClient.getAdminClientCluster()); storeToRoutingStrategy.put(store, storeRoutingStrategy); foundStore = true; break; } } if(!foundStore) { logger.error("Store Name not found on the cluster"); throw new VoldemortException("Store Name not found on the cluster"); } } /** * Remove a list of stores from the session * * First commit all entries for these stores and then cleanup resources * * @param storeNameToRemove List of stores to be removed from the current * streaming session * **/ @SuppressWarnings({}) public void removeStoreFromSession(List<String> storeNameToRemove) { logger.info("closing the Streaming session for a few stores"); commitToVoldemort(storeNameToRemove); cleanupSessions(storeNameToRemove); } /** ** * @param key - The key * * @param value - The value * * @param storeName takes an additional store name as a parameter * * If a store is added mid way through a streaming session we do not * play catchup and entries that were processed earlier during the * session will not be applied for the store. * **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public void streamingPut(ByteArray key, Versioned<byte[]> value, String storeName) { // If store does not exist in the stores list // add it and checkout a socket if(!storeNames.contains(storeName)) { addStoreToSession(storeName); } if(MARKED_BAD) { logger.error("Cannot stream more entries since Recovery Callback Failed!"); throw new VoldemortException("Cannot stream more entries since Recovery Callback Failed! You Need to restart the session"); } List<Node> nodeList = storeToRoutingStrategy.get(storeName).routeRequest(key.get()); // sent the k/v pair to the nodes for(Node node: nodeList) { if(blackListedNodes != null && blackListedNodes.size() > 0) { if(blackListedNodes.contains(node.getId())) continue; } // if node! in blacklistednodes VAdminProto.PartitionEntry partitionEntry = VAdminProto.PartitionEntry.newBuilder() .setKey(ProtoUtils.encodeBytes(key)) .setVersioned(ProtoUtils.encodeVersioned(value)) .build(); VAdminProto.UpdatePartitionEntriesRequest.Builder updateRequest = VAdminProto.UpdatePartitionEntriesRequest.newBuilder() .setStore(storeName) .setPartitionEntry(partitionEntry); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(storeName, node.getId())); try { if(nodeIdStoreInitialized.get(new Pair(storeName, node.getId()))) { ProtoUtils.writeMessage(outputStream, updateRequest.build()); } else { ProtoUtils.writeMessage(outputStream, VAdminProto.VoldemortAdminRequest.newBuilder() .setType(VAdminProto.AdminRequestType.UPDATE_PARTITION_ENTRIES) .setUpdatePartitionEntries(updateRequest) .build()); outputStream.flush(); nodeIdStoreInitialized.put(new Pair(storeName, node.getId()), true); } entriesProcessed++; } catch(IOException e) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } e.printStackTrace(); } } int secondsTime = calendar.get(Calendar.SECOND); if(entriesProcessed == CHECKPOINT_COMMIT_SIZE || secondsTime % TIME_COMMIT_SIZE == 0) { entriesProcessed = 0; commitToVoldemort(); } throttler.maybeThrottle(1); } /** * Flush the network buffer and write all entries to the server Wait for an * ack from the server This is a blocking call. It is invoked on every * Commit batch size of entries It is also called on the close session call */ public synchronized void commitToVoldemort() { entriesProcessed = 0; commitToVoldemort(storeNames); } /** * Flush the network buffer and write all entries to the serve. then wait * for an ack from the server. This is a blocking call. It is invoked on * every Commit batch size of entries, It is also called on the close * session call * * @param storeNameToCommit List of stores to be flushed and committed * */ @SuppressWarnings({ "unchecked", "rawtypes", "unused" }) private void commitToVoldemort(List<String> storeNamesToCommit) { logger.info("Trying to commit to Voldemort"); for(Node node: nodesToStream) { for(String store: storeNamesToCommit) { if(!nodeIdStoreInitialized.get(new Pair(store, node.getId()))) continue; nodeIdStoreInitialized.put(new Pair(store, node.getId()), false); DataOutputStream outputStream = nodeIdStoreToOutputStreamRequest.get(new Pair(store, node.getId())); try { ProtoUtils.writeEndOfStream(outputStream); outputStream.flush(); DataInputStream inputStream = nodeIdStoreToInputStreamRequest.get(new Pair(store, node.getId())); VAdminProto.UpdatePartitionEntriesResponse.Builder updateResponse = ProtoUtils.readToBuilder(inputStream, VAdminProto.UpdatePartitionEntriesResponse.newBuilder()); if(updateResponse.hasError()) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } } else { logger.info("Commit successful"); logger.info("calling checkpoint callback"); Future future = streamingresults.submit(checkpointCallback); try { future.get(); } catch(InterruptedException e1) { logger.warn("Checkpoint callback failed!"); e1.printStackTrace(); } catch(ExecutionException e1) { logger.warn("Checkpoint callback failed!"); e1.printStackTrace(); } } } catch(IOException e) { logger.warn("Invoking the Recovery Callback"); Future future = streamingresults.submit(recoveryCallback); try { future.get(); } catch(InterruptedException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } catch(ExecutionException e1) { MARKED_BAD = true; logger.error("Recovery Callback failed"); e1.printStackTrace(); throw new VoldemortException("Recovery Callback failed"); } e.printStackTrace(); } } } } /** ** * @param resetCheckpointCallback - the callback that allows for the user to * clean up the checkpoint at the end of the streaming session so a * new session could, if necessary, start from 0 position. **/ @SuppressWarnings({ "unchecked", "rawtypes" }) public synchronized void closeStreamingSessions(Callable resetCheckpointCallback) { closeStreamingSessions(); Future future = streamingresults.submit(resetCheckpointCallback); try { future.get(); } catch(InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch(ExecutionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * Close the streaming session Flush all n/w buffers and call the commit * callback **/ @SuppressWarnings({}) public synchronized void closeStreamingSessions() { logger.info("closing the Streaming session"); commitToVoldemort(); cleanupSessions(); } /** * Helper method to Close all open socket connections and checkin back to * the pool */ private void cleanupSessions() { cleanupSessions(storeNames); } /** * Helper method to Close all open socket connections and checkin back to * the pool * * @param storeNameToCleanUp List of stores to be cleanedup from the current * streaming session */ @SuppressWarnings({ "rawtypes", "unchecked" }) private void cleanupSessions(List<String> storeNamesToCleanUp) { logger.info("Performing cleanup"); for(String store: storeNamesToCleanUp) { for(Node node: nodesToStream) { SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, node.getId())); close(sands.getSocket()); SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store, node.getId())); streamingSocketPool.checkin(destination, sands); } } cleanedUp = true; } }
added a reentrantlock to synchronize access the streamingclient consumer may implement a time based flushing through a scheduled executor service or a timer thread(like in YASP) this helps achieveing a lock step access
src/java/voldemort/client/protocol/admin/StreamingClient.java
added a reentrantlock to synchronize access the streamingclient consumer may implement a time based flushing through a scheduled executor service or a timer thread(like in YASP) this helps achieveing a lock step access
Java
apache-2.0
5d0e38d808e0ea105a622526aa6ebc8fd27e8818
0
palantir/atlasdb,EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb
package com.palantir.atlasdb.performance; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import org.immutables.value.Value; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.Multiset; import org.openjdk.jmh.util.Statistics; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.collect.Lists; public class PerformanceResults { private final Collection<RunResult> results; public PerformanceResults(Collection<RunResult> results) { this.results = results; } public void writeToFile(File file) throws IOException { try (BufferedWriter fout = new BufferedWriter(new FileWriter(file))) { long date = System.currentTimeMillis(); List<ImmutablePerformanceResult> newResults = results.stream().map(r -> { String[] benchmarkParts = r.getParams().getBenchmark().split("\\."); String benchmarkSuite = benchmarkParts[benchmarkParts.length - 2]; String benchmarkName = benchmarkParts[benchmarkParts.length - 1]; return ImmutablePerformanceResult.builder() .date(date) .suite(benchmarkSuite) .benchmark(benchmarkName) .backend(r.getParams().getParam((BenchmarkParam.BACKEND.getKey()))) .samples(r.getPrimaryResult().getStatistics().getN()) .std(r.getPrimaryResult().getStatistics().getStandardDeviation()) .mean(r.getPrimaryResult().getStatistics().getMean()) .data(getData(r)) .units(r.getParams().getTimeUnit()) .build(); }).collect(Collectors.toList()); new ObjectMapper().writeValue(fout, newResults); } } private List<Double> getData(RunResult result) { return result.getBenchmarkResults().stream() .flatMap(b -> getRawResults(b.getPrimaryResult().getStatistics()).stream()) .collect(Collectors.toList()); } private List<Double> getRawResults(Statistics statistics) { try { Field f = statistics.getClass().getDeclaredField("values"); f.setAccessible(true); Multiset<Double> rawResults = (Multiset<Double>) f.get(statistics); return rawResults.entrySet().stream() .flatMap(e -> DoubleStream.iterate(e.getKey(), d -> d).limit(e.getValue()).boxed()) .collect(Collectors.toList()); } catch (NoSuchFieldException | IllegalAccessException e) { return Lists.newArrayList(); } } @JsonDeserialize(as = ImmutablePerformanceResult.class) @JsonSerialize(as = ImmutablePerformanceResult.class) @Value.Immutable static abstract class PerformanceResult { public abstract long date(); public abstract String suite(); public abstract String benchmark(); public abstract String backend(); public abstract long samples(); public abstract double std(); public abstract double mean(); public abstract List<Double> data(); public abstract TimeUnit units(); } }
atlasdb-perf/src/main/java/com/palantir/atlasdb/performance/PerformanceResults.java
package com.palantir.atlasdb.performance; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import org.immutables.value.Value; import org.openjdk.jmh.results.RunResult; import org.openjdk.jmh.util.Multiset; import org.openjdk.jmh.util.Statistics; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.collect.Lists; public class PerformanceResults { private final Collection<RunResult> results; public PerformanceResults(Collection<RunResult> results) { this.results = results; } public void writeToFile(File file) throws IOException { try (BufferedWriter fout = new BufferedWriter(new FileWriter(file))) { long time = System.currentTimeMillis(); List<ImmutablePerformanceResult> newResults = results.stream().map(r -> { String[] benchmarkParts = r.getParams().getBenchmark().split("\\."); String benchmarkSuite = benchmarkParts[benchmarkParts.length - 2]; String benchmarkName = benchmarkParts[benchmarkParts.length - 1]; return ImmutablePerformanceResult.builder() .date(time) .suite(benchmarkSuite) .benchmark(benchmarkName) .backend(r.getParams().getParam((BenchmarkParam.BACKEND.getKey()))) .samples(r.getPrimaryResult().getStatistics().getN()) .std(r.getPrimaryResult().getStatistics().getStandardDeviation()) .mean(r.getPrimaryResult().getStatistics().getMean()) .data(getData(r)) .units(r.getParams().getTimeUnit()) .build(); }).collect(Collectors.toList()); new ObjectMapper().writeValue(fout, newResults); } } private List<Double> getData(RunResult result) { return result.getBenchmarkResults().stream() .flatMap(b -> getRawResults(b.getPrimaryResult().getStatistics()).stream()) .collect(Collectors.toList()); } private List<Double> getRawResults(Statistics statistics) { try { Field f = statistics.getClass().getDeclaredField("values"); f.setAccessible(true); Multiset<Double> rawResults = (Multiset<Double>) f.get(statistics); return rawResults.entrySet().stream() .flatMap(e -> DoubleStream.of(e.getKey()).limit(e.getValue()).boxed()) .collect(Collectors.toList()); } catch (NoSuchFieldException | IllegalAccessException e) { return Lists.newArrayList(); } } @JsonDeserialize(as = ImmutablePerformanceResult.class) @JsonSerialize(as = ImmutablePerformanceResult.class) @Value.Immutable static abstract class PerformanceResult { public abstract long date(); public abstract String suite(); public abstract String benchmark(); public abstract String backend(); public abstract long samples(); public abstract double std(); public abstract double mean(); public abstract List<Double> data(); public abstract TimeUnit units(); } }
repeat duplicated output values
atlasdb-perf/src/main/java/com/palantir/atlasdb/performance/PerformanceResults.java
repeat duplicated output values
Java
apache-2.0
8ac3338c2c70299dcb467d6489a7f9b965b6d16f
0
gbif/registry,gbif/registry
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.registry.ws.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; /** * This filter solved an issue that was preventing form parameters to be read in request filters. */ @Configuration @Order(Ordered.HIGHEST_PRECEDENCE) public class DebugFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(DebugFilter.class); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); } }
registry-spring-boot-ws/src/main/java/org/gbif/registry/ws/security/DebugFilter.java
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.registry.ws.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * This filter solved an issue that was preventing form parameters to be read in request filters. */ @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class DebugFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(DebugFilter.class); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); } }
changing component bvy configuration annotation
registry-spring-boot-ws/src/main/java/org/gbif/registry/ws/security/DebugFilter.java
changing component bvy configuration annotation
Java
apache-2.0
0928050d65a051de3887976bd5057ee72b3021b5
0
powertac/powertac-server,powertac/powertac-server,powertac/powertac-server,powertac/powertac-server
/* * Copyright (c) 2011-2015 by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powertac.common; //import org.codehaus.groovy.grails.commons.ApplicationHolder import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.Instant; import org.powertac.common.interfaces.Accounting; import org.powertac.common.interfaces.TariffMarket; import org.powertac.common.spring.SpringApplicationContext; import org.powertac.common.state.Domain; import org.powertac.common.state.StateChange; /** * A TariffSubscription is an entity representing an association between a Customer * and a Tariff. Instances of this class are not intended to be serialized. * You get one by calling the subscribe() method on Tariff. If there is no * current subscription for that Customer (which in most cases is actually * a population model), then a new TariffSubscription is created and * returned from the Tariff. * @author John Collins, Carsten Block */ @Domain public class TariffSubscription { static private Logger log = LogManager.getLogger(TariffSubscription.class.getName()); long id = IdGenerator.createId(); private TimeService timeService; private Accounting accountingService; private TariffMarket tariffMarketService; /** The customer who has this Subscription */ private CustomerInfo customer; /** The tariff for which this subscription applies */ private Tariff tariff; /** Total number of customers within a customer model that are committed * to this tariff subscription. This needs to be a count, otherwise tiered * rates cannot be applied properly. */ private int customersCommitted = 0 ; /** List of expiration dates. This is used only if the Tariff has a minDuration, * before which a subscribed Customer cannot back out without a penalty. Each * entry in this list is a pair [expiration-date, customer-count]. New entries * are added chronologically at the end of the list, so the front of the list * holds the oldest subscriptions - the ones that can be unsubscribed soonest * without penalty. */ private List<ExpirationRecord> expirations; /** Total usage so far in the current day, needed to compute charges for * tiered rates. */ private double totalUsage = 0.0; /** Count of customers who will not be subscribers in the next timeslot */ private int pendingUnsubscribeCount = 0; // ------------- Regulation capacity ---------------- /** Pending economic regulation (from phase 1) */ private double pendingRegulationRatio = 0.0; /** Available regulation capacity for the current timeslot. */ RegulationAccumulator regulationAccumulator; /** Actual up-regulation (positive) or down-regulation (negative) * from previous timeslot. * Should always be zero after the customer model has run. */ private double regulation = 0.0; /** * You need a CustomerInfo and a Tariff to create one of these. */ public TariffSubscription (CustomerInfo customer, Tariff tariff) { super(); this.customer = customer; this.tariff = tariff; expirations = new ArrayList<ExpirationRecord>(); setRegulationCap(new RegulationAccumulator(0.0, 0.0)); } public long getId () { return id; } public CustomerInfo getCustomer () { return customer; } public Tariff getTariff () { return tariff; } public int getCustomersCommitted () { return customersCommitted; } @StateChange public void setCustomersCommitted (int value) { customersCommitted = value; } public double getTotalUsage () { return totalUsage; } // ============================ Customer API =============================== /** * Subscribes some number of discrete customers. This is typically some portion of the population in a * population model. We assume this is called from Tariff, as a result of calling tariff.subscribe(). * Also, we record the expiration date of the tariff contract, just in case the tariff has a * minDuration. For the purpose of computing expiration, all contracts are assumed to begin at * 00:00 on the day of the subscription. */ @StateChange public void subscribe (int customerCount) { // first, update the customer count setCustomersCommitted(getCustomersCommitted() + customerCount); // if the Tariff has a minDuration, then we have to record the expiration date. // we do this by adding an entry to end of list, or updating the entry at the end. // An entry is a pair [Instant, count] long minDuration = tariff.getMinDuration(); //if (minDuration > 0) { // Compute the 00:00 Instant for the current time Instant start = getTimeService().getCurrentTime(); if (expirations.size() > 0 && expirations.get(expirations.size() - 1).getHorizon() == start.getMillis() + minDuration) { // update existing entry expirations.get(expirations.size() - 1).updateCount(customerCount); } else { // need a new entry expirations.add(new ExpirationRecord(start.getMillis() + minDuration, customerCount)); } //} // post the signup bonus if (tariff.getSignupPayment() != 0.0) { log.debug("signup bonus: " + customerCount + " customers, total = " + customerCount * tariff.getSignupPayment()); } // signup payment is positive for a bonus, so it's a debit for the broker. getAccounting().addTariffTransaction(TariffTransaction.Type.SIGNUP, tariff, customer, customerCount, 0.0, customerCount * -tariff.getSignupPayment()); } /** * Removes customerCount customers (at most) from this subscription, * posts early-withdrawal fees if appropriate. */ public void unsubscribe (int customerCount) { getTariffMarket().subscribeToTariff(getTariff(), getCustomer(), -customerCount); pendingUnsubscribeCount += customerCount; } /** * Handles the actual unsubscribe operation. Intended to be called by * the TariffMarket (phase 4) to avoid subscription changes between customer * consumption/production and balancing. */ @StateChange public void deferredUnsubscribe (int customerCount) { pendingUnsubscribeCount = 0; if (customerCount == customersCommitted) { // common case setRegulationCap(new RegulationAccumulator(0.0, 0.0)); setRegulation(0.0); } // first, make customerCount no larger than the subscription count if (customerCount > customersCommitted) { log.error("tariff " + tariff.getId() + " customer " + customer.getName() + ": attempt to unsubscribe " + customerCount + " from subscription of " + customersCommitted); customerCount = customersCommitted; } // customerCount = Math.min(customerCount, customersCommitted); // adjustRegulationCapacity((double)(customersCommitted - customerCount) // / customersCommitted); // find the number of customers who can withdraw without penalty int freeAgentCount = getExpiredCustomerCount(); int penaltyCount = Math.max (customerCount - freeAgentCount, 0); // update the expirations list int expCount = customerCount; while (expCount > 0 && expirations.get(0) != null) { int cec = expirations.get(0).getCount(); if (cec <= expCount) { expCount -= cec; expirations.remove(0); } else { expirations.get(0).updateCount(-expCount); expCount = 0; } } setCustomersCommitted(getCustomersCommitted() - customerCount); // if count is now zero, set regulation capacity to zero if (0 == getCustomersCommitted()) { regulationAccumulator.setDownRegulationCapacity(0.0); regulationAccumulator.setUpRegulationCapacity(0.0); } // Post withdrawal and possible penalties double withdrawPayment = -tariff.getEarlyWithdrawPayment(); if (tariff.isRevoked()) { withdrawPayment = 0.0; } getAccounting().addTariffTransaction(TariffTransaction.Type.WITHDRAW, tariff, customer, customerCount, 0.0, penaltyCount * withdrawPayment); if (tariff.getSignupPayment() < 0.0) { // Refund signup payment getAccounting().addTariffTransaction(TariffTransaction.Type.REFUND, tariff, customer, customerCount, 0.0, customerCount * tariff.getSignupPayment()); } } // private void adjustRegulationCapacity (double ratio) // { // regulationAccumulator.setUpRegulationCapacity(regulationAccumulator // .getUpRegulationCapacity() * ratio); // regulationAccumulator.setDownRegulationCapacity(regulationAccumulator // .getDownRegulationCapacity() * ratio); // } /** * Handles the subscription switch in case the underlying Tariff has been * revoked. The actual processing of tariff revocations, including switching * subscriptions to superseding tariffs, is deferred to be handled by the * tariff market. */ public Tariff handleRevokedTariff () { // if the tariff is not revoked, then just return this subscription if (!tariff.isRevoked()) { log.warn("Tariff " + tariff.getId() + " is not revoked."); return tariff; } // if no subscribers, we can ignore this if (0 == customersCommitted) { return null; } // if the tariff has already been superseded, then switch subscription to // that new tariff Tariff newTariff = null; //Tariff newTariff = tariff.getIsSupersededBy(); if (newTariff == null) { // there is no superseding tariff, so we have to revert to the default tariff. newTariff = getTariffMarket().getDefaultTariff(tariff.getTariffSpec() .getPowerType()); } if (newTariff == null) { // there is no exact match for original power type - choose generic newTariff = getTariffMarket().getDefaultTariff(tariff.getTariffSpec() .getPowerType().getGenericType()); } getTariffMarket().subscribeToTariff(tariff, customer, -customersCommitted); getTariffMarket().subscribeToTariff(newTariff, customer, customersCommitted); log.info("Tariff " + tariff.getId() + " superseded by " + newTariff.getId() + " for " + customersCommitted + " customers"); // customersCommitted = 0; return newTariff; } /** * Generates and returns a TariffTransaction instance for the current timeslot that * represents the amount of production (negative amount) or consumption * (positive amount), along with the credit/debit that results. Also generates * a separate TariffTransaction for the fixed periodic payment if it's non-zero. * Note that the power usage value and the numbers in the * TariffTransaction are aggregated across the subscribed population, * not per-member values. */ public void usePower (double kwh) { // deal with no-regulation customers ensureRegulationCapacity(); // do economic control first double kWhPerMember = kwh / customersCommitted; double actualKwh = (kWhPerMember - getEconomicRegulation(kWhPerMember, totalUsage)) * customersCommitted; log.info("usePower " + kwh + ", actual " + actualKwh + ", customer=" + customer.getName()); // generate the usage transaction TariffTransaction.Type txType = actualKwh < 0 ? TariffTransaction.Type.PRODUCE: TariffTransaction.Type.CONSUME; getAccounting().addTariffTransaction(txType, tariff, customer, customersCommitted, -actualKwh, customersCommitted * -tariff.getUsageCharge(actualKwh / customersCommitted, totalUsage, true)); if (getTimeService().getHourOfDay() == 0) { //reset the daily usage counter totalUsage = 0.0; } totalUsage += actualKwh / customersCommitted; // generate the periodic payment if necessary if (tariff.getPeriodicPayment() != 0.0) { getAccounting().addTariffTransaction(TariffTransaction.Type.PERIODIC, tariff, customer, customersCommitted, 0.0, customersCommitted * -tariff.getPeriodicPayment() / 24.0); } } /** * Returns the regulation in aggregate kwh for the previous timeslot. * Intended to be called by Customer models only. Value is non-negative for * consumption power types, non-positive for production types. * Note that this * method is not idempotent; if you call it twice in the same timeslot, the * second time returns zero. * * @deprecated Use getRegulation() instead, but remember that it returns * a per-member value, while this method returns an aggregate value. */ @Deprecated public synchronized double getCurtailment () { double sgn = 1.0; if (tariff.getPowerType().isProduction()) sgn = -1.0; double result = sgn * Math.max(sgn * regulation, 0.0) * customersCommitted; setRegulation(0.0); return result; } /** * Returns the regulation quantity exercised per member * in the previous timeslot. For non-storage devices, * only up-regulation through curtailment is supported, * and the result will be a non-negative value. * For storage devices, it may be positive (up-regulation) or negative * (down-regulation). * Intended to be called by customer models. This method is not idempotent, * because the regulation quantity is reset to zero after it's accessed. */ public synchronized double getRegulation () { double result = regulation; setRegulation(0.0); return result; } @StateChange public void setRegulation (double newValue) { regulation = newValue; } /** * Communicates the ability of the customer model to handle regulation * requests. Quantities are per-member. */ @StateChange public void setRegulationCapacity (RegulationCapacity capacity) { regulationAccumulator = new RegulationAccumulator(capacity); } // Local Regulation management void setRegulationCap (RegulationAccumulator capacity) { regulationAccumulator = capacity; } /** * Ensures that regulationAccumulator is non-null - * needed for non-regulatable customer models */ public void ensureRegulationCapacity () { if (null == regulationAccumulator) { setRegulationCap(new RegulationAccumulator(0.0, 0.0)); } } /** * True just in case this subscription allows regulation. */ public boolean hasRegulationRate () { return this.tariff.hasRegulationRate(); } /** * Returns the result of economic control in kwh for the current timeslot. * Value is the minimum of what's requested and what's allowed by the * Rates in effect given the time and cumulative usage. Intended to be * called within usePower() to implement economic control. * The parameters and return value are per-member values, not aggregated * across the subscription. * * Depending on the value of pendingRegulationRatio, there are three possible * outcomes: * <ul> * <li>(0.0 <= pendingRegulationRatio <= 1.0) represents simple curtailment. * The returned value will be the minimum of the proposedUsage. * This is the only possible result for a tariff without * RegulationRates.</li> * <li>(-1.0 <= pendingRegulationRatio < 0.0) represents down-regulation, * dumping energy into a thermal or electrical storage device. Amount is * limited by the available regulation capacity. This case is only * supported under a RegulationRate.</li> * <li>(1.0 < pendingRegulationRatio <= 2.0) represents discharge of an * electrical storage device. Amount is * limited by the available regulation capacity. This case is only * supported under a RegulationRate.</li> * </ul> * * Note that this method is not idempotent -- it should be called at most * once in each timeslot; this scheme makes one call every time the customer * uses power. */ double getEconomicRegulation (double proposedUsage, double cumulativeUsage) { // reset the regulation qty here setRegulation(0.0); double result = 0.0; if (getTariff().hasRegulationRate()) { if (pendingRegulationRatio < 0.0) { // down-regulation - negative result result = (-pendingRegulationRatio) * regulationAccumulator.getDownRegulationCapacity(); regulationAccumulator.setDownRegulationCapacity(regulationAccumulator .getDownRegulationCapacity() - result); } else if (pendingRegulationRatio > 1.0) { // discharge: between proposed usage and up-regulation capacity if (regulationAccumulator.getUpRegulationCapacity() > proposedUsage) { double excess = regulationAccumulator.getUpRegulationCapacity() - proposedUsage; result = proposedUsage + (pendingRegulationRatio - 1.0) * excess; regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - result); } } else { // curtailment based on regulation capacity result = pendingRegulationRatio * regulationAccumulator.getUpRegulationCapacity(); regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - result); } } else { // find the minimum of what's asked for and what's allowed. double proposedUpRegulation = proposedUsage * pendingRegulationRatio; double mur = tariff.getMaxUpRegulation(proposedUsage, cumulativeUsage); result = Math.min(proposedUpRegulation, mur); log.debug("proposedUpRegulation=" + proposedUpRegulation + ", maxUpRegulation=" + mur); regulationAccumulator.setUpRegulationCapacity(mur - result); } addRegulation(result); // saved until next timeslot pendingRegulationRatio = 0.0; return result; } // ===================== Demand Response / Balancing API ==================== /** * Posts the ratio for an EconomicControlEvent to the subscription for the * current timeslot. */ @StateChange public synchronized void postRatioControl (double ratio) { pendingRegulationRatio = ratio; } /** * Posts a BalancingControlEvent to the subscription and generate the correct * TariffTransaction. This updates * the regulation for the current timeslot by the amount of the control. * A positive value for kwh represents up-regulation, or an * increase in production - in other words, a net gain for the broker's * energy account balance. The kwh value is a population value, not a * per-member value. */ @StateChange public synchronized void postBalancingControl (double kwh) { // issue compensating tariff transaction getAccounting().addRegulationTransaction(tariff, customer, customersCommitted, kwh, customersCommitted * tariff.getRegulationCharge(-kwh / customersCommitted, totalUsage, true)); double kWhPerMember = kwh / customersCommitted; addRegulation(kWhPerMember); if (kWhPerMember >= 0.0) { // up-regulation regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - kWhPerMember); } else { regulationAccumulator.setDownRegulationCapacity(regulationAccumulator .getDownRegulationCapacity() - kWhPerMember); } totalUsage -= kWhPerMember; } /** * Returns the maximum aggregate up-regulation possible after the * customer model has run and possibly applied economic controls. * Since this is potentially * accessed through the balancing market after customers have updated their * subscriptions, it's possible * that the value will have to be changed due to a change in customer count. * TODO: may need to be modified -- see issue #733. */ public RegulationAccumulator getRemainingRegulationCapacity () { if (0 == customersCommitted) { // nothing to do here... return new RegulationAccumulator(0.0, 0.0); } // generate aggregate value here double up = regulationAccumulator.getUpRegulationCapacity() * customersCommitted; double down = regulationAccumulator.getDownRegulationCapacity() * customersCommitted; if (0 == pendingUnsubscribeCount) { log.info("regulation capacity for " + getCustomer().getName() + ":" + this.getTariff().getId() + " (" + up + ", " + down + ")"); return new RegulationAccumulator(up, down); } else { // we have some unsubscribes - need to adjust double ratio = (double)(customersCommitted - pendingUnsubscribeCount) / customersCommitted; log.info("remaining regulation capacity for " + getCustomer().getName() + ":" + this.getTariff().getId() + " reduced by " + ratio + " to (" + up * ratio + ", " + down * ratio + ")"); return new RegulationAccumulator(up * ratio, down * ratio); } } /** * Adds kwh to the regulation exercised in the current timeslot. * Intended to be called during exercise of economic or balancing controls. * The kwh argument is a per-member value; positive for up-regulation, * negative for down-regulation. */ void addRegulation (double kwh) { setRegulation(regulation + kwh); } // ================= access to Spring components ======================= private TimeService getTimeService () { if (null == timeService) timeService = (TimeService)SpringApplicationContext.getBean("timeService"); return timeService; } private Accounting getAccounting () { if (null == accountingService) accountingService = (Accounting)SpringApplicationContext.getBean("accountingService"); return accountingService; } private TariffMarket getTariffMarket () { if (null == tariffMarketService) tariffMarketService = (TariffMarket)SpringApplicationContext.getBean("tariffMarketService"); return tariffMarketService; } // -------------------- Expiration data ------------------- /** * Returns the number of individual customers who may withdraw from this * subscription without penalty. Should return the total customer count * for a non-expiring tariff. */ public int getExpiredCustomerCount () { int cc = 0; Instant now = getTimeService().getCurrentTime(); for (ExpirationRecord exp : expirations) { if (exp.getHorizon() <= now.getMillis()) { cc += exp.getCount(); } } return cc; } private class ExpirationRecord { private long horizon; private int count; ExpirationRecord (long horizon, int count) { super(); this.horizon = horizon; this.count = count; } long getHorizon () { return horizon; } int getCount () { return count; } int updateCount (int increment) { count += increment; return count; } } }
src/main/java/org/powertac/common/TariffSubscription.java
/* * Copyright (c) 2011-2015 by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.powertac.common; //import org.codehaus.groovy.grails.commons.ApplicationHolder import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joda.time.Instant; import org.powertac.common.interfaces.Accounting; import org.powertac.common.interfaces.TariffMarket; import org.powertac.common.spring.SpringApplicationContext; import org.powertac.common.state.Domain; import org.powertac.common.state.StateChange; /** * A TariffSubscription is an entity representing an association between a Customer * and a Tariff. Instances of this class are not intended to be serialized. * You get one by calling the subscribe() method on Tariff. If there is no * current subscription for that Customer (which in most cases is actually * a population model), then a new TariffSubscription is created and * returned from the Tariff. * @author John Collins, Carsten Block */ @Domain public class TariffSubscription { static private Logger log = LogManager.getLogger(TariffSubscription.class.getName()); long id = IdGenerator.createId(); private TimeService timeService; private Accounting accountingService; private TariffMarket tariffMarketService; /** The customer who has this Subscription */ private CustomerInfo customer; /** The tariff for which this subscription applies */ private Tariff tariff; /** Total number of customers within a customer model that are committed * to this tariff subscription. This needs to be a count, otherwise tiered * rates cannot be applied properly. */ private int customersCommitted = 0 ; /** List of expiration dates. This is used only if the Tariff has a minDuration, * before which a subscribed Customer cannot back out without a penalty. Each * entry in this list is a pair [expiration-date, customer-count]. New entries * are added chronologically at the end of the list, so the front of the list * holds the oldest subscriptions - the ones that can be unsubscribed soonest * without penalty. */ private List<ExpirationRecord> expirations; /** Total usage so far in the current day, needed to compute charges for * tiered rates. */ private double totalUsage = 0.0; /** Count of customers who will not be subscribers in the next timeslot */ private int pendingUnsubscribeCount = 0; // ------------- Regulation capacity ---------------- /** Pending economic regulation (from phase 1) */ private double pendingRegulationRatio = 0.0; /** Available regulation capacity for the current timeslot. */ RegulationAccumulator regulationAccumulator; /** Actual up-regulation (positive) or down-regulation (negative) * from previous timeslot. * Should always be zero after the customer model has run. */ private double regulation = 0.0; /** * You need a CustomerInfo and a Tariff to create one of these. */ public TariffSubscription (CustomerInfo customer, Tariff tariff) { super(); this.customer = customer; this.tariff = tariff; expirations = new ArrayList<ExpirationRecord>(); setRegulationCap(new RegulationAccumulator(0.0, 0.0)); } public long getId () { return id; } public CustomerInfo getCustomer () { return customer; } public Tariff getTariff () { return tariff; } public int getCustomersCommitted () { return customersCommitted; } @StateChange public void setCustomersCommitted (int value) { customersCommitted = value; } public double getTotalUsage () { return totalUsage; } // ============================ Customer API =============================== /** * Subscribes some number of discrete customers. This is typically some portion of the population in a * population model. We assume this is called from Tariff, as a result of calling tariff.subscribe(). * Also, we record the expiration date of the tariff contract, just in case the tariff has a * minDuration. For the purpose of computing expiration, all contracts are assumed to begin at * 00:00 on the day of the subscription. */ @StateChange public void subscribe (int customerCount) { // first, update the customer count setCustomersCommitted(getCustomersCommitted() + customerCount); // if the Tariff has a minDuration, then we have to record the expiration date. // we do this by adding an entry to end of list, or updating the entry at the end. // An entry is a pair [Instant, count] long minDuration = tariff.getMinDuration(); //if (minDuration > 0) { // Compute the 00:00 Instant for the current time Instant start = getTimeService().truncateInstant(getTimeService().getCurrentTime(), TimeService.DAY); if (expirations.size() > 0 && expirations.get(expirations.size() - 1).getHorizon() == start.getMillis() + minDuration) { // update existing entry expirations.get(expirations.size() - 1).updateCount(customerCount); } else { // need a new entry expirations.add(new ExpirationRecord(start.getMillis() + minDuration, customerCount)); } //} // post the signup bonus if (tariff.getSignupPayment() != 0.0) { log.debug("signup bonus: " + customerCount + " customers, total = " + customerCount * tariff.getSignupPayment()); } // signup payment is positive for a bonus, so it's a debit for the broker. getAccounting().addTariffTransaction(TariffTransaction.Type.SIGNUP, tariff, customer, customerCount, 0.0, customerCount * -tariff.getSignupPayment()); } /** * Removes customerCount customers (at most) from this subscription, * posts early-withdrawal fees if appropriate. */ public void unsubscribe (int customerCount) { getTariffMarket().subscribeToTariff(getTariff(), getCustomer(), -customerCount); pendingUnsubscribeCount += customerCount; } /** * Handles the actual unsubscribe operation. Intended to be called by * the TariffMarket (phase 4) to avoid subscription changes between customer * consumption/production and balancing. */ @StateChange public void deferredUnsubscribe (int customerCount) { pendingUnsubscribeCount = 0; if (customerCount == customersCommitted) { // common case setRegulationCap(new RegulationAccumulator(0.0, 0.0)); setRegulation(0.0); } // first, make customerCount no larger than the subscription count if (customerCount > customersCommitted) { log.error("tariff " + tariff.getId() + " customer " + customer.getName() + ": attempt to unsubscribe " + customerCount + " from subscription of " + customersCommitted); customerCount = customersCommitted; } // customerCount = Math.min(customerCount, customersCommitted); // adjustRegulationCapacity((double)(customersCommitted - customerCount) // / customersCommitted); // find the number of customers who can withdraw without penalty int freeAgentCount = getExpiredCustomerCount(); int penaltyCount = Math.max (customerCount - freeAgentCount, 0); // update the expirations list int expCount = customerCount; while (expCount > 0 && expirations.get(0) != null) { int cec = expirations.get(0).getCount(); if (cec <= expCount) { expCount -= cec; expirations.remove(0); } else { expirations.get(0).updateCount(-expCount); expCount = 0; } } setCustomersCommitted(getCustomersCommitted() - customerCount); // if count is now zero, set regulation capacity to zero if (0 == getCustomersCommitted()) { regulationAccumulator.setDownRegulationCapacity(0.0); regulationAccumulator.setUpRegulationCapacity(0.0); } // Post withdrawal and possible penalties double withdrawPayment = -tariff.getEarlyWithdrawPayment(); if (tariff.isRevoked()) { withdrawPayment = 0.0; } getAccounting().addTariffTransaction(TariffTransaction.Type.WITHDRAW, tariff, customer, customerCount, 0.0, penaltyCount * withdrawPayment); if (tariff.getSignupPayment() < 0.0) { // Refund signup payment getAccounting().addTariffTransaction(TariffTransaction.Type.REFUND, tariff, customer, customerCount, 0.0, customerCount * tariff.getSignupPayment()); } } // private void adjustRegulationCapacity (double ratio) // { // regulationAccumulator.setUpRegulationCapacity(regulationAccumulator // .getUpRegulationCapacity() * ratio); // regulationAccumulator.setDownRegulationCapacity(regulationAccumulator // .getDownRegulationCapacity() * ratio); // } /** * Handles the subscription switch in case the underlying Tariff has been * revoked. The actual processing of tariff revocations, including switching * subscriptions to superseding tariffs, is deferred to be handled by the * tariff market. */ public Tariff handleRevokedTariff () { // if the tariff is not revoked, then just return this subscription if (!tariff.isRevoked()) { log.warn("Tariff " + tariff.getId() + " is not revoked."); return tariff; } // if no subscribers, we can ignore this if (0 == customersCommitted) { return null; } // if the tariff has already been superseded, then switch subscription to // that new tariff Tariff newTariff = null; //Tariff newTariff = tariff.getIsSupersededBy(); if (newTariff == null) { // there is no superseding tariff, so we have to revert to the default tariff. newTariff = getTariffMarket().getDefaultTariff(tariff.getTariffSpec() .getPowerType()); } if (newTariff == null) { // there is no exact match for original power type - choose generic newTariff = getTariffMarket().getDefaultTariff(tariff.getTariffSpec() .getPowerType().getGenericType()); } getTariffMarket().subscribeToTariff(tariff, customer, -customersCommitted); getTariffMarket().subscribeToTariff(newTariff, customer, customersCommitted); log.info("Tariff " + tariff.getId() + " superseded by " + newTariff.getId() + " for " + customersCommitted + " customers"); // customersCommitted = 0; return newTariff; } /** * Generates and returns a TariffTransaction instance for the current timeslot that * represents the amount of production (negative amount) or consumption * (positive amount), along with the credit/debit that results. Also generates * a separate TariffTransaction for the fixed periodic payment if it's non-zero. * Note that the power usage value and the numbers in the * TariffTransaction are aggregated across the subscribed population, * not per-member values. */ public void usePower (double kwh) { // deal with no-regulation customers ensureRegulationCapacity(); // do economic control first double kWhPerMember = kwh / customersCommitted; double actualKwh = (kWhPerMember - getEconomicRegulation(kWhPerMember, totalUsage)) * customersCommitted; log.info("usePower " + kwh + ", actual " + actualKwh + ", customer=" + customer.getName()); // generate the usage transaction TariffTransaction.Type txType = actualKwh < 0 ? TariffTransaction.Type.PRODUCE: TariffTransaction.Type.CONSUME; getAccounting().addTariffTransaction(txType, tariff, customer, customersCommitted, -actualKwh, customersCommitted * -tariff.getUsageCharge(actualKwh / customersCommitted, totalUsage, true)); if (getTimeService().getHourOfDay() == 0) { //reset the daily usage counter totalUsage = 0.0; } totalUsage += actualKwh / customersCommitted; // generate the periodic payment if necessary if (tariff.getPeriodicPayment() != 0.0) { getAccounting().addTariffTransaction(TariffTransaction.Type.PERIODIC, tariff, customer, customersCommitted, 0.0, customersCommitted * -tariff.getPeriodicPayment() / 24.0); } } /** * Returns the regulation in aggregate kwh for the previous timeslot. * Intended to be called by Customer models only. Value is non-negative for * consumption power types, non-positive for production types. * Note that this * method is not idempotent; if you call it twice in the same timeslot, the * second time returns zero. * * @deprecated Use getRegulation() instead, but remember that it returns * a per-member value, while this method returns an aggregate value. */ @Deprecated public synchronized double getCurtailment () { double sgn = 1.0; if (tariff.getPowerType().isProduction()) sgn = -1.0; double result = sgn * Math.max(sgn * regulation, 0.0) * customersCommitted; setRegulation(0.0); return result; } /** * Returns the regulation quantity exercised per member * in the previous timeslot. For non-storage devices, * only up-regulation through curtailment is supported, * and the result will be a non-negative value. * For storage devices, it may be positive (up-regulation) or negative * (down-regulation). * Intended to be called by customer models. This method is not idempotent, * because the regulation quantity is reset to zero after it's accessed. */ public synchronized double getRegulation () { double result = regulation; setRegulation(0.0); return result; } @StateChange public void setRegulation (double newValue) { regulation = newValue; } /** * Communicates the ability of the customer model to handle regulation * requests. Quantities are per-member. */ @StateChange public void setRegulationCapacity (RegulationCapacity capacity) { regulationAccumulator = new RegulationAccumulator(capacity); } // Local Regulation management void setRegulationCap (RegulationAccumulator capacity) { regulationAccumulator = capacity; } /** * Ensures that regulationAccumulator is non-null - * needed for non-regulatable customer models */ public void ensureRegulationCapacity () { if (null == regulationAccumulator) { setRegulationCap(new RegulationAccumulator(0.0, 0.0)); } } /** * True just in case this subscription allows regulation. */ public boolean hasRegulationRate () { return this.tariff.hasRegulationRate(); } /** * Returns the result of economic control in kwh for the current timeslot. * Value is the minimum of what's requested and what's allowed by the * Rates in effect given the time and cumulative usage. Intended to be * called within usePower() to implement economic control. * The parameters and return value are per-member values, not aggregated * across the subscription. * * Depending on the value of pendingRegulationRatio, there are three possible * outcomes: * <ul> * <li>(0.0 <= pendingRegulationRatio <= 1.0) represents simple curtailment. * The returned value will be the minimum of the proposedUsage. * This is the only possible result for a tariff without * RegulationRates.</li> * <li>(-1.0 <= pendingRegulationRatio < 0.0) represents down-regulation, * dumping energy into a thermal or electrical storage device. Amount is * limited by the available regulation capacity. This case is only * supported under a RegulationRate.</li> * <li>(1.0 < pendingRegulationRatio <= 2.0) represents discharge of an * electrical storage device. Amount is * limited by the available regulation capacity. This case is only * supported under a RegulationRate.</li> * </ul> * * Note that this method is not idempotent -- it should be called at most * once in each timeslot; this scheme makes one call every time the customer * uses power. */ double getEconomicRegulation (double proposedUsage, double cumulativeUsage) { // reset the regulation qty here setRegulation(0.0); double result = 0.0; if (getTariff().hasRegulationRate()) { if (pendingRegulationRatio < 0.0) { // down-regulation - negative result result = (-pendingRegulationRatio) * regulationAccumulator.getDownRegulationCapacity(); regulationAccumulator.setDownRegulationCapacity(regulationAccumulator .getDownRegulationCapacity() - result); } else if (pendingRegulationRatio > 1.0) { // discharge: between proposed usage and up-regulation capacity if (regulationAccumulator.getUpRegulationCapacity() > proposedUsage) { double excess = regulationAccumulator.getUpRegulationCapacity() - proposedUsage; result = proposedUsage + (pendingRegulationRatio - 1.0) * excess; regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - result); } } else { // curtailment based on regulation capacity result = pendingRegulationRatio * regulationAccumulator.getUpRegulationCapacity(); regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - result); } } else { // find the minimum of what's asked for and what's allowed. double proposedUpRegulation = proposedUsage * pendingRegulationRatio; double mur = tariff.getMaxUpRegulation(proposedUsage, cumulativeUsage); result = Math.min(proposedUpRegulation, mur); log.debug("proposedUpRegulation=" + proposedUpRegulation + ", maxUpRegulation=" + mur); regulationAccumulator.setUpRegulationCapacity(mur - result); } addRegulation(result); // saved until next timeslot pendingRegulationRatio = 0.0; return result; } // ===================== Demand Response / Balancing API ==================== /** * Posts the ratio for an EconomicControlEvent to the subscription for the * current timeslot. */ @StateChange public synchronized void postRatioControl (double ratio) { pendingRegulationRatio = ratio; } /** * Posts a BalancingControlEvent to the subscription and generate the correct * TariffTransaction. This updates * the regulation for the current timeslot by the amount of the control. * A positive value for kwh represents up-regulation, or an * increase in production - in other words, a net gain for the broker's * energy account balance. The kwh value is a population value, not a * per-member value. */ @StateChange public synchronized void postBalancingControl (double kwh) { // issue compensating tariff transaction getAccounting().addRegulationTransaction(tariff, customer, customersCommitted, kwh, customersCommitted * tariff.getRegulationCharge(-kwh / customersCommitted, totalUsage, true)); double kWhPerMember = kwh / customersCommitted; addRegulation(kWhPerMember); if (kWhPerMember >= 0.0) { // up-regulation regulationAccumulator.setUpRegulationCapacity(regulationAccumulator .getUpRegulationCapacity() - kWhPerMember); } else { regulationAccumulator.setDownRegulationCapacity(regulationAccumulator .getDownRegulationCapacity() - kWhPerMember); } totalUsage -= kWhPerMember; } /** * Returns the maximum aggregate up-regulation possible after the * customer model has run and possibly applied economic controls. * Since this is potentially * accessed through the balancing market after customers have updated their * subscriptions, it's possible * that the value will have to be changed due to a change in customer count. * TODO: may need to be modified -- see issue #733. */ public RegulationAccumulator getRemainingRegulationCapacity () { if (0 == customersCommitted) { // nothing to do here... return new RegulationAccumulator(0.0, 0.0); } // generate aggregate value here double up = regulationAccumulator.getUpRegulationCapacity() * customersCommitted; double down = regulationAccumulator.getDownRegulationCapacity() * customersCommitted; if (0 == pendingUnsubscribeCount) { log.info("regulation capacity for " + getCustomer().getName() + ":" + this.getTariff().getId() + " (" + up + ", " + down + ")"); return new RegulationAccumulator(up, down); } else { // we have some unsubscribes - need to adjust double ratio = (double)(customersCommitted - pendingUnsubscribeCount) / customersCommitted; log.info("remaining regulation capacity for " + getCustomer().getName() + ":" + this.getTariff().getId() + " reduced by " + ratio + " to (" + up * ratio + ", " + down * ratio + ")"); return new RegulationAccumulator(up * ratio, down * ratio); } } /** * Adds kwh to the regulation exercised in the current timeslot. * Intended to be called during exercise of economic or balancing controls. * The kwh argument is a per-member value; positive for up-regulation, * negative for down-regulation. */ void addRegulation (double kwh) { setRegulation(regulation + kwh); } // ================= access to Spring components ======================= private TimeService getTimeService () { if (null == timeService) timeService = (TimeService)SpringApplicationContext.getBean("timeService"); return timeService; } private Accounting getAccounting () { if (null == accountingService) accountingService = (Accounting)SpringApplicationContext.getBean("accountingService"); return accountingService; } private TariffMarket getTariffMarket () { if (null == tariffMarketService) tariffMarketService = (TariffMarket)SpringApplicationContext.getBean("tariffMarketService"); return tariffMarketService; } // -------------------- Expiration data ------------------- /** * Returns the number of individual customers who may withdraw from this * subscription without penalty. Should return the total customer count * for a non-expiring tariff. */ public int getExpiredCustomerCount () { int cc = 0; Instant today = getTimeService().truncateInstant(getTimeService().getCurrentTime(), TimeService.DAY); for (ExpirationRecord exp : expirations) { if (exp.getHorizon() <= today.getMillis()) { cc += exp.getCount(); } } return cc; } private class ExpirationRecord { private long horizon; private int count; ExpirationRecord (long horizon, int count) { super(); this.horizon = horizon; this.count = count; } long getHorizon () { return horizon; } int getCount () { return count; } int updateCount (int increment) { count += increment; return count; } } }
#831 - remove one-day truncation of time values wrt tariff expiration
src/main/java/org/powertac/common/TariffSubscription.java
#831 - remove one-day truncation of time values wrt tariff expiration
Java
apache-2.0
c300226cba144b1f3641626d0a9e6cf6fc813b12
0
apache/felix-dev,apache/felix-dev,apache/felix-dev,apache/felix-dev
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.eventadmin.impl.handler; import java.util.Collection; import java.util.Iterator; import org.apache.felix.eventadmin.impl.security.PermissionsUtil; import org.apache.felix.eventadmin.impl.util.LogWrapper; import org.osgi.framework.Bundle; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; /** * This is a proxy for event handlers. It gets the real event handler * on demand and prepares some information for faster processing. * * It checks the timeout handling for the implementation as well as * blacklisting the handler. * * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a> */ public class EventHandlerProxy { /** The service reference for the event handler. */ private final ServiceReference reference; /** The handler context. */ private final EventHandlerTracker.HandlerContext handlerContext; /** The event topics. */ private volatile String[] topics; /** Optional filter. */ private volatile Filter filter; /** Lazy fetched event handler. */ private volatile EventHandler handler; /** Is this handler blacklisted? */ private volatile boolean blacklisted; /** Use timeout. */ private boolean useTimeout; /** Deliver async ordered. */ private boolean asyncOrderedDelivery; /** * Create an EventHandlerProxy. * * @param context The handler context * @param reference Reference to the EventHandler */ public EventHandlerProxy(final EventHandlerTracker.HandlerContext context, final ServiceReference reference) { this.handlerContext = context; this.reference = reference; } /** * Update the state with current properties from the service * @return <code>true</code> if the handler configuration is valid. */ public boolean update() { this.blacklisted = false; boolean valid = true; // First check, topic final Object topicObj = reference.getProperty(EventConstants.EVENT_TOPIC); if (topicObj instanceof String) { if ( topicObj.toString().equals("*") ) { this.topics = null; } else { this.topics = new String[] {topicObj.toString()}; } } else if (topicObj instanceof String[]) { // check if one value matches '*' final String[] values = (String[])topicObj; boolean matchAll = false; for(int i=0;i<values.length;i++) { if ( "*".equals(values[i]) ) { matchAll = true; } } if ( matchAll ) { this.topics = null; } else { this.topics = values; } } else if (topicObj instanceof Collection) { final Collection col = (Collection)topicObj; final String[] values = new String[col.size()]; int index = 0; // check if one value matches '*' final Iterator i = col.iterator(); boolean matchAll = false; while ( i.hasNext() ) { final String v = i.next().toString(); values[index] = v; index++; if ( "*".equals(v) ) { matchAll = true; } } if ( matchAll ) { this.topics = null; } else { this.topics = values; } } else if ( topicObj == null && !this.handlerContext.requireTopic ) { this.topics = null; } else { final String reason; if ( topicObj == null ) { reason = "Missing"; } else { reason = "Neither of type String nor String[] : " + topicObj.getClass().getName(); } LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_TOPICS : " + reason + " - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); this.topics = null; valid = false; } // Second check filter (but only if topics is valid) Filter handlerFilter = null; if ( valid ) { final Object filterObj = reference.getProperty(EventConstants.EVENT_FILTER); if (filterObj instanceof String) { try { handlerFilter = this.handlerContext.bundleContext.createFilter(filterObj.toString()); } catch (final InvalidSyntaxException e) { valid = false; LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_FILTER - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]", e); } } else if ( filterObj != null ) { valid = false; LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_FILTER - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } } this.filter = handlerFilter; // new in 1.3 - deliver this.asyncOrderedDelivery = true; Object delivery = reference.getProperty(EventConstants.EVENT_DELIVERY); if ( delivery instanceof Collection ) { delivery = ((Collection)delivery).toArray(new String[((Collection)delivery).size()]); } if ( delivery instanceof String ) { this.asyncOrderedDelivery = !(EventConstants.DELIVERY_ASYNC_UNORDERED.equals(delivery.toString())); } else if ( delivery instanceof String[] ) { final String[] deliveryArray = (String[])delivery; boolean foundOrdered = false, foundUnordered = false; for(int i=0; i<deliveryArray.length; i++) { final String value = deliveryArray[i]; if ( EventConstants.DELIVERY_ASYNC_UNORDERED.equals(value) ) { foundUnordered = true; } else if ( EventConstants.DELIVERY_ASYNC_ORDERED.equals(value) ) { foundOrdered = true; } else { LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_DELIVERY - Ignoring invalid value for event delivery property " + value + " of ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } } if ( !foundOrdered && foundUnordered ) { this.asyncOrderedDelivery = false; } } else if ( delivery != null ) { LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_DELIVERY - Ignoring event delivery property " + delivery + " of ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } // make sure to release the handler this.release(); return valid; } /** * Dispose the proxy and release the handler */ public void dispose() { this.release(); } /** * Get the event handler. */ private synchronized EventHandler obtain() { if (this.handler == null) { try { this.handler = (EventHandler)this.handlerContext.bundleContext.getService(this.reference); if ( this.handler != null ) { this.checkTimeout(this.handler.getClass().getName()); } } catch (final IllegalStateException ignore) { // event handler might be stopped - ignore } } return this.handler; } /** * Release the handler */ private synchronized void release() { if ( this.handler != null ) { try { this.handlerContext.bundleContext.ungetService(this.reference); } catch (final IllegalStateException ignore) { // event handler might be stopped - ignore } this.handler = null; } } /** * Get the topics of this handler. * If this handler matches all topics <code>null</code> is returned */ public String[] getTopics() { return this.topics; } /** * Check if this handler is allowed to receive the event * - blacklisted * - check filter * - check permission */ public boolean canDeliver(final Event event) { if ( this.blacklisted ) { return false; } final Bundle bundle = reference.getBundle(); // is service unregistered? if (bundle == null) { return false; } // filter match final Filter eventFilter = this.filter; if ( eventFilter != null && !event.matches(eventFilter) ) { return false; } // permission check final Object p = PermissionsUtil.createSubscribePermission(event.getTopic()); if (p != null && !bundle.hasPermission(p) ) { return false; } return true; } /** * Should a timeout be used for this handler? */ public boolean useTimeout() { return this.useTimeout; } /** * Should async events be delivered in order? */ public boolean isAsyncOrderedDelivery() { return this.asyncOrderedDelivery; } /** * Check the timeout configuration for this handler. */ private void checkTimeout(final String className) { if ( this.handlerContext.ignoreTimeoutMatcher != null ) { for(int i=0;i<this.handlerContext.ignoreTimeoutMatcher.length;i++) { if ( this.handlerContext.ignoreTimeoutMatcher[i] != null) { if ( this.handlerContext.ignoreTimeoutMatcher[i].match(className) ) { this.useTimeout = false; return; } } } } this.useTimeout = true; } /** * Send the event. */ public void sendEvent(final Event event) { final EventHandler handlerService = this.obtain(); if (handlerService == null) { return; } try { handlerService.handleEvent(event); } catch (final Throwable e) { // The spec says that we must catch exceptions and log them: LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Exception during event dispatch [" + event + " | " + this.reference + " | Bundle(" + this.reference.getBundle() + ")]", e); } } /** * Blacklist the handler. */ public void blackListHandler() { LogWrapper.getLogger().log( LogWrapper.LOG_WARNING, "Blacklisting ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")] due to timeout!"); this.blacklisted = true; // we can free the handler now. this.release(); } }
eventadmin/impl/src/main/java/org/apache/felix/eventadmin/impl/handler/EventHandlerProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.felix.eventadmin.impl.handler; import java.util.Collection; import org.apache.felix.eventadmin.impl.security.PermissionsUtil; import org.apache.felix.eventadmin.impl.util.LogWrapper; import org.osgi.framework.Bundle; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; /** * This is a proxy for event handlers. It gets the real event handler * on demand and prepares some information for faster processing. * * It checks the timeout handling for the implementation as well as * blacklisting the handler. * * @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a> */ public class EventHandlerProxy { /** The service reference for the event handler. */ private final ServiceReference reference; /** The handler context. */ private final EventHandlerTracker.HandlerContext handlerContext; /** The event topics. */ private volatile String[] topics; /** Optional filter. */ private volatile Filter filter; /** Lazy fetched event handler. */ private volatile EventHandler handler; /** Is this handler blacklisted? */ private volatile boolean blacklisted; /** Use timeout. */ private boolean useTimeout; /** Deliver async ordered. */ private boolean asyncOrderedDelivery; /** * Create an EventHandlerProxy. * * @param context The handler context * @param reference Reference to the EventHandler */ public EventHandlerProxy(final EventHandlerTracker.HandlerContext context, final ServiceReference reference) { this.handlerContext = context; this.reference = reference; } /** * Update the state with current properties from the service * @return <code>true</code> if the handler configuration is valid. */ public boolean update() { this.blacklisted = false; boolean valid = true; // First check, topic final Object topicObj = reference.getProperty(EventConstants.EVENT_TOPIC); if (topicObj instanceof String) { if ( topicObj.toString().equals("*") ) { this.topics = null; } else { this.topics = new String[] {topicObj.toString()}; } } else if (topicObj instanceof String[]) { // check if one value matches '*' final String[] values = (String[])topicObj; boolean matchAll = false; for(int i=0;i<values.length;i++) { if ( "*".equals(values[i]) ) { matchAll = true; } } if ( matchAll ) { this.topics = null; } else { this.topics = values; } } else if ( topicObj == null && !this.handlerContext.requireTopic ) { this.topics = null; } else { final String reason; if ( topicObj == null ) { reason = "Missing"; } else { reason = "Neither of type String nor String[] : " + topicObj.getClass().getName(); } LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_TOPICS : " + reason + " - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); this.topics = null; valid = false; } // Second check filter (but only if topics is valid) Filter handlerFilter = null; if ( valid ) { final Object filterObj = reference.getProperty(EventConstants.EVENT_FILTER); if (filterObj instanceof String) { try { handlerFilter = this.handlerContext.bundleContext.createFilter(filterObj.toString()); } catch (final InvalidSyntaxException e) { valid = false; LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_FILTER - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]", e); } } else if ( filterObj != null ) { valid = false; LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_FILTER - Ignoring ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } } this.filter = handlerFilter; // new in 1.3 - deliver this.asyncOrderedDelivery = true; Object delivery = reference.getProperty(EventConstants.EVENT_DELIVERY); if ( delivery instanceof Collection ) { delivery = ((Collection)delivery).toArray(new String[((Collection)delivery).size()]); } if ( delivery instanceof String ) { this.asyncOrderedDelivery = !(EventConstants.DELIVERY_ASYNC_UNORDERED.equals(delivery.toString())); } else if ( delivery instanceof String[] ) { final String[] deliveryArray = (String[])delivery; boolean foundOrdered = false, foundUnordered = false; for(int i=0; i<deliveryArray.length; i++) { final String value = deliveryArray[i]; if ( EventConstants.DELIVERY_ASYNC_UNORDERED.equals(value) ) { foundUnordered = true; } else if ( EventConstants.DELIVERY_ASYNC_ORDERED.equals(value) ) { foundOrdered = true; } else { LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_DELIVERY - Ignoring invalid value for event delivery property " + value + " of ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } } if ( !foundOrdered && foundUnordered ) { this.asyncOrderedDelivery = false; } } else if ( delivery != null ) { LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Invalid EVENT_DELIVERY - Ignoring event delivery property " + delivery + " of ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")]"); } // make sure to release the handler this.release(); return valid; } /** * Dispose the proxy and release the handler */ public void dispose() { this.release(); } /** * Get the event handler. */ private synchronized EventHandler obtain() { if (this.handler == null) { try { this.handler = (EventHandler)this.handlerContext.bundleContext.getService(this.reference); if ( this.handler != null ) { this.checkTimeout(this.handler.getClass().getName()); } } catch (final IllegalStateException ignore) { // event handler might be stopped - ignore } } return this.handler; } /** * Release the handler */ private synchronized void release() { if ( this.handler != null ) { try { this.handlerContext.bundleContext.ungetService(this.reference); } catch (final IllegalStateException ignore) { // event handler might be stopped - ignore } this.handler = null; } } /** * Get the topics of this handler. * If this handler matches all topics <code>null</code> is returned */ public String[] getTopics() { return this.topics; } /** * Check if this handler is allowed to receive the event * - blacklisted * - check filter * - check permission */ public boolean canDeliver(final Event event) { if ( this.blacklisted ) { return false; } final Bundle bundle = reference.getBundle(); // is service unregistered? if (bundle == null) { return false; } // filter match final Filter eventFilter = this.filter; if ( eventFilter != null && !event.matches(eventFilter) ) { return false; } // permission check final Object p = PermissionsUtil.createSubscribePermission(event.getTopic()); if (p != null && !bundle.hasPermission(p) ) { return false; } return true; } /** * Should a timeout be used for this handler? */ public boolean useTimeout() { return this.useTimeout; } /** * Should async events be delivered in order? */ public boolean isAsyncOrderedDelivery() { return this.asyncOrderedDelivery; } /** * Check the timeout configuration for this handler. */ private void checkTimeout(final String className) { if ( this.handlerContext.ignoreTimeoutMatcher != null ) { for(int i=0;i<this.handlerContext.ignoreTimeoutMatcher.length;i++) { if ( this.handlerContext.ignoreTimeoutMatcher[i] != null) { if ( this.handlerContext.ignoreTimeoutMatcher[i].match(className) ) { this.useTimeout = false; return; } } } } this.useTimeout = true; } /** * Send the event. */ public void sendEvent(final Event event) { final EventHandler handlerService = this.obtain(); if (handlerService == null) { return; } try { handlerService.handleEvent(event); } catch (final Throwable e) { // The spec says that we must catch exceptions and log them: LogWrapper.getLogger().log( this.reference, LogWrapper.LOG_WARNING, "Exception during event dispatch [" + event + " | " + this.reference + " | Bundle(" + this.reference.getBundle() + ")]", e); } } /** * Blacklist the handler. */ public void blackListHandler() { LogWrapper.getLogger().log( LogWrapper.LOG_WARNING, "Blacklisting ServiceReference [" + this.reference + " | Bundle(" + this.reference.getBundle() + ")] due to timeout!"); this.blacklisted = true; // we can free the handler now. this.release(); } }
FELIX-3518 - Update to EventAdmin Spec 1.3 git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@1383606 13f79535-47bb-0310-9956-ffa450edef68
eventadmin/impl/src/main/java/org/apache/felix/eventadmin/impl/handler/EventHandlerProxy.java
FELIX-3518 - Update to EventAdmin Spec 1.3
Java
apache-2.0
b6204f75178045da209612e8abd3f68c1e8651d2
0
OpenCollabZA/sakai,colczr/sakai,introp-software/sakai,kingmook/sakai,kingmook/sakai,surya-janani/sakai,wfuedu/sakai,bkirschn/sakai,udayg/sakai,puramshetty/sakai,liubo404/sakai,ouit0408/sakai,Fudan-University/sakai,whumph/sakai,tl-its-umich-edu/sakai,udayg/sakai,duke-compsci290-spring2016/sakai,pushyamig/sakai,zqian/sakai,buckett/sakai-gitflow,ouit0408/sakai,lorenamgUMU/sakai,buckett/sakai-gitflow,clhedrick/sakai,wfuedu/sakai,pushyamig/sakai,buckett/sakai-gitflow,joserabal/sakai,ouit0408/sakai,willkara/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,conder/sakai,introp-software/sakai,frasese/sakai,udayg/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,tl-its-umich-edu/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,zqian/sakai,joserabal/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,joserabal/sakai,liubo404/sakai,ktakacs/sakai,colczr/sakai,liubo404/sakai,zqian/sakai,kingmook/sakai,bzhouduke123/sakai,whumph/sakai,ktakacs/sakai,noondaysun/sakai,conder/sakai,ouit0408/sakai,colczr/sakai,kwedoff1/sakai,clhedrick/sakai,liubo404/sakai,tl-its-umich-edu/sakai,joserabal/sakai,Fudan-University/sakai,frasese/sakai,puramshetty/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,rodriguezdevera/sakai,zqian/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,noondaysun/sakai,ktakacs/sakai,hackbuteer59/sakai,clhedrick/sakai,surya-janani/sakai,zqian/sakai,clhedrick/sakai,OpenCollabZA/sakai,Fudan-University/sakai,puramshetty/sakai,lorenamgUMU/sakai,colczr/sakai,zqian/sakai,bzhouduke123/sakai,joserabal/sakai,frasese/sakai,bkirschn/sakai,OpenCollabZA/sakai,puramshetty/sakai,noondaysun/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,lorenamgUMU/sakai,kwedoff1/sakai,surya-janani/sakai,whumph/sakai,clhedrick/sakai,kingmook/sakai,kingmook/sakai,noondaysun/sakai,ouit0408/sakai,surya-janani/sakai,rodriguezdevera/sakai,udayg/sakai,kingmook/sakai,puramshetty/sakai,willkara/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,colczr/sakai,bkirschn/sakai,bkirschn/sakai,puramshetty/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,ktakacs/sakai,colczr/sakai,buckett/sakai-gitflow,conder/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,introp-software/sakai,whumph/sakai,colczr/sakai,pushyamig/sakai,kwedoff1/sakai,introp-software/sakai,Fudan-University/sakai,pushyamig/sakai,noondaysun/sakai,Fudan-University/sakai,buckett/sakai-gitflow,udayg/sakai,kwedoff1/sakai,OpenCollabZA/sakai,OpenCollabZA/sakai,joserabal/sakai,udayg/sakai,bzhouduke123/sakai,udayg/sakai,udayg/sakai,conder/sakai,lorenamgUMU/sakai,noondaysun/sakai,noondaysun/sakai,introp-software/sakai,conder/sakai,pushyamig/sakai,introp-software/sakai,liubo404/sakai,puramshetty/sakai,ktakacs/sakai,Fudan-University/sakai,liubo404/sakai,clhedrick/sakai,surya-janani/sakai,clhedrick/sakai,rodriguezdevera/sakai,wfuedu/sakai,frasese/sakai,hackbuteer59/sakai,surya-janani/sakai,introp-software/sakai,joserabal/sakai,willkara/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,bkirschn/sakai,wfuedu/sakai,kwedoff1/sakai,conder/sakai,OpenCollabZA/sakai,pushyamig/sakai,frasese/sakai,OpenCollabZA/sakai,pushyamig/sakai,ktakacs/sakai,whumph/sakai,kingmook/sakai,whumph/sakai,bzhouduke123/sakai,ouit0408/sakai,kwedoff1/sakai,pushyamig/sakai,kingmook/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,bkirschn/sakai,bkirschn/sakai,frasese/sakai,willkara/sakai,whumph/sakai,wfuedu/sakai,introp-software/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,tl-its-umich-edu/sakai,liubo404/sakai,ktakacs/sakai,kwedoff1/sakai,hackbuteer59/sakai,puramshetty/sakai,ouit0408/sakai,OpenCollabZA/sakai,hackbuteer59/sakai,surya-janani/sakai,willkara/sakai,kwedoff1/sakai,zqian/sakai,wfuedu/sakai,zqian/sakai,ouit0408/sakai,frasese/sakai,colczr/sakai,joserabal/sakai,conder/sakai,willkara/sakai,buckett/sakai-gitflow,willkara/sakai,rodriguezdevera/sakai,liubo404/sakai,bzhouduke123/sakai,hackbuteer59/sakai,conder/sakai,surya-janani/sakai,willkara/sakai,bkirschn/sakai,wfuedu/sakai,bzhouduke123/sakai,Fudan-University/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.site.tool; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.tools.generic.SortTool; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.archive.api.ImportMetadata; import org.sakaiproject.archive.cover.ArchiveService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzPermissionException; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.api.MenuItem; import org.sakaiproject.cheftool.menu.MenuEntry; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.coursemanagement.api.AcademicSession; import org.sakaiproject.coursemanagement.api.CourseOffering; import org.sakaiproject.coursemanagement.api.CourseSet; import org.sakaiproject.coursemanagement.api.Enrollment; import org.sakaiproject.coursemanagement.api.EnrollmentSet; import org.sakaiproject.coursemanagement.api.Membership; import org.sakaiproject.coursemanagement.api.Section; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.email.cover.EmailService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.EntityTransferrer; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.ImportException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.id.cover.IdManager; import org.sakaiproject.importer.api.ImportDataSource; import org.sakaiproject.importer.api.ImportService; import org.sakaiproject.importer.api.SakaiArchive; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.sitemanage.api.model.*; import org.sakaiproject.site.util.SiteSetupQuestionFileParser; import org.sakaiproject.site.util.Participant; import org.sakaiproject.site.util.SiteParticipantHelper; import org.sakaiproject.site.util.SiteConstants; import org.sakaiproject.site.util.SiteComparator; import org.sakaiproject.site.util.ToolComparator; import org.sakaiproject.sitemanage.api.SectionField; import org.sakaiproject.sitemanage.api.SiteHelper; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserAlreadyDefinedException; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserIdInvalidException; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.api.UserPermissionException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ArrayUtil; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * SiteAction controls the interface for worksite setup. * </p> */ public class SiteAction extends PagedResourceActionII { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(SiteAction.class); private ContentHostingService m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private ImportService importService = org.sakaiproject.importer.cover.ImportService .getInstance(); /** portlet configuration parameter values* */ /** Resource bundle using current language locale */ private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric"); private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager .get(org.sakaiproject.coursemanagement.api.CourseManagementService.class); private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager .get(org.sakaiproject.authz.api.GroupProvider.class); private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager .get(org.sakaiproject.authz.api.AuthzGroupService.class); private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class); private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class); private org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class); private ContentHostingService contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private static org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService questionService = (org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService) ComponentManager .get(org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService.class); private static final String SITE_MODE_SITESETUP = "sitesetup"; private static final String SITE_MODE_SITEINFO = "siteinfo"; private static final String SITE_MODE_HELPER = "helper"; private static final String SITE_MODE_HELPER_DONE = "helper.done"; private static final String STATE_SITE_MODE = "site_mode"; protected final static String[] TEMPLATE = { "-list",// 0 "-type", "-newSiteInformation", "-editFeatures", "", "-addParticipant", "", "", "-siteDeleteConfirm", "", "-newSiteConfirm",// 10 "", "-siteInfo-list",// 12 "-siteInfo-editInfo", "-siteInfo-editInfoConfirm", "-addRemoveFeatureConfirm",// 15 "", "", "-siteInfo-editAccess", "-addParticipant-sameRole", "-addParticipant-differentRole",// 20 "-addParticipant-notification", "-addParticipant-confirm", "", "", "",// 25 "-modifyENW", "-importSites", "-siteInfo-import", "-siteInfo-duplicate", "",// 30 "",// 31 "",// 32 "",// 33 "",// 34 "",// 35 "-newSiteCourse",// 36 "-newSiteCourseManual",// 37 "",// 38 "",// 39 "",// 40 "",// 41 "-gradtoolsConfirm",// 42 "-siteInfo-editClass",// 43 "-siteInfo-addCourseConfirm",// 44 "-siteInfo-importMtrlMaster", // 45 -- htripath for import // material from a file "-siteInfo-importMtrlCopy", // 46 "-siteInfo-importMtrlCopyConfirm", "-siteInfo-importMtrlCopyConfirmMsg", // 48 "",//"-siteInfo-group", // 49 moved to the group helper "",//"-siteInfo-groupedit", // 50 moved to the group helper "",//"-siteInfo-groupDeleteConfirm", // 51, moved to the group helper "", "-findCourse", // 53 "-questions", // 54 "",// 55 "",// 56 "",// 57 "-siteInfo-importSelection", //58 "-siteInfo-importMigrate", //59 "-importSitesMigrate" //60 }; /** Name of state attribute for Site instance id */ private static final String STATE_SITE_INSTANCE_ID = "site.instance.id"; /** Name of state attribute for Site Information */ private static final String STATE_SITE_INFO = "site.info"; /** Name of state attribute for CHEF site type */ private static final String STATE_SITE_TYPE = "site-type"; /** Name of state attribute for possible site types */ private static final String STATE_SITE_TYPES = "site_types"; private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type"; private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types"; private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types"; private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types"; private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types"; // Names of state attributes corresponding to properties of a site private final static String PROP_SITE_CONTACT_EMAIL = "contact-email"; private final static String PROP_SITE_CONTACT_NAME = "contact-name"; private final static String PROP_SITE_TERM = "term"; private final static String PROP_SITE_TERM_EID = "term_eid"; /** * Name of the state attribute holding the site list column list is sorted * by */ private static final String SORTED_BY = "site.sorted.by"; /** Name of the state attribute holding the site list column to sort by */ private static final String SORTED_ASC = "site.sort.asc"; /** State attribute for list of sites to be deleted. */ private static final String STATE_SITE_REMOVALS = "site.removals"; /** Name of the state attribute holding the site list View selected */ private static final String STATE_VIEW_SELECTED = "site.view.selected"; /** Names of lists related to tools */ private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList"; private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome"; private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress"; private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected"; private static final String STATE_PROJECT_TOOL_LIST = "projectToolList"; private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet"; private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap"; private final static String STATE_MULTIPLE_TOOL_CONFIGURATION = "multipleToolConfiguration"; private final static String SITE_DEFAULT_LIST = ServerConfigurationService .getString("site.types"); private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname"; private static final String STATE_SITE_ADD_COURSE = "canAddCourse"; // %%% get rid of the IdAndText tool lists and just use ToolConfiguration or // ToolRegistration lists // %%% same for CourseItems // Names for other state attributes that are lists private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the // list // of // site // pages // consistent // with // Worksite // Setup // page // patterns /** * The name of the state form field containing additional information for a * course request */ private static final String FORM_ADDITIONAL = "form.additional"; /** %%% in transition from putting all form variables in state */ private final static String FORM_TITLE = "form_title"; private final static String FORM_DESCRIPTION = "form_description"; private final static String FORM_HONORIFIC = "form_honorific"; private final static String FORM_INSTITUTION = "form_institution"; private final static String FORM_SUBJECT = "form_subject"; private final static String FORM_PHONE = "form_phone"; private final static String FORM_EMAIL = "form_email"; private final static String FORM_REUSE = "form_reuse"; private final static String FORM_RELATED_CLASS = "form_related_class"; private final static String FORM_RELATED_PROJECT = "form_related_project"; private final static String FORM_NAME = "form_name"; private final static String FORM_SHORT_DESCRIPTION = "form_short_description"; private final static String FORM_ICON_URL = "iconUrl"; /** site info edit form variables */ private final static String FORM_SITEINFO_TITLE = "siteinfo_title"; private final static String FORM_SITEINFO_TERM = "siteinfo_term"; private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description"; private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description"; private final static String FORM_SITEINFO_SKIN = "siteinfo_skin"; private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include"; private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url"; private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name"; private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email"; private final static String FORM_WILL_NOTIFY = "form_will_notify"; /** Context action */ private static final String CONTEXT_ACTION = "SiteAction"; /** The name of the Attribute for display template index */ private static final String STATE_TEMPLATE_INDEX = "site.templateIndex"; /** State attribute for state initialization. */ private static final String STATE_INITIALIZED = "site.initialized"; /** State attribute for state initialization. */ private static final String STATE_TEMPLATE_SITE = "site.templateSite"; /** The action for menu */ private static final String STATE_ACTION = "site.action"; /** The user copyright string */ private static final String STATE_MY_COPYRIGHT = "resources.mycopyright"; /** The copyright character */ private static final String COPYRIGHT_SYMBOL = "copyright (c)"; /** The null/empty string */ private static final String NULL_STRING = ""; /** The state attribute alerting user of a sent course request */ private static final String REQUEST_SENT = "site.request.sent"; /** The state attributes in the make public vm */ private static final String STATE_JOINABLE = "state_joinable"; private static final String STATE_JOINERROLE = "state_joinerRole"; /** the list of selected user */ private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list"; private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles"; private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants"; private static final String STATE_PARTICIPANT_LIST = "state_participant_list"; private static final String STATE_ADD_PARTICIPANTS = "state_add_participants"; /** for changing participant roles */ private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole"; private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role"; /** for remove user */ private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list"; private static final String STATE_IMPORT = "state_import"; private static final String STATE_IMPORT_SITES = "state_import_sites"; private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool"; /** for navigating between sites in site list */ private static final String STATE_SITES = "state_sites"; private static final String STATE_PREV_SITE = "state_prev_site"; private static final String STATE_NEXT_SITE = "state_next_site"; /** for course information */ private final static String STATE_TERM_COURSE_LIST = "state_term_course_list"; private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash"; private final static String STATE_TERM_SELECTED = "state_term_selected"; private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected"; private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected"; private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider"; private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen"; private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual"; private final static String STATE_AUTO_ADD = "state_auto_add"; private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number"; private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields"; public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections"; public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list"; public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list"; private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates"; private final static String STATE_ICONS = "icons"; // site template used to create a UM Grad Tools student site public static final String SITE_GTS_TEMPLATE = "!gtstudent"; // the type used to identify a UM Grad Tools student site public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent"; // list of UM Grad Tools site types for editing public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types"; public static final String SITE_DUPLICATED = "site_duplicated"; public static final String SITE_DUPLICATED_NAME = "site_duplicated_named"; // used for site creation wizard title public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps"; public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step"; // types of site whose title can be editable public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type"; // types of site where site view roster permission is editable public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type"; // htripath : for import material from file - classic import private static final String ALL_ZIP_IMPORT_SITES = "allzipImports"; private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports"; private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports"; private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName"; private static final String SESSION_CONTEXT_ID = "sessionContextId"; // page size for worksite setup tool private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup"; // page size for site info tool private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo"; private static final String IMPORT_DATA_SOURCE = "import_data_source"; private static final String EMAIL_CHAR = "@"; // Special tool id for Home page private static final String HOME_TOOL_ID = "home"; private static final String SITE_INFORMATION_TOOL="sakai.iframe.site"; private static final String STATE_CM_LEVELS = "site.cm.levels"; private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts"; private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections"; private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection"; private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested"; private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections"; private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list"; private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId"; private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list"; private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections"; private String cmSubjectCategory; private boolean warnedNoSubjectCategory = false; // the string marks the protocol part in url private static final String PROTOCOL_STRING = "://"; private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar"; // the string for course site type private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type"; private static final String SITE_TEMPLATE_PREFIX = "template"; private static final String STATE_TYPE_SELECTED = "state_type_selected"; // the template index after exist the question mode private static final String STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE = "state_site_setup_question_next_template"; // SAK-12912, the answers to site setup questions private static final String STATE_SITE_SETUP_QUESTION_ANSWER = "state_site_setup_question_answer"; // SAK-13389, the non-official participant private static final String ADD_NON_OFFICIAL_PARTICIPANT = "add_non_official_participant"; // the list of visited templates private static final String STATE_VISITED_TEMPLATES = "state_visited_templates"; private String STATE_GROUP_HELPER_ID = "state_group_helper_id"; // used in the configuration file to specify which tool attributes are configurable through WSetup tool, and what are the default value for them. private String CONFIG_TOOL_ATTRIBUTE = "wsetup.config.tool.attribute_"; private String CONFIG_TOOL_ATTRIBUTE_DEFAULT = "wsetup.config.tool.attribute.default_"; /** * Populate the state object, if needed. */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata) { // Cleanout if the helper has been asked to start afresh. if (state.getAttribute(SiteHelper.SITE_CREATE_START) != null) { cleanState(state); cleanStateHelper(state); // Removed from possible previous invokations. state.removeAttribute(SiteHelper.SITE_CREATE_START); state.removeAttribute(SiteHelper.SITE_CREATE_CANCELLED); state.removeAttribute(SiteHelper.SITE_CREATE_SITE_ID); } super.initState(state, portlet, rundata); // store current userId in state User user = UserDirectoryService.getCurrentUser(); String userId = user.getEid(); state.setAttribute(STATE_CM_CURRENT_USERID, userId); PortletConfig config = portlet.getPortletConfig(); // types of sites that can either be public or private String changeableTypes = StringUtil.trimToNull(config .getInitParameter("publicChangeableSiteTypes")); if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) { if (changeableTypes != null) { state .setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes .split(",")))); } else { state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector()); } } // type of sites that are always public String publicTypes = StringUtil.trimToNull(config .getInitParameter("publicSiteTypes")); if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) { if (publicTypes != null) { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList( Arrays.asList(publicTypes.split(",")))); } else { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector()); } } // types of sites that are always private String privateTypes = StringUtil.trimToNull(config .getInitParameter("privateSiteTypes")); if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) { if (privateTypes != null) { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList( Arrays.asList(privateTypes.split(",")))); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // default site type String defaultType = StringUtil.trimToNull(config .getInitParameter("defaultSiteType")); if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) { if (defaultType != null) { state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // certain type(s) of site cannot get its "joinable" option set if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) { if (ServerConfigurationService .getStrings("wsetup.disable.joinable") != null) { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService .getStrings("wsetup.disable.joinable")))); } else { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector()); } } // course site type if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null) { state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course")); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } // skins if any if (state.getAttribute(STATE_ICONS) == null) { setupIcons(state); } if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) { List gradToolsSiteTypes = new Vector(); if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) { gradToolsSiteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("gradToolsSiteType"))); } state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes); } if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("titleEditableSiteType")))); } else { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector()); } if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) { List siteTypes = new Vector(); if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) { siteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("editViewRosterSiteType"))); } state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes); } if (state.getAttribute(STATE_SITE_MODE) == null) { // get site tool mode from tool registry String site_mode = config.getInitParameter(STATE_SITE_MODE); // When in helper mode we don't have if (site_mode == null) { site_mode = SITE_MODE_HELPER; } state.setAttribute(STATE_SITE_MODE, site_mode); } } // initState /** * cleanState removes the current site instance and it's properties from * state */ private void cleanState(SessionState state) { state.removeAttribute(STATE_SITE_INSTANCE_ID); state.removeAttribute(STATE_SITE_INFO); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); // remove those state attributes related to course site creation state.removeAttribute(STATE_TERM_COURSE_LIST); state.removeAttribute(STATE_TERM_COURSE_HASH); state.removeAttribute(STATE_TERM_SELECTED); state.removeAttribute(STATE_INSTRUCTOR_SELECTED); state.removeAttribute(STATE_FUTURE_TERM_SELECTED); state.removeAttribute(STATE_ADD_CLASS_PROVIDER); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_PROVIDER_SECTION_LIST); state.removeAttribute(STATE_CM_LEVELS); state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTION); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_CURRENT_USERID); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); // don't we need to clean this // too? -daisyf state.removeAttribute(STATE_TEMPLATE_SITE); state.removeAttribute(STATE_TYPE_SELECTED); state.removeAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); state.removeAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE); } // cleanState /** * Fire up the permissions editor */ public void doPermissions(RunData data, Context context) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = ToolManager.getCurrentPlacement().getContext(); String siteRef = SiteService.siteReference(contextString); // if it is in Worksite setup tool, pass the selected site's reference if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)) .equals(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { Site s = getStateSite(state); if (s != null) { siteRef = s.getReference(); } } } // setup for editing the permissions of the site for this tool, using // the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb .getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "site."); } // doPermissions /** * Build the context for normal display */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { rb = new ResourceLoader("sitesetupgeneric"); context.put("tlang", rb); // TODO: what is all this doing? if we are in helper mode, we are // already setup and don't get called here now -ggolden /* * String helperMode = (String) * state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode != * null) { Site site = getStateSite(state); if (site != null) { if * (site.getType() != null && ((List) * state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) { * context.put("editViewRoster", Boolean.TRUE); } else { * context.put("editViewRoster", Boolean.FALSE); } } else { * context.put("editViewRoster", Boolean.FALSE); } // for new, don't * show site.del in Permission page context.put("hiddenLock", * "site.del"); * * String template = PermissionsAction.buildHelperContext(portlet, * context, data, state); if (template == null) { addAlert(state, * rb.getString("theisa")); } else { return template; } } */ String template = null; context.put("action", CONTEXT_ACTION); // updatePortlet(state, portlet, data); if (state.getAttribute(STATE_INITIALIZED) == null) { init(portlet, data, state); } String indexString = (String) state.getAttribute(STATE_TEMPLATE_INDEX); // update the visited template list with the current template index addIntoStateVisitedTemplates(state, indexString); template = buildContextForTemplate(getPrevVisitedTemplate(state), Integer.valueOf(indexString), portlet, context, data, state); return template; } // buildMainPanelContext /** * add index into the visited template indices list * @param state * @param index */ private void addIntoStateVisitedTemplates(SessionState state, String index) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices.size() == 0 || !templateIndices.contains(index)) { // this is to prevent from page refreshing accidentally updates the list templateIndices.add(index); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } /** * remove the last index * @param state */ private void removeLastIndexInStateVisitedTemplates(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices!=null && templateIndices.size() > 0) { // this is to prevent from page refreshing accidentally updates the list templateIndices.remove(templateIndices.size()-1); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } private String getPrevVisitedTemplate(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >1 ) { return templateIndices.get(templateIndices.size()-2); } else { return null; } } /** * whether template indexed has been visited * @param state * @param templateIndex * @return */ private boolean isTemplateVisited(SessionState state, String templateIndex) { boolean rv = false; List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >0 ) { rv = templateIndices.contains(templateIndex); } return rv; } /** * Build the context for each template using template_index parameter passed * in a form hidden field. Each case is associated with a template. (Not all * templates implemented). See String[] TEMPLATES. * * @param index * is the number contained in the template's template_index */ private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // the last visited template index if (preIndex != null) context.put("backIndex", preIndex); context.put("templateIndex", String.valueOf(index)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); //can the user create course sites? context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite()); Site site = getStateSite(state); switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e); } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e); } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED); context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0)); setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); // template site - Denny setTemplateListForContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType))); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } else { if (courseManagementIsImplemented()) { } else { context.put("templateIndex", "37"); } } // whether to show course skin selection choices or not courseSkinSelection(context, state, null, siteInfo); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } } if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) { context.put("titleEditableSiteType", Boolean.FALSE); siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE); } else { context.put("titleEditableSiteType", state .getAttribute(TITLE_EDITABLE_SITE_TYPE)); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-editFeatures.vm * */ String type = (String) state.getAttribute(STATE_SITE_TYPE); if (type != null && type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (type.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } context.put("defaultTools", ServerConfigurationService .getToolsRequired(type)); toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService .getDefaultTools(type); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (site != null && SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); // The Home tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // get the email alias when an Email Archive tool has been selected String channelReference = site!=null?mailArchiveChannelReference(site.getId()):""; List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } else { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); if (site != null) { context.put("SiteTitle", site.getTitle()); context.put("existSite", Boolean.TRUE); context.put("backIndex", "12"); // back to site info list page } else { context.put("existSite", Boolean.FALSE); context.put("backIndex", "2"); // back to new site information page } return (String) getContext(data).get("template") + TEMPLATE[3]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction"); if (pickerAction != null && !"".equals(pickerAction)) { context.put("hasPickerDefined", Boolean.TRUE); context.put("officialAccountPickerLabel", ServerConfigurationService .getString("officialAccountPickerLabel")); context.put("officialAccountPickerAction", pickerAction); } if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } // whether to show the non-official participant section or not String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT); if (addNonOfficialParticipant != null) { if (addNonOfficialParticipant.equalsIgnoreCase("true")) { context.put("nonOfficialAccount", Boolean.TRUE); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } } else { context.put("nonOfficialAccount", Boolean.FALSE); } } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool // all info related to multiple tools multipleToolIntoContext(context, state); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // show the Add Participant menu b.add(new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant")); // show the Edit Class Roster menu if (ServerConfigurationService.getBoolean("site.setup.allow.editRoster", true) && siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group // if the manage group helper is available, not // stealthed and not hidden, show the link if (setHelper("wsetup.groupHelper", "sakai-site-manage-group-helper", state, STATE_GROUP_HELPER_ID)) { b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper")); } } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { //a configuration param for showing/hiding Import From Site with Clean Up String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString()); if (importFromSite.equalsIgnoreCase("true")) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_importSelection")); } else { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); } // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType()))); context.put("type", site.getType()); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); // whether to show course skin selection choices or not courseSkinSelection(context, state, site, null); setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("oDescription", site.getDescription()); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("oShort_description", site.getShortDescription()); context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN)); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL)); context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE)); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("oName", siteProperties .getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); context.put("oEmail", siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, (String) state .getAttribute(STATE_SITE_TYPE), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); // all info related to multiple tools multipleToolIntoContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[15]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // the template site, if using one Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); // use the type's template, if defined String realmTemplate = "!site.template"; // if create based on template, use the roles from the template if (templateSite != null) { realmTemplate = SiteService.siteReference(templateSite.getId()); } else if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 19: /* * buildContextForTemplate chef_site-addParticipant-sameRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("form_selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[19]; case 20: /* * buildContextForTemplate chef_site-addParticipant-differentRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); return (String) getContext(data).get("template") + TEMPLATE[20]; case 21: /* * buildContextForTemplate chef_site-addParticipant-notification.vm * */ context.put("title", site.getTitle()); context.put("sitePublished", Boolean.valueOf(site.isPublished())); if (state.getAttribute("form_selectedNotify") == null) { state.setAttribute("form_selectedNotify", Boolean.FALSE); } context.put("notify", state.getAttribute("form_selectedNotify")); boolean same_role = state.getAttribute("form_same_role") == null ? true : ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); if (same_role) { context.put("backIndex", "19"); } else { context.put("backIndex", "20"); } return (String) getContext(data).get("template") + TEMPLATE[21]; case 22: /* * buildContextForTemplate chef_site-addParticipant-confirm.vm * */ context.put("title", site.getTitle()); context.put("participants", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("notify", state.getAttribute("form_selectedNotify")); context.put("roles", getRoles(state)); context.put("same_role", state.getAttribute("form_same_role")); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context .put("selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[22]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("continue", "15"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("continue", "18"); } context.put("function", "eventSubmit_doAdd_features"); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's // all info related to multiple tools multipleToolIntoContext(context, state); context.put("toolManager", ToolManager.getInstance()); String emailId = (String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put("existingSite", Boolean.valueOf(existingSite)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 60: /* * buildContextForTemplate chef_site-importSitesMigrate.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } // get the tool id list List<String> toolIdList = new Vector<String>(); if (existingSite) { // list all site tools which are displayed on its own page List<SitePage> sitePages = site.getPages(); if (sitePages != null) { for (SitePage page: sitePages) { List<ToolConfiguration> pageToolsList = page.getTools(0); // we only handle one tool per page case if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1) { toolIdList.add(pageToolsList.get(0).getToolId()); } } } } else { // during site creation toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList); // order it SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator()); Hashtable<String, String> toolTitleTable = new Hashtable<String, String>(); for(;iToolIdList.hasNext();) { String toolId = (String) iToolIdList.next(); try { String toolTitle = ToolManager.getTool(toolId).getTitle(); toolTitleTable.put(toolId, toolTitle); } catch (Exception e) { Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage()); } } context.put("selectedTools", toolTitleTable); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[60]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 58: /* * buildContextForTemplate chef_siteinfo-importSelection.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[58]; case 59: /* * buildContextForTemplate chef_siteinfo-importMigrate.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[59]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", number>0?new Integer(number - 1):0); if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) { context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); } } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; // case 49, 50, 51 have been implemented in helper mode case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } int cmLevelSize = 0; if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { cmLevelSize = cmLevels.size(); Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS); int numSelections = 0; if (selections != null) numSelections = selections.size(); // execution will fall through these statements based on number of selections already made if (numSelections == cmLevelSize - 1) { levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1)); } else if (numSelections == cmLevelSize - 2) { levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid()); } else if (numSelections < cmLevelSize) { levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1))); } // always set the top level levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0))); // clean further element inside the array for (int i = numSelections + 1; i<cmLevelSize; i++) { levelOpts[i] = null; } context.put("cmLevelOptions", Arrays.asList(levelOpts)); state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } case 54: /* * build context for chef_site-questions.vm */ SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { context.put("questionSet", siteTypeQuestions); context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER)); } context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); return (String) getContext(data).get("template") + TEMPLATE[54]; } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } // buildContextForTemplate private void multipleToolIntoContext(Context context, SessionState state) { // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET )); context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); context.put(STATE_MULTIPLE_TOOL_CONFIGURATION, state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION)); } /** * show course site skin selection or not * @param context * @param state * @param site * @param siteInfo */ private void courseSkinSelection(Context context, SessionState state, Site site, SiteInfo siteInfo) { // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. // The setting defaults to be false. context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state.getAttribute(FORM_SITEINFO_SKIN)); } else { if (site != null && site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } else if (siteInfo != null && StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } } /** * Launch the Page Order Helper Tool -- for ordering, adding and customizing * pages * * @see case 12 * */ public void doPageOrderHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), "sakai-site-pageorder-helper"); } /** * Launch the Manage Group helper Tool -- for adding, editing and deleting groups * */ public void doManageGroupHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), (String) state.getAttribute(STATE_GROUP_HELPER_ID));//"sakai-site-manage-group-helper"); } public boolean setHelper(String helperName, String defaultHelperId, SessionState state, String stateHelperString) { String helperId = ServerConfigurationService.getString(helperName, defaultHelperId); // if the state variable regarding the helper is not set yet, set it with the configured helper id if (state.getAttribute(stateHelperString) == null) { state.setAttribute(stateHelperString, helperId); } if (notStealthOrHiddenTool(helperId)) { return true; } return false; } // htripath: import materials from classic /** * Master import -- for import materials from a file * * @see case 45 * */ public void doAttachmentsMtrlFrmFile(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // state.setAttribute(FILE_UPLOAD_MAX_SIZE, // ServerConfigurationService.getString("content.upload.max", "1")); state.setAttribute(STATE_TEMPLATE_INDEX, "45"); } // doImportMtrlFrmFile /** * Handle File Upload request * * @see case 46 * @throws Exception */ public void doUpload_Mtrl_Frm_File(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List allzipList = new Vector(); List finalzipList = new Vector(); List directcopyList = new Vector(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = data.getParameters().getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString( "content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch (Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; M_log.warn(this + ".doUpload_Mtrl_Frm_File: wrong setting of content.upload.max = " + max_file_size_mb, e); } if (fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { addAlert(state, rb.getString("importFile.choosefile")); } else { byte[] fileData = fileFromUpload.get(); if (fileData.length >= max_bytes) { addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileData.length > 0) { if (importService.isValidArchive(fileData)) { ImportDataSource importDataSource = importService .parseFromFile(fileData); Log.info("chef", "Getting import items from manifest."); List lst = importDataSource.getItemCategories(); if (lst != null && lst.size() > 0) { Iterator iter = lst.iterator(); while (iter.hasNext()) { ImportMetadata importdata = (ImportMetadata) iter .next(); // Log.info("chef","Preparing import // item '" + importdata.getId() + "'"); if ((!importdata.isMandatory()) && (importdata.getFileName() .endsWith(".xml"))) { allzipList.add(importdata); } else { directcopyList.add(importdata); } } } // set Attributes state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList); state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList); state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName); state.setAttribute(IMPORT_DATA_SOURCE, importDataSource); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } else { // uploaded file is not a valid archive addAlert(state, rb.getString("importFile.invalidfile")); } } } } // doImportMtrlFrmFile /** * Handle addition to list request * * @param data */ public void doAdd_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("addImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); fnlList.add(removeItems(value, zipList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Helper class for Add and remove * * @param value * @param items * @return */ public ImportMetadata removeItems(String value, List items) { ImportMetadata result = null; for (int i = 0; i < items.size(); i++) { ImportMetadata item = (ImportMetadata) items.get(i); if (value.equals(item.getId())) { result = (ImportMetadata) items.remove(i); break; } } return result; } /** * Handle the request for remove * * @param data */ public void doRemove_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("removeImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); zipList.add(removeItems(value, fnlList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Handle the request for copy * * @param data */ public void doCopyMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "47"); } // doCopy_MtrlSite /** * Handle the request for Save * * @param data * @throws ImportException */ public void doSaveMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES); ImportDataSource importDataSource = (ImportDataSource) state .getAttribute(IMPORT_DATA_SOURCE); // combine the selected import items with the mandatory import items fnlList.addAll(directList); Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size() + " top level items"); Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName()); if (importDataSource instanceof SakaiArchive) { Log.info("chef", "doSaveMtrlSite() our data source is a Sakai format"); ((SakaiArchive) importDataSource).buildSourceFolder(fnlList); Log.info("chef", "doSaveMtrlSite() source folder is " + ((SakaiArchive) importDataSource).getSourceFolder()); ArchiveService.merge(((SakaiArchive) importDataSource) .getSourceFolder(), siteId, null); } else { importService.doImportItems(importDataSource .getItemsForCategories(fnlList), siteId); } // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.removeAttribute(IMPORT_DATA_SOURCE); state.setAttribute(STATE_TEMPLATE_INDEX, "48"); // state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } // doSave_MtrlSite public void doSaveMtrlSiteMsg(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // htripath-end /** * Handle the site search request. */ public void doSite_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtil.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSite_search /** * Handle a Search Clear request. */ public void doSite_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSite_search_clear private void coursesIntoContext(SessionState state, Context context, Site site) { List providerCourseList = SiteParticipantHelper.getProviderCourseList((String) state.getAttribute(STATE_SITE_INSTANCE_ID)); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); String sectionTitleString = ""; for(int i = 0; i < providerCourseList.size(); i++) { String sectionId = (String) providerCourseList.get(i); try { Section s = cms.getSection(sectionId); sectionTitleString = (i>0)?sectionTitleString + "<br />" + s.getTitle():s.getTitle(); } catch (Exception e) { M_log.warn(this + ".coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId, e); } } context.put("providedSectionTitle", sectionTitleString); context.put("providerCourseList", providerCourseList); } // put manual requested courses into context courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList"); // put manual requested courses into context courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList"); } private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) { String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name)); if (courseListString != null) { List courseList = new Vector(); if (courseListString.indexOf("+") != -1) { courseList = new ArrayList(Arrays.asList(courseListString.split("\\+"))); } else { courseList.add(courseListString); } if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS)) { // need to construct the list of SectionObjects List<SectionObject> soList = new Vector(); for (int i=0; i<courseList.size();i++) { String courseEid = (String) courseList.get(i); try { Section s = cms.getSection(courseEid); if (s!=null) soList.add(new SectionObject(s)); } catch (Exception e) { M_log.warn(this + ".courseListFromStringIntoContext: cannot find section " + courseEid, e); } } if (soList.size() > 0) state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList); } else { // the list is of String objects state.setAttribute(state_attribute_string, courseList); } } context.put(context_string, state.getAttribute(state_attribute_string)); } /** * buildInstructorSectionsList Build the CourseListItem list for this * Instructor for the requested Term * */ private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context) { // Site information // The sections of the specified term having this person as Instructor context.put("providerCourseSectionList", state .getAttribute("providerCourseSectionList")); context.put("manualCourseSectionList", state .getAttribute("manualCourseSectionList")); context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); setTermListForContext(context, state, true); //-> future terms only context.put(STATE_TERM_COURSE_LIST, state .getAttribute(STATE_TERM_COURSE_LIST)); context.put("tlang", rb); } // buildInstructorSectionsList /** * {@inheritDoc} */ protected int sizeResources(SessionState state) { int size = 0; String search = ""; String userId = SessionManager.getCurrentSessionUserId(); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using // the criteria size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null); } else if (view.equals(rb.getString("java.my"))) { // search for a specific user site // for the particular user id in the // criteria - exact match only try { SiteService.getSite(SiteService .getUserSiteId(search)); size++; } catch (IdUnusedException e) { } } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null); } } } else { Site userWorkspaceSite = null; try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "sizeResources, template index = 0: Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { size++; } } else { size++; } } size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null); } } } } // for SiteInfo list page else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST); size = (l != null) ? l.size() : 0; } return size; } // sizeResources /** * {@inheritDoc} */ protected List readResourcesPage(SessionState state, int first, int last) { String search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { // get sort type SortType sortType = null; String sortBy = (String) state.getAttribute(SORTED_BY); boolean sortAsc = (new Boolean((String) state .getAttribute(SORTED_ASC))).booleanValue(); if (sortBy.equals(SortType.TITLE_ASC.toString())) { sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC; } else if (sortBy.equals(SortType.TYPE_ASC.toString())) { sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC; } else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_BY_ASC : SortType.CREATED_BY_DESC; } else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_ON_ASC : SortType.CREATED_ON_DESC; } else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) { sortType = sortAsc ? SortType.PUBLISHED_ASC : SortType.PUBLISHED_DESC; } if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using the // criteria return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null, sortType, new PagingPosition(first, last)); } else if (view.equalsIgnoreCase(rb.getString("java.my"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only List rv = new Vector(); try { Site userSite = SiteService.getSite(SiteService .getUserSiteId(search)); rv.add(userSite); } catch (IdUnusedException e) { } return rv; } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)); } else { // search for a specific site return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ANY, view, search, null, sortType, new PagingPosition(first, last)); } } } else { List rv = new Vector(); Site userWorkspaceSite = null; String userId = SessionManager.getCurrentSessionUserId(); try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "readResourcesPage template index = 0 :Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { rv.add(userWorkspaceSite); } } else { rv.add(userWorkspaceSite); } } rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null, sortType, new PagingPosition(first, last))); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last))); } else { rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null, sortType, new PagingPosition(first, last))); } } return rv; } } // if in Site Info list view else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector(); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); Iterator sortedParticipants = null; if (sortedBy != null) { sortedParticipants = new SortedIterator(participants .iterator(), new SiteComparator(sortedBy, sortedAsc)); participants.clear(); while (sortedParticipants.hasNext()) { participants.add(sortedParticipants.next()); } } PagingPosition page = new PagingPosition(first, last); page.validate(participants.size()); participants = participants.subList(page.getFirst() - 1, page.getLast()); return participants; } return null; } // readResourcesPage /** * get the selected tool ids from import sites */ private boolean select_import_tools(ParameterParser params, SessionState state) { // has the user selected any tool for importing? boolean anyToolSelected = false; Hashtable importTools = new Hashtable(); // the tools for current site List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String // toolId's for (int i = 0; i < selectedTools.size(); i++) { // any tools chosen from import sites? String toolId = (String) selectedTools.get(i); if (params.getStrings(toolId) != null) { importTools.put(toolId, new ArrayList(Arrays.asList(params .getStrings(toolId)))); if (!anyToolSelected) { anyToolSelected = true; } } } state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools); return anyToolSelected; } // select_import_tools /** * Is it from the ENW edit page? * * @return ture if the process went through the ENW page; false, otherwise */ private boolean fromENWModifyView(SessionState state) { boolean fromENW = false; List oTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); List toolList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); for (int i = 0; i < toolList.size() && !fromENW; i++) { String toolId = (String) toolList.get(i); if (toolId.equals("sakai.mailbox") || isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { if (oTools == null) { // if during site creation proces fromENW = true; } else if (!oTools.contains(toolId)) { // if user is adding either EmailArchive tool, News tool or // Web Content tool, go to the Customize page for the tool fromENW = true; } } } return fromENW; } /** * doNew_site is called when the Site list tool bar New... button is clicked * */ public void doNew_site(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // start clean cleanState(state); List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } } // doNew_site /** * doMenu_site_delete is called when the Site list tool bar Delete button is * clicked * */ public void doMenu_site_delete(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } String[] removals = (String[]) params.getStrings("selectedMembers"); state.setAttribute(STATE_SITE_REMOVALS, removals); // present confirm delete template state.setAttribute(STATE_TEMPLATE_INDEX, "8"); } // doMenu_site_delete public void doSite_delete_confirmed(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { M_log .warn("SiteAction.doSite_delete_confirmed selectedMembers null"); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the // site list return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites if (!chosenList.isEmpty()) { for (ListIterator i = chosenList.listIterator(); i.hasNext();) { String id = (String) i.next(); String site_title = NULL_STRING; try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + ".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site site = SiteService.getSite(id); site_title = site.getTitle(); SiteService.removeSite(site); } catch (IdUnusedException e) { M_log.warn(this +".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + site_title + "(" + id + ") " + rb.getString("java.couldnt") + " "); } catch (PermissionException e) { M_log.warn(this + ".doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").", e); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } else { M_log.warn(this + ".doSite_delete_confirmed - allowRemoveSite failed for site "+ id); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site // list // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); } // doSite_delete_confirmed /** * get the Site object based on SessionState attribute values * * @return Site object related to current state; null if no such Site object * could be found */ protected Site getStateSite(SessionState state) { Site site = null; if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { try { site = SiteService.getSite((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); } catch (Exception ignore) { } } return site; } // getStateSite /** * do called when "eventSubmit_do" is in the request parameters to c is * called from site list menu entry Revise... to get a locked site as * editable and to go to the correct template to begin DB version of writes * changes to disk at site commit whereas XML version writes at server * shutdown */ public void doGet_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // check form filled out correctly if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites String siteId = ""; if (!chosenList.isEmpty()) { if (chosenList.size() != 1) { addAlert(state, rb.getString("java.please")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } siteId = (String) chosenList.get(0); getReviseSite(state, siteId); state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // reset the paging info resetPaging(state); if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_PAGESIZE_SITESETUP, state .getAttribute(STATE_PAGESIZE)); } Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // when first entered Site Info, set the participant list size to // 200 as default state.setAttribute(STATE_PAGESIZE, new Integer(200)); // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } else { // restore the page size in site info tool state.setAttribute(STATE_PAGESIZE, h.get(siteId)); } } // doGet_site /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_reuse(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // create a new Site object based on selected Site object and put in // state // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_reuse /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_revise(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // get site as Site object, check SiteCreationStatus and SiteType of // site, put in state, and set STATE_TEMPLATE_INDEX correctly // set mode to state_mode_site_type SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_revise /** * doView_sites is called when "eventSubmit_doView_sites" is in the request * parameters */ public void doView_sites(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_VIEW_SELECTED, params.getString("view")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); resetPaging(state); } // doView_sites /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doView(RunData data) throws Exception { // called from chef_site-list.vm with a select option to build query of // sites // // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doView /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doSite_type(RunData data) { /* * for measuring how long it takes to load sections java.util.Date date = * new java.util.Date(); M_log.debug("***1. start preparing * section:"+date); */ SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); String type = StringUtil.trimToNull(params.getString("itemType")); int totalSteps = 0; if (type == null) { addAlert(state, rb.getString("java.select") + " "); } else { state.setAttribute(STATE_TYPE_SELECTED, type); setNewSiteType(state, type); if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { User user = UserDirectoryService.getCurrentUser(); String currentUserId = user.getEid(); String userId = params.getString("userId"); if (userId == null || "".equals(userId)) { userId = currentUserId; } else { // implies we are trying to pick sections owned by other // users. Currently "select section by user" page only // take one user per sitte request - daisy's note 1 ArrayList<String> list = new ArrayList(); list.add(userId); state.setAttribute(STATE_CM_AUTHORIZER_LIST, list); } state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId); String academicSessionEid = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(academicSessionEid); state.setAttribute(STATE_TERM_SELECTED, t); if (t != null) { List sections = prepareCourseAndSectionListing(userId, t .getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) { state.setAttribute(STATE_TERM_COURSE_LIST, sections); state.setAttribute(STATE_TEMPLATE_INDEX, "36"); state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented()) { state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } } else { // not course type state.setAttribute(STATE_TEMPLATE_INDEX, "37"); totalSteps = 5; } } else if (type.equals("project")) { totalSteps = 4; state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { // if a GradTools site use pre-defined site info and exclude // from public listing SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } User currentUser = UserDirectoryService.getCurrentUser(); siteInfo.title = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.description = rb.getString("java.gradsite") + " " + currentUser.getDisplayName(); siteInfo.short_description = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.include = false; state.setAttribute(STATE_SITE_INFO, siteInfo); // skip directly to confirm creation of site state.setAttribute(STATE_TEMPLATE_INDEX, "42"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } // get the user selected template getSelectedTemplate(state, params, type); } if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) { state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1)); } redirectToQuestionVM(state, type); } // doSite_type /** * see whether user selected any template * @param state * @param params * @param type */ private void getSelectedTemplate(SessionState state, ParameterParser params, String type) { String templateSiteId = params.getString("selectTemplate" + type); if (templateSiteId != null) { Site templateSite = null; try { templateSite = SiteService.getSite(templateSiteId); // save the template site in state state.setAttribute(STATE_TEMPLATE_SITE, templateSite); // the new site type is based on the template site setNewSiteType(state, templateSite.getType()); }catch (Exception e) { // should never happened, as the list of templates are generated // from existing sites M_log.warn(this + ".doSite_type" + e.getClass().getName(), e); } // grab site info from template SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // copy information from template site siteInfo.description = templateSite.getDescription(); siteInfo.short_description = templateSite.getShortDescription(); siteInfo.iconUrl = templateSite.getIconUrl(); siteInfo.infoUrl = templateSite.getInfoUrl(); siteInfo.joinable = templateSite.isJoinable(); siteInfo.joinerRole = templateSite.getJoinerRole(); //siteInfo.include = false; List<String> toolIdsSelected = new Vector<String>(); List pageList = templateSite.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); if (pageToolList != null && pageToolList.size() > 0) { Tool tConfig = ((ToolConfiguration) pageToolList.get(0)).getTool(); if (tConfig != null) { toolIdsSelected.add(tConfig.getId()); } } } } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdsSelected); state.setAttribute(STATE_SITE_INFO, siteInfo); } } /** * Depend on the setup question setting, redirect the site setup flow * @param state * @param type */ private void redirectToQuestionVM(SessionState state, String type) { // SAK-12912: check whether there is any setup question defined SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions(type); if (siteTypeQuestions != null) { List questionList = siteTypeQuestions.getQuestions(); if (questionList != null && questionList.size() > 0) { // there is at least one question defined for this type if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE, state.getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, "54"); } } } } /** * Determine whether the selected term is considered of "future term" * @param state * @param t */ private void isFutureTermSelected(SessionState state) { AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); int weeks = 0; Calendar c = (Calendar) Calendar.getInstance().clone(); try { weeks = Integer .parseInt(ServerConfigurationService .getString( "roster.available.weeks.before.term.start", "0")); c.add(Calendar.DATE, weeks * 7); } catch (Exception ignore) { } if (t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) { // if a future term is selected state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE); } else { state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE); } } public void doChange_user(RunData data) { doSite_type(data); } // doChange_user /** * */ private void removeSection(SessionState state, ParameterParser params) { // v2.4 - added by daisyf // RemoveSection - remove any selected course from a list of // provider courses // check if any section need to be removed removeAnyFlagedSection(state, params); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerChosenList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); collectNewSiteInfo(siteInfo, state, params, providerChosenList); // next step //state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } /** * dispatch to different functions based on the option value in the * parameter */ public void doManual_add_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) { readCourseSectionInfo(state, params); String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); updateSiteInfo(params, state); if (option.equalsIgnoreCase("add")) { if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(uniqname.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String eid = StringUtil.trimToZero((String) iInstructors.next()); try { UserDirectoryService.getUserByEid(eid); } catch (UserNotDefinedException e) { addAlert( state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService .getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doManual_add_course: cannot find user with eid=" + eid, e); } } } } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } updateCurrentStep(state, true); } } else if (option.equalsIgnoreCase("back")) { doBack(data); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doManual_add_course /** * dispatch to different functions based on the option value in the * parameter */ public void doSite_information(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("continue")) { doContinue(data); // if create based on template, skip the feature selection Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doSite_information /** * read the input information of subject, course and section in the manual * site creation page */ private void readCourseSectionInfo(SessionState state, ParameterParser params) { String option = params.getString("option"); int oldNumber = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { oldNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(); } // read the user input int validInputSites = 0; boolean validInput = true; List multiCourseInputs = new Vector(); for (int i = 0; i < oldNumber; i++) { List requiredFields = sectionFieldProvider.getRequiredFields(); List aCourseInputs = new Vector(); int emptyInputNum = 0; // iterate through all required fields for (int k = 0; k < requiredFields.size(); k++) { SectionField sectionField = (SectionField) requiredFields .get(k); String fieldLabel = sectionField.getLabelKey(); String fieldInput = StringUtil.trimToZero(params .getString(fieldLabel + i)); sectionField.setValue(fieldInput); aCourseInputs.add(sectionField); if (fieldInput.length() == 0) { // is this an empty String input? emptyInputNum++; } } // is any input invalid? if (emptyInputNum == 0) { // valid if all the inputs are not empty multiCourseInputs.add(validInputSites++, aCourseInputs); } else if (emptyInputNum == requiredFields.size()) { // ignore if all inputs are empty if (option.equalsIgnoreCase("change")) { multiCourseInputs.add(validInputSites++, aCourseInputs); } } else { // input invalid validInput = false; } } // how many more course/section to include in the site? if (option.equalsIgnoreCase("change")) { if (params.getString("number") != null) { int newNumber = Integer.parseInt(params.getString("number")); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber)); List requiredFields = sectionFieldProvider.getRequiredFields(); for (int j = 0; j < newNumber; j++) { // add a new course input List aCourseInputs = new Vector(); // iterate through all required fields for (int m = 0; m < requiredFields.size(); m++) { aCourseInputs = sectionFieldProvider.getRequiredFields(); } multiCourseInputs.add(aCourseInputs); } } } state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs); if (!option.equalsIgnoreCase("change")) { if (!validInput || validInputSites == 0) { // not valid input addAlert(state, rb.getString("java.miss")); } // valid input, adjust the add course number state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites)); } // set state attributes state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params .getString("additional"))); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // store the manually requested sections in one site property if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0) { AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(), (List) multiCourseInputs.get(0)); // default title String title = sectionFieldProvider.getSectionTitle(t.getEid(), (List) multiCourseInputs.get(0)); try { title = cms.getSection(sectionEid).getTitle(); } catch (IdNotFoundException e) { // cannot find section, use the default title M_log.warn(this + ":readCourseSectionInfo: cannot find section with eid=" + sectionEid); } siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // readCourseSectionInfo /** * * @param state * @param type */ private void setNewSiteType(SessionState state, String type) { state.setAttribute(STATE_SITE_TYPE, type); // start out with fresh site information SiteInfo siteInfo = new SiteInfo(); siteInfo.site_type = type; siteInfo.published = true; state.setAttribute(STATE_SITE_INFO, siteInfo); // set tool registration list setToolRegistrationList(state, type); } /** * Set the state variables for tool registration list basd on site type * @param state * @param type */ private void setToolRegistrationList(SessionState state, String type) { state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the tool id set which allows for multiple instances Set multipleToolIdSet = new HashSet(); Hashtable multipleToolConfiguration = new Hashtable<String, Hashtable<String, String>>(); // get registered tools list Set categories = new HashSet(); categories.add(type); Set toolRegistrations = ToolManager.findTools(categories, null); if ((toolRegistrations == null || toolRegistrations.size() == 0) && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // use default site type and try getting tools again type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); categories.clear(); categories.add(type); toolRegistrations = ToolManager.findTools(categories, null); } List tools = new Vector(); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); tools.add(newTool); String originalToolId = findOriginalToolId(state, tr.getId()); if (isMultipleInstancesAllowed(originalToolId)) { // of a tool which allows multiple instances multipleToolIdSet.add(tr.getId()); // get the configuration for multiple instance Hashtable<String, String> toolConfigurations = getMultiToolConfiguration(originalToolId); multipleToolConfiguration.put(tr.getId(), toolConfigurations); } } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools); state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); } /** * Set the field on which to sort the list of students * */ public void doSort_roster(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the field on which to sort the student list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort_roster /** * Set the field on which to sort the list of sites * */ public void doSort_sites(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // call this method at the start of a sort for proper paging resetPaging(state); // get the field on which to sort the site list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } state.setAttribute(SORTED_BY, criterion); } // doSort_sites /** * doContinue is called when "eventSubmit_doContinue" is in the request * parameters */ public void doContinue(RunData data) { // Put current form data in state and continue to the next template, // make any permanent changes SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); // Let actionForTemplate know to make any permanent changes before // continuing to the next template String direction = "continue"; String option = params.getString("option"); actionForTemplate(direction, index, params, state); if (state.getAttribute(STATE_MESSAGE) == null) { if (index == 36 && ("add").equals(option)) { // this is the Add extra Roster(s) case after a site is created state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } else if (params.getString("continue") != null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } } }// doContinue /** * handle with continue add new course site options * */ public void doContinue_new_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = data.getParameters().getString("option"); if (option.equals("continue")) { doContinue(data); // if create based on template, skip the feature selection Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equalsIgnoreCase("change")) { // change term String termId = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(termId); state.setAttribute(STATE_TERM_SELECTED, t); isFutureTermSelected(state); } else if (option.equalsIgnoreCase("cancel_edit")) { // cancel doCancel(data); } else if (option.equalsIgnoreCase("add")) { isFutureTermSelected(state); // continue doContinue(data); } } // doContinue_new_course /** * doBack is called when "eventSubmit_doBack" is in the request parameters * Pass parameter to actionForTemplate to request action for backward * direction */ public void doBack(RunData data) { // Put current form data in state and return to the previous template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int currentIndex = Integer.parseInt((String) state .getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back")); // Let actionForTemplate know not to make any permanent changes before // continuing to the next template String direction = "back"; actionForTemplate(direction, currentIndex, params, state); // remove the last template index from the list removeLastIndexInStateVisitedTemplates(state); }// doBack /** * doFinish is called when a site has enough information to be saved as an * unpublished site */ public void doFinish(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); addNewSite(params, state); Site site = getStateSite(state); Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite == null) { // normal site creation: add the features. saveFeatures(params, state, site); } else { // create based on template: skip add features, and copying all the contents from the tools in template site importToolContent(site.getId(), templateSite.getId(), site, true); } // for course sites String siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { String siteId = site.getId(); ResourcePropertiesEdit rp = site.getPropertiesEdit(); AcademicSession term = null; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } // update the site and related realm based on the rosters chosen or requested updateCourseSiteSections(state, siteId, rp, term); } // commit site commitSite(site); // transfer site content from template site if (templateSite != null) { sendTemplateUseNotification(site, UserDirectoryService.getCurrentUser(), templateSite); } String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); // now that the site exists, we can set the email alias when an // Email Archive tool has been selected setSiteAlias(state, siteId); // save user answers saveSiteSetupQuestionUserAnswers(state, siteId); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); // clean state variables cleanState(state); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(SiteHelper.SITE_CREATE_SITE_ID, site.getId()); state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } }// doFinish /** * set site mail alias * @param state * @param siteId */ private void setSiteAlias(SessionState state, String siteId) { List oTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); if (oTools == null || (oTools!=null && !oTools.contains("sakai.mailbox"))) { // set alias only if the email archive tool is newly added String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { String channelReference = mailArchiveChannelReference(siteId); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { addAlert(state, rb.getString("java.addalias") + " "); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.addalias") + ee); } } } } /** * save user answers * @param state * @param siteId */ private void saveSiteSetupQuestionUserAnswers(SessionState state, String siteId) { // update the database with user answers to SiteSetup questions if (state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER) != null) { Set<SiteSetupUserAnswer> userAnswers = (Set<SiteSetupUserAnswer>) state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); for(Iterator<SiteSetupUserAnswer> aIterator = userAnswers.iterator(); aIterator.hasNext();) { SiteSetupUserAnswer userAnswer = aIterator.next(); userAnswer.setSiteId(siteId); // save to db questionService.saveSiteSetupUserAnswer(userAnswer); } } } /** * Update course site and related realm based on the roster chosen or requested * @param state * @param siteId * @param rp * @param term */ private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) { // whether this is in the process of editing a site? boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false; List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); int manualAddNumber = 0; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { manualAddNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); } List<SectionObject> cmRequestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); String realm = SiteService.siteReference(siteId); if ((providerCourseList != null) && (providerCourseList.size() != 0)) { try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realm); String providerRealm = buildExternalRealm(siteId, state, providerCourseList, StringUtil.trimToNull(realmEdit.getProviderGroupId())); realmEdit.setProviderGroupId(providerRealm); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseSiteSections: IdUnusedException, not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.realm")); } // catch (AuthzPermissionException e) // { // M_log.warn(this + " PermissionException, user does not // have permission to edit AuthzGroup object."); // addAlert(state, rb.getString("java.notaccess")); // return; // } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".updateCourseSiteSections: " + rb.getString("java.problem"), e); } sendSiteNotification(state, providerCourseList); } if (manualAddNumber != 0) { // set the manual sections to the site property String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":""; // manualCourseInputs is a list of a list of SectionField List manualCourseInputs = (List) state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < manualAddNumber; j++) { manualSections = manualSections.concat( sectionFieldProvider.getSectionEid( term.getEid(), (List) manualCourseInputs.get(j))) .concat("+"); } // trim the trailing plus sign manualSections = trimTrailingString(manualSections, "+"); rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections); // send request sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual"); } if (cmRequestedSections != null && cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { // set the cmRequest sections to the site property String cmRequestedSectionString = ""; if (!editingSite) { // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < cmRequestedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest"); } else { cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):""; // get the selected cm section if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null ) { List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmRequestedSectionString.length() != 0) { cmRequestedSectionString = cmRequestedSectionString.concat("+"); } for (int j = 0; j < cmSelectedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest"); } } // update site property if (cmRequestedSectionString.length() > 0) { rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString); } else { rp.removeProperty(STATE_CM_REQUESTED_SECTIONS); } } } /** * Trim the trailing occurance of specified string * @param cmRequestedSectionString * @param trailingString * @return */ private String trimTrailingString(String cmRequestedSectionString, String trailingString) { if (cmRequestedSectionString.endsWith(trailingString)) { cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString)); } return cmRequestedSectionString; } /** * buildExternalRealm creates a site/realm id in one of three formats, for a * single section, for multiple sections of the same course, or for a * cross-listing having multiple courses * * @param sectionList * is a Vector of CourseListItem * @param id * The site id */ private String buildExternalRealm(String id, SessionState state, List<String> providerIdList, String existingProviderIdString) { String realm = SiteService.siteReference(id); if (!AuthzGroupService.allowUpdate(realm)) { addAlert(state, rb.getString("java.rosters")); return null; } List<String> allProviderIdList = new Vector<String>(); // see if we need to keep existing provider settings if (existingProviderIdString != null) { allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString))); } // update the list with newly added providers allProviderIdList.addAll(providerIdList); if (allProviderIdList == null || allProviderIdList.size() == 0) return null; String[] providers = new String[allProviderIdList.size()]; providers = (String[]) allProviderIdList.toArray(providers); String providerId = groupProvider.packId(providers); return providerId; } // buildExternalRealm /** * Notification sent when a course site needs to be set up by Support * */ private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields, String fromContext) { User cUser = UserDirectoryService.getCurrentUser(); String sendEmailToRequestee = null; StringBuilder buf = new StringBuilder(); // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { String officialAccountName = ServerConfigurationService .getString("officialAccountName", ""); SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); AcademicSession term = null; boolean termExist = false; if (state.getAttribute(STATE_TERM_SELECTED) != null) { termExist = true; term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); } String productionSiteName = ServerConfigurationService .getServerName(); String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String message_subject = NULL_STRING; String content = NULL_STRING; String sessionUserName = cUser.getDisplayName(); String additional = NULL_STRING; if (request.equals("new")) { additional = siteInfo.getAdditional(); } else { additional = (String) state.getAttribute(FORM_ADDITIONAL); } boolean isFutureTerm = false; if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { isFutureTerm = true; } // message subject if (termExist) { message_subject = rb.getString("java.sitereqfrom") + " " + sessionUserName + " " + rb.getString("java.for") + " " + term.getEid(); } else { message_subject = rb.getString("java.official") + " " + sessionUserName; } // there is no offical instructor for future term sites String requestId = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (!isFutureTerm) { // To site quest account - the instructor of record's if (requestId != null) { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(requestId.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String instructorId = (String) iInstructors.next(); try { User instructor = UserDirectoryService.getUserByEid(instructorId); rb.setContextLocale(rb.getLocale(instructor.getId())); // reset buf.setLength(0); to = instructor.getEmail(); from = requestEmail; headerTo = to; replyTo = requestEmail; buf.append(rb.getString("java.hello") + " \n\n"); buf.append(rb.getString("java.receiv") + " " + sessionUserName + ", "); buf.append(rb.getString("java.who") + "\n"); if (termExist) { buf.append(term.getTitle()); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append("\n" + rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id); buf.append("\n\n" + rb.getString("java.according") + " " + sessionUserName + " " + rb.getString("java.record")); buf.append(" " + rb.getString("java.canyou") + " " + sessionUserName + " " + rb.getString("java.assoc") + "\n\n"); buf.append(rb.getString("java.respond") + " " + sessionUserName + rb.getString("java.appoint") + "\n\n"); buf.append(rb.getString("java.thanks") + "\n"); buf.append(productionSiteName + " " + rb.getString("java.support")); content = buf.toString(); // send the email EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert back the local setting to default rb.setContextLocale(Locale.getDefault()); } catch (Exception e) { sendEmailToRequestee = sendEmailToRequestee == null?instructorId:sendEmailToRequestee.concat(", ").concat(instructorId); } } } } // To Support from = cUser.getEmail(); // set locale to system default rb.setContextLocale(Locale.getDefault()); to = requestEmail; headerTo = requestEmail; replyTo = cUser.getEmail(); buf.setLength(0); buf.append(rb.getString("java.to") + "\t\t" + productionSiteName + " " + rb.getString("java.supp") + "\n"); buf.append("\n" + rb.getString("java.from") + "\t" + sessionUserName + "\n"); if (request.equals("new")) { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitereq") + "\n"); } else { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitechreq") + "\n"); } buf.append(rb.getString("java.date") + "\t" + local_date + " " + local_time + "\n\n"); if (request.equals("new")) { buf.append(rb.getString("java.approval") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } else { buf.append(rb.getString("java.approval2") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } if (termExist) { buf.append(term.getTitle()); } if (requestListSize > 1) { buf.append(" " + rb.getString("java.forthese") + " " + requestListSize + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.forthis") + "\n\n"); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append(rb.getString("java.name") + "\t" + sessionUserName + " (" + officialAccountName + " " + cUser.getEid() + ")\n"); buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n"); buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id + "\n"); buf.append(rb.getString("java.siteinstr") + "\n" + additional + "\n\n"); if (!isFutureTerm) { if (sendEmailToRequestee == null) { buf.append(rb.getString("java.authoriz") + " " + requestId + " " + rb.getString("java.asreq")); } else { buf.append(rb.getString("java.thesiteemail") + " " + sendEmailToRequestee + " " + rb.getString("java.asreq")); } } content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // To the Instructor from = requestEmail; to = cUser.getEmail(); // set the locale to individual receipient's setting rb.setContextLocale(rb.getLocale(cUser.getId())); headerTo = to; replyTo = to; buf.setLength(0); buf.append(rb.getString("java.isbeing") + " "); buf.append(rb.getString("java.meantime") + "\n\n"); buf.append(rb.getString("java.copy") + "\n\n"); buf.append(content); buf.append("\n" + rb.getString("java.wish") + " " + requestEmail); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert the locale to system default rb.setContextLocale(Locale.getDefault()); state.setAttribute(REQUEST_SENT, new Boolean(true)); } // if } // sendSiteRequest private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) { // what are the required fields shown in the UI List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector(); for (int i = 0; i < requiredFields.size(); i++) { List requiredFieldList = (List) requestFields .get(i); for (int j = 0; j < requiredFieldList.size(); j++) { SectionField requiredField = (SectionField) requiredFieldList .get(j); buf.append(requiredField.getLabelKey() + "\t" + requiredField.getValue() + "\n"); } } } private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) { // what are the required fields shown in the UI for (int i = 0; i < cmRequestedSections.size(); i++) { SectionObject so = (SectionObject) cmRequestedSections.get(i); buf.append(so.getTitle() + "(" + so.getEid() + ")" + so.getCategory() + "\n"); } } /** * Notification sent when a course site is set up automatcally * */ private void sendSiteNotification(SessionState state, List notifySites) { // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { // send emails Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); String term_name = ""; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term_name = ((AcademicSession) state .getAttribute(STATE_TERM_SELECTED)).getEid(); } String message_subject = rb.getString("java.official") + " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name; String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String sender = UserDirectoryService.getCurrentUser() .getDisplayName(); String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); try { userId = UserDirectoryService.getUserEid(userId); } catch (UserNotDefinedException e) { M_log.warn(this + ".sendSiteNotification:" + rb.getString("user.notdefined") + " " + userId, e); } // To Support //set local to default rb.setContextLocale(Locale.getDefault()); from = UserDirectoryService.getCurrentUser().getEmail(); to = requestEmail; headerTo = requestEmail; replyTo = UserDirectoryService.getCurrentUser().getEmail(); StringBuilder buf = new StringBuilder(); buf.append("\n" + rb.getString("java.fromwork") + " " + ServerConfigurationService.getServerName() + " " + rb.getString("java.supp") + ":\n\n"); buf.append(rb.getString("java.off") + " '" + title + "' (id " + id + "), " + rb.getString("java.wasset") + " "); buf.append(sender + " (" + userId + ", " + rb.getString("java.email2") + " " + replyTo + ") "); buf.append(rb.getString("java.on") + " " + local_date + " " + rb.getString("java.at") + " " + local_time + " "); buf.append(rb.getString("java.for") + " " + term_name + ", "); int nbr_sections = notifySites.size(); if (nbr_sections > 1) { buf.append(rb.getString("java.withrost") + " " + Integer.toString(nbr_sections) + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.withrost2") + "\n\n"); } for (int i = 0; i < nbr_sections; i++) { String course = (String) notifySites.get(i); buf.append(rb.getString("java.course2") + " " + course + "\n"); } String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if } // sendSiteNotification /** * doCancel called when "eventSubmit_doCancel_create" is in the request * parameters to c */ public void doCancel_create(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); state.setAttribute(SiteHelper.SITE_CREATE_CANCELLED, Boolean.TRUE); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel_create /** * doCancel called when "eventSubmit_doCancel" is in the request parameters * to c int index = Integer.valueOf(params.getString * ("templateIndex")).intValue(); */ public void doCancel(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.removeAttribute(STATE_MESSAGE); String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX); String backIndex = params.getString("back"); state.setAttribute(STATE_TEMPLATE_INDEX, backIndex); if (currentIndex.equals("3")) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_MESSAGE); removeEditToolState(state); } else if (currentIndex.equals("5")) { // remove related state variables removeAddParticipantContext(state); params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("13") || currentIndex.equals("14")) { // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_ICON_URL); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("15")) { params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("cancelIndex")); removeEditToolState(state); } // htripath: added 'currentIndex.equals("45")' for import from file // cancel else if (currentIndex.equals("19") || currentIndex.equals("20") || currentIndex.equals("21") || currentIndex.equals("22") || currentIndex.equals("45")) { // from adding participant pages // remove related state variables removeAddParticipantContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("3")) { // from adding class if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (currentIndex.equals("27") || currentIndex.equals("28") || currentIndex.equals("59") || currentIndex.equals("60")) { // from import if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // worksite setup if (getStateSite(state) == null) { // in creating new site process state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // in editing site process state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { // site info state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } else if (currentIndex.equals("26")) { if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP) && getStateSite(state) == null) { // from creating site state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // from revising site state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } removeEditToolState(state); } else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) { // cancel back to edit class view state.removeAttribute(STATE_TERM_SELECTED); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // if all fails to match else if (isTemplateVisited(state, "12")) { // go to site info list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else { // go to WSetup list view state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel /** * doMenu_customize is called when "eventSubmit_doBack" is in the request * parameters Pass parameter to actionForTemplate to request action for * backward direction */ public void doMenu_customize(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "15"); }// doMenu_customize /** * doBack_to_list cancels an outstanding site edit, cleans state and returns * to the site list * */ public void doBack_to_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); if (site != null) { Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); h.put(site.getId(), state.getAttribute(STATE_PAGESIZE)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } // restore the page size for Worksite setup tool if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) { state.setAttribute(STATE_PAGESIZE, state .getAttribute(STATE_PAGESIZE_SITESETUP)); state.removeAttribute(STATE_PAGESIZE_SITESETUP); } cleanState(state); setupFormNamesAndConstants(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_list /** * reset to sublist with index as the last item * @param state * @param index */ private void resetVisitedTemplateListToIndex(SessionState state, String index) { if (state.getAttribute(STATE_VISITED_TEMPLATES) != null) { List<String> l = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (l != null && l.indexOf(index) >=0 && l.indexOf(index) < l.size()) { state.setAttribute(STATE_VISITED_TEMPLATES, l.subList(0, l.indexOf(index)+1)); } } } /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doAdd_custom_link(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if ((params.getString("name")) == null || (params.getString("url") == null)) { Tool tr = ToolManager.getTool("sakai.iframe"); Site site = getStateSite(state); SitePage page = site.addPage(); page.setTitle(params.getString("name")); // the visible label on // the tool menu ToolConfiguration tool = page.addTool(); tool.setTool("sakai.iframe", tr); tool.setTitle(params.getString("name")); commitSite(site); } else { addAlert(state, rb.getString("java.reqmiss")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("templateIndex")); } } // doAdd_custom_link /** * toolId might be of form original tool id concatenated with number * find whether there is an counterpart in the the multipleToolIdSet * @param state * @param toolId * @return */ private String findOriginalToolId(SessionState state, String toolId) { // treat home tool differently if (toolId.equals(HOME_TOOL_ID)) { return toolId; } else { Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationList = ToolManager.findTools(categories, null); String rv = null; if (toolRegistrationList != null) { for (Iterator i=toolRegistrationList.iterator(); rv == null && i.hasNext();) { Tool tool = (Tool) i.next(); String tId = tool.getId(); rv = originalToolId(toolId, tId); } } return rv; } } private String originalToolId(String toolId, String toolRegistrationId) { String rv = null; if (toolId.indexOf(toolRegistrationId) != -1) { // the multiple tool id format is of TOOL_IDx, where x is an intger >= 1 if (toolId.endsWith(toolRegistrationId)) { rv = toolRegistrationId; } else { String suffix = toolId.substring(toolId.indexOf(toolRegistrationId) + toolRegistrationId.length()); try { Integer.parseInt(suffix); rv = toolRegistrationId; } catch (Exception e) { // not the right tool id M_log.debug(this + ".findOriginalToolId not matchign tool id = " + toolRegistrationId + " original tool id=" + toolId + e.getMessage(), e); } } } return rv; } /** * Read from tool registration whether multiple registration is allowed for this tool * @param toolId * @return */ private boolean isMultipleInstancesAllowed(String toolId) { Tool tool = ToolManager.getTool(toolId); if (tool != null) { Properties tProperties = tool.getRegisteredConfig(); return (tProperties.containsKey("allowMultipleInstances") && tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false; } return false; } private Hashtable<String, String> getMultiToolConfiguration(String toolId) { Hashtable<String, String> rv = new Hashtable<String, String>(); // read from configuration file ArrayList<String> attributes=new ArrayList<String>(); String attributesConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE + toolId); if ( attributesConfig != null && attributesConfig.length() > 0) { attributes = new ArrayList(Arrays.asList(attributesConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default setting for News tool attributes.add("channel-url"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool attributes.add("source"); } } ArrayList<String> defaultValues =new ArrayList<String>(); String defaultValueConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE_DEFAULT + toolId); if ( defaultValueConfig != null && defaultValueConfig.length() > 0) { defaultValues = new ArrayList(Arrays.asList(defaultValueConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default value defaultValues.add("http://www.sakaiproject.org/news-rss-feed"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool defaultValues.add("http://"); } } if (attributes != null && attributes.size() > 0) { for (int i = 0; i<attributes.size();i++) { rv.put(attributes.get(i), defaultValues.get(i)); } } return rv; } /** * doSave_revised_features */ public void doSave_revised_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site site = getStateSite(state); saveFeatures(params, state, site); String id = site.getId(); // now that the site exists, we can set the email alias when an Email // Archive tool has been selected setSiteAlias(state, id); if (state.getAttribute(STATE_MESSAGE) == null) { // clean state variables state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); state.setAttribute(STATE_SITE_INSTANCE_ID, id); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } // refresh the whole page scheduleTopRefresh(); } // doSave_revised_features /** * doMenu_add_participant */ public void doMenu_add_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // doMenu_add_participant /** * doMenu_siteInfo_addParticipant */ public void doMenu_siteInfo_addParticipant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } } // doMenu_siteInfo_addParticipant /** * doMenu_siteInfo_cancel_access */ public void doMenu_siteInfo_cancel_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // doMenu_siteInfo_cancel_access /** * doMenu_siteInfo_importSelection */ public void doMenu_siteInfo_importSelection(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "58"); } } // doMenu_siteInfo_importSelection /** * doMenu_siteInfo_import */ public void doMenu_siteInfo_import(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } } // doMenu_siteInfo_import public void doMenu_siteInfo_importMigrate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "59"); } } // doMenu_siteInfo_importMigrate /** * doMenu_siteInfo_editClass */ public void doMenu_siteInfo_editClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // doMenu_siteInfo_editClass /** * doMenu_siteInfo_addClass */ public void doMenu_siteInfo_addClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID); if (termEid == null) { // no term eid stored, need to get term eid from the term title String termTitle = site.getProperties().getProperty(PROP_SITE_TERM); List asList = cms.getAcademicSessions(); if (termTitle != null && asList != null) { boolean found = false; for (int i = 0; i<asList.size() && !found; i++) { AcademicSession as = (AcademicSession) asList.get(i); if (as.getTitle().equals(termTitle)) { termEid = as.getEid(); site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + site.getId(), e); } found=true; } } } } state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid)); try { List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) state.setAttribute(STATE_TERM_COURSE_LIST, sections); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + termEid, e); } state.setAttribute(STATE_TEMPLATE_INDEX, "36"); } // doMenu_siteInfo_addClass /** * doMenu_siteInfo_duplicate */ public void doMenu_siteInfo_duplicate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "29"); } } // doMenu_siteInfo_import /** * doMenu_edit_site_info * */ public void doMenu_edit_site_info(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourceProperties siteProperties = Site.getProperties(); state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle()); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) { state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf( Site.isPubView()).toString()); } state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription()); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site .getShortDescription()); state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); if (Site.getIconUrl() != null) { state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); } // site contact information String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { String creatorId = siteProperties .getProperty(ResourceProperties.PROP_CREATOR); try { User u = UserDirectoryService.getUser(creatorId); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } catch (UserNotDefinedException e) { } } if (contactName != null) { state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); } if (contactEmail != null) { state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "13"); } } // doMenu_edit_site_info /** * doMenu_edit_site_tools * */ public void doMenu_edit_site_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "3"); } } // doMenu_edit_site_tools /** * doMenu_edit_site_access * */ public void doMenu_edit_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doMenu_edit_site_access /** * Back to worksite setup's list view * */ public void doBack_to_site_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_SITE_INSTANCE_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_site_list /** * doSave_site_info * */ public void doSave_siteInfo(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit(); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (siteTitleEditable(state, site_type)) { Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE)); } Site.setDescription((String) state .getAttribute(FORM_SITEINFO_DESCRIPTION)); Site.setShortDescription((String) state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); if (site_type != null) { if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // set icon url for course String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN); setAppearance(state, Site, skin); } else { // set icon url for others String iconUrl = (String) state .getAttribute(FORM_SITEINFO_ICON_URL); Site.setIconUrl(iconUrl); } } // site contact information String contactName = (String) state .getAttribute(FORM_SITEINFO_CONTACT_NAME); if (contactName != null) { siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName); } String contactEmail = (String) state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL); if (contactEmail != null) { siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { try { SiteService.save(Site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_CONTACT_NAME); state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL); // back to site info view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // refresh the whole page scheduleTopRefresh(); } } // doSave_siteInfo /** * Check to see whether the site's title is editable or not * @param state * @param site_type * @return */ private boolean siteTitleEditable(SessionState state, String site_type) { return site_type != null && (!site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE)) || (state.getAttribute(TITLE_EDITABLE_SITE_TYPE) != null && ((List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE)).contains(site_type))); } /** * init * */ private void init(VelocityPortlet portlet, RunData data, SessionState state) { state.setAttribute(STATE_ACTION, "SiteAction"); setupFormNamesAndConstants(state); if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) { state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable()); } if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))){ String siteId = ToolManager.getCurrentPlacement().getContext(); getReviseSite(state, siteId); Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); state.setAttribute(STATE_PAGESIZE, new Integer(200)); } } if (state.getAttribute(STATE_SITE_TYPES) == null) { PortletConfig config = portlet.getPortletConfig(); // all site types (SITE_DEFAULT_LIST overrides tool config) String t = StringUtil.trimToNull(SITE_DEFAULT_LIST); if ( t == null ) t = StringUtil.trimToNull(config.getInitParameter("siteTypes")); if (t != null) { List types = new ArrayList(Arrays.asList(t.split(","))); if (cms == null) { // if there is no CourseManagementService, disable the process of creating course site String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)); types.remove(courseType); } state.setAttribute(STATE_SITE_TYPES, types); } else { t = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES); if (t != null) { state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays .asList(t.split(",")))); } else { state.setAttribute(STATE_SITE_TYPES, new Vector()); } } } /*<p> * This is a change related to SAK-12912 * initialize the question list */ if (!questionService.hasAnySiteTypeQuestions()) { if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable()) { SiteSetupQuestionFileParser.updateConfig(); } } // show UI for adding non-official participant(s) or not // if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them. // the setting defaults to be true if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null) { state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true")); } if (state.getAttribute(STATE_VISITED_TEMPLATES) == null) { List<String> templates = new Vector<String>(); if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) { templates.add("0"); // the default page of WSetup tool } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { templates.add("12");// the default page of Site Info tool } state.setAttribute(STATE_VISITED_TEMPLATES, templates); } } // init public void doNavigate_to_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = StringUtil.trimToNull(data.getParameters().getString( "option")); if (siteId != null) { getReviseSite(state, siteId); } else { doBack_to_list(data); } } // doNavigate_to_site /** * Get site information for revise screen */ private void getReviseSite(SessionState state, String siteId) { if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) { state.setAttribute(STATE_SELECTED_USER_LIST, new Vector()); } List sites = (List) state.getAttribute(STATE_SITES); try { Site site = SiteService.getSite(siteId); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); if (sites != null) { int pos = -1; for (int index = 0; index < sites.size() && pos == -1; index++) { if (((Site) sites.get(index)).getId().equals(siteId)) { pos = index; } } // has any previous site in the list? if (pos > 0) { state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1)); } else { state.removeAttribute(STATE_PREV_SITE); } // has any next site in the list? if (pos < sites.size() - 1) { state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1)); } else { state.removeAttribute(STATE_NEXT_SITE); } } String type = site.getType(); if (type == null) { if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } state.setAttribute(STATE_SITE_TYPE, type); } catch (IdUnusedException e) { M_log.warn(this + ".getReviseSite: " + e.toString() + " site id = " + siteId, e); } // one site has been selected state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // getReviseSite /** * doUpdate_participant * */ public void doUpdate_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site s = getStateSite(state); String realmId = SiteService.siteReference(s.getId()); if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId())) { try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId); // does the site has maintain type user(s) before updating // participants? String maintainRoleString = realmEdit.getMaintainRole(); boolean hadMaintainUser = !realmEdit.getUsersHasRole( maintainRoleString).isEmpty(); // update participant roles List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); // remove all roles and then add back those that were checked for (int i = 0; i < participants.size(); i++) { String id = null; // added participant Participant participant = (Participant) participants.get(i); id = participant.getUniqname(); if (id != null) { // get the newly assigned role String inputRoleField = "role" + id; String roleId = params.getString(inputRoleField); // only change roles when they are different than before if (roleId != null) { // get the grant active status boolean activeGrant = true; String activeGrantField = "activeGrant" + id; if (params.getString(activeGrantField) != null) { activeGrant = params .getString(activeGrantField) .equalsIgnoreCase("true") ? true : false; } boolean fromProvider = !participant.isRemoveable(); if (fromProvider && !roleId.equals(participant.getRole())) { fromProvider = false; } realmEdit.addMember(id, roleId, activeGrant, fromProvider); } } } // remove selected users if (params.getStrings("selectedUser") != null) { List removals = new ArrayList(Arrays.asList(params .getStrings("selectedUser"))); state.setAttribute(STATE_SELECTED_USER_LIST, removals); for (int i = 0; i < removals.size(); i++) { String rId = (String) removals.get(i); try { User user = UserDirectoryService.getUser(rId); realmEdit.removeMember(user.getId()); } catch (UserNotDefinedException e) { M_log.warn(this + ".doUpdate_participant: IdUnusedException " + rId + ". ", e); } } } if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString) .isEmpty()) { // if after update, the "had maintain type user" status // changed, show alert message and don't save the update addAlert(state, rb .getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + "."); } else { AuthzGroupService.save(realmEdit); // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); // then update all related group realms for the role doUpdate_related_group_participants(s, realmId); } } catch (GroupNotDefinedException e) { addAlert(state, rb.getString("java.problem2")); M_log.warn(this + ".doUpdate_participant: IdUnusedException " + s.getTitle() + "(" + realmId + "). ", e); } catch (AuthzPermissionException e) { addAlert(state, rb.getString("java.changeroles")); M_log.warn(this + ".doUpdate_participant: PermissionException " + s.getTitle() + "(" + realmId + "). ", e); } } } // doUpdate_participant /** * update realted group realm setting according to parent site realm changes * @param s * @param realmId */ private void doUpdate_related_group_participants(Site s, String realmId) { Collection groups = s.getGroups(); if (groups != null) { try { for (Iterator iGroups = groups.iterator(); iGroups.hasNext();) { Group g = (Group) iGroups.next(); try { Set gMembers = g.getMembers(); for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();) { Member gMember = (Member) iGMembers.next(); String gMemberId = gMember.getUserId(); Member siteMember = s.getMember(gMemberId); if ( siteMember == null) { // user has been removed from the site g.removeMember(gMemberId); } else { // if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided" if (!g.getUserRole(gMemberId).equals(siteMember.getRole())) { g.removeMember(gMemberId); g.addMember(gMemberId, siteMember.getRole().getId(), siteMember.isActive(), false); } } } // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false)); } catch (Exception ee) { M_log.warn(this + ".doUpdate_related_group_participants: " + ee.getMessage() + g.getId(), ee); } } // commit, save the site SiteService.save(s); } catch (Exception e) { M_log.warn(this + ".doUpdate_related_group_participants: " + e.getMessage() + s.getId(), e); } } } /** * doUpdate_site_access * */ public void doUpdate_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site sEdit = getStateSite(state); ParameterParser params = data.getParameters(); String publishUnpublish = params.getString("publishunpublish"); String include = params.getString("include"); String joinable = params.getString("joinable"); if (sEdit != null) { // editing existing site // publish site or not if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { sEdit.setPublished(true); } else { sEdit.setPublished(false); } // site public choice if (include != null) { // if there is pubview input, use it sEdit.setPubView(include.equalsIgnoreCase("true") ? true : false); } else if (state.getAttribute(STATE_SITE_TYPE) != null) { String type = (String) state.getAttribute(STATE_SITE_TYPE); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public sEdit.setPubView(true); } else if (privateSiteTypes.contains(type)) { // site are always private sEdit.setPubView(false); } } else { sEdit.setPubView(false); } // publish site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { state.setAttribute(STATE_JOINABLE, Boolean.TRUE); sEdit.setJoinable(true); String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { state.setAttribute(STATE_JOINERROLE, joinerRole); sEdit.setJoinerRole(joinerRole); } else { state.setAttribute(STATE_JOINERROLE, ""); addAlert(state, rb.getString("java.joinsite") + " "); } } else { state.setAttribute(STATE_JOINABLE, Boolean.FALSE); state.removeAttribute(STATE_JOINERROLE); sEdit.setJoinable(false); sEdit.setJoinerRole(null); } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(sEdit); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // TODO: hard coding this frame id is fragile, portal dependent, // and needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); } } else { // adding new site if (state.getAttribute(STATE_SITE_INFO) != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { siteInfo.published = true; } else { siteInfo.published = false; } // site public choice if (include != null) { siteInfo.include = include.equalsIgnoreCase("true") ? true : false; } else if (StringUtil.trimToNull(siteInfo.site_type) != null) { String type = StringUtil.trimToNull(siteInfo.site_type); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public siteInfo.include = true; } else if (privateSiteTypes.contains(type)) { // site are always private siteInfo.include = false; } } else { siteInfo.include = false; } // joinable site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { siteInfo.joinable = true; String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { siteInfo.joinerRole = joinerRole; } else { addAlert(state, rb.getString("java.joinsite") + " "); } } else { siteInfo.joinable = false; siteInfo.joinerRole = null; } state.setAttribute(STATE_SITE_INFO, siteInfo); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "10"); updateCurrentStep(state, true); } } } // doUpdate_site_access /** * /* Actions for vm templates under the "chef_site" root. This method is * called by doContinue. Each template has a hidden field with the value of * template-index that becomes the value of index for the switch statement * here. Some cases not implemented. */ private void actionForTemplate(String direction, int index, ParameterParser params, SessionState state) { // Continue - make any permanent changes, Back - keep any data entered // on the form boolean forward = direction.equals("continue") ? true : false; SiteInfo siteInfo = new SiteInfo(); switch (index) { case 0: /* * actionForTemplate chef_site-list.vm * */ break; case 1: /* * actionForTemplate chef_site-type.vm * */ break; case 2: /* * actionForTemplate chef_site-newSiteInformation.vm * */ if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // defaults to be true siteInfo.include = true; state.setAttribute(STATE_SITE_INFO, siteInfo); updateSiteInfo(params, state); // alerts after clicking Continue but not Back if (forward) { if (StringUtil.trimToNull(siteInfo.title) == null) { addAlert(state, rb.getString("java.reqfields")); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); return; } } else { // removing previously selected template site state.removeAttribute(STATE_TEMPLATE_SITE); } updateSiteAttributes(state); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 3: /* * actionForTemplate chef_site-editFeatures.vm * */ if (forward) { // editing existing site or creating a new one? Site site = getStateSite(state); getFeatures(params, state, site==null?"18":"15"); if (state.getAttribute(STATE_MESSAGE) == null && site==null) { updateCurrentStep(state, forward); } } break; case 5: /* * actionForTemplate chef_site-addParticipant.vm * */ if (forward) { checkAddParticipant(params, state); } else { // remove related state variables removeAddParticipantContext(state); } break; case 8: /* * actionForTemplate chef_site-siteDeleteConfirm.vm * */ break; case 10: /* * actionForTemplate chef_site-newSiteConfirm.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } break; case 12: /* * actionForTemplate chef_site_siteInfo-list.vm * */ break; case 13: /* * actionForTemplate chef_site_siteInfo-editInfo.vm * */ if (forward) { Site Site = getStateSite(state); if (siteTitleEditable(state, Site.getType())) { // site titel is editable and could not be null String title = StringUtil.trimToNull(params .getString("title")); state.setAttribute(FORM_SITEINFO_TITLE, title); if (title == null) { addAlert(state, rb.getString("java.specify") + " "); } } String description = StringUtil.trimToNull(params .getString("description")); StringBuilder alertMsg = new StringBuilder(); state.setAttribute(FORM_SITEINFO_DESCRIPTION, FormattedText.processFormattedText(description, alertMsg)); String short_description = StringUtil.trimToNull(params .getString("short_description")); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, short_description); String skin = params.getString("skin"); if (skin != null) { // if there is a skin input for course site skin = StringUtil.trimToNull(skin); state.setAttribute(FORM_SITEINFO_SKIN, skin); } else { // if ther is a icon input for non-course site String icon = StringUtil.trimToNull(params .getString("icon")); if (icon != null) { if (icon.endsWith(PROTOCOL_STRING)) { addAlert(state, rb.getString("alert.protocol")); } state.setAttribute(FORM_SITEINFO_ICON_URL, icon); } else { state.removeAttribute(FORM_SITEINFO_ICON_URL); } } // site contact information String contactName = StringUtil.trimToZero(params .getString("siteContactName")); state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); String email = StringUtil.trimToZero(params .getString("siteContactEmail")); String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "14"); } } break; case 14: /* * actionForTemplate chef_site_siteInfo-editInfoConfirm.vm * */ break; case 15: /* * actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm * */ break; case 18: /* * actionForTemplate chef_siteInfo-editAccess.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } case 19: /* * actionForTemplate chef_site-addParticipant-sameRole.vm * */ String roleId = StringUtil.trimToNull(params .getString("selectRole")); if (roleId == null && forward) { addAlert(state, rb.getString("java.pleasesel") + " "); } else { state.setAttribute("form_selectedRole", params .getString("selectRole")); } break; case 20: /* * actionForTemplate chef_site-addParticipant-differentRole.vm * */ if (forward) { getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS); } break; case 21: /* * actionForTemplate chef_site-addParticipant-notification.vm ' */ if (params.getString("notify") == null) { if (forward) addAlert(state, rb.getString("java.pleasechoice") + " "); } else { state.setAttribute("form_selectedNotify", new Boolean(params .getString("notify"))); } break; case 22: /* * actionForTemplate chef_site-addParticipant-confirm.vm * */ break; case 24: /* * actionForTemplate * chef_site-siteInfo-editAccess-globalAccess-confirm.vm * */ break; case 26: /* * actionForTemplate chef_site-modifyENW.vm * */ updateSelectedToolList(state, params, forward); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 27: /* * actionForTemplate chef_site-importSites.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); importToolIntoSite(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 60: /* * actionForTemplate chef_site-importSitesMigrate.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // Remove all old contents before importing contents from new site importToolIntoSiteMigrate(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 28: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 58: /* * actionForTemplate chef_siteinfo-importSelection.vm * */ break; case 59: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 29: /* * actionForTemplate chef_siteinfo-duplicate.vm * */ if (forward) { if (state.getAttribute(SITE_DUPLICATED) == null) { if (StringUtil.trimToNull(params.getString("title")) == null) { addAlert(state, rb.getString("java.dupli") + " "); } else { String title = params.getString("title"); state.setAttribute(SITE_DUPLICATED_NAME, title); String nSiteId = IdManager.createUuid(); try { String oSiteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); Site site = SiteService.addSite(nSiteId, getStateSite(state)); // get the new site icon url if (site.getIconUrl() != null) { site.setIconUrl(transferSiteResource(oSiteId, nSiteId, site.getIconUrl())); } try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } try { site = SiteService.getSite(nSiteId); // set title site.setTitle(title); // import tool content importToolContent(nSiteId, oSiteId, site, false); } catch (Exception e1) { // if goes here, IdService // or SiteService has done // something wrong. M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + e1 + ":" + nSiteId + "when duplicating site", e1); } if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // for course site, need to // read in the input for // term information String termId = StringUtil.trimToNull(params .getString("selectTerm")); if (termId != null) { AcademicSession term = cms.getAcademicSession(termId); if (term != null) { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } else { M_log.warn("termId=" + termId + " not found"); } } } try { SiteService.save(site); if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // also remove the provider id attribute if any String realm = SiteService.siteReference(site.getId()); try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm); realmEdit.setProviderGroupId(null); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "+ realm, e); addAlert(state, rb.getString("java.realm")); } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.problem"), e); } } } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // TODO: hard coding this frame id // is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.setAttribute(SITE_DUPLICATED, Boolean.TRUE); } catch (IdInvalidException e) { addAlert(state, rb.getString("java.siteinval")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.siteinval") + " site id = " + nSiteId, e); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitebeenused")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.sitebeenused") + " site id = " + nSiteId, e); } catch (PermissionException e) { addAlert(state, rb.getString("java.allowcreate")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.allowcreate") + " site id = " + nSiteId, e); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // site duplication confirmed state.removeAttribute(SITE_DUPLICATED); state.removeAttribute(SITE_DUPLICATED_NAME); // return to the list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } break; case 33: break; case 36: /* * actionForTemplate chef_site-newSiteCourse.vm */ if (forward) { List providerChosenList = new Vector(); if (params.getStrings("providerCourseAdd") == null) { state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (params.getString("manualAdds") == null) { addAlert(state, rb.getString("java.manual") + " "); } } if (state.getAttribute(STATE_MESSAGE) == null) { // The list of courses selected from provider listing if (params.getStrings("providerCourseAdd") != null) { providerChosenList = new ArrayList(Arrays.asList(params .getStrings("providerCourseAdd"))); // list of // course // ids String userId = (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED); String currentUserId = (String) state .getAttribute(STATE_CM_CURRENT_USERID); if (userId == null || (userId != null && userId .equals(currentUserId))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); } else { // STATE_CM_AUTHORIZER_SECTIONS are SectionObject, // so need to prepare it // also in this page, u can pick either section from // current user OR // sections from another users but not both. - // daisy's note 1 for now // till we are ready to add more complexity List sectionObjectList = prepareSectionObject( providerChosenList, userId); state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS, sectionObjectList); state .removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // set special instruction & we will keep // STATE_CM_AUTHORIZER_LIST String additional = StringUtil.trimToZero(params .getString("additional")); state.setAttribute(FORM_ADDITIONAL, additional); } } collectNewSiteInfo(siteInfo, state, params, providerChosenList); } // next step state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } break; case 38: break; case 39: break; case 42: /* * actionForTemplate chef_site-gradtoolsConfirm.vm * */ break; case 43: /* * actionForTemplate chef_site-editClass.vm * */ if (forward) { if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null && params.getStrings("cmRequestedClassDeletes") == null && !direction.equals("back")) { addAlert(state, rb.getString("java.classes")); } if (params.getStrings("providerClassDeletes") != null) { // build the deletions list List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); List providerCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("providerClassDeletes"))); for (ListIterator i = providerCourseDeleteList .listIterator(); i.hasNext();) { providerCourseList.remove((String) i.next()); } state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } if (params.getStrings("manualClassDeletes") != null) { // build the deletions list List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); List manualCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("manualClassDeletes"))); for (ListIterator i = manualCourseDeleteList.listIterator(); i .hasNext();) { manualCourseList.remove((String) i.next()); } state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList); } if (params.getStrings("cmRequestedClassDeletes") != null) { // build the deletions list List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes"))); for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i .hasNext();) { String sectionId = (String) i.next(); try { SectionObject so = new SectionObject(cms.getSection(sectionId)); SectionObject soFound = null; for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();) { SectionObject k = (SectionObject) j.next(); if (k.eid.equals(sectionId)) { soFound = k; } } if (soFound != null) cmRequestedCourseList.remove(soFound); } catch (Exception e) { M_log.warn( this + e.getMessage() + sectionId, e); } } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList); } updateCourseClasses(state, new Vector(), new Vector()); } break; case 44: if (forward) { AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); Site site = getStateSite(state); ResourcePropertiesEdit pEdit = site.getPropertiesEdit(); // update the course site property and realm based on the selection updateCourseSiteSections(state, site.getId(), pEdit, a); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage() + site.getId(), e); } removeAddClassContext(state); } break; case 54: if (forward) { // store answers to site setup questions if (getAnswersToSetupQuestions(params, state)) { state.setAttribute(STATE_TEMPLATE_INDEX, state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); } } break; } }// actionFor Template /** * This is used to update exsiting site attributes with encoded site id in it. A new resource item is added to new site when needed * * @param oSiteId * @param nSiteId * @param siteAttribute * @return the new migrated resource url */ private String transferSiteResource(String oSiteId, String nSiteId, String siteAttribute) { String rv = ""; String accessUrl = ServerConfigurationService.getAccessUrl(); if (siteAttribute.indexOf(oSiteId) != -1 && accessUrl != null) { // stripe out the access url, get the relative form of "url" Reference ref = EntityManager.newReference(siteAttribute.replaceAll(accessUrl, "")); try { ContentResource resource = m_contentHostingService.getResource(ref.getId()); // the new resource ContentResource nResource = null; String nResourceId = resource.getId().replaceAll(oSiteId, nSiteId); try { nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n2Exception) { // copy the resource then try { nResourceId = m_contentHostingService.copy(resource.getId(), nResourceId); nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n3Exception) { } } // get the new resource url rv = nResource != null?nResource.getUrl(false):""; } catch (Exception refException) { M_log.warn(this + ":transferSiteResource: cannot find resource with ref=" + ref.getReference() + " " + refException.getMessage()); } } return rv; } /** * * @param nSiteId * @param oSiteId * @param site */ private void importToolContent(String nSiteId, String oSiteId, Site site, boolean bypassSecurity) { // import tool content if (bypassSecurity) { // importing from template, bypass the permission checking: // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); } List pageList = site.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList .listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool(); String toolId = tool != null?tool.getId():""; if (toolId.equalsIgnoreCase("sakai.resources")) { // handle // resource // tool // specially transferCopyEntities( toolId, m_contentHostingService .getSiteCollection(oSiteId), m_contentHostingService .getSiteCollection(nSiteId)); } else if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) { // handle Home tool specially, need to update the site infomration display url if needed String newSiteInfoUrl = transferSiteResource(oSiteId, nSiteId, site.getInfoUrl()); site.setInfoUrl(newSiteInfoUrl); } else { // other // tools transferCopyEntities(toolId, oSiteId, nSiteId); } } } if (bypassSecurity) { SecurityService.clearAdvisors(); } } /** * get user answers to setup questions * @param params * @param state * @return */ protected boolean getAnswersToSetupQuestions(ParameterParser params, SessionState state) { boolean rv = true; String answerString = null; String answerId = null; Set userAnswers = new HashSet(); SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { List<SiteSetupQuestion> questions = siteTypeQuestions.getQuestions(); for (Iterator i = questions.iterator(); i.hasNext();) { SiteSetupQuestion question = (SiteSetupQuestion) i.next(); // get the selected answerId answerId = params.get(question.getId()); if (question.isRequired() && answerId == null) { rv = false; addAlert(state, rb.getString("sitesetupquestion.alert")); } else if (answerId != null) { SiteSetupQuestionAnswer answer = questionService.getSiteSetupQuestionAnswer(answerId); if (answer != null) { if (answer.getIsFillInBlank()) { // need to read the text input instead answerString = params.get("fillInBlank_" + answerId); } SiteSetupUserAnswer uAnswer = questionService.newSiteSetupUserAnswer(); uAnswer.setAnswerId(answerId); uAnswer.setAnswerString(answerString); uAnswer.setQuestionId(question.getId()); uAnswer.setUserId(SessionManager.getCurrentSessionUserId()); //update the state variable userAnswers.add(uAnswer); } } } state.setAttribute(STATE_SITE_SETUP_QUESTION_ANSWER, userAnswers); } return rv; } /** * get user answers to setup questions * @param params * @return */ protected void saveAnswersToSetupQuestions(SessionState state) { String answerFolderReference = SiteSetupQuestionFileParser.getAnswerFolderReference(); try { contentHostingService.addResource(answerFolderReference + ""); } catch (Exception e) { M_log.warn(this + e.getMessage()); } } /** * update current step index within the site creation wizard * * @param state * The SessionState object * @param forward * Moving forward or backward? */ private void updateCurrentStep(SessionState state, boolean forward) { if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { int currentStep = ((Integer) state .getAttribute(SITE_CREATE_CURRENT_STEP)).intValue(); if (forward) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep + 1)); } else { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep - 1)); } } } /** * remove related state variable for adding class * * @param state * SessionState object */ private void removeAddClassContext(SessionState state) { // remove related state variables state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTIONS); sitePropertiesIntoState(state); } // removeAddClassContext private void updateCourseClasses(SessionState state, List notifyClasses, List requestClasses) { List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST); List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST); List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); Site site = getStateSite(state); String id = site.getId(); String realmId = SiteService.siteReference(id); if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0)) { // no section access so remove Provider Id try { AuthzGroup realmEdit1 = AuthzGroupService .getAuthzGroup(realmId); realmEdit1.setProviderGroupId(NULL_STRING); AuthzGroupService.save(realmEdit1); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotedit")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0)) { // section access so rewrite Provider Id, don't need the current realm provider String String externalRealm = buildExternalRealm(id, state, providerCourseSectionList, null); try { AuthzGroup realmEdit2 = AuthzGroupService .getAuthzGroup(realmId); realmEdit2.setProviderGroupId(externalRealm); AuthzGroupService.save(realmEdit2); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotclasses")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } // the manual request course into properties setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE); // the cm request course into properties setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS); // clean the related site groups // if the group realm provider id is not listed for the site, remove the related group for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();) { Group group = (Group) iGroups.next(); try { AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference()); String gProviderId = StringUtil.trimToNull(gRealm.getProviderGroupId()); if (gProviderId != null) { if ((manualCourseSectionList== null && cmRequestedCourseList == null) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList == null) || (manualCourseSectionList == null && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId)) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId))) { AuthzGroupService.removeAuthzGroup(group.getReference()); } } } catch (Exception e) { M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference(), e); } } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(site); } else { } if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { try { // send out class request notifications sendSiteRequest(state, "change", ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(), (List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS), "manual"); } catch (Exception e) { M_log.warn(this +".updateCourseClasses:" + e.toString(), e); } } if (notifyClasses != null && notifyClasses.size() > 0) { try { // send out class access confirmation notifications sendSiteNotification(state, notifyClasses); } catch (Exception e) { M_log.warn(this + ".updateCourseClasses:" + e.toString(), e); } } } // updateCourseClasses private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) { if ((courseSectionList != null) && (courseSectionList.size() != 0)) { // store the requested sections in one site property String sections = ""; for (int j = 0; j < courseSectionList.size();) { sections = sections + (String) courseSectionList.get(j); j++; if (j < courseSectionList.size()) { sections = sections + "+"; } } ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(propertyName, sections); } else { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.removeProperty(propertyName); } } /** * Sets selected roles for multiple users * * @param params * The ParameterParser object * @param listName * The state variable */ private void getSelectedRoles(SessionState state, ParameterParser params, String listName) { Hashtable pSelectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); if (pSelectedRoles == null) { pSelectedRoles = new Hashtable(); } List userList = (List) state.getAttribute(listName); for (int i = 0; i < userList.size(); i++) { String userId = null; if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) { userId = ((Participant) userList.get(i)).getUniqname(); } else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) { userId = (String) userList.get(i); } if (userId != null) { String rId = StringUtil.trimToNull(params.getString("role" + userId)); if (rId == null) { addAlert(state, rb.getString("java.rolefor") + " " + userId + ". "); pSelectedRoles.remove(userId); } else { pSelectedRoles.put(userId, rId); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles); } // getSelectedRoles /** * dispatch function for changing participants roles */ public void doSiteinfo_edit_role(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("same_role_true")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE); state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params .getString("role_to_all")); } else if (option.equalsIgnoreCase("same_role_false")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE); state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) { state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable()); } } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * dispatch function for changing site global access */ public void doSiteinfo_edit_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("joinable")) { state.setAttribute("form_joinable", Boolean.TRUE); state.setAttribute("form_joinerRole", getStateSite(state) .getJoinerRole()); } else if (option.equalsIgnoreCase("unjoinable")) { state.setAttribute("form_joinable", Boolean.FALSE); state.removeAttribute("form_joinerRole"); } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * save changes to site global access */ public void doSiteinfo_save_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site s = getStateSite(state); boolean joinable = ((Boolean) state.getAttribute("form_joinable")) .booleanValue(); s.setJoinable(joinable); if (joinable) { // set the joiner role String joinerRole = (String) state.getAttribute("form_joinerRole"); s.setJoinerRole(joinerRole); } if (state.getAttribute(STATE_MESSAGE) == null) { // release site edit commitSite(s); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doSiteinfo_save_globalAccess /** * updateSiteAttributes * */ private void updateSiteAttributes(SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { M_log .warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null"); return; } Site site = getStateSite(state); if (site != null) { if (StringUtil.trimToNull(siteInfo.title) != null) { site.setTitle(siteInfo.title); } if (siteInfo.description != null) { site.setDescription(siteInfo.description); } site.setPublished(siteInfo.published); setAppearance(state, site, siteInfo.iconUrl); site.setJoinable(siteInfo.joinable); if (StringUtil.trimToNull(siteInfo.joinerRole) != null) { site.setJoinerRole(siteInfo.joinerRole); } // Make changes and then put changed site back in state String id = site.getId(); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } if (SiteService.allowUpdateSite(id)) { try { SiteService.getSite(id); state.setAttribute(STATE_SITE_INSTANCE_ID, id); } catch (IdUnusedException e) { M_log.warn(this + ".updateSiteAttributes: IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found", e); } } // no permission else { addAlert(state, rb.getString("java.makechanges")); M_log.warn(this + ".updateSiteAttributes: PermissionException " + siteInfo.getTitle() + "(" + id + ")"); } } } // updateSiteAttributes /** * %%% legacy properties, to be removed */ private void updateSiteInfo(ParameterParser params, SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (params.getString("title") != null) { siteInfo.title = params.getString("title"); } if (params.getString("description") != null) { StringBuilder alertMsg = new StringBuilder(); String description = params.getString("description"); siteInfo.description = FormattedText.processFormattedText(description, alertMsg); } if (params.getString("short_description") != null) { siteInfo.short_description = params.getString("short_description"); } if (params.getString("additional") != null) { siteInfo.additional = params.getString("additional"); } if (params.getString("iconUrl") != null) { siteInfo.iconUrl = params.getString("iconUrl"); } else { siteInfo.iconUrl = params.getString("skin"); } if (params.getString("joinerRole") != null) { siteInfo.joinerRole = params.getString("joinerRole"); } if (params.getString("joinable") != null) { boolean joinable = params.getBoolean("joinable"); siteInfo.joinable = joinable; if (!joinable) siteInfo.joinerRole = NULL_STRING; } if (params.getString("itemStatus") != null) { siteInfo.published = Boolean .valueOf(params.getString("itemStatus")).booleanValue(); } // site contact information String name = StringUtil .trimToZero(params.getString("siteContactName")); siteInfo.site_contact_name = name; String email = StringUtil.trimToZero(params .getString("siteContactEmail")); if (email != null) { String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } siteInfo.site_contact_email = email; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // updateSiteInfo /** * getParticipantList * */ private Collection getParticipantList(SessionState state) { List members = new Vector(); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List providerCourseList = null; providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } Collection participants = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList); state.setAttribute(STATE_PARTICIPANT_LIST, participants); return participants; } // getParticipantList /** * getRoles * */ private List getRoles(SessionState state) { List roles = new Vector(); String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); roles.addAll(realm.getRoles()); Collections.sort(roles); } catch (GroupNotDefinedException e) { M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e); } return roles; } // getRoles private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint) { // Add synoptic announcements tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(toolId); tool.setTool(toolId, reg); tool.setTitle(toolTitle); tool.setLayoutHints(layoutHint); } private void saveFeatures(ParameterParser params, SessionState state, Site site) { // get the list of Worksite Setup configured pages List wSetupPageList = state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST)!=null?(List) state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST):new Vector(); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); WorksiteSetupPage wSetupHome = new WorksiteSetupPage(); List pageList = new Vector(); // declare some flags used in making decisions about Home, whether to // add, remove, or do nothing boolean hasHome = false; boolean homeInWSetupPageList = false; List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // if features were selected, diff wSetupPageList and chosenList to get // page adds and removes // boolean values for adding synoptic views boolean hasAnnouncement = false; boolean hasSchedule = false; boolean hasChat = false; boolean hasDiscussion = false; boolean hasEmail = false; boolean hasSiteInfo = false; boolean hasMessageCenter = false; // tools to be imported from other sites? Hashtable importTools = null; if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) { importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL); } // Home tool chosen? if (chosenList.contains(HOME_TOOL_ID)) { // add home tool later hasHome = true; } // order the id list chosenList = orderToolIds(state, site.getType(), chosenList); // Special case - Worksite Setup Home comes from a hardcoded checkbox on // the vm template rather than toolRegistrationList // see if Home was chosen for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String choice = (String) j.next(); if (choice.equals("sakai.mailbox")) { hasEmail = true; String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { if (!Validator.checkEmailLocal(alias)) { addAlert(state, rb.getString("java.theemail")); } else { try { String channelReference = mailArchiveChannelReference(site .getId()); // first, clear any alias set to this channel AliasService.removeTargetAliases(channelReference); // check // to // see // whether // the // alias // has // been // used try { String target = AliasService.getTarget(alias); if (target != null) { addAlert(state, rb .getString("java.emailinuse") + " "); } } catch (IdUnusedException ee) { try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException exception) { } catch (IdInvalidException exception) { } catch (PermissionException exception) { } } } catch (PermissionException exception) { } } } } else if (choice.equals("sakai.announcements")) { hasAnnouncement = true; } else if (choice.equals("sakai.schedule")) { hasSchedule = true; } else if (choice.equals("sakai.chat")) { hasChat = true; } else if (choice.equals("sakai.discussion")) { hasDiscussion = true; } else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) { hasMessageCenter = true; } else if (choice.equals("sakai.siteinfo")) { hasSiteInfo = true; } } // see if Home and/or Help in the wSetupPageList (can just check title // here, because we checked patterns before adding to the list) for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { wSetupPage = (WorksiteSetupPage) i.next(); if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) { homeInWSetupPageList = true; } } if (hasHome) { SitePage page = null; // Were the synoptic views of Announcement, Discussioin, Chat // existing before the editing boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false; if (homeInWSetupPageList) { if (!SiteService.isUserSite(site.getId())) { // for non-myworkspace site, if Home is chosen and Home is // in the wSetupPageList, remove synoptic tools WorksiteSetupPage homePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i .hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i .next(); if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) { homePage = comparePage; } } page = site.getPage(homePage.getPageId()); List toolList = page.getTools(); List removeToolList = new Vector(); // get those synoptic tools for (ListIterator iToolList = toolList.listIterator(); iToolList .hasNext();) { ToolConfiguration tool = (ToolConfiguration) iToolList .next(); Tool t = tool.getTool(); if (t!= null) { if (t.getId().equals("sakai.synoptic.announcement")) { hadAnnouncement = true; if (!hasAnnouncement) { removeToolList.add(tool);// if Announcement // tool isn't // selected, remove // the synotic // Announcement } } else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) { hadSchedule = true; if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) { // if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule removeToolList.add(tool); } } else if (t.getId().equals("sakai.synoptic.discussion")) { hadDiscussion = true; if (!hasDiscussion) { removeToolList.add(tool);// if Discussion // tool isn't // selected, remove // the synoptic // Discussion } } else if (t.getId().equals("sakai.synoptic.chat")) { hadChat = true; if (!hasChat) { removeToolList.add(tool);// if Chat tool // isn't selected, // remove the // synoptic Chat } } else if (t.getId().equals("sakai.synoptic.messagecenter")) { hadMessageCenter = true; if (!hasMessageCenter) { removeToolList.add(tool);// if Messages and/or Forums tools // isn't selected, // remove the // synoptic Message Center tool } } } } // remove those synoptic tools for (ListIterator rToolList = removeToolList.listIterator(); rToolList .hasNext();) { page.removeTool((ToolConfiguration) rToolList.next()); } } } else { // if Home is chosen and Home is not in wSetupPageList, add Home // to site and wSetupPageList page = site.addPage(); page.setTitle(rb.getString("java.home")); wSetupHome.pageId = page.getId(); wSetupHome.pageTitle = page.getTitle(); wSetupHome.toolId = HOME_TOOL_ID; wSetupPageList.add(wSetupHome); // Add worksite information tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(SITE_INFORMATION_TOOL); tool.setTool(SITE_INFORMATION_TOOL, reg); tool.setTitle(reg.getTitle()); tool.setLayoutHints("0,0"); } if (!SiteService.isUserSite(site.getId())) { // add synoptical tools to home tool in non-myworkspace site try { if (hasAnnouncement && !hadAnnouncement) { // Add synoptic announcements tool addSynopticTool(page, "sakai.synoptic.announcement", rb .getString("java.recann"), "0,1"); } if (hasDiscussion && !hadDiscussion) { // Add synoptic discussion tool addSynopticTool(page, "sakai.synoptic.discussion", rb .getString("java.recdisc"), "1,1"); } if (hasChat && !hadChat) { // Add synoptic chat tool addSynopticTool(page, "sakai.synoptic.chat", rb .getString("java.recent"), "2,1"); } if (hasSchedule && !hadSchedule) { // Add synoptic schedule tool if not stealth or hidden if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb .getString("java.reccal"), "3,1"); } if (hasMessageCenter && !hadMessageCenter) { // Add synoptic Message Center addSynopticTool(page, "sakai.synoptic.messagecenter", rb .getString("java.recmsg"), "4,1"); } if (hasAnnouncement || hasDiscussion || hasChat || hasSchedule || hasMessageCenter) { page.setLayout(SitePage.LAYOUT_DOUBLE_COL); } else { page.setLayout(SitePage.LAYOUT_SINGLE_COL); } } catch (Exception e) { M_log.warn(this + ".saveFeatures: " + e.getMessage() + " site id = " + site.getId(), e); } } } // add Home // if Home is in wSetupPageList and not chosen, remove Home feature from // wSetupPageList and site if (!hasHome && homeInWSetupPageList) { // remove Home from wSetupPageList WorksiteSetupPage removePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next(); if (comparePage.getToolId().equals(HOME_TOOL_ID)) { removePage = comparePage; } } SitePage siteHome = site.getPage(removePage.getPageId()); site.removePage(siteHome); wSetupPageList.remove(removePage); } // declare flags used in making decisions about whether to add, remove, // or do nothing boolean inChosenList; boolean inWSetupPageList; Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationSet = ToolManager.findTools(categories, null); // first looking for any tool for removal Vector removePageIds = new Vector(); for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page id + tool id for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } inChosenList = false; for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); if (pageToolId.equals(toolId)) { inChosenList = true; } } if (!inChosenList) { removePageIds.add(wSetupPage.getPageId()); } } for (int i = 0; i < removePageIds.size(); i++) { // if the tool exists in the wSetupPageList, remove it from the site String removeId = (String) removePageIds.get(i); SitePage sitePage = site.getPage(removeId); site.removePage(sitePage); // and remove it from wSetupPageList for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); if (!wSetupPage.getPageId().equals(removeId)) { wSetupPage = null; } } if (wSetupPage != null) { wSetupPageList.remove(wSetupPage); } } // then looking for any tool to add for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList) .listIterator(); j.hasNext();) { String toolId = (String) j.next(); // Is the tool in the wSetupPageList? inWSetupPageList = false; for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page Id + toolId for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } if (pageToolId.equals(toolId)) { inWSetupPageList = true; // but for tool of multiple instances, need to change the title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { SitePage pEdit = (SitePage) site .getPage(wSetupPage.pageId); pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId)); List toolList = pEdit.getTools(); for (ListIterator jTool = toolList.listIterator(); jTool .hasNext();) { ToolConfiguration tool = (ToolConfiguration) jTool .next(); String tId = tool.getTool().getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } } } } } if (inWSetupPageList) { // if the tool already in the list, do nothing so to save the // option settings } else { // if in chosen list but not in wSetupPageList, add it to the // site (one tool on a page) Tool toolRegFound = null; for (Iterator i = toolRegistrationSet.iterator(); i.hasNext();) { Tool toolReg = (Tool) i.next(); if (toolId.indexOf(toolReg.getId()) != -1) { toolRegFound = toolReg; } } if (toolRegFound != null) { // we know such a tool, so add it WorksiteSetupPage addPage = new WorksiteSetupPage(); SitePage page = site.addPage(); addPage.pageId = page.getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title page.setTitle((String) multipleToolIdTitleMap.get(toolId)); } else { // other tools with default title page.setTitle(toolRegFound.getTitle()); } page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool(toolRegFound.getId(), toolRegFound); addPage.toolId = toolId; wSetupPageList.add(addPage); // set tool title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } else { tool.setTitle(toolRegFound.getTitle()); } } } } // for // reorder Home and Site Info only if the site has not been customized order before if (!site.isCustomPageOrdered()) { // the steps for moving page within the list int moves = 0; if (hasHome) { SitePage homePage = null; // Order tools - move Home to the top - first find it pageList = site.getPages(); if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); if (rb.getString("java.home").equals(page.getTitle())) { homePage = page; break; } } } if (homePage != null) { moves = pageList.indexOf(homePage); for (int n = 0; n < moves; n++) { homePage.moveUp(); } } } // if Site Info is newly added, more it to the last if (hasSiteInfo) { SitePage siteInfoPage = null; pageList = site.getPages(); String[] toolIds = { "sakai.siteinfo" }; if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); siteInfoPage == null && i.hasNext();) { SitePage page = (SitePage) i.next(); int s = page.getTools(toolIds).size(); if (s > 0) { siteInfoPage = page; break; } } if (siteInfoPage != null) { // move home from it's index to the first position moves = pageList.indexOf(siteInfoPage); for (int n = moves; n < pageList.size(); n++) { siteInfoPage.moveDown(); } } } } } // if there is no email tool chosen if (!hasEmail) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } // commit commitSite(site); // import importToolIntoSite(chosenList, importTools, site); } // saveFeatures /** * Save configuration values for multiple tool instances */ private void saveMultipleToolConfiguration(SessionState state, ToolConfiguration tool, String toolId) { // get the configuration of multiple tool instance Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); // set tool attributes Hashtable<String, String> attributes = multipleToolConfiguration.get(toolId); if (attributes != null) { for(String attribute : attributes.keySet()) { String attributeValue = attributes.get(attribute); // if we have a value if (attributeValue != null) { // if this value is not the same as the tool's registered, set it in the placement if (!attributeValue.equals(tool.getTool().getRegisteredConfig().getProperty(attribute))) { tool.getPlacementConfig().setProperty(attribute, attributeValue); } // otherwise clear it else { tool.getPlacementConfig().remove(attribute); } } // if no value else { tool.getPlacementConfig().remove(attribute); } } } } /** * Is the tool stealthed or hidden * @param toolId * @return */ private boolean notStealthOrHiddenTool(String toolId) { return (ToolManager.getTool(toolId) != null && !ServerConfigurationService .getString( "stealthTools@org.sakaiproject.tool.api.ActiveToolManager") .contains(toolId) && !ServerConfigurationService .getString( "hiddenTools@org.sakaiproject.tool.api.ActiveToolManager") .contains(toolId)); } /** * getFeatures gets features for a new site * */ private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) { List idsSelected = new Vector(); List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); boolean goToToolConfigPage = false; boolean homeSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); // toolId's & titles of // chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals(HOME_TOOL_ID)) { homeSelected = true; } else if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // if user is adding either EmailArchive tool, News tool // or Web Content tool, go to the Customize page for the // tool if (!existTools.contains(toolId)) { goToToolConfigPage = true; multipleToolIdSet.add(toolId); multipleToolIdTitleMap.put(toolId, ToolManager.getTool(toolId).getTitle()); } } else if (toolId.equals("sakai.mailbox") && !existTools.contains(toolId)) { // get the email alias when an Email Archive tool // has been selected goToToolConfigPage = true; String channelReference = mailArchiveChannelReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); List aliases = AliasService.getAliases( channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId()); } } idsSelected.add(toolId); } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean( homeSelected)); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's // in case of import String importString = params.getString("import"); if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); List importSites = new Vector(); if (params.getStrings("importSites") != null) { importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); } if (importSites.size() == 0) { addAlert(state, rb.getString("java.toimport") + " "); } else { Hashtable sites = new Hashtable(); for (int index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); if (!sites.containsKey(s)) { sites.put(s, new Vector()); } } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } else { state.removeAttribute(STATE_IMPORT); } // of // ToolRegistration // toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (state.getAttribute(STATE_IMPORT) != null) { // go to import tool page state.setAttribute(STATE_TEMPLATE_INDEX, "27"); } else if (goToToolConfigPage) { // go to the configuration page for multiple instances of tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to next page state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex); } state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); } } // getFeatures // import tool content into site private void importToolIntoSite(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntities(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSite private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntitiesMigrate(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSiteMigrate public void saveSiteStatus(SessionState state, boolean published) { Site site = getStateSite(state); site.setPublished(published); } // saveSiteStatus public void commitSite(Site site, boolean published) { site.setPublished(published); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } } // commitSite public void commitSite(Site site) { try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } }// commitSite private boolean isValidDomain(String email) { String invalidNonOfficialAccountString = ServerConfigurationService .getString("invalidNonOfficialAccountString", null); if (invalidNonOfficialAccountString != null) { String[] invalidDomains = invalidNonOfficialAccountString.split(","); for (int i = 0; i < invalidDomains.length; i++) { String domain = invalidDomains[i].trim(); if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) { return false; } } } return true; } private void checkAddParticipant(ParameterParser params, SessionState state) { // get the participants to be added int i; Vector pList = new Vector(); HashSet existingUsers = new HashSet(); Site site = null; String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); try { site = SiteService.getSite(siteId); } catch (IdUnusedException e) { addAlert(state, rb.getString("java.specif") + " " + siteId); M_log.warn(this + ".checkAddParticipant: "+ rb.getString("java.specif") + " " + siteId, e); } // accept officialAccounts and/or nonOfficialAccount account names String officialAccounts = ""; String nonOfficialAccounts = ""; // check that there is something with which to work officialAccounts = StringUtil.trimToNull((params .getString("officialAccount"))); nonOfficialAccounts = StringUtil.trimToNull(params .getString("nonOfficialAccount")); state.setAttribute("officialAccountValue", officialAccounts); state.setAttribute("nonOfficialAccountValue", nonOfficialAccounts); // if there is no uniquname or nonOfficialAccount entered if (officialAccounts == null && nonOfficialAccounts == null) { addAlert(state, rb.getString("java.guest")); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); return; } String at = "@"; if (officialAccounts != null) { // adding officialAccounts String[] officialAccountArray = officialAccounts .split("\r\n"); for (i = 0; i < officialAccountArray.length; i++) { String officialAccount = StringUtil.trimToNull(officialAccountArray[i].replaceAll("[\t\r\n]", "")); // if there is some text, try to use it if (officialAccount != null) { // automaticially add nonOfficialAccount account Participant participant = new Participant(); User u = null; try { // look for user based on eid first u = UserDirectoryService.getUserByEid(officialAccount); } catch (UserNotDefinedException e) { M_log.warn(this + ".checkAddParticipant: " + officialAccount + " " + rb.getString("java.username") + " ", e); //Changed user lookup to satisfy BSP-1010 (jholtzman) // continue to look for the user by their email address Collection usersWithEmail = UserDirectoryService.findUsersByEmail(officialAccount); if(usersWithEmail != null) { if(usersWithEmail.size() == 0) { // If the collection is empty, we didn't find any users with this email address M_log.info("Unable to find users with email " + officialAccount); } else if (usersWithEmail.size() == 1) { // We found one user with this email address. Use it. u = (User)usersWithEmail.iterator().next(); } else if (usersWithEmail.size() > 1) { // If we have multiple users with this email address, pick one and log this error condition // TODO Should we not pick a user? Throw an exception? M_log.warn("Found multiple user with email " + officialAccount); u = (User)usersWithEmail.iterator().next(); } } } if (u != null) { M_log.info("found user with eid " + officialAccount); if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be added // again existingUsers.add(officialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = u.getEid(); participant.active = true; pList.add(participant); } } } } } // officialAccounts if (nonOfficialAccounts != null) { String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n"); for (i = 0; i < nonOfficialAccountArray.length; i++) { String nonOfficialAccount = StringUtil.trimToNull(nonOfficialAccountArray[i].replaceAll("[ \t\r\n]", "")); // remove the trailing dots while (nonOfficialAccount != null && nonOfficialAccount.endsWith(".")) { nonOfficialAccount = nonOfficialAccount.substring(0, nonOfficialAccount.length() - 1); } if (nonOfficialAccount != null && nonOfficialAccount.length() > 0) { String[] parts = nonOfficialAccount.split(at); if (nonOfficialAccount.indexOf(at) == -1) { // must be a valid email address addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress")); } else if ((parts.length != 2) || (parts[0].length() == 0)) { // must have both id and address part addAlert(state, nonOfficialAccount + " " + rb.getString("java.notemailid")); } else if (!Validator.checkEmailLocal(parts[0])) { addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + rb.getString("java.theemail")); } else if (nonOfficialAccount != null && !isValidDomain(nonOfficialAccount)) { // wrong string inside nonOfficialAccount id addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + " "); } else { Participant participant = new Participant(); try { // if the nonOfficialAccount user already exists User u = UserDirectoryService .getUserByEid(nonOfficialAccount); if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be // added again existingUsers.add(nonOfficialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = nonOfficialAccount; participant.active = true; pList.add(participant); } } catch (UserNotDefinedException e) { // if the nonOfficialAccount user is not in the system // yet participant.name = nonOfficialAccount; participant.uniqname = nonOfficialAccount; // TODO: // what // would // the // UDS // case // this // name // to? // -ggolden participant.active = true; pList.add(participant); } } } // if } // } // nonOfficialAccounts boolean same_role = true; if (params.getString("same_role") == null) { addAlert(state, rb.getString("java.roletype") + " "); } else { same_role = params.getString("same_role").equals("true") ? true : false; state.setAttribute("form_same_role", new Boolean(same_role)); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } else { if (same_role) { state.setAttribute(STATE_TEMPLATE_INDEX, "19"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "20"); } } // remove duplicate or existing user from participant list pList = removeDuplicateParticipants(pList, state); state.setAttribute(STATE_ADD_PARTICIPANTS, pList); // if the add participant list is empty after above removal, stay in the // current page if (pList.size() == 0) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // add alert for attempting to add existing site user(s) if (!existingUsers.isEmpty()) { int count = 0; String accounts = ""; for (Iterator eIterator = existingUsers.iterator(); eIterator .hasNext();) { if (count == 0) { accounts = (String) eIterator.next(); } else { accounts = accounts + ", " + (String) eIterator.next(); } count++; } addAlert(state, rb.getString("add.existingpart.1") + accounts + rb.getString("add.existingpart.2")); } return; } // checkAddParticipant private Vector removeDuplicateParticipants(List pList, SessionState state) { // check the uniqness of list member Set s = new HashSet(); Set uniqnameSet = new HashSet(); Vector rv = new Vector(); for (int i = 0; i < pList.size(); i++) { Participant p = (Participant) pList.get(i); if (!uniqnameSet.contains(p.getUniqname())) { // no entry for the account yet rv.add(p); uniqnameSet.add(p.getUniqname()); } else { // found duplicates s.add(p.getUniqname()); } } if (!s.isEmpty()) { int count = 0; String accounts = ""; for (Iterator i = s.iterator(); i.hasNext();) { if (count == 0) { accounts = (String) i.next(); } else { accounts = accounts + ", " + (String) i.next(); } count++; } if (count == 1) { addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + "."); } else { addAlert(state, rb.getString("add.duplicatedpart") + accounts + "."); } } return rv; } public void doAdd_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteTitle = getStateSite(state).getTitle(); String nonOfficialAccountLabel = ServerConfigurationService.getString( "nonOfficialAccountLabel", ""); Hashtable selectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); boolean notify = false; if (state.getAttribute("form_selectedNotify") != null) { notify = ((Boolean) state.getAttribute("form_selectedNotify")) .booleanValue(); } boolean same_role = ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); Hashtable eIdRoles = new Hashtable(); List addParticipantList = (List) state .getAttribute(STATE_ADD_PARTICIPANTS); for (int i = 0; i < addParticipantList.size(); i++) { Participant p = (Participant) addParticipantList.get(i); String eId = p.getEid(); // role defaults to same role String role = (String) state.getAttribute("form_selectedRole"); if (!same_role) { // if all added participants have different role role = (String) selectedRoles.get(eId); } if (isOfficialAccount(eId)) { // if this is a officialAccount // update the hashtable eIdRoles.put(eId, role); } else { // if this is an nonOfficialAccount try { UserDirectoryService.getUserByEid(eId); } catch (UserNotDefinedException e) { // if there is no such user yet, add the user try { UserEdit uEdit = UserDirectoryService .addUser(null, eId); // set email address uEdit.setEmail(eId); // set the guest user type uEdit.setType("guest"); // set password to a positive random number Random generator = new Random(System .currentTimeMillis()); Integer num = new Integer(generator .nextInt(Integer.MAX_VALUE)); if (num.intValue() < 0) num = new Integer(num.intValue() * -1); String pw = num.toString(); uEdit.setPassword(pw); // and save UserDirectoryService.commitEdit(uEdit); boolean notifyNewUserEmail = (ServerConfigurationService .getString("notifyNewUserEmail", Boolean.TRUE .toString())) .equalsIgnoreCase(Boolean.TRUE.toString()); if (notifyNewUserEmail) { userNotificationProvider.notifyNewUserEmail(uEdit, pw, siteTitle); } } catch (UserIdInvalidException ee) { addAlert(state, nonOfficialAccountLabel + " id " + eId + " " + rb.getString("java.isinval")); M_log.warn(this + ".doAdd_participant: " + nonOfficialAccountLabel + " id " + eId + " " + rb.getString("java.isinval"), ee); } catch (UserAlreadyDefinedException ee) { addAlert(state, "The " + nonOfficialAccountLabel + " " + eId + " " + rb.getString("java.beenused")); M_log.warn(this + ".doAdd_participant: The " + nonOfficialAccountLabel + " " + eId + " " + rb.getString("java.beenused"), ee); } catch (UserPermissionException ee) { addAlert(state, rb.getString("java.haveadd") + " " + eId); M_log.warn(this + ".doAdd_participant: " + rb.getString("java.haveadd") + " " + eId, ee); } } if (state.getAttribute(STATE_MESSAGE) == null) { eIdRoles.put(eId, role); } } } // batch add and updates the successful added list List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify); // update the not added user list String notAddedOfficialAccounts = NULL_STRING; String notAddedNonOfficialAccounts = NULL_STRING; for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) { String iEId = (String) iEIds.next(); if (!addedParticipantEIds.contains(iEId)) { if (isOfficialAccount(iEId)) { // no email in eid notAddedOfficialAccounts = notAddedOfficialAccounts .concat(iEId + "\n"); } else { // email in eid notAddedNonOfficialAccounts = notAddedNonOfficialAccounts .concat(iEId + "\n"); } } } if (addedParticipantEIds.size() != 0 && (!notAddedOfficialAccounts.equals(NULL_STRING) || !notAddedNonOfficialAccounts.equals(NULL_STRING))) { // at lease one officialAccount account or an nonOfficialAccount // account added, and there are also failures addAlert(state, rb.getString("java.allusers")); } if (notAddedOfficialAccounts.equals(NULL_STRING) && notAddedNonOfficialAccounts.equals(NULL_STRING)) { // all account has been added successfully removeAddParticipantContext(state); } else { state.setAttribute("officialAccountValue", notAddedOfficialAccounts); state.setAttribute("nonOfficialAccountValue", notAddedNonOfficialAccounts); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "22"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } return; } // doAdd_participant /** * whether the eId is considered of official account * @param eId * @return */ private boolean isOfficialAccount(String eId) { return eId.indexOf(EMAIL_CHAR) == -1; } /** * remove related state variable for adding participants * * @param state * SessionState object */ private void removeAddParticipantContext(SessionState state) { // remove related state variables state.removeAttribute("form_selectedRole"); state.removeAttribute("officialAccountValue"); state.removeAttribute("nonOfficialAccountValue"); state.removeAttribute("form_same_role"); state.removeAttribute("form_selectedNotify"); state.removeAttribute(STATE_ADD_PARTICIPANTS); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES); } // removeAddParticipantContext private String getSetupRequestEmailAddress() { String from = ServerConfigurationService.getString("setup.request", null); if (from == null) { from = "postmaster@".concat(ServerConfigurationService .getServerName()); M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from); } return from; } /* * Given a list of user eids, add users to realm If the user account does * not exist yet inside the user directory, assign role to it @return A list * of eids for successfully added users */ private List addUsersRealm(SessionState state, Hashtable eIdRoles, boolean notify) { // return the list of user eids for successfully added user List addedUserEIds = new Vector(); StringBuilder message = new StringBuilder(); if (eIdRoles != null && !eIdRoles.isEmpty()) { // get the current site Site sEdit = getStateSite(state); if (sEdit != null) { // get realm object String realmId = sEdit.getReference(); try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realmId); for (Iterator eIds = eIdRoles.keySet().iterator(); eIds .hasNext();) { String eId = (String) eIds.next(); String role = (String) eIdRoles.get(eId); try { User user = UserDirectoryService.getUserByEid(eId); if (AuthzGroupService.allowUpdate(realmId) || SiteService .allowUpdateSiteMembership(sEdit .getId())) { realmEdit.addMember(user.getId(), role, true, false); addedUserEIds.add(eId); // send notification if (notify) { String emailId = user.getEmail(); String userName = user.getDisplayName(); // send notification email if (this.userNotificationProvider == null) { M_log.warn("notification provider is null!"); } else { userNotificationProvider.notifyAddedParticipant(!isOfficialAccount(eId), user, sEdit.getTitle()); } } } } catch (UserNotDefinedException e) { message.append(eId + " " + rb.getString("java.account") + " \n"); M_log.warn(this + ".addUsersRealm: " + eId + " "+ rb.getString("java.account"), e); } // try } // for try { AuthzGroupService.save(realmEdit); // post event about adding participant EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); } catch (GroupNotDefinedException ee) { message.append(rb.getString("java.realm") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.realm") + realmId, ee); } catch (AuthzPermissionException ee) { message.append(rb.getString("java.permeditsite") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.permeditsite") + realmId, ee); } } catch (GroupNotDefinedException eee) { message.append(rb.getString("java.realm") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.realm") + realmId, eee); } catch (Exception eee) { M_log.warn(this + ".addUsersRealm: " + eee.getMessage() + " realmId=" + realmId, eee); } } } if (message.length() != 0) { addAlert(state, message.toString()); } // if return addedUserEIds; } // addUsersRealm /** * addNewSite is called when the site has enough information to create a new * site * */ private void addNewSite(ParameterParser params, SessionState state) { if (getStateSite(state) != null) { // There is a Site in state already, so use it rather than creating // a new Site return; } // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } String id = StringUtil.trimToNull(siteInfo.getSiteId()); if (id == null) { // get id id = IdManager.createUuid(); siteInfo.site_id = id; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (state.getAttribute(STATE_MESSAGE) == null) { try { Site site = null; // if create based on template, Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { site = SiteService.addSite(id, templateSite); } else { site = SiteService.addSite(id, siteInfo.site_type); } // add current user as the maintainer site.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false); String title = StringUtil.trimToNull(siteInfo.title); String description = siteInfo.description; setAppearance(state, site, siteInfo.iconUrl); site.setDescription(description); if (title != null) { site.setTitle(title); } site.setType(siteInfo.site_type); ResourcePropertiesEdit rp = site.getPropertiesEdit(); site.setShortDescription(siteInfo.short_description); site.setPubView(siteInfo.include); site.setJoinable(siteInfo.joinable); site.setJoinerRole(siteInfo.joinerRole); site.setPublished(siteInfo.published); // site contact information rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name); rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); // commit newly added site in order to enable related realm commitSite(site); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists")); M_log.warn(this + ".addNewSite: " + rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (IdInvalidException e) { addAlert(state, rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid")); M_log.warn(this + ".addNewSite: " + rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (PermissionException e) { addAlert(state, rb.getString("java.permission") + " " + id + "."); M_log.warn(this + ".addNewSite: " + rb.getString("java.permission") + " " + id + ".", e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } } } // addNewSite private void sendTemplateUseNotification(Site site, User currentUser, Site templateSite) { // send an email to track who are using the template String from = getSetupRequestEmailAddress(); // send it to the email archive of the template site // TODO: need a better way to get the email archive address //String domain = from.substring(from.indexOf('@')); String templateEmailArchive = templateSite.getId() + "@" + ServerConfigurationService.getServerName(); String to = templateEmailArchive; String headerTo = templateEmailArchive; String replyTo = templateEmailArchive; String message_subject = templateSite.getId() + ": copied by " + currentUser.getDisplayId (); if (from != null && templateEmailArchive != null) { StringBuffer buf = new StringBuffer(); buf.setLength(0); // email body buf.append("Dear template maintainer,\n\n"); buf.append("Congratulations!\n\n"); buf.append("The following user just created a new site based on your template.\n\n"); buf.append("Template name: " + templateSite.getTitle() + "\n"); buf.append("User : " + currentUser.getDisplayName() + " (" + currentUser.getDisplayId () + ")\n"); buf.append("Date : " + new java.util.Date() + "\n"); buf.append("New site Id : " + site.getId() + "\n"); buf.append("New site name: " + site.getTitle() + "\n\n"); buf.append("Cheers,\n"); buf.append("Alliance Team\n"); String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } } /** * created based on setTermListForContext - Denny * @param context * @param state */ private void setTemplateListForContext(Context context, SessionState state) { Hashtable<String, List<Site>> templateList = new Hashtable<String, List<Site>>(); // find all template sites. String[] siteTemplates = null; if (ServerConfigurationService.getString("site.templates") != null) { siteTemplates = StringUtil.split(ServerConfigurationService.getString("site.templates"), ","); } for (String siteTemplateId:siteTemplates) { try { Site siteTemplate = SiteService.getSite(siteTemplateId); if (siteTemplate != null) { // get the type of template String type = siteTemplate.getType(); if (type != null) { // populate the list according to template site type List<Site> subTemplateList = new Vector<Site>(); if (templateList.containsKey(type)) { subTemplateList = templateList.get(type); } subTemplateList.add(siteTemplate); templateList.put(type, subTemplateList); } } } catch (IdUnusedException e) { M_log.warn(this + ".setTemplateListForContext: cannot find site with id " + siteTemplateId, e); } } context.put("templateList", templateList); } // setTemplateListForContext /** * %%% legacy properties, to be cleaned up * */ private void sitePropertiesIntoState(SessionState state) { try { Site site = getStateSite(state); SiteInfo siteInfo = new SiteInfo(); if (site != null) { // set from site attributes siteInfo.title = site.getTitle(); siteInfo.description = site.getDescription(); siteInfo.iconUrl = site.getIconUrl(); siteInfo.infoUrl = site.getInfoUrl(); siteInfo.joinable = site.isJoinable(); siteInfo.joinerRole = site.getJoinerRole(); siteInfo.published = site.isPublished(); siteInfo.include = site.isPubView(); siteInfo.short_description = site.getShortDescription(); } siteInfo.additional = ""; state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type); state.setAttribute(STATE_SITE_INFO, siteInfo); } catch (Exception e) { M_log.warn(this + ".sitePropertiesIntoState: " + e.getMessage(), e); } } // sitePropertiesIntoState /** * pageMatchesPattern returns true if a SitePage matches a WorkSite Setup * pattern * */ private boolean pageMatchesPattern(SessionState state, SitePage page) { List pageToolList = page.getTools(); // if no tools on the page, return false if (pageToolList == null || pageToolList.size() == 0) { return false; } // for the case where the page has one tool ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList .get(0); // don't compare tool properties, which may be changed using Options List toolList = new Vector(); int count = pageToolList.size(); boolean match = false; // check Worksite Setup Home pattern if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.home"))) { return true; } // Home else if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.help"))) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if tooId isn't sakai.contactSupport, return false if (!(toolConfiguration.getTool().getId()) .equals("sakai.contactSupport")) { return false; } return true; } // Help else if (page.getTitle() != null && page.getTitle().equals("Chat")) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if the tool doesn't match, return false if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) { return false; } // if the channel doesn't match value for main channel, return false String channel = toolConfiguration.getPlacementConfig() .getProperty("channel"); if (channel == null) { return false; } if (!(channel.equals(NULL_STRING))) { return false; } return true; } // Chat else { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); if (pageToolList != null || pageToolList.size() != 0) { // if tool attributes don't match, return false match = false; for (ListIterator i = toolList.listIterator(); i.hasNext();) { MyTool tool = (MyTool) i.next(); if (toolConfiguration.getTitle() != null) { if (toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf( tool.getId()) != -1) { match = true; } } } if (!match) { return false; } } } // Others return true; } // pageMatchesPattern /** * siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list * of pages and tools that match WorkSite Setup configurations into state */ private void siteToolsIntoState(SessionState state) { // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); String wSetupTool = NULL_STRING; List wSetupPageList = new Vector(); Site site = getStateSite(state); List pageList = site.getPages(); // Put up tool lists filtered by category String type = site.getType(); if (type == null) { if (SiteService.isUserSite(site.getId())) { type = "myworkspace"; } else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // for those sites without type, use the tool set for default // site type type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } if (type == null) { M_log.warn(this + ": - unknown STATE_SITE_TYPE"); } else { state.setAttribute(STATE_SITE_TYPE, type); } // set tool registration list setToolRegistrationList(state, type); List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); // for the selected tools boolean check_home = false; Vector idSelected = new Vector(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); // collect the pages consistent with Worksite Setup patterns if (pageMatchesPattern(state, page)) { if (page.getTitle().equals(rb.getString("java.home"))) { wSetupTool = HOME_TOOL_ID; check_home = true; } else { List pageToolList = page.getTools(); wSetupTool = ((ToolConfiguration) pageToolList.get(0)).getTool().getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool))) { String mId = page.getId() + wSetupTool; idSelected.add(mId); multipleToolIdTitleMap.put(mId, page.getTitle()); MyTool newTool = new MyTool(); newTool.title = ToolManager.getTool(wSetupTool).getTitle(); newTool.id = mId; newTool.selected = false; boolean hasThisMultipleTool = false; int j = 0; for (; j < toolRegList.size() && !hasThisMultipleTool; j++) { MyTool t = (MyTool) toolRegList.get(j); if (t.getId().equals(wSetupTool)) { hasThisMultipleTool = true; newTool.description = t.getDescription(); } } if (hasThisMultipleTool) { toolRegList.add(j - 1, newTool); } else { toolRegList.add(newTool); } } else { idSelected.add(wSetupTool); } } WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); wSetupPage.pageId = page.getId(); wSetupPage.pageTitle = page.getTitle(); wSetupPage.toolId = wSetupTool; wSetupPageList.add(wSetupPage); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home)); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList); // of // ToolRegistration // toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home)); state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList); } // siteToolsIntoState /** * reset the state variables used in edit tools mode * * @state The SessionState object */ private void removeEditToolState(SessionState state) { state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); //state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); } private List orderToolIds(SessionState state, String type, List toolIdList) { List rv = new Vector(); if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null && ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)) .booleanValue()) { rv.add(HOME_TOOL_ID); } // look for null site type if (type != null && toolIdList != null) { Set categories = new HashSet(); categories.add(type); Set tools = ToolManager.findTools(categories, null); SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator()); for (; i.hasNext();) { String tool_id = ((Tool) i.next()).getId(); for (ListIterator j = toolIdList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); String rToolId = originalToolId(toolId, tool_id); if (rToolId != null) { rv.add(toolId); } } } } return rv; } // orderToolIds private void setupFormNamesAndConstants(SessionState state) { TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal(); String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear() + ", " + UserDirectoryService.getCurrentUser().getDisplayName() + ". All Rights Reserved. "; state.setAttribute(STATE_MY_COPYRIGHT, mycopyright); state.setAttribute(STATE_SITE_INSTANCE_ID, null); state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString()); SiteInfo siteInfo = new SiteInfo(); Participant participant = new Participant(); participant.name = NULL_STRING; participant.uniqname = NULL_STRING; participant.active = true; state.setAttribute(STATE_SITE_INFO, siteInfo); state.setAttribute("form_participantToAdd", participant); state.setAttribute(FORM_ADDITIONAL, NULL_STRING); // legacy state.setAttribute(FORM_HONORIFIC, "0"); state.setAttribute(FORM_REUSE, "0"); state.setAttribute(FORM_RELATED_CLASS, "0"); state.setAttribute(FORM_RELATED_PROJECT, "0"); state.setAttribute(FORM_INSTITUTION, "0"); // sundry form variables state.setAttribute(FORM_PHONE, ""); state.setAttribute(FORM_EMAIL, ""); state.setAttribute(FORM_SUBJECT, ""); state.setAttribute(FORM_DESCRIPTION, ""); state.setAttribute(FORM_TITLE, ""); state.setAttribute(FORM_NAME, ""); state.setAttribute(FORM_SHORT_DESCRIPTION, ""); } // setupFormNamesAndConstants /** * setupSkins * */ private void setupIcons(SessionState state) { List icons = new Vector(); String[] iconNames = null; String[] iconUrls = null; String[] iconSkins = null; // get icon information if (ServerConfigurationService.getStrings("iconNames") != null) { iconNames = ServerConfigurationService.getStrings("iconNames"); } if (ServerConfigurationService.getStrings("iconUrls") != null) { iconUrls = ServerConfigurationService.getStrings("iconUrls"); } if (ServerConfigurationService.getStrings("iconSkins") != null) { iconSkins = ServerConfigurationService.getStrings("iconSkins"); } if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length)) { for (int i = 0; i < iconNames.length; i++) { MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]), StringUtil.trimToNull((String) iconUrls[i]), StringUtil .trimToNull((String) iconSkins[i])); icons.add(s); } } state.setAttribute(STATE_ICONS, icons); } private void setAppearance(SessionState state, Site edit, String iconUrl) { // set the icon edit.setIconUrl(iconUrl); if (iconUrl == null) { // this is the default case - no icon, no (default) skin edit.setSkin(null); return; } // if this icon is in the config appearance list, find a skin to set List icons = (List) state.getAttribute(STATE_ICONS); for (Iterator i = icons.iterator(); i.hasNext();) { Object icon = (Object) i.next(); if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) { edit.setSkin(((MyIcon) icon).getSkin()); return; } } } /** * A dispatch funtion when selecting course features */ public void doAdd_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // editing existing site or creating a new one? Site site = getStateSite(state); // dispatch if (option.startsWith("add_")) { // this could be format of originalToolId plus number of multiplication String addToolId = option.substring("add_".length(), option.length()); // find the original tool id String originToolId = findOriginalToolId(state, addToolId); if (originToolId != null) { Tool tool = ToolManager.getTool(originToolId); if (tool != null) { insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId))); updateSelectedToolList(state, params, false); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } } } else if (option.equalsIgnoreCase("import")) { // import or not updateSelectedToolList(state, params, false); String importSites = params.getString("import"); if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); } } else { state.removeAttribute(STATE_IMPORT); } } else if (option.equalsIgnoreCase("continue")) { // continue updateSelectedToolList(state, params, false); doContinue(data); } else if (option.equalsIgnoreCase("back")) { // back doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (site == null) { // cancel doCancel_create(data); } else { // cancel editing doCancel(data); } } } // doAdd_features /** * update the selected tool list * * @param params * The ParameterParser object * @param verifyData * Need to verify input data or not */ private void updateSelectedToolList(SessionState state, ParameterParser params, boolean verifyData) { List selectedTools = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); Vector<String> idSelected = (Vector<String>) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); boolean has_home = false; String emailId = null; for (int i = 0; i < selectedTools.size(); i++) { String id = (String) selectedTools.get(i); if (id.equalsIgnoreCase(HOME_TOOL_ID)) { has_home = true; } else if (id.equalsIgnoreCase("sakai.mailbox")) { // if Email archive tool is selected, check the email alias emailId = StringUtil.trimToNull(params.getString("emailId")); if (verifyData) { if (emailId == null) { addAlert(state, rb.getString("java.emailarchive") + " "); } else { if (!Validator.checkEmailLocal(emailId)) { addAlert(state, rb.getString("java.theemail")); } else { // check to see whether the alias has been used by // other sites try { String target = AliasService.getTarget(emailId); if (target != null) { if (state .getAttribute(STATE_SITE_INSTANCE_ID) != null) { String siteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); String channelReference = mailArchiveChannelReference(siteId); if (!target.equals(channelReference)) { // the email alias is not used by // current site addAlert(state, rb.getString("java.emailinuse") + " "); } } else { addAlert(state, rb.getString("java.emailinuse") + " "); } } } catch (IdUnusedException ee) { } } } } } else if (isMultipleInstancesAllowed(findOriginalToolId(state, id)) && (idSelected != null && !idSelected.contains(id) || idSelected == null)) { // newly added mutliple instances String title = StringUtil.trimToNull(params.getString("title_" + id)); if (title != null) { // save the titles entered multipleToolIdTitleMap.put(id, title); } // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(id); if (attributes == null) { // if missing, get the default setting for original id attributes = multipleToolConfiguration.get(findOriginalToolId(state, id)); } if (attributes != null) { for(Enumeration<String> e = attributes.keys(); e.hasMoreElements();) { String attribute = e.nextElement(); String attributeInput = StringUtil.trimToNull(params.getString(attribute + "_" + id)); if (attributeInput != null) { // save the attribute input attributes.put(attribute, attributeInput); } } multipleToolConfiguration.put(id, attributes); } } } // update the state objects state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home)); state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId); } // updateSelectedToolList /** * find the tool in the tool list and insert another tool instance to the list * @param state * @param toolId * @param defaultTitle * @param defaultDescription * @param insertTimes */ private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) { // the list of available tools List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // get the attributes of multiple tool instances Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); int toolListedTimes = 0; int index = 0; int insertIndex = 0; while (index < toolList.size()) { MyTool tListed = (MyTool) toolList.get(index); if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) { toolListedTimes++; } if (toolListedTimes > 0 && insertIndex == 0) { // update the insert index insertIndex = index; } index++; } List toolSelected = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // insert multiple tools for (int i = 0; i < insertTimes; i++) { toolSelected.add(toolId + toolListedTimes); // We need to insert a specific tool entry only if all the specific // tool entries have been selected String newToolId = toolId + toolListedTimes; MyTool newTool = new MyTool(); newTool.title = defaultTitle; newTool.id = newToolId; newTool.description = defaultDescription; toolList.add(insertIndex, newTool); toolListedTimes++; // add title multipleToolIdTitleMap.put(newTool.id, defaultTitle); // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(newToolId); if (attributes == null) { // if missing, get the default setting for original id attributes = new Hashtable<String, String>(); Hashtable<String, String> oAttributes = multipleToolConfiguration.get(findOriginalToolId(state, newToolId)); // add the entry for the newly added tool if (attributes != null) { attributes = (Hashtable<String, String>) oAttributes.clone(); multipleToolConfiguration.put(newToolId, attributes); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected); } // insertTool /** * * set selected participant role Hashtable */ private void setSelectedParticipantRoles(SessionState state) { List selectedUserIds = (List) state .getAttribute(STATE_SELECTED_USER_LIST); List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); List selectedParticipantList = new Vector(); Hashtable selectedParticipantRoles = new Hashtable(); if (!selectedUserIds.isEmpty() && participantList != null) { for (int i = 0; i < participantList.size(); i++) { String id = ""; Object o = (Object) participantList.get(i); if (o.getClass().equals(Participant.class)) { // get participant roles id = ((Participant) o).getUniqname(); selectedParticipantRoles.put(id, ((Participant) o) .getRole()); } if (selectedUserIds.contains(id)) { selectedParticipantList.add(participantList.get(i)); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles); state .setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList); } // setSelectedParticipantRol3es public class MyIcon { protected String m_name = null; protected String m_url = null; protected String m_skin = null; public MyIcon(String name, String url, String skin) { m_name = name; m_url = url; m_skin = skin; } public String getName() { return m_name; } public String getUrl() { return m_url; } public String getSkin() { return m_skin; } } // a utility class for working with ToolConfigurations and ToolRegistrations // %%% convert featureList from IdAndText to Tool so getFeatures item.id = // chosen-feature.id is a direct mapping of data public class MyTool { public String id = NULL_STRING; public String title = NULL_STRING; public String description = NULL_STRING; public boolean selected = false; public String getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description; } public boolean getSelected() { return selected; } } /* * WorksiteSetupPage is a utility class for working with site pages * configured by Worksite Setup * */ public class WorksiteSetupPage { public String pageId = NULL_STRING; public String pageTitle = NULL_STRING; public String toolId = NULL_STRING; public String getPageId() { return pageId; } public String getPageTitle() { return pageTitle; } public String getToolId() { return toolId; } } // WorksiteSetupPage public class SiteInfo { public String site_id = NULL_STRING; // getId of Resource public String external_id = NULL_STRING; // if matches site_id // connects site with U-M // course information public String site_type = ""; public String iconUrl = NULL_STRING; public String infoUrl = NULL_STRING; public boolean joinable = false; public String joinerRole = NULL_STRING; public String title = NULL_STRING; // the short name of the site public String short_description = NULL_STRING; // the short (20 char) // description of the // site public String description = NULL_STRING; // the longer description of // the site public String additional = NULL_STRING; // additional information on // crosslists, etc. public boolean published = false; public boolean include = true; // include the site in the Sites index; // default is true. public String site_contact_name = NULL_STRING; // site contact name public String site_contact_email = NULL_STRING; // site contact email public String getSiteId() { return site_id; } public String getSiteType() { return site_type; } public String getTitle() { return title; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } public String getInfoUrll() { return infoUrl; } public boolean getJoinable() { return joinable; } public String getJoinerRole() { return joinerRole; } public String getAdditional() { return additional; } public boolean getPublished() { return published; } public boolean getInclude() { return include; } public String getSiteContactName() { return site_contact_name; } public String getSiteContactEmail() { return site_contact_email; } } // SiteInfo // dissertation tool related /** * doFinish_grad_tools is called when creation of a Grad Tools site is * confirmed */ public void doFinish_grad_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // set up for the coming template state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); // add the pre-configured Grad Tools tools to a new site addGradToolsFeatures(state); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); }// doFinish_grad_tools /** * addGradToolsFeatures adds features to a new Grad Tools student site * */ private void addGradToolsFeatures(SessionState state) { Site edit = null; Site template = null; // get a unique id String id = IdManager.createUuid(); // get the Grad Tools student site template try { template = SiteService.getSite(SITE_GTS_TEMPLATE); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + e.getMessage() + SITE_GTS_TEMPLATE, e); } if (template != null) { // create a new site based on the template try { edit = SiteService.addSite(id, template); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " add/edit site id=" + id, e); } // set the tab, etc. if (edit != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); edit.setShortDescription(siteInfo.short_description); edit.setTitle(siteInfo.title); edit.setPublished(true); edit.setPubView(false); edit.setType(SITE_TYPE_GRADTOOLS_STUDENT); // ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); try { SiteService.save(edit); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " commitEdit site id=" + id, e); } // now that the site and realm exist, we can set the email alias // set the GradToolsStudent site alias as: // gradtools-uniqname@servername String alias = "gradtools-" + SessionManager.getCurrentSessionUserId(); String channelReference = mailArchiveChannelReference(id); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { M_log.warn(this + ".addGradToolsFeatures:" + SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ", ee); } } } } // addGradToolsFeatures /** * handle with add site options * */ public void doAdd_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("finish")) { doFinish(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } } // doAdd_site_option /** * handle with duplicate site options * */ public void doDuplicate_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("duplicate")) { doContinue(data); } else if (option.equals("cancel")) { doCancel(data); } else if (option.equals("finish")) { doContinue(data); } } // doDuplicate_site_option /** * Special check against the Dissertation service, which might not be * here... * * @return */ protected boolean isGradToolsCandidate(String userId) { // DissertationService.isCandidate(userId) - but the hard way Object service = ComponentManager .get("org.sakaiproject.api.app.dissertation.DissertationService"); if (service == null) return false; // the method signature Class[] signature = new Class[1]; signature[0] = String.class; // the method name String methodName = "isCandidate"; // find a method of this class with this name and signature try { Method method = service.getClass().getMethod(methodName, signature); // the parameters Object[] args = new Object[1]; args[0] = userId; // make the call Boolean rv = (Boolean) method.invoke(service, args); return rv.booleanValue(); } catch (Throwable t) { } return false; } /** * User has a Grad Tools student site * * @return */ protected boolean hasGradToolsStudentSite(String userId) { boolean has = false; int n = 0; try { n = SiteService.countSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, SITE_TYPE_GRADTOOLS_STUDENT, null, null); if (n > 0) has = true; } catch (Exception e) { M_log.warn(this + ".addGradToolsStudentSite:" + e.getMessage(), e); } return has; }// hasGradToolsStudentSite /** * Get the mail archive channel reference for the main container placement * for this site. * * @param siteId * The site id. * @return The mail archive channel reference for this site. */ protected String mailArchiveChannelReference(String siteId) { Object m = ComponentManager .get("org.sakaiproject.mailarchive.api.MailArchiveService"); if (m != null) { return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER; } else { return ""; } } /** * Transfer a copy of all entites from another context for any entity * producer that claims this tool id. * * @param toolId * The tool id. * @param fromContext * The context to import from. * @param toContext * The context to import into. */ protected void transferCopyEntities(String toolId, String fromContext, String toContext) { // TODO: used to offer to resources first - why? still needed? -ggolden // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector()); } } catch (Throwable t) { M_log.warn(this + ".transferCopyEntities: Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } protected void transferCopyEntitiesMigrate(String toolId, String fromContext, String toContext) { for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector(), true); } } catch (Throwable t) { M_log.warn( "Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } /** * @return Get a list of all tools that support the import (transfer copy) * option */ protected Set importTools() { HashSet rv = new HashSet(); // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { EntityTransferrer et = (EntityTransferrer) ep; String[] tools = et.myToolIds(); if (tools != null) { for (int t = 0; t < tools.length; t++) { rv.add(tools[t]); } } } } return rv; } /** * @param state * @return Get a list of all tools that should be included as options for * import */ protected List getToolsAvailableForImport(SessionState state, List<String> toolIdList) { // The Web Content and News tools do not follow the standard rules for // import // Even if the current site does not contain the tool, News and WC will // be // an option if the imported site contains it boolean displayWebContent = false; boolean displayNews = false; Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)) .keySet(); Iterator sitesIter = importSites.iterator(); while (sitesIter.hasNext()) { Site site = (Site) sitesIter.next(); if (site.getToolForCommonId("sakai.iframe") != null) displayWebContent = true; if (site.getToolForCommonId("sakai.news") != null) displayNews = true; } if (displayWebContent && !toolIdList.contains("sakai.iframe")) toolIdList.add("sakai.iframe"); if (displayNews && !toolIdList.contains("sakai.news")) toolIdList.add("sakai.news"); return toolIdList; } // getToolsAvailableForImport private void setTermListForContext(Context context, SessionState state, boolean upcomingOnly) { List terms; if (upcomingOnly) { terms = cms != null?cms.getCurrentAcademicSessions():null; } else { // get all terms = cms != null?cms.getAcademicSessions():null; } if (terms != null && terms.size() > 0) { context.put("termList", terms); } } // setTermListForContext private void setSelectedTermForContext(Context context, SessionState state, String stateAttribute) { if (state.getAttribute(stateAttribute) != null) { context.put("selectedTerm", state.getAttribute(stateAttribute)); } } // setSelectedTermForContext /** * rewrote for 2.4 * * @param userId * @param academicSessionEid * @param courseOfferingHash * @param sectionHash */ private void prepareCourseAndSectionMap(String userId, String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash) { // looking for list of courseOffering and sections that should be // included in // the selection list. The course offering must be offered // 1. in the specific academic Session // 2. that the specified user has right to attach its section to a // course site // map = (section.eid, sakai rolename) if (groupProvider == null) { M_log.warn("Group provider not found"); return; } Map map = groupProvider.getGroupRolesForUser(userId); if (map == null) return; Set keys = map.keySet(); Set roleSet = getRolesAllowedToAttachSection(); for (Iterator i = keys.iterator(); i.hasNext();) { String sectionEid = (String) i.next(); String role = (String) map.get(sectionEid); if (includeRole(role, roleSet)) { Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } // now consider those user with affiliated sections List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid); if (affiliatedSectionEids != null) { for (int k = 0; k < affiliatedSectionEids.size(); k++) { String sectionEid = (String) affiliatedSectionEids.get(k); Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } } // prepareCourseAndSectionMap private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) { try { section = cms.getSection(sectionEid); } catch (IdNotFoundException e) { M_log.warn(this + ".getCourseOfferingAndSectionMap:" + " cannot find section id=" + sectionEid, e); } if (section != null) { String courseOfferingEid = section.getCourseOfferingEid(); CourseOffering courseOffering = cms .getCourseOffering(courseOfferingEid); String sessionEid = courseOffering.getAcademicSession() .getEid(); if (academicSessionEid.equals(sessionEid)) { // a long way to the conclusion that yes, this course // offering // should be included in the selected list. Sigh... // -daisyf ArrayList sectionList = (ArrayList) sectionHash .get(courseOffering.getEid()); if (sectionList == null) { sectionList = new ArrayList(); } sectionList.add(new SectionObject(section)); sectionHash.put(courseOffering.getEid(), sectionList); courseOfferingHash.put(courseOffering.getEid(), courseOffering); } } } /** * for 2.4 * * @param role * @return */ private boolean includeRole(String role, Set roleSet) { boolean includeRole = false; for (Iterator i = roleSet.iterator(); i.hasNext();) { String r = (String) i.next(); if (r.equals(role)) { includeRole = true; break; } } return includeRole; } // includeRole protected Set getRolesAllowedToAttachSection() { // Use !site.template.[site_type] String azgId = "!site.template.course"; AuthzGroup azgTemplate; try { azgTemplate = AuthzGroupService.getAuthzGroup(azgId); } catch (GroupNotDefinedException e) { M_log.warn(this + ".getRolesAllowedToAttachSection: Could not find authz group " + azgId, e); return new HashSet(); } Set roles = azgTemplate.getRolesIsAllowed("site.upd"); roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd")); return roles; } // getRolesAllowedToAttachSection /** * Here, we will preapre two HashMap: 1. courseOfferingHash stores * courseOfferingId and CourseOffering 2. sectionHash stores * courseOfferingId and a list of its Section We sorted the CourseOffering * by its eid & title and went through them one at a time to construct the * CourseObject that is used for the displayed in velocity. Each * CourseObject will contains a list of CourseOfferingObject(again used for * vm display). Usually, a CourseObject would only contain one * CourseOfferingObject. A CourseObject containing multiple * CourseOfferingObject implies that this is a cross-listing situation. * * @param userId * @param academicSessionEid * @return */ private List prepareCourseAndSectionListing(String userId, String academicSessionEid, SessionState state) { // courseOfferingHash = (courseOfferingEid, vourseOffering) // sectionHash = (courseOfferingEid, list of sections) HashMap courseOfferingHash = new HashMap(); HashMap sectionHash = new HashMap(); prepareCourseAndSectionMap(userId, academicSessionEid, courseOfferingHash, sectionHash); // courseOfferingHash & sectionHash should now be filled with stuffs // put section list in state for later use state.setAttribute(STATE_PROVIDER_SECTION_LIST, getSectionList(sectionHash)); ArrayList offeringList = new ArrayList(); Set keys = courseOfferingHash.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { CourseOffering o = (CourseOffering) courseOfferingHash .get((String) i.next()); offeringList.add(o); } Collection offeringListSorted = sortOffering(offeringList); ArrayList resultedList = new ArrayList(); // use this to keep track of courseOffering that we have dealt with // already // this is important 'cos cross-listed offering is dealt with together // with its // equivalents ArrayList dealtWith = new ArrayList(); for (Iterator j = offeringListSorted.iterator(); j.hasNext();) { CourseOffering o = (CourseOffering) j.next(); if (!dealtWith.contains(o.getEid())) { // 1. construct list of CourseOfferingObject for CourseObject ArrayList l = new ArrayList(); CourseOfferingObject coo = new CourseOfferingObject(o, (ArrayList) sectionHash.get(o.getEid())); l.add(coo); // 2. check if course offering is cross-listed Set set = cms.getEquivalentCourseOfferings(o.getEid()); if (set != null) { for (Iterator k = set.iterator(); k.hasNext();) { CourseOffering eo = (CourseOffering) k.next(); if (courseOfferingHash.containsKey(eo.getEid())) { // => cross-listed, then list them together CourseOfferingObject coo_equivalent = new CourseOfferingObject( eo, (ArrayList) sectionHash.get(eo.getEid())); l.add(coo_equivalent); dealtWith.add(eo.getEid()); } } } CourseObject co = new CourseObject(o, l); dealtWith.add(o.getEid()); resultedList.add(co); } } return resultedList; } // prepareCourseAndSectionListing /** * Sort CourseOffering by order of eid, title uisng velocity SortTool * * @param offeringList * @return */ private Collection sortOffering(ArrayList offeringList) { return sortCmObject(offeringList); /* * List propsList = new ArrayList(); propsList.add("eid"); * propsList.add("title"); SortTool sort = new SortTool(); return * sort.sort(offeringList, propsList); */ } // sortOffering /** * sort any Cm object such as CourseOffering, CourseOfferingObject, * SectionObject provided object has getter & setter for eid & title * * @param list * @return */ private Collection sortCmObject(List list) { if (list != null) { List propsList = new ArrayList(); propsList.add("eid"); propsList.add("title"); SortTool sort = new SortTool(); return sort.sort(list, propsList); } else { return list; } } // sortCmObject /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class SectionObject { public Section section; public String eid; public String title; public String category; public String categoryDescription; public boolean isLecture; public boolean attached; public String authorizer; public SectionObject(Section section) { this.section = section; this.eid = section.getEid(); this.title = section.getTitle(); this.category = section.getCategory(); this.categoryDescription = cms .getSectionCategoryDescription(section.getCategory()); if ("01.lct".equals(section.getCategory())) { this.isLecture = true; } else { this.isLecture = false; } Set set = authzGroupService.getAuthzGroupIds(section.getEid()); if (set != null && !set.isEmpty()) { this.attached = true; } else { this.attached = false; } } public Section getSection() { return section; } public String getEid() { return eid; } public String getTitle() { return title; } public String getCategory() { return category; } public String getCategoryDescription() { return categoryDescription; } public boolean getIsLecture() { return isLecture; } public boolean getAttached() { return attached; } public String getAuthorizer() { return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } } // SectionObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseObject { public String eid; public String title; public List courseOfferingObjects; public CourseObject(CourseOffering offering, List courseOfferingObjects) { this.eid = offering.getEid(); this.title = offering.getTitle(); this.courseOfferingObjects = courseOfferingObjects; } public String getEid() { return eid; } public String getTitle() { return title; } public List getCourseOfferingObjects() { return courseOfferingObjects; } } // CourseObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseOfferingObject { public String eid; public String title; public List sections; public CourseOfferingObject(CourseOffering offering, List unsortedSections) { List propsList = new ArrayList(); propsList.add("category"); propsList.add("eid"); SortTool sort = new SortTool(); this.sections = new ArrayList(); if (unsortedSections != null) { this.sections = (List) sort.sort(unsortedSections, propsList); } this.eid = offering.getEid(); this.title = offering.getTitle(); } public String getEid() { return eid; } public String getTitle() { return title; } public List getSections() { return sections; } } // CourseOfferingObject constructor /** * get campus user directory for dispaly in chef_newSiteCourse.vm * * @return */ private String getCampusDirectory() { return ServerConfigurationService.getString( "site-manage.campusUserDirectory", null); } // getCampusDirectory private void removeAnyFlagedSection(SessionState state, ParameterParser params) { List all = new ArrayList(); List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerCourseList != null && providerCourseList.size() > 0) { all.addAll(providerCourseList); } List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); if (manualCourseList != null && manualCourseList.size() > 0) { all.addAll(manualCourseList); } for (int i = 0; i < all.size(); i++) { String eid = (String) all.get(i); String field = "removeSection" + eid; String toRemove = params.getString(field); if ("true".equals(toRemove)) { // eid is in either providerCourseList or manualCourseList // either way, just remove it if (providerCourseList != null) providerCourseList.remove(eid); if (manualCourseList != null) manualCourseList.remove(eid); } } List<SectionObject> requestedCMSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedCMSections != null) { for (int i = 0; i < requestedCMSections.size(); i++) { SectionObject so = (SectionObject) requestedCMSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { requestedCMSections.remove(so); } } if (requestedCMSections.size() == 0) state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); } List<SectionObject> authorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSections != null) { for (int i = 0; i < authorizerSections.size(); i++) { SectionObject so = (SectionObject) authorizerSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { authorizerSections.remove(so); } } if (authorizerSections.size() == 0) state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); } // if list is empty, set to null. This is important 'cos null is // the indication that the list is empty in the code. See case 2 on line // 1081 if (manualCourseList != null && manualCourseList.size() == 0) manualCourseList = null; if (providerCourseList != null && providerCourseList.size() == 0) providerCourseList = null; } private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state, ParameterParser params, List providerChosenList) { if (state.getAttribute(STATE_MESSAGE) == null) { siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // site title is the title of the 1st section selected - // daisyf's note if (providerChosenList != null && providerChosenList.size() >= 1) { String title = prepareTitle((List) state .getAttribute(STATE_PROVIDER_SECTION_LIST), providerChosenList); siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (params.getString("manualAdds") != null && ("true").equals(params.getString("manualAdds"))) { // if creating a new site state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); } else if (params.getString("findCourse") != null && ("true").equals(params.getString("findCourse"))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); prepFindPage(state); } else { // no manual add state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); if (getStateSite(state) != null) { // if revising a site, go to the confirmation // page of adding classes //state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } else { // if creating a site, go the the site // information entry page state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } } } } /** * By default, courseManagement is implemented * * @return */ private boolean courseManagementIsImplemented() { boolean returnValue = true; String isImplemented = ServerConfigurationService.getString( "site-manage.courseManagementSystemImplemented", "true"); if (("false").equals(isImplemented)) returnValue = false; return returnValue; } private List getCMSections(String offeringEid) { if (offeringEid == null || offeringEid.trim().length() == 0) return null; if (cms != null) { Set sections = cms.getSections(offeringEid); Collection c = sortCmObject(new ArrayList(sections)); return (List) c; } return new ArrayList(0); } private List getCMCourseOfferings(String subjectEid, String termID) { if (subjectEid == null || subjectEid.trim().length() == 0 || termID == null || termID.trim().length() == 0) return null; if (cms != null) { Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// , // termID); ArrayList returnList = new ArrayList(); Iterator coIt = offerings.iterator(); while (coIt.hasNext()) { CourseOffering co = (CourseOffering) coIt.next(); AcademicSession as = co.getAcademicSession(); if (as != null && as.getEid().equals(termID)) returnList.add(co); } Collection c = sortCmObject(returnList); return (List) c; } return new ArrayList(0); } private List<String> getCMLevelLabels() { List<String> rv = new Vector<String>(); Set courseSets = cms.getCourseSets(); String currentLevel = ""; rv = addCategories(rv, courseSets); // course and section exist in the CourseManagementService rv.add(rb.getString("cm.level.course")); rv.add(rb.getString("cm.level.section")); return rv; } /** * a recursive function to add courseset categories * @param rv * @param courseSets */ private List<String> addCategories(List<String> rv, Set courseSets) { if (courseSets != null) { for (Iterator i = courseSets.iterator(); i.hasNext();) { // get the CourseSet object level CourseSet cs = (CourseSet) i.next(); String level = cs.getCategory(); if (!rv.contains(level)) { rv.add(level); } try { // recursively add child categories rv = addCategories(rv, cms.getChildCourseSets(cs.getEid())); } catch (IdNotFoundException e) { // current CourseSet not found } } } return rv; } private void prepFindPage(SessionState state) { final List cmLevels = getCMLevelLabels(), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); int lvlSz = 0; if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) { // TODO: no cm levels configured, redirect to manual add return; } if (selections != null && selections.size() == lvlSz) { Section sect = cms.getSection((String) selections.get(selections .size() - 1)); SectionObject so = new SectionObject(sect); state.setAttribute(STATE_CM_SELECTED_SECTION, so); } else state.removeAttribute(STATE_CM_SELECTED_SECTION); state.setAttribute(STATE_CM_LEVELS, cmLevels); state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); // check the configuration setting for choosing next screen Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue()) { // go to the course/section selection page state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { // skip the course/section selection page, go directly into the manually create course page state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } private void addRequestedSection(SessionState state) { SectionObject so = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); String uniqueName = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (so == null) return; so.setAuthorizer(uniqueName); if (getStateSite(state) == null) { // creating new site List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedSections == null) { requestedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!requestedSections.contains(so)) requestedSections.add(so); // if the title has not yet been set and there is just // one section, set the title to that section's EID if (requestedSections.size() == 1) { SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo == null) { siteInfo = new SiteInfo(); } if (siteInfo.title == null || siteInfo.title.trim().length() == 0) { siteInfo.title = so.getEid(); } state.setAttribute(STATE_SITE_INFO, siteInfo); } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } else { // editing site state.setAttribute(STATE_CM_SELECTED_SECTION, so); List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmSelectedSections == null) { cmSelectedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!cmSelectedSections.contains(so)) cmSelectedSections.add(so); state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); } public void doFind_course(RunData data) { final SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); final ParameterParser params = data.getParameters(); final String option = params.get("option"); if (option != null) { if ("continue".equals(option)) { String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { try { UserDirectoryService.getUserByEid(uniqname); addRequestedSection(state); } catch (UserNotDefinedException e) { addAlert(state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doFind_course:" + rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2"), e); } } } else { addRequestedSection(state); } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } doContinue(data); return; } else if ("back".equals(option)) { doBack(data); return; } else if ("cancel".equals(option)) { if (getStateSite(state) == null) { doCancel_create(data);// cancel from new site creation } else { doCancel(data);// cancel from site info editing } return; } else if (option.equals("add")) { addRequestedSection(state); return; } else if (option.equals("manual")) { // TODO: send to case 37 state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); return; } else if (option.equals("remove")) removeAnyFlagedSection(state, params); } final List selections = new ArrayList(3); int cmLevel = getCMLevelLabels().size(); String deptChanged = params.get("deptChanged"); if ("true".equals(deptChanged)) { // when dept changes, remove selection on courseOffering and // courseSection cmLevel = 1; } for (int i = 0; i < cmLevel; i++) { String val = params.get("idField_" + i); if (val == null || val.trim().length() < 1) { break; } selections.add(val); } state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); prepFindPage(state); } /** * return the title of the 1st section in the chosen list that has an * enrollment set. No discrimination on section category * * @param sectionList * @param chosenList * @return */ private String prepareTitle(List sectionList, List chosenList) { String title = null; HashMap map = new HashMap(); for (Iterator i = sectionList.iterator(); i.hasNext();) { SectionObject o = (SectionObject) i.next(); map.put(o.getEid(), o.getSection()); } for (int j = 0; j < chosenList.size(); j++) { String eid = (String) chosenList.get(j); Section s = (Section) map.get(eid); // we will always has a title regardless but we prefer it to be the // 1st section on the chosen list that has an enrollment set if (j == 0) { title = s.getTitle(); } if (s.getEnrollmentSet() != null) { title = s.getTitle(); break; } } return title; } // prepareTitle /** * return an ArrayList of SectionObject * * @param sectionHash * contains an ArrayList collection of SectionObject * @return */ private ArrayList getSectionList(HashMap sectionHash) { ArrayList list = new ArrayList(); // values is an ArrayList of section Collection c = sectionHash.values(); for (Iterator i = c.iterator(); i.hasNext();) { ArrayList l = (ArrayList) i.next(); list.addAll(l); } return list; } private String getAuthorizers(SessionState state) { String authorizers = ""; ArrayList list = (ArrayList) state .getAttribute(STATE_CM_AUTHORIZER_LIST); if (list != null) { for (int i = 0; i < list.size(); i++) { if (i == 0) { authorizers = (String) list.get(i); } else { authorizers = authorizers + ", " + list.get(i); } } } return authorizers; } private List prepareSectionObject(List sectionList, String userId) { ArrayList list = new ArrayList(); if (sectionList != null) { for (int i = 0; i < sectionList.size(); i++) { String sectionEid = (String) sectionList.get(i); Section s = cms.getSection(sectionEid); SectionObject so = new SectionObject(s); so.setAuthorizer(userId); list.add(so); } } return list; } /** * change collection object to list object * @param c * @return */ private List collectionToList(Collection c) { List rv = new Vector(); if (c!=null) { for (Iterator i = c.iterator(); i.hasNext();) { rv.add(i.next()); } } return rv; } protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { ToolSession toolSession = SessionManager.getCurrentToolSession(); SessionState state = getState(req); if (SITE_MODE_HELPER_DONE.equals(state.getAttribute(STATE_SITE_MODE))) { String url = (String) SessionManager.getCurrentToolSession().getAttribute(Tool.HELPER_DONE_URL); SessionManager.getCurrentToolSession().removeAttribute(Tool.HELPER_DONE_URL); // TODO: Implement cleanup. cleanState(state); // Helper cleanup. cleanStateHelper(state); if (M_log.isDebugEnabled()) { M_log.debug("Sending redirect to: "+ url); } try { res.sendRedirect(url); } catch (IOException e) { M_log.warn("Problem sending redirect to: "+ url, e); } return; } else { super.toolModeDispatch(methodBase, methodExt, req, res); } } private void cleanStateHelper(SessionState state) { state.removeAttribute(STATE_SITE_MODE); state.removeAttribute(STATE_TEMPLATE_INDEX); state.removeAttribute(STATE_INITIALIZED); } }
site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.site.tool; import java.io.IOException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.tools.generic.SortTool; import org.sakaiproject.alias.api.Alias; import org.sakaiproject.alias.cover.AliasService; import org.sakaiproject.archive.api.ImportMetadata; import org.sakaiproject.archive.cover.ArchiveService; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.AuthzPermissionException; import org.sakaiproject.authz.api.GroupNotDefinedException; import org.sakaiproject.authz.api.Member; import org.sakaiproject.authz.api.PermissionsHelper; import org.sakaiproject.authz.api.Role; import org.sakaiproject.authz.api.SecurityAdvisor; import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.PagedResourceActionII; import org.sakaiproject.cheftool.PortletConfig; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.api.MenuItem; import org.sakaiproject.cheftool.menu.MenuEntry; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.coursemanagement.api.AcademicSession; import org.sakaiproject.coursemanagement.api.CourseOffering; import org.sakaiproject.coursemanagement.api.CourseSet; import org.sakaiproject.coursemanagement.api.Enrollment; import org.sakaiproject.coursemanagement.api.EnrollmentSet; import org.sakaiproject.coursemanagement.api.Membership; import org.sakaiproject.coursemanagement.api.Section; import org.sakaiproject.coursemanagement.api.exception.IdNotFoundException; import org.sakaiproject.email.cover.EmailService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.EntityPropertyNotDefinedException; import org.sakaiproject.entity.api.EntityPropertyTypeException; import org.sakaiproject.entity.api.EntityTransferrer; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.ImportException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.id.cover.IdManager; import org.sakaiproject.importer.api.ImportDataSource; import org.sakaiproject.importer.api.ImportService; import org.sakaiproject.importer.api.SakaiArchive; import org.sakaiproject.javax.PagingPosition; import org.sakaiproject.site.api.Group; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.sitemanage.api.model.*; import org.sakaiproject.site.util.SiteSetupQuestionFileParser; import org.sakaiproject.site.util.Participant; import org.sakaiproject.site.util.SiteParticipantHelper; import org.sakaiproject.site.util.SiteConstants; import org.sakaiproject.site.util.SiteComparator; import org.sakaiproject.site.util.ToolComparator; import org.sakaiproject.sitemanage.api.SectionField; import org.sakaiproject.sitemanage.api.SiteHelper; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.api.TimeBreakdown; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.user.api.User; import org.sakaiproject.user.api.UserAlreadyDefinedException; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.user.api.UserIdInvalidException; import org.sakaiproject.user.api.UserNotDefinedException; import org.sakaiproject.user.api.UserPermissionException; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ArrayUtil; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.SortedIterator; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; /** * <p> * SiteAction controls the interface for worksite setup. * </p> */ public class SiteAction extends PagedResourceActionII { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(SiteAction.class); private ContentHostingService m_contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private ImportService importService = org.sakaiproject.importer.cover.ImportService .getInstance(); /** portlet configuration parameter values* */ /** Resource bundle using current language locale */ private static ResourceLoader rb = new ResourceLoader("sitesetupgeneric"); private org.sakaiproject.coursemanagement.api.CourseManagementService cms = (org.sakaiproject.coursemanagement.api.CourseManagementService) ComponentManager .get(org.sakaiproject.coursemanagement.api.CourseManagementService.class); private org.sakaiproject.authz.api.GroupProvider groupProvider = (org.sakaiproject.authz.api.GroupProvider) ComponentManager .get(org.sakaiproject.authz.api.GroupProvider.class); private org.sakaiproject.authz.api.AuthzGroupService authzGroupService = (org.sakaiproject.authz.api.AuthzGroupService) ComponentManager .get(org.sakaiproject.authz.api.AuthzGroupService.class); private org.sakaiproject.sitemanage.api.SectionFieldProvider sectionFieldProvider = (org.sakaiproject.sitemanage.api.SectionFieldProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.SectionFieldProvider.class); private org.sakaiproject.sitemanage.api.AffiliatedSectionProvider affiliatedSectionProvider = (org.sakaiproject.sitemanage.api.AffiliatedSectionProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.AffiliatedSectionProvider.class); private org.sakaiproject.sitemanage.api.UserNotificationProvider userNotificationProvider = (org.sakaiproject.sitemanage.api.UserNotificationProvider) ComponentManager .get(org.sakaiproject.sitemanage.api.UserNotificationProvider.class); private ContentHostingService contentHostingService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); private static org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService questionService = (org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService) ComponentManager .get(org.sakaiproject.sitemanage.api.model.SiteSetupQuestionService.class); private static final String SITE_MODE_SITESETUP = "sitesetup"; private static final String SITE_MODE_SITEINFO = "siteinfo"; private static final String SITE_MODE_HELPER = "helper"; private static final String SITE_MODE_HELPER_DONE = "helper.done"; private static final String STATE_SITE_MODE = "site_mode"; protected final static String[] TEMPLATE = { "-list",// 0 "-type", "-newSiteInformation", "-editFeatures", "", "-addParticipant", "", "", "-siteDeleteConfirm", "", "-newSiteConfirm",// 10 "", "-siteInfo-list",// 12 "-siteInfo-editInfo", "-siteInfo-editInfoConfirm", "-addRemoveFeatureConfirm",// 15 "", "", "-siteInfo-editAccess", "-addParticipant-sameRole", "-addParticipant-differentRole",// 20 "-addParticipant-notification", "-addParticipant-confirm", "", "", "",// 25 "-modifyENW", "-importSites", "-siteInfo-import", "-siteInfo-duplicate", "",// 30 "",// 31 "",// 32 "",// 33 "",// 34 "",// 35 "-newSiteCourse",// 36 "-newSiteCourseManual",// 37 "",// 38 "",// 39 "",// 40 "",// 41 "-gradtoolsConfirm",// 42 "-siteInfo-editClass",// 43 "-siteInfo-addCourseConfirm",// 44 "-siteInfo-importMtrlMaster", // 45 -- htripath for import // material from a file "-siteInfo-importMtrlCopy", // 46 "-siteInfo-importMtrlCopyConfirm", "-siteInfo-importMtrlCopyConfirmMsg", // 48 "",//"-siteInfo-group", // 49 moved to the group helper "",//"-siteInfo-groupedit", // 50 moved to the group helper "",//"-siteInfo-groupDeleteConfirm", // 51, moved to the group helper "", "-findCourse", // 53 "-questions", // 54 "",// 55 "",// 56 "",// 57 "-siteInfo-importSelection", //58 "-siteInfo-importMigrate", //59 "-importSitesMigrate" //60 }; /** Name of state attribute for Site instance id */ private static final String STATE_SITE_INSTANCE_ID = "site.instance.id"; /** Name of state attribute for Site Information */ private static final String STATE_SITE_INFO = "site.info"; /** Name of state attribute for CHEF site type */ private static final String STATE_SITE_TYPE = "site-type"; /** Name of state attribute for possible site types */ private static final String STATE_SITE_TYPES = "site_types"; private static final String STATE_DEFAULT_SITE_TYPE = "default_site_type"; private static final String STATE_PUBLIC_CHANGEABLE_SITE_TYPES = "changeable_site_types"; private static final String STATE_PUBLIC_SITE_TYPES = "public_site_types"; private static final String STATE_PRIVATE_SITE_TYPES = "private_site_types"; private static final String STATE_DISABLE_JOINABLE_SITE_TYPE = "disable_joinable_site_types"; // Names of state attributes corresponding to properties of a site private final static String PROP_SITE_CONTACT_EMAIL = "contact-email"; private final static String PROP_SITE_CONTACT_NAME = "contact-name"; private final static String PROP_SITE_TERM = "term"; private final static String PROP_SITE_TERM_EID = "term_eid"; /** * Name of the state attribute holding the site list column list is sorted * by */ private static final String SORTED_BY = "site.sorted.by"; /** Name of the state attribute holding the site list column to sort by */ private static final String SORTED_ASC = "site.sort.asc"; /** State attribute for list of sites to be deleted. */ private static final String STATE_SITE_REMOVALS = "site.removals"; /** Name of the state attribute holding the site list View selected */ private static final String STATE_VIEW_SELECTED = "site.view.selected"; /** Names of lists related to tools */ private static final String STATE_TOOL_REGISTRATION_LIST = "toolRegistrationList"; private static final String STATE_TOOL_REGISTRATION_SELECTED_LIST = "toolRegistrationSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST = "toolRegistrationOldSelectedList"; private static final String STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME = "toolRegistrationOldSelectedHome"; private static final String STATE_TOOL_EMAIL_ADDRESS = "toolEmailAddress"; private static final String STATE_TOOL_HOME_SELECTED = "toolHomeSelected"; private static final String STATE_PROJECT_TOOL_LIST = "projectToolList"; private final static String STATE_MULTIPLE_TOOL_ID_SET = "multipleToolIdSet"; private final static String STATE_MULTIPLE_TOOL_ID_TITLE_MAP = "multipleToolIdTitleMap"; private final static String STATE_MULTIPLE_TOOL_CONFIGURATION = "multipleToolConfiguration"; private final static String SITE_DEFAULT_LIST = ServerConfigurationService .getString("site.types"); private final static String STATE_SITE_QUEST_UNIQNAME = "site_quest_uniqname"; private static final String STATE_SITE_ADD_COURSE = "canAddCourse"; // %%% get rid of the IdAndText tool lists and just use ToolConfiguration or // ToolRegistration lists // %%% same for CourseItems // Names for other state attributes that are lists private final static String STATE_WORKSITE_SETUP_PAGE_LIST = "wSetupPageList"; // the // list // of // site // pages // consistent // with // Worksite // Setup // page // patterns /** * The name of the state form field containing additional information for a * course request */ private static final String FORM_ADDITIONAL = "form.additional"; /** %%% in transition from putting all form variables in state */ private final static String FORM_TITLE = "form_title"; private final static String FORM_DESCRIPTION = "form_description"; private final static String FORM_HONORIFIC = "form_honorific"; private final static String FORM_INSTITUTION = "form_institution"; private final static String FORM_SUBJECT = "form_subject"; private final static String FORM_PHONE = "form_phone"; private final static String FORM_EMAIL = "form_email"; private final static String FORM_REUSE = "form_reuse"; private final static String FORM_RELATED_CLASS = "form_related_class"; private final static String FORM_RELATED_PROJECT = "form_related_project"; private final static String FORM_NAME = "form_name"; private final static String FORM_SHORT_DESCRIPTION = "form_short_description"; private final static String FORM_ICON_URL = "iconUrl"; /** site info edit form variables */ private final static String FORM_SITEINFO_TITLE = "siteinfo_title"; private final static String FORM_SITEINFO_TERM = "siteinfo_term"; private final static String FORM_SITEINFO_DESCRIPTION = "siteinfo_description"; private final static String FORM_SITEINFO_SHORT_DESCRIPTION = "siteinfo_short_description"; private final static String FORM_SITEINFO_SKIN = "siteinfo_skin"; private final static String FORM_SITEINFO_INCLUDE = "siteinfo_include"; private final static String FORM_SITEINFO_ICON_URL = "siteinfo_icon_url"; private final static String FORM_SITEINFO_CONTACT_NAME = "siteinfo_contact_name"; private final static String FORM_SITEINFO_CONTACT_EMAIL = "siteinfo_contact_email"; private final static String FORM_WILL_NOTIFY = "form_will_notify"; /** Context action */ private static final String CONTEXT_ACTION = "SiteAction"; /** The name of the Attribute for display template index */ private static final String STATE_TEMPLATE_INDEX = "site.templateIndex"; /** State attribute for state initialization. */ private static final String STATE_INITIALIZED = "site.initialized"; /** State attribute for state initialization. */ private static final String STATE_TEMPLATE_SITE = "site.templateSite"; /** The action for menu */ private static final String STATE_ACTION = "site.action"; /** The user copyright string */ private static final String STATE_MY_COPYRIGHT = "resources.mycopyright"; /** The copyright character */ private static final String COPYRIGHT_SYMBOL = "copyright (c)"; /** The null/empty string */ private static final String NULL_STRING = ""; /** The state attribute alerting user of a sent course request */ private static final String REQUEST_SENT = "site.request.sent"; /** The state attributes in the make public vm */ private static final String STATE_JOINABLE = "state_joinable"; private static final String STATE_JOINERROLE = "state_joinerRole"; /** the list of selected user */ private static final String STATE_SELECTED_USER_LIST = "state_selected_user_list"; private static final String STATE_SELECTED_PARTICIPANT_ROLES = "state_selected_participant_roles"; private static final String STATE_SELECTED_PARTICIPANTS = "state_selected_participants"; private static final String STATE_PARTICIPANT_LIST = "state_participant_list"; private static final String STATE_ADD_PARTICIPANTS = "state_add_participants"; /** for changing participant roles */ private static final String STATE_CHANGEROLE_SAMEROLE = "state_changerole_samerole"; private static final String STATE_CHANGEROLE_SAMEROLE_ROLE = "state_changerole_samerole_role"; /** for remove user */ private static final String STATE_REMOVEABLE_USER_LIST = "state_removeable_user_list"; private static final String STATE_IMPORT = "state_import"; private static final String STATE_IMPORT_SITES = "state_import_sites"; private static final String STATE_IMPORT_SITE_TOOL = "state_import_site_tool"; /** for navigating between sites in site list */ private static final String STATE_SITES = "state_sites"; private static final String STATE_PREV_SITE = "state_prev_site"; private static final String STATE_NEXT_SITE = "state_next_site"; /** for course information */ private final static String STATE_TERM_COURSE_LIST = "state_term_course_list"; private final static String STATE_TERM_COURSE_HASH = "state_term_course_hash"; private final static String STATE_TERM_SELECTED = "state_term_selected"; private final static String STATE_INSTRUCTOR_SELECTED = "state_instructor_selected"; private final static String STATE_FUTURE_TERM_SELECTED = "state_future_term_selected"; private final static String STATE_ADD_CLASS_PROVIDER = "state_add_class_provider"; private final static String STATE_ADD_CLASS_PROVIDER_CHOSEN = "state_add_class_provider_chosen"; private final static String STATE_ADD_CLASS_MANUAL = "state_add_class_manual"; private final static String STATE_AUTO_ADD = "state_auto_add"; private final static String STATE_MANUAL_ADD_COURSE_NUMBER = "state_manual_add_course_number"; private final static String STATE_MANUAL_ADD_COURSE_FIELDS = "state_manual_add_course_fields"; public final static String PROP_SITE_REQUEST_COURSE = "site-request-course-sections"; public final static String SITE_PROVIDER_COURSE_LIST = "site_provider_course_list"; public final static String SITE_MANUAL_COURSE_LIST = "site_manual_course_list"; private final static String STATE_SUBJECT_AFFILIATES = "site.subject.affiliates"; private final static String STATE_ICONS = "icons"; // site template used to create a UM Grad Tools student site public static final String SITE_GTS_TEMPLATE = "!gtstudent"; // the type used to identify a UM Grad Tools student site public static final String SITE_TYPE_GRADTOOLS_STUDENT = "GradToolsStudent"; // list of UM Grad Tools site types for editing public static final String GRADTOOLS_SITE_TYPES = "gradtools_site_types"; public static final String SITE_DUPLICATED = "site_duplicated"; public static final String SITE_DUPLICATED_NAME = "site_duplicated_named"; // used for site creation wizard title public static final String SITE_CREATE_TOTAL_STEPS = "site_create_total_steps"; public static final String SITE_CREATE_CURRENT_STEP = "site_create_current_step"; // types of site whose title can be editable public static final String TITLE_EDITABLE_SITE_TYPE = "title_editable_site_type"; // types of site where site view roster permission is editable public static final String EDIT_VIEW_ROSTER_SITE_TYPE = "edit_view_roster_site_type"; // htripath : for import material from file - classic import private static final String ALL_ZIP_IMPORT_SITES = "allzipImports"; private static final String FINAL_ZIP_IMPORT_SITES = "finalzipImports"; private static final String DIRECT_ZIP_IMPORT_SITES = "directzipImports"; private static final String CLASSIC_ZIP_FILE_NAME = "classicZipFileName"; private static final String SESSION_CONTEXT_ID = "sessionContextId"; // page size for worksite setup tool private static final String STATE_PAGESIZE_SITESETUP = "state_pagesize_sitesetup"; // page size for site info tool private static final String STATE_PAGESIZE_SITEINFO = "state_pagesize_siteinfo"; private static final String IMPORT_DATA_SOURCE = "import_data_source"; private static final String EMAIL_CHAR = "@"; // Special tool id for Home page private static final String HOME_TOOL_ID = "home"; private static final String SITE_INFORMATION_TOOL="sakai.iframe.site"; private static final String STATE_CM_LEVELS = "site.cm.levels"; private static final String STATE_CM_LEVEL_OPTS = "site.cm.level_opts"; private static final String STATE_CM_LEVEL_SELECTIONS = "site.cm.level.selections"; private static final String STATE_CM_SELECTED_SECTION = "site.cm.selectedSection"; private static final String STATE_CM_REQUESTED_SECTIONS = "site.cm.requested"; private static final String STATE_CM_SELECTED_SECTIONS = "site.cm.selectedSections"; private static final String STATE_PROVIDER_SECTION_LIST = "site_provider_section_list"; private static final String STATE_CM_CURRENT_USERID = "site_cm_current_userId"; private static final String STATE_CM_AUTHORIZER_LIST = "site_cm_authorizer_list"; private static final String STATE_CM_AUTHORIZER_SECTIONS = "site_cm_authorizer_sections"; private String cmSubjectCategory; private boolean warnedNoSubjectCategory = false; // the string marks the protocol part in url private static final String PROTOCOL_STRING = "://"; private static final String TOOL_ID_SUMMARY_CALENDAR = "sakai.summary.calendar"; // the string for course site type private static final String STATE_COURSE_SITE_TYPE = "state_course_site_type"; private static final String SITE_TEMPLATE_PREFIX = "template"; private static final String STATE_TYPE_SELECTED = "state_type_selected"; // the template index after exist the question mode private static final String STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE = "state_site_setup_question_next_template"; // SAK-12912, the answers to site setup questions private static final String STATE_SITE_SETUP_QUESTION_ANSWER = "state_site_setup_question_answer"; // SAK-13389, the non-official participant private static final String ADD_NON_OFFICIAL_PARTICIPANT = "add_non_official_participant"; // the list of visited templates private static final String STATE_VISITED_TEMPLATES = "state_visited_templates"; private String STATE_GROUP_HELPER_ID = "state_group_helper_id"; // used in the configuration file to specify which tool attributes are configurable through WSetup tool, and what are the default value for them. private String CONFIG_TOOL_ATTRIBUTE = "wsetup.config.tool.attribute_"; private String CONFIG_TOOL_ATTRIBUTE_DEFAULT = "wsetup.config.tool.attribute.default_"; /** * Populate the state object, if needed. */ protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata) { // Cleanout if the helper has been asked to start afresh. if (state.getAttribute(SiteHelper.SITE_CREATE_START) != null) { cleanState(state); cleanStateHelper(state); // Removed from possible previous invokations. state.removeAttribute(SiteHelper.SITE_CREATE_START); state.removeAttribute(SiteHelper.SITE_CREATE_CANCELLED); state.removeAttribute(SiteHelper.SITE_CREATE_SITE_ID); } super.initState(state, portlet, rundata); // store current userId in state User user = UserDirectoryService.getCurrentUser(); String userId = user.getEid(); state.setAttribute(STATE_CM_CURRENT_USERID, userId); PortletConfig config = portlet.getPortletConfig(); // types of sites that can either be public or private String changeableTypes = StringUtil.trimToNull(config .getInitParameter("publicChangeableSiteTypes")); if (state.getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES) == null) { if (changeableTypes != null) { state .setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new ArrayList(Arrays.asList(changeableTypes .split(",")))); } else { state.setAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES, new Vector()); } } // type of sites that are always public String publicTypes = StringUtil.trimToNull(config .getInitParameter("publicSiteTypes")); if (state.getAttribute(STATE_PUBLIC_SITE_TYPES) == null) { if (publicTypes != null) { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new ArrayList( Arrays.asList(publicTypes.split(",")))); } else { state.setAttribute(STATE_PUBLIC_SITE_TYPES, new Vector()); } } // types of sites that are always private String privateTypes = StringUtil.trimToNull(config .getInitParameter("privateSiteTypes")); if (state.getAttribute(STATE_PRIVATE_SITE_TYPES) == null) { if (privateTypes != null) { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new ArrayList( Arrays.asList(privateTypes.split(",")))); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // default site type String defaultType = StringUtil.trimToNull(config .getInitParameter("defaultSiteType")); if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) == null) { if (defaultType != null) { state.setAttribute(STATE_DEFAULT_SITE_TYPE, defaultType); } else { state.setAttribute(STATE_PRIVATE_SITE_TYPES, new Vector()); } } // certain type(s) of site cannot get its "joinable" option set if (state.getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE) == null) { if (ServerConfigurationService .getStrings("wsetup.disable.joinable") != null) { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new ArrayList(Arrays.asList(ServerConfigurationService .getStrings("wsetup.disable.joinable")))); } else { state.setAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE, new Vector()); } } // course site type if (state.getAttribute(STATE_COURSE_SITE_TYPE) == null) { state.setAttribute(STATE_COURSE_SITE_TYPE, ServerConfigurationService.getString("courseSiteType", "course")); } if (state.getAttribute(STATE_TOP_PAGE_MESSAGE) == null) { state.setAttribute(STATE_TOP_PAGE_MESSAGE, new Integer(0)); } // skins if any if (state.getAttribute(STATE_ICONS) == null) { setupIcons(state); } if (state.getAttribute(GRADTOOLS_SITE_TYPES) == null) { List gradToolsSiteTypes = new Vector(); if (ServerConfigurationService.getStrings("gradToolsSiteType") != null) { gradToolsSiteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("gradToolsSiteType"))); } state.setAttribute(GRADTOOLS_SITE_TYPES, gradToolsSiteTypes); } if (ServerConfigurationService.getStrings("titleEditableSiteType") != null) { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("titleEditableSiteType")))); } else { state.setAttribute(TITLE_EDITABLE_SITE_TYPE, new Vector()); } if (state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE) == null) { List siteTypes = new Vector(); if (ServerConfigurationService.getStrings("editViewRosterSiteType") != null) { siteTypes = new ArrayList(Arrays .asList(ServerConfigurationService .getStrings("editViewRosterSiteType"))); } state.setAttribute(EDIT_VIEW_ROSTER_SITE_TYPE, siteTypes); } if (state.getAttribute(STATE_SITE_MODE) == null) { // get site tool mode from tool registry String site_mode = config.getInitParameter(STATE_SITE_MODE); // When in helper mode we don't have if (site_mode == null) { site_mode = SITE_MODE_HELPER; } state.setAttribute(STATE_SITE_MODE, site_mode); } } // initState /** * cleanState removes the current site instance and it's properties from * state */ private void cleanState(SessionState state) { state.removeAttribute(STATE_SITE_INSTANCE_ID); state.removeAttribute(STATE_SITE_INFO); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); // remove those state attributes related to course site creation state.removeAttribute(STATE_TERM_COURSE_LIST); state.removeAttribute(STATE_TERM_COURSE_HASH); state.removeAttribute(STATE_TERM_SELECTED); state.removeAttribute(STATE_INSTRUCTOR_SELECTED); state.removeAttribute(STATE_FUTURE_TERM_SELECTED); state.removeAttribute(STATE_ADD_CLASS_PROVIDER); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_PROVIDER_SECTION_LIST); state.removeAttribute(STATE_CM_LEVELS); state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTION); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_CURRENT_USERID); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); // don't we need to clean this // too? -daisyf state.removeAttribute(STATE_TEMPLATE_SITE); state.removeAttribute(STATE_TYPE_SELECTED); state.removeAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); state.removeAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE); } // cleanState /** * Fire up the permissions editor */ public void doPermissions(RunData data, Context context) { // get into helper mode with this helper tool startHelper(data.getRequest(), "sakai.permissions.helper"); SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String contextString = ToolManager.getCurrentPlacement().getContext(); String siteRef = SiteService.siteReference(contextString); // if it is in Worksite setup tool, pass the selected site's reference if (state.getAttribute(STATE_SITE_MODE) != null && ((String) state.getAttribute(STATE_SITE_MODE)) .equals(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { Site s = getStateSite(state); if (s != null) { siteRef = s.getReference(); } } } // setup for editing the permissions of the site for this tool, using // the roles of this site, too state.setAttribute(PermissionsHelper.TARGET_REF, siteRef); // ... with this description state.setAttribute(PermissionsHelper.DESCRIPTION, rb .getString("setperfor") + " " + SiteService.getSiteDisplay(contextString)); // ... showing only locks that are prpefixed with this state.setAttribute(PermissionsHelper.PREFIX, "site."); } // doPermissions /** * Build the context for normal display */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { rb = new ResourceLoader("sitesetupgeneric"); context.put("tlang", rb); // TODO: what is all this doing? if we are in helper mode, we are // already setup and don't get called here now -ggolden /* * String helperMode = (String) * state.getAttribute(PermissionsAction.STATE_MODE); if (helperMode != * null) { Site site = getStateSite(state); if (site != null) { if * (site.getType() != null && ((List) * state.getAttribute(EDIT_VIEW_ROSTER_SITE_TYPE)).contains(site.getType())) { * context.put("editViewRoster", Boolean.TRUE); } else { * context.put("editViewRoster", Boolean.FALSE); } } else { * context.put("editViewRoster", Boolean.FALSE); } // for new, don't * show site.del in Permission page context.put("hiddenLock", * "site.del"); * * String template = PermissionsAction.buildHelperContext(portlet, * context, data, state); if (template == null) { addAlert(state, * rb.getString("theisa")); } else { return template; } } */ String template = null; context.put("action", CONTEXT_ACTION); // updatePortlet(state, portlet, data); if (state.getAttribute(STATE_INITIALIZED) == null) { init(portlet, data, state); } String indexString = (String) state.getAttribute(STATE_TEMPLATE_INDEX); // update the visited template list with the current template index addIntoStateVisitedTemplates(state, indexString); template = buildContextForTemplate(getPrevVisitedTemplate(state), Integer.valueOf(indexString), portlet, context, data, state); return template; } // buildMainPanelContext /** * add index into the visited template indices list * @param state * @param index */ private void addIntoStateVisitedTemplates(SessionState state, String index) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices.size() == 0 || !templateIndices.contains(index)) { // this is to prevent from page refreshing accidentally updates the list templateIndices.add(index); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } /** * remove the last index * @param state */ private void removeLastIndexInStateVisitedTemplates(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices!=null && templateIndices.size() > 0) { // this is to prevent from page refreshing accidentally updates the list templateIndices.remove(templateIndices.size()-1); state.setAttribute(STATE_VISITED_TEMPLATES, templateIndices); } } private String getPrevVisitedTemplate(SessionState state) { List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >1 ) { return templateIndices.get(templateIndices.size()-2); } else { return null; } } /** * whether template indexed has been visited * @param state * @param templateIndex * @return */ private boolean isTemplateVisited(SessionState state, String templateIndex) { boolean rv = false; List<String> templateIndices = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (templateIndices != null && templateIndices.size() >0 ) { rv = templateIndices.contains(templateIndex); } return rv; } /** * Build the context for each template using template_index parameter passed * in a form hidden field. Each case is associated with a template. (Not all * templates implemented). See String[] TEMPLATES. * * @param index * is the number contained in the template's template_index */ private String buildContextForTemplate(String preIndex, int index, VelocityPortlet portlet, Context context, RunData data, SessionState state) { String realmId = ""; String site_type = ""; String sortedBy = ""; String sortedAsc = ""; ParameterParser params = data.getParameters(); context.put("tlang", rb); context.put("alertMessage", state.getAttribute(STATE_MESSAGE)); // the last visited template index if (preIndex != null) context.put("backIndex", preIndex); context.put("templateIndex", String.valueOf(index)); // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { state.setAttribute(STATE_SITE_INFO, siteInfo); } // Lists used in more than one template // Access List roles = new Vector(); // the hashtables for News and Web Content tools Hashtable newsTitles = new Hashtable(); Hashtable newsUrls = new Hashtable(); Hashtable wcTitles = new Hashtable(); Hashtable wcUrls = new Hashtable(); List toolRegistrationList = new Vector(); List toolRegistrationSelectedList = new Vector(); ResourceProperties siteProperties = null; // for showing site creation steps if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) != null) { context.put("totalSteps", state .getAttribute(SITE_CREATE_TOTAL_STEPS)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { context.put("step", state.getAttribute(SITE_CREATE_CURRENT_STEP)); } String hasGradSites = ServerConfigurationService.getString( "withDissertation", Boolean.FALSE.toString()); context.put("cms", cms); // course site type context.put("courseSiteType", state.getAttribute(STATE_COURSE_SITE_TYPE)); //can the user create course sites? context.put(STATE_SITE_ADD_COURSE, SiteService.allowAddCourseSite()); Site site = getStateSite(state); switch (index) { case 0: /* * buildContextForTemplate chef_site-list.vm * */ // site types List sTypes = (List) state.getAttribute(STATE_SITE_TYPES); // make sure auto-updates are enabled Hashtable views = new Hashtable(); if (SecurityService.isSuperUser()) { views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); views.put(rb.getString("java.my") + " " + rb.getString("java.sites"), rb.getString("java.my")); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); views.put(type + " " + rb.getString("java.sites"), type); } if (hasGradSites.equalsIgnoreCase("true")) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } context.put("superUser", Boolean.TRUE); } else { context.put("superUser", Boolean.FALSE); views.put(rb.getString("java.allmy"), rb .getString("java.allmy")); // if there is a GradToolsStudent choice inside boolean remove = false; if (hasGradSites.equalsIgnoreCase("true")) { try { // the Grad Tools site option is only presented to // GradTools Candidates String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a grad student? if (!isGradToolsCandidate(userId)) { // not a gradstudent remove = true; } } catch (Exception e) { remove = true; M_log.warn(this + "buildContextForTemplate chef_site-list.vm list GradToolsStudent sites", e); } } else { // not support for dissertation sites remove = true; } // do not show this site type in views // sTypes.remove(new String(SITE_TYPE_GRADTOOLS_STUDENT)); for (int sTypeIndex = 0; sTypeIndex < sTypes.size(); sTypeIndex++) { String type = (String) sTypes.get(sTypeIndex); if (!type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { views .put(type + " " + rb.getString("java.sites"), type); } } if (!remove) { views.put(rb.getString("java.gradtools") + " " + rb.getString("java.sites"), rb .getString("java.gradtools")); } // default view if (state.getAttribute(STATE_VIEW_SELECTED) == null) { state.setAttribute(STATE_VIEW_SELECTED, rb .getString("java.allmy")); } } context.put("views", views); if (state.getAttribute(STATE_VIEW_SELECTED) != null) { context.put("viewSelected", (String) state .getAttribute(STATE_VIEW_SELECTED)); } String search = (String) state.getAttribute(STATE_SEARCH); context.put("search_term", search); sortedBy = (String) state.getAttribute(SORTED_BY); if (sortedBy == null) { state.setAttribute(SORTED_BY, SortType.TITLE_ASC.toString()); sortedBy = SortType.TITLE_ASC.toString(); } sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); String portalUrl = ServerConfigurationService.getPortalUrl(); context.put("portalUrl", portalUrl); List sites = prepPage(state); state.setAttribute(STATE_SITES, sites); context.put("sites", sites); context.put("totalPageNumber", new Integer(totalPageNumber(state))); context.put("searchString", state.getAttribute(STATE_SEARCH)); context.put("form_search", FORM_SEARCH); context.put("formPageNumber", FORM_PAGE_NUMBER); context.put("prev_page_exists", state .getAttribute(STATE_PREV_PAGE_EXISTS)); context.put("next_page_exists", state .getAttribute(STATE_NEXT_PAGE_EXISTS)); context.put("current_page", state.getAttribute(STATE_CURRENT_PAGE)); // put the service in the context (used for allow update calls on // each site) context.put("service", SiteService.getInstance()); context.put("sortby_title", SortType.TITLE_ASC.toString()); context.put("sortby_type", SortType.TYPE_ASC.toString()); context.put("sortby_createdby", SortType.CREATED_BY_ASC.toString()); context.put("sortby_publish", SortType.PUBLISHED_ASC.toString()); context.put("sortby_createdon", SortType.CREATED_ON_ASC.toString()); // top menu bar Menu bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.new"), "doNew_site")); } bar.add(new MenuEntry(rb.getString("java.revise"), null, true, MenuItem.CHECKED_NA, "doGet_site", "sitesForm")); bar.add(new MenuEntry(rb.getString("java.delete"), null, true, MenuItem.CHECKED_NA, "doMenu_site_delete", "sitesForm")); context.put("menu", bar); // default to be no pageing context.put("paged", Boolean.FALSE); Menu bar2 = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); // add the search commands addSearchMenus(bar2, state); context.put("menu2", bar2); pagingInfoToContext(state, context); return (String) getContext(data).get("template") + TEMPLATE[0]; case 1: /* * buildContextForTemplate chef_site-type.vm * */ if (hasGradSites.equalsIgnoreCase("true")) { context.put("withDissertation", Boolean.TRUE); try { // the Grad Tools site option is only presented to UM grad // students String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); // am I a UM grad student? Boolean isGradStudent = new Boolean( isGradToolsCandidate(userId)); context.put("isGradStudent", isGradStudent); // if I am a UM grad student, do I already have a Grad Tools // site? boolean noGradToolsSite = true; if (hasGradToolsStudentSite(userId)) noGradToolsSite = false; context .put("noGradToolsSite", new Boolean(noGradToolsSite)); } catch (Exception e) { M_log.warn(this + "buildContextForTemplate chef_site-type.vm ", e); } } else { context.put("withDissertation", Boolean.FALSE); } List types = (List) state.getAttribute(STATE_SITE_TYPES); context.put("siteTypes", types); // put selected/default site type into context String typeSelected = (String) state.getAttribute(STATE_TYPE_SELECTED); context.put("typeSelected", state.getAttribute(STATE_TYPE_SELECTED) != null?state.getAttribute(STATE_TYPE_SELECTED):types.get(0)); setTermListForContext(context, state, true); // true => only // upcoming terms setSelectedTermForContext(context, state, STATE_TERM_SELECTED); // template site - Denny setTemplateListForContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[1]; case 2: /* * buildContextForTemplate chef_site-newSiteInformation.vm * */ context.put("siteTypes", state.getAttribute(STATE_SITE_TYPES)); String siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("type", siteType); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, siteType))); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } List<SectionObject> cmRequestedList = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (cmRequestedList != null) { context.put("cmRequestedSections", cmRequestedList); } List<SectionObject> cmAuthorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (cmAuthorizerSectionList != null) { context .put("cmAuthorizerSections", cmAuthorizerSectionList); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } else { if (courseManagementIsImplemented()) { } else { context.put("templateIndex", "37"); } } // whether to show course skin selection choices or not courseSkinSelection(context, state, null, siteInfo); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put(FORM_ICON_URL, siteInfo.iconUrl); } } if (state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE) != null) { context.put("titleEditableSiteType", Boolean.FALSE); siteInfo.title = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TITLE); } else { context.put("titleEditableSiteType", state .getAttribute(TITLE_EDITABLE_SITE_TYPE)); } context.put(FORM_TITLE, siteInfo.title); context.put(FORM_SHORT_DESCRIPTION, siteInfo.short_description); context.put(FORM_DESCRIPTION, siteInfo.description); // defalt the site contact person to the site creator if (siteInfo.site_contact_name.equals(NULL_STRING) && siteInfo.site_contact_email.equals(NULL_STRING)) { User user = UserDirectoryService.getCurrentUser(); siteInfo.site_contact_name = user.getDisplayName(); siteInfo.site_contact_email = user.getEmail(); } context.put("form_site_contact_name", siteInfo.site_contact_name); context.put("form_site_contact_email", siteInfo.site_contact_email); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[2]; case 3: /* * buildContextForTemplate chef_site-editFeatures.vm * */ String type = (String) state.getAttribute(STATE_SITE_TYPE); if (type != null && type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (type.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } context.put("defaultTools", ServerConfigurationService .getToolsRequired(type)); toolRegistrationSelectedList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // If this is the first time through, check for tools // which should be selected by default. List defaultSelectedTools = ServerConfigurationService .getDefaultTools(type); if (toolRegistrationSelectedList == null) { toolRegistrationSelectedList = new Vector(defaultSelectedTools); } context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); boolean myworkspace_site = false; // Put up tool lists filtered by category List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes.contains(type)) { myworkspace_site = false; } if (site != null && SiteService.isUserSite(site.getId()) || (type != null && type.equalsIgnoreCase("myworkspace"))) { myworkspace_site = true; type = "myworkspace"; } context.put("myworkspace_site", new Boolean(myworkspace_site)); context.put(STATE_TOOL_REGISTRATION_LIST, state.getAttribute(STATE_TOOL_REGISTRATION_LIST)); // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); // The Home tool checkbox needs special treatment to be selected // by // default. Boolean checkHome = (Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED); if (checkHome == null) { if ((defaultSelectedTools != null) && defaultSelectedTools.contains(HOME_TOOL_ID)) { checkHome = Boolean.TRUE; } } context.put("check_home", checkHome); // get the email alias when an Email Archive tool has been selected String channelReference = site!=null?mailArchiveChannelReference(site.getId()):""; List aliases = AliasService.getAliases(channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases .get(0)).getId()); } else { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); context.put("import", state.getAttribute(STATE_IMPORT)); context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); if (site != null) { context.put("SiteTitle", site.getTitle()); context.put("existSite", Boolean.TRUE); context.put("backIndex", "12"); // back to site info list page } else { context.put("existSite", Boolean.FALSE); context.put("backIndex", "2"); // back to new site information page } return (String) getContext(data).get("template") + TEMPLATE[3]; case 5: /* * buildContextForTemplate chef_site-addParticipant.vm * */ context.put("title", site.getTitle()); roles = getRoles(state); context.put("roles", roles); siteType = (String) state.getAttribute(STATE_SITE_TYPE); context.put("isCourseSite", siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))?Boolean.TRUE:Boolean.FALSE); // Note that (for now) these strings are in both sakai.properties // and sitesetupgeneric.properties context.put("officialAccountSectionTitle", ServerConfigurationService .getString("officialAccountSectionTitle")); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName")); context.put("officialAccountLabel", ServerConfigurationService .getString("officialAccountLabel")); String pickerAction = ServerConfigurationService.getString("officialAccountPickerAction"); if (pickerAction != null && !"".equals(pickerAction)) { context.put("hasPickerDefined", Boolean.TRUE); context.put("officialAccountPickerLabel", ServerConfigurationService .getString("officialAccountPickerLabel")); context.put("officialAccountPickerAction", pickerAction); } if (state.getAttribute("officialAccountValue") != null) { context.put("officialAccountValue", (String) state .getAttribute("officialAccountValue")); } // whether to show the non-official participant section or not String addNonOfficialParticipant = (String) state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT); if (addNonOfficialParticipant != null) { if (addNonOfficialParticipant.equalsIgnoreCase("true")) { context.put("nonOfficialAccount", Boolean.TRUE); context.put("nonOfficialAccountSectionTitle", ServerConfigurationService .getString("nonOfficialAccountSectionTitle")); context.put("nonOfficialAccountName", ServerConfigurationService .getString("nonOfficialAccountName")); context.put("nonOfficialAccountLabel", ServerConfigurationService .getString("nonOfficialAccountLabel")); if (state.getAttribute("nonOfficialAccountValue") != null) { context.put("nonOfficialAccountValue", (String) state .getAttribute("nonOfficialAccountValue")); } } else { context.put("nonOfficialAccount", Boolean.FALSE); } } if (state.getAttribute("form_same_role") != null) { context.put("form_same_role", ((Boolean) state .getAttribute("form_same_role")).toString()); } else { context.put("form_same_role", Boolean.TRUE.toString()); } context.put("backIndex", "12"); return (String) getContext(data).get("template") + TEMPLATE[5]; case 8: /* * buildContextForTemplate chef_site-siteDeleteConfirm.vm * */ String site_title = NULL_STRING; String[] removals = (String[]) state .getAttribute(STATE_SITE_REMOVALS); List remove = new Vector(); String user = SessionManager.getCurrentSessionUserId(); String workspace = SiteService.getUserSiteId(user); if (removals != null && removals.length != 0) { for (int i = 0; i < removals.length; i++) { String id = (String) removals[i]; if (!(id.equals(workspace))) { try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + "buildContextForTemplate chef_site-siteDeleteConfirm.vm - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site removeSite = SiteService.getSite(id); remove.add(removeSite); } catch (IdUnusedException e) { M_log.warn(this + ".buildContextForTemplate chef_site-siteDeleteConfirm.vm: IdUnusedException", e); } } else { addAlert(state, site_title + " " + rb.getString("java.couldntdel") + " "); } } else { addAlert(state, rb.getString("java.yourwork")); } } if (remove.size() == 0) { addAlert(state, rb.getString("java.click")); } } context.put("removals", remove); return (String) getContext(data).get("template") + TEMPLATE[8]; case 10: /* * buildContextForTemplate chef_site-newSiteConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("isProjectSite", Boolean.FALSE); if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { context.put("selectedAuthorizerCourse", state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { context.put("selectedRequestedCourse", state .getAttribute(STATE_CM_REQUESTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(number - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("skins", state.getAttribute(STATE_ICONS)); if (StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } else { context.put("isCourseSite", Boolean.FALSE); if (siteType != null && siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } if (StringUtil.trimToNull(siteInfo.iconUrl) != null) { context.put("iconUrl", siteInfo.iconUrl); } } context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); context.put("siteContactName", siteInfo.site_contact_name); context.put("siteContactEmail", siteInfo.site_contact_email); siteType = (String) state.getAttribute(STATE_SITE_TYPE); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); // %%% use Tool // all info related to multiple tools multipleToolIntoContext(context, state); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); context.put("published", new Boolean(siteInfo.published)); context.put("joinable", new Boolean(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); context.put("importSiteTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("siteService", SiteService.getInstance()); // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[10]; case 12: /* * buildContextForTemplate chef_site-siteInfo-list.vm * */ context.put("userDirectoryService", UserDirectoryService .getInstance()); try { siteProperties = site.getProperties(); siteType = site.getType(); if (siteType != null) { state.setAttribute(STATE_SITE_TYPE, siteType); } boolean isMyWorkspace = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { isMyWorkspace = true; context.put("siteUserId", SiteService .getSiteUserId(site.getId())); } } context.put("isMyWorkspace", Boolean.valueOf(isMyWorkspace)); String siteId = site.getId(); if (state.getAttribute(STATE_ICONS) != null) { List skins = (List) state.getAttribute(STATE_ICONS); for (int i = 0; i < skins.size(); i++) { MyIcon s = (MyIcon) skins.get(i); if (!StringUtil .different(s.getUrl(), site.getIconUrl())) { context.put("siteUnit", s.getName()); break; } } } context.put("siteIcon", site.getIconUrl()); context.put("siteTitle", site.getTitle()); context.put("siteDescription", site.getDescription()); context.put("siteJoinable", new Boolean(site.isJoinable())); if (site.isPublished()) { context.put("published", Boolean.TRUE); } else { context.put("published", Boolean.FALSE); context.put("owner", site.getCreatedBy().getSortName()); } Time creationTime = site.getCreatedTime(); if (creationTime != null) { context.put("siteCreationDate", creationTime .toStringLocalFull()); } boolean allowUpdateSite = SiteService.allowUpdateSite(siteId); context.put("allowUpdate", Boolean.valueOf(allowUpdateSite)); boolean allowUpdateGroupMembership = SiteService .allowUpdateGroupMembership(siteId); context.put("allowUpdateGroupMembership", Boolean .valueOf(allowUpdateGroupMembership)); boolean allowUpdateSiteMembership = SiteService .allowUpdateSiteMembership(siteId); context.put("allowUpdateSiteMembership", Boolean .valueOf(allowUpdateSiteMembership)); Menu b = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (allowUpdateSite) { // top menu bar if (!isMyWorkspace) { b.add(new MenuEntry(rb.getString("java.editsite"), "doMenu_edit_site_info")); } b.add(new MenuEntry(rb.getString("java.edittools"), "doMenu_edit_site_tools")); // if the page order helper is available, not // stealthed and not hidden, show the link if (notStealthOrHiddenTool("sakai-site-pageorder-helper")) { b.add(new MenuEntry(rb.getString("java.orderpages"), "doPageOrderHelper")); } } if (allowUpdateSiteMembership) { // show add participant menu if (!isMyWorkspace) { // show the Add Participant menu b.add(new MenuEntry(rb.getString("java.addp"), "doMenu_siteInfo_addParticipant")); // show the Edit Class Roster menu if (siteType != null && siteType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { b.add(new MenuEntry(rb.getString("java.editc"), "doMenu_siteInfo_editClass")); } } } if (allowUpdateGroupMembership) { // show Manage Groups menu if (!isMyWorkspace && (ServerConfigurationService .getString("wsetup.group.support") == "" || ServerConfigurationService .getString("wsetup.group.support") .equalsIgnoreCase(Boolean.TRUE.toString()))) { // show the group toolbar unless configured // to not support group // if the manage group helper is available, not // stealthed and not hidden, show the link if (setHelper("wsetup.groupHelper", "sakai-site-manage-group-helper", state, STATE_GROUP_HELPER_ID)) { b.add(new MenuEntry(rb.getString("java.group"), "doManageGroupHelper")); } } } if (allowUpdateSite) { if (!isMyWorkspace) { List gradToolsSiteTypes = (List) state .getAttribute(GRADTOOLS_SITE_TYPES); boolean isGradToolSite = false; if (siteType != null && gradToolsSiteTypes.contains(siteType)) { isGradToolSite = true; } if (siteType == null || siteType != null && !isGradToolSite) { // hide site access for GRADTOOLS // type of sites b.add(new MenuEntry( rb.getString("java.siteaccess"), "doMenu_edit_site_access")); } if (siteType == null || siteType != null && !isGradToolSite) { // hide site duplicate and import // for GRADTOOLS type of sites if (SiteService.allowAddSite(null)) { b.add(new MenuEntry(rb.getString("java.duplicate"), "doMenu_siteInfo_duplicate")); } List updatableSites = SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null); // import link should be visible even if only one // site if (updatableSites.size() > 0) { //a configuration param for showing/hiding Import From Site with Clean Up String importFromSite = ServerConfigurationService.getString("clean.import.site",Boolean.TRUE.toString()); if (importFromSite.equalsIgnoreCase("true")) { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_importSelection")); } else { b.add(new MenuEntry( rb.getString("java.import"), "doMenu_siteInfo_import")); } // a configuration param for // showing/hiding import // from file choice String importFromFile = ServerConfigurationService .getString("site.setup.import.file", Boolean.TRUE.toString()); if (importFromFile.equalsIgnoreCase("true")) { // htripath: June // 4th added as per // Kris and changed // desc of above b.add(new MenuEntry(rb .getString("java.importFile"), "doAttachmentsMtrlFrmFile")); } } } } } if (b.size() > 0) { // add the menus to vm context.put("menu", b); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // editing from worksite setup tool context.put("fromWSetup", Boolean.TRUE); if (state.getAttribute(STATE_PREV_SITE) != null) { context.put("prevSite", state .getAttribute(STATE_PREV_SITE)); } if (state.getAttribute(STATE_NEXT_SITE) != null) { context.put("nextSite", state .getAttribute(STATE_NEXT_SITE)); } } else { context.put("fromWSetup", Boolean.FALSE); } // allow view roster? boolean allowViewRoster = SiteService.allowViewRoster(siteId); if (allowViewRoster) { context.put("viewRoster", Boolean.TRUE); } else { context.put("viewRoster", Boolean.FALSE); } // set participant list if (allowUpdateSite || allowViewRoster || allowUpdateSiteMembership) { Collection participantsCollection = getParticipantList(state); sortedBy = (String) state.getAttribute(SORTED_BY); sortedAsc = (String) state.getAttribute(SORTED_ASC); if (sortedBy == null) { state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); sortedBy = SiteConstants.SORTED_BY_PARTICIPANT_NAME; } if (sortedAsc == null) { sortedAsc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, sortedAsc); } if (sortedBy != null) context.put("currentSortedBy", sortedBy); if (sortedAsc != null) context.put("currentSortAsc", sortedAsc); context.put("participantListSize", new Integer(participantsCollection.size())); context.put("participantList", prepPage(state)); pagingInfoToContext(state, context); } context.put("include", Boolean.valueOf(site.isPubView())); // site contact information String contactName = siteProperties .getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { User u = site.getCreatedBy(); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } if (contactName != null) { context.put("contactName", contactName); } if (contactEmail != null) { context.put("contactEmail", contactEmail); } if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); coursesIntoContext(state, context, site); context.put("term", siteProperties .getProperty(PROP_SITE_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } } catch (Exception e) { M_log.warn(this + " buildContextForTemplate chef_site-siteInfo-list.vm ", e); } roles = getRoles(state); context.put("roles", roles); // will have the choice to active/inactive user or not String activeInactiveUser = ServerConfigurationService.getString( "activeInactiveUser", Boolean.FALSE.toString()); if (activeInactiveUser.equalsIgnoreCase("true")) { context.put("activeInactiveUser", Boolean.TRUE); } else { context.put("activeInactiveUser", Boolean.FALSE); } context.put("groupsWithMember", site .getGroupsWithMember(UserDirectoryService.getCurrentUser() .getId())); return (String) getContext(data).get("template") + TEMPLATE[12]; case 13: /* * buildContextForTemplate chef_site-siteInfo-editInfo.vm * */ siteProperties = site.getProperties(); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("siteTitleEditable", Boolean.valueOf(siteTitleEditable(state, site.getType()))); context.put("type", site.getType()); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); // whether to show course skin selection choices or not courseSkinSelection(context, state, site, null); setTermListForContext(context, state, true); // true->only future terms if (state.getAttribute(FORM_SITEINFO_TERM) == null) { String currentTerm = site.getProperties().getProperty( PROP_SITE_TERM); if (currentTerm != null) { state.setAttribute(FORM_SITEINFO_TERM, currentTerm); } } setSelectedTermForContext(context, state, FORM_SITEINFO_TERM); } else { context.put("isCourseSite", Boolean.FALSE); if (state.getAttribute(FORM_SITEINFO_ICON_URL) == null && StringUtil.trimToNull(site.getIconUrl()) != null) { state.setAttribute(FORM_SITEINFO_ICON_URL, site .getIconUrl()); } if (state.getAttribute(FORM_SITEINFO_ICON_URL) != null) { context.put("iconUrl", state .getAttribute(FORM_SITEINFO_ICON_URL)); } } context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("form_site_contact_name", state .getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("form_site_contact_email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[13]; case 14: /* * buildContextForTemplate chef_site-siteInfo-editInfoConfirm.vm * */ siteProperties = site.getProperties(); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("siteTerm", state.getAttribute(FORM_SITEINFO_TERM)); } else { context.put("isCourseSite", Boolean.FALSE); } context.put("oTitle", site.getTitle()); context.put("title", state.getAttribute(FORM_SITEINFO_TITLE)); context.put("description", state .getAttribute(FORM_SITEINFO_DESCRIPTION)); context.put("oDescription", site.getDescription()); context.put("short_description", state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); context.put("oShort_description", site.getShortDescription()); context.put("skin", state.getAttribute(FORM_SITEINFO_SKIN)); context.put("oSkin", site.getIconUrl()); context.put("skins", state.getAttribute(STATE_ICONS)); context.put("oIcon", site.getIconUrl()); context.put("icon", state.getAttribute(FORM_SITEINFO_ICON_URL)); context.put("include", state.getAttribute(FORM_SITEINFO_INCLUDE)); context.put("oInclude", Boolean.valueOf(site.isPubView())); context.put("name", state.getAttribute(FORM_SITEINFO_CONTACT_NAME)); context.put("oName", siteProperties .getProperty(PROP_SITE_CONTACT_NAME)); context.put("email", state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL)); context.put("oEmail", siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL)); return (String) getContext(data).get("template") + TEMPLATE[14]; case 15: /* * buildContextForTemplate chef_site-addRemoveFeatureConfirm.vm * */ context.put("title", site.getTitle()); site_type = (String) state.getAttribute(STATE_SITE_TYPE); myworkspace_site = false; if (SiteService.isUserSite(site.getId())) { if (SiteService.getSiteUserId(site.getId()).equals( SessionManager.getCurrentSessionUserId())) { myworkspace_site = true; site_type = "myworkspace"; } } context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("selectedTools", orderToolIds(state, (String) state .getAttribute(STATE_SITE_TYPE), (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); context.put("oldSelectedHome", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME)); context.put("continueIndex", "12"); if (state.getAttribute(STATE_TOOL_EMAIL_ADDRESS) != null) { context.put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); } context.put("serverName", ServerConfigurationService .getServerName()); // all info related to multiple tools multipleToolIntoContext(context, state); return (String) getContext(data).get("template") + TEMPLATE[15]; case 18: /* * buildContextForTemplate chef_siteInfo-editAccess.vm * */ List publicChangeableSiteTypes = (List) state .getAttribute(STATE_PUBLIC_CHANGEABLE_SITE_TYPES); List unJoinableSiteTypes = (List) state .getAttribute(STATE_DISABLE_JOINABLE_SITE_TYPE); if (site != null) { // editing existing site context.put("site", site); siteType = state.getAttribute(STATE_SITE_TYPE) != null ? (String) state .getAttribute(STATE_SITE_TYPE) : null; if (siteType != null && publicChangeableSiteTypes.contains(siteType)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(site.isPubView())); if (siteType != null && !unJoinableSiteTypes.contains(siteType)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); if (state.getAttribute(STATE_JOINABLE) == null) { state.setAttribute(STATE_JOINABLE, Boolean.valueOf(site .isJoinable())); } if (state.getAttribute(STATE_JOINERROLE) == null || state.getAttribute(STATE_JOINABLE) != null && ((Boolean) state.getAttribute(STATE_JOINABLE)) .booleanValue()) { state.setAttribute(STATE_JOINERROLE, site .getJoinerRole()); } if (state.getAttribute(STATE_JOINABLE) != null) { context.put("joinable", state .getAttribute(STATE_JOINABLE)); } if (state.getAttribute(STATE_JOINERROLE) != null) { context.put("joinerRole", state .getAttribute(STATE_JOINERROLE)); } } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } context.put("roles", getRoles(state)); } else { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo.site_type != null && publicChangeableSiteTypes .contains(siteInfo.site_type)) { context.put("publicChangeable", Boolean.TRUE); } else { context.put("publicChangeable", Boolean.FALSE); } context.put("include", Boolean.valueOf(siteInfo.getInclude())); context.put("published", Boolean.valueOf(siteInfo .getPublished())); if (siteInfo.site_type != null && !unJoinableSiteTypes.contains(siteInfo.site_type)) { // site can be set as joinable context.put("disableJoinable", Boolean.FALSE); context.put("joinable", Boolean.valueOf(siteInfo.joinable)); context.put("joinerRole", siteInfo.joinerRole); } else { // site cannot be set as joinable context.put("disableJoinable", Boolean.TRUE); } // the template site, if using one Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); // use the type's template, if defined String realmTemplate = "!site.template"; // if create based on template, use the roles from the template if (templateSite != null) { realmTemplate = SiteService.siteReference(templateSite.getId()); } else if (siteInfo.site_type != null) { realmTemplate = realmTemplate + "." + siteInfo.site_type; } try { AuthzGroup r = AuthzGroupService.getAuthzGroup(realmTemplate); context.put("roles", r.getRoles()); } catch (GroupNotDefinedException e) { try { AuthzGroup rr = AuthzGroupService.getAuthzGroup("!site.template"); context.put("roles", rr.getRoles()); } catch (GroupNotDefinedException ee) { } } // new site, go to confirmation page context.put("continue", "10"); siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("isProjectSite", Boolean.FALSE); } else { context.put("isCourseSite", Boolean.FALSE); if (siteType.equalsIgnoreCase("project")) { context.put("isProjectSite", Boolean.TRUE); } } } return (String) getContext(data).get("template") + TEMPLATE[18]; case 19: /* * buildContextForTemplate chef_site-addParticipant-sameRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("form_selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[19]; case 20: /* * buildContextForTemplate chef_site-addParticipant-differentRole.vm * */ context.put("title", site.getTitle()); context.put("roles", getRoles(state)); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context.put("participantList", state .getAttribute(STATE_ADD_PARTICIPANTS)); return (String) getContext(data).get("template") + TEMPLATE[20]; case 21: /* * buildContextForTemplate chef_site-addParticipant-notification.vm * */ context.put("title", site.getTitle()); context.put("sitePublished", Boolean.valueOf(site.isPublished())); if (state.getAttribute("form_selectedNotify") == null) { state.setAttribute("form_selectedNotify", Boolean.FALSE); } context.put("notify", state.getAttribute("form_selectedNotify")); boolean same_role = state.getAttribute("form_same_role") == null ? true : ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); if (same_role) { context.put("backIndex", "19"); } else { context.put("backIndex", "20"); } return (String) getContext(data).get("template") + TEMPLATE[21]; case 22: /* * buildContextForTemplate chef_site-addParticipant-confirm.vm * */ context.put("title", site.getTitle()); context.put("participants", state .getAttribute(STATE_ADD_PARTICIPANTS)); context.put("notify", state.getAttribute("form_selectedNotify")); context.put("roles", getRoles(state)); context.put("same_role", state.getAttribute("form_same_role")); context.put("selectedRoles", state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES)); context .put("selectedRole", state .getAttribute("form_selectedRole")); return (String) getContext(data).get("template") + TEMPLATE[22]; case 26: /* * buildContextForTemplate chef_site-modifyENW.vm * */ site_type = (String) state.getAttribute(STATE_SITE_TYPE); boolean existingSite = site != null ? true : false; if (existingSite) { // revising a existing site's tool context.put("existingSite", Boolean.TRUE); context.put("continue", "15"); } else { // new site context.put("existingSite", Boolean.FALSE); context.put("continue", "18"); } context.put("function", "eventSubmit_doAdd_features"); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's // all info related to multiple tools multipleToolIntoContext(context, state); context.put("toolManager", ToolManager.getInstance()); String emailId = (String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS); if (emailId != null) { context.put("emailId", emailId); } context.put("serverName", ServerConfigurationService .getServerName()); context.put("oldSelectedTools", state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST)); return (String) getContext(data).get("template") + TEMPLATE[26]; case 27: /* * buildContextForTemplate chef_site-importSites.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } context.put("existingSite", Boolean.valueOf(existingSite)); context.put(STATE_TOOL_REGISTRATION_LIST, state .getAttribute(STATE_TOOL_REGISTRATION_LIST)); context.put("selectedTools", orderToolIds(state, site_type, (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST))); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[27]; case 60: /* * buildContextForTemplate chef_site-importSitesMigrate.vm * */ existingSite = site != null ? true : false; site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (existingSite) { // revising a existing site's tool context.put("continue", "12"); context.put("back", "28"); context.put("totalSteps", "2"); context.put("step", "2"); context.put("currentSite", site); } else { // new site, go to edit access page context.put("back", "3"); if (fromENWModifyView(state)) { context.put("continue", "26"); } else { context.put("continue", "18"); } } // get the tool id list List<String> toolIdList = new Vector<String>(); if (existingSite) { // list all site tools which are displayed on its own page List<SitePage> sitePages = site.getPages(); if (sitePages != null) { for (SitePage page: sitePages) { List<ToolConfiguration> pageToolsList = page.getTools(0); // we only handle one tool per page case if ( page.getLayout() == SitePage.LAYOUT_SINGLE_COL && pageToolsList.size() == 1) { toolIdList.add(pageToolsList.get(0).getToolId()); } } } } else { // during site creation toolIdList = (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdList); // order it SortedIterator iToolIdList = new SortedIterator(getToolsAvailableForImport(state, toolIdList).iterator(),new ToolComparator()); Hashtable<String, String> toolTitleTable = new Hashtable<String, String>(); for(;iToolIdList.hasNext();) { String toolId = (String) iToolIdList.next(); try { String toolTitle = ToolManager.getTool(toolId).getTitle(); toolTitleTable.put(toolId, toolTitle); } catch (Exception e) { Log.info("chef", this + " buildContexForTemplate case 60: cannot get tool title for " + toolId + e.getMessage()); } } context.put("selectedTools", toolTitleTable); // String toolId's context.put("importSites", state.getAttribute(STATE_IMPORT_SITES)); context.put("importSitesTools", state .getAttribute(STATE_IMPORT_SITE_TOOL)); context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context.put("importSupportedTools", importTools()); return (String) getContext(data).get("template") + TEMPLATE[60]; case 28: /* * buildContextForTemplate chef_siteinfo-import.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[28]; case 58: /* * buildContextForTemplate chef_siteinfo-importSelection.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[58]; case 59: /* * buildContextForTemplate chef_siteinfo-importMigrate.vm * */ context.put("currentSite", site); context.put("importSiteList", state .getAttribute(STATE_IMPORT_SITES)); context.put("sites", SiteService.getSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, null, null, null, SortType.TITLE_ASC, null)); return (String) getContext(data).get("template") + TEMPLATE[59]; case 29: /* * buildContextForTemplate chef_siteinfo-duplicate.vm * */ context.put("siteTitle", site.getTitle()); String sType = site.getType(); if (sType != null && sType.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { context.put("isCourseSite", Boolean.TRUE); context.put("currentTermId", site.getProperties().getProperty( PROP_SITE_TERM)); setTermListForContext(context, state, true); // true upcoming only } else { context.put("isCourseSite", Boolean.FALSE); } if (state.getAttribute(SITE_DUPLICATED) == null) { context.put("siteDuplicated", Boolean.FALSE); } else { context.put("siteDuplicated", Boolean.TRUE); context.put("duplicatedName", state .getAttribute(SITE_DUPLICATED_NAME)); } return (String) getContext(data).get("template") + TEMPLATE[29]; case 36: /* * buildContextForTemplate chef_site-newSiteCourse.vm */ // SAK-9824 Boolean enableCourseCreationForUser = ServerConfigurationService.getBoolean("site.enableCreateAnyUser", Boolean.FALSE); context.put("enableCourseCreationForUser", enableCourseCreationForUser); if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); setTermListForContext(context, state, true); // true -> upcoming only List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); coursesIntoContext(state, context, site); AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); context.put("term", t); if (t != null) { String userId = UserDirectoryService.getCurrentUser().getEid(); List courses = prepareCourseAndSectionListing(userId, t .getEid(), state); if (courses != null && courses.size() > 0) { Vector notIncludedCourse = new Vector(); // remove included sites for (Iterator i = courses.iterator(); i.hasNext();) { CourseObject c = (CourseObject) i.next(); if (providerCourseList == null || providerCourseList != null && !providerCourseList.contains(c.getEid())) { notIncludedCourse.add(c); } } state.setAttribute(STATE_TERM_COURSE_LIST, notIncludedCourse); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); } } // step number used in UI state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer("1")); } else { // need to include both list 'cos STATE_CM_AUTHORIZER_SECTIONS // contains sections that doens't belongs to current user and // STATE_ADD_CLASS_PROVIDER_CHOSEN contains section that does - // v2.4 daisyf if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null || state.getAttribute(STATE_CM_AUTHORIZER_SECTIONS) != null) { List<String> providerSectionList = (List<String>) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerSectionList != null) { /* List list1 = prepareSectionObject(providerSectionList, (String) state .getAttribute(STATE_CM_CURRENT_USERID)); */ context.put("selectedProviderCourse", providerSectionList); } List<SectionObject> authorizerSectionList = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSectionList != null) { List authorizerList = (List) state .getAttribute(STATE_CM_AUTHORIZER_LIST); //authorizerList is a list of SectionObject /* String userId = null; if (authorizerList != null) { userId = (String) authorizerList.get(0); } List list2 = prepareSectionObject( authorizerSectionList, userId); */ ArrayList list2 = new ArrayList(); for (int i=0; i<authorizerSectionList.size();i++){ SectionObject so = (SectionObject)authorizerSectionList.get(i); list2.add(so.getEid()); } context.put("selectedAuthorizerCourse", list2); } } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { context.put("selectedManualCourse", Boolean.TRUE); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("currentUserId", (String) state .getAttribute(STATE_CM_CURRENT_USERID)); context.put("form_additional", (String) state .getAttribute(FORM_ADDITIONAL)); context.put("authorizers", getAuthorizers(state)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { context.put("backIndex", "1"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", ""); } List ll = (List) state.getAttribute(STATE_TERM_COURSE_LIST); context.put("termCourseList", state .getAttribute(STATE_TERM_COURSE_LIST)); // added for 2.4 -daisyf context.put("campusDirectory", getCampusDirectory()); context.put("userId", (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED)); /* * for measuring how long it takes to load sections java.util.Date * date = new java.util.Date(); M_log.debug("***2. finish at: * "+date); M_log.debug("***3. userId:"+(String) state * .getAttribute(STATE_INSTRUCTOR_SELECTED)); */ return (String) getContext(data).get("template") + TEMPLATE[36]; case 37: /* * buildContextForTemplate chef_site-newSiteCourseManual.vm */ if (site != null) { context.put("site", site); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); } buildInstructorSectionsList(state, params, context); context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("form_additional", siteInfo.additional); context.put("form_title", siteInfo.title); context.put("form_description", siteInfo.description); context.put("officialAccountName", ServerConfigurationService .getString("officialAccountName", "")); context.put("value_uniqname", state .getAttribute(STATE_SITE_QUEST_UNIQNAME)); int number = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { number = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("currentNumber", new Integer(number)); } context.put("currentNumber", new Integer(number)); context.put("listSize", number>0?new Integer(number - 1):0); if (state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null && ((List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)).size() > 0) { context.put("fieldValues", state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { List l = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); context.put("selectedProviderCourse", l); context.put("size", new Integer(l.size() - 1)); } if (state.getAttribute(STATE_CM_REQUESTED_SECTIONS) != null) { List l = (List) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); context.put("cmRequestedSections", l); } if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (site == null) { if (state.getAttribute(STATE_AUTO_ADD) != null) { context.put("autoAdd", Boolean.TRUE); } } isFutureTermSelected(state); context.put("isFutureTerm", state .getAttribute(STATE_FUTURE_TERM_SELECTED)); context.put("weeksAhead", ServerConfigurationService.getString( "roster.available.weeks.before.term.start", "0")); return (String) getContext(data).get("template") + TEMPLATE[37]; case 42: /* * buildContextForTemplate chef_site-gradtoolsConfirm.vm * */ siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); context.put("title", siteInfo.title); context.put("description", siteInfo.description); context.put("short_description", siteInfo.short_description); toolRegistrationList = (Vector) state .getAttribute(STATE_PROJECT_TOOL_LIST); toolRegistrationSelectedList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); context.put(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolRegistrationSelectedList); // String toolId's context.put(STATE_TOOL_REGISTRATION_LIST, toolRegistrationList); // %%% // use // Tool context.put("check_home", state .getAttribute(STATE_TOOL_HOME_SELECTED)); context .put("emailId", state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); context.put("serverName", ServerConfigurationService .getServerName()); context.put("include", new Boolean(siteInfo.include)); return (String) getContext(data).get("template") + TEMPLATE[42]; case 43: /* * buildContextForTemplate chef_siteInfo-editClass.vm * */ bar = new MenuImpl(portlet, data, (String) state .getAttribute(STATE_ACTION)); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString("java.addclasses"), "doMenu_siteInfo_addClass")); } context.put("menu", bar); context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); return (String) getContext(data).get("template") + TEMPLATE[43]; case 44: /* * buildContextForTemplate chef_siteInfo-addCourseConfirm.vm * */ context.put("siteTitle", site.getTitle()); coursesIntoContext(state, context, site); context.put("providerAddCourses", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int addNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue() - 1; context.put("manualAddNumber", new Integer(addNumber)); context.put("requestFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); context.put("backIndex", "37"); } else { context.put("backIndex", "36"); } // those manual inputs context.put("form_requiredFields", sectionFieldProvider .getRequiredFields()); context.put("fieldValues", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); return (String) getContext(data).get("template") + TEMPLATE[44]; // htripath - import materials from classic case 45: /* * buildContextForTemplate chef_siteInfo-importMtrlMaster.vm * */ return (String) getContext(data).get("template") + TEMPLATE[45]; case 46: /* * buildContextForTemplate chef_siteInfo-importMtrlCopy.vm * */ // this is for list display in listbox context .put("allZipSites", state .getAttribute(ALL_ZIP_IMPORT_SITES)); context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); // zip file // context.put("zipreffile",state.getAttribute(CLASSIC_ZIP_FILE_NAME)); return (String) getContext(data).get("template") + TEMPLATE[46]; case 47: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[47]; case 48: /* * buildContextForTemplate chef_siteInfo-importMtrlCopyConfirm.vm * */ context.put("finalZipSites", state .getAttribute(FINAL_ZIP_IMPORT_SITES)); return (String) getContext(data).get("template") + TEMPLATE[48]; // case 49, 50, 51 have been implemented in helper mode case 53: { /* * build context for chef_site-findCourse.vm */ AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); List cmLevels = (List) state.getAttribute(STATE_CM_LEVELS), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); if (cmLevels == null) { cmLevels = getCMLevelLabels(); } SectionObject selectedSect = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); List<SectionObject> requestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (courseManagementIsImplemented() && cms != null) { context.put("cmsAvailable", new Boolean(true)); } int cmLevelSize = 0; if (cms == null || !courseManagementIsImplemented() || cmLevels == null || cmLevels.size() < 1) { // TODO: redirect to manual entry: case #37 } else { cmLevelSize = cmLevels.size(); Object levelOpts[] = state.getAttribute(STATE_CM_LEVEL_OPTS) == null?new Object[cmLevelSize]:(Object[])state.getAttribute(STATE_CM_LEVEL_OPTS); int numSelections = 0; if (selections != null) numSelections = selections.size(); // execution will fall through these statements based on number of selections already made if (numSelections == cmLevelSize - 1) { levelOpts[numSelections] = getCMSections((String) selections.get(numSelections-1)); } else if (numSelections == cmLevelSize - 2) { levelOpts[numSelections] = getCMCourseOfferings((String) selections.get(numSelections-1), t.getEid()); } else if (numSelections < cmLevelSize) { levelOpts[numSelections] = sortCmObject(cms.findCourseSets((String) cmLevels.get(numSelections==0?0:numSelections-1))); } // always set the top level levelOpts[0] = sortCmObject(cms.findCourseSets((String) cmLevels.get(0))); // clean further element inside the array for (int i = numSelections + 1; i<cmLevelSize; i++) { levelOpts[i] = null; } context.put("cmLevelOptions", Arrays.asList(levelOpts)); state.setAttribute(STATE_CM_LEVEL_OPTS, levelOpts); } if (state.getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN) != null) { context.put("selectedProviderCourse", state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN)); } if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { int courseInd = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); context.put("manualAddNumber", new Integer(courseInd - 1)); context.put("manualAddFields", state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS)); } context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); context.put("cmLevels", cmLevels); context.put("cmLevelSelections", selections); context.put("selectedCourse", selectedSect); context.put("cmRequestedSections", requestedSections); if (state.getAttribute(STATE_SITE_MODE).equals(SITE_MODE_SITEINFO)) { context.put("editSite", Boolean.TRUE); context.put("cmSelectedSections", state.getAttribute(STATE_CM_SELECTED_SECTIONS)); } if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { if (state.getAttribute(STATE_TERM_COURSE_LIST) != null) { context.put("backIndex", "36"); } else { context.put("backIndex", "1"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { context.put("backIndex", "36"); } context.put("authzGroupService", AuthzGroupService.getInstance()); return (String) getContext(data).get("template") + TEMPLATE[53]; } case 54: /* * build context for chef_site-questions.vm */ SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { context.put("questionSet", siteTypeQuestions); context.put("userAnswers", state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER)); } context.put("continueIndex", state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); return (String) getContext(data).get("template") + TEMPLATE[54]; } // should never be reached return (String) getContext(data).get("template") + TEMPLATE[0]; } // buildContextForTemplate private void multipleToolIntoContext(Context context, SessionState state) { // titles for multiple tool instances context.put(STATE_MULTIPLE_TOOL_ID_SET, state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET )); context.put(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP )); context.put(STATE_MULTIPLE_TOOL_CONFIGURATION, state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION)); } /** * show course site skin selection or not * @param context * @param state * @param site * @param siteInfo */ private void courseSkinSelection(Context context, SessionState state, Site site, SiteInfo siteInfo) { // Display of appearance icon/url list with course site based on // "disable.course.site.skin.selection" value set with // sakai.properties file. // The setting defaults to be false. context.put("disableCourseSelection", ServerConfigurationService.getString("disable.course.site.skin.selection", "false").equals("true")?Boolean.TRUE:Boolean.FALSE); context.put("skins", state.getAttribute(STATE_ICONS)); if (state.getAttribute(FORM_SITEINFO_SKIN) != null) { context.put("selectedIcon", state.getAttribute(FORM_SITEINFO_SKIN)); } else { if (site != null && site.getIconUrl() != null) { context.put("selectedIcon", site.getIconUrl()); } else if (siteInfo != null && StringUtil.trimToNull(siteInfo.getIconUrl()) != null) { context.put("selectedIcon", siteInfo.getIconUrl()); } } } /** * Launch the Page Order Helper Tool -- for ordering, adding and customizing * pages * * @see case 12 * */ public void doPageOrderHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), "sakai-site-pageorder-helper"); } /** * Launch the Manage Group helper Tool -- for adding, editing and deleting groups * */ public void doManageGroupHelper(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // pass in the siteId of the site to be ordered (so it can configure // sites other then the current site) SessionManager.getCurrentToolSession().setAttribute( HELPER_ID + ".siteId", ((Site) getStateSite(state)).getId()); // launch the helper startHelper(data.getRequest(), (String) state.getAttribute(STATE_GROUP_HELPER_ID));//"sakai-site-manage-group-helper"); } public boolean setHelper(String helperName, String defaultHelperId, SessionState state, String stateHelperString) { String helperId = ServerConfigurationService.getString(helperName, defaultHelperId); // if the state variable regarding the helper is not set yet, set it with the configured helper id if (state.getAttribute(stateHelperString) == null) { state.setAttribute(stateHelperString, helperId); } if (notStealthOrHiddenTool(helperId)) { return true; } return false; } // htripath: import materials from classic /** * Master import -- for import materials from a file * * @see case 45 * */ public void doAttachmentsMtrlFrmFile(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // state.setAttribute(FILE_UPLOAD_MAX_SIZE, // ServerConfigurationService.getString("content.upload.max", "1")); state.setAttribute(STATE_TEMPLATE_INDEX, "45"); } // doImportMtrlFrmFile /** * Handle File Upload request * * @see case 46 * @throws Exception */ public void doUpload_Mtrl_Frm_File(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List allzipList = new Vector(); List finalzipList = new Vector(); List directcopyList = new Vector(); // see if the user uploaded a file FileItem fileFromUpload = null; String fileName = null; fileFromUpload = data.getParameters().getFileItem("file"); String max_file_size_mb = ServerConfigurationService.getString( "content.upload.max", "1"); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch (Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; M_log.warn(this + ".doUpload_Mtrl_Frm_File: wrong setting of content.upload.max = " + max_file_size_mb, e); } if (fileFromUpload == null) { // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getString("importFile.size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileFromUpload.getFileName() == null || fileFromUpload.getFileName().length() == 0) { addAlert(state, rb.getString("importFile.choosefile")); } else { byte[] fileData = fileFromUpload.get(); if (fileData.length >= max_bytes) { addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("importFile.exceeded")); } else if (fileData.length > 0) { if (importService.isValidArchive(fileData)) { ImportDataSource importDataSource = importService .parseFromFile(fileData); Log.info("chef", "Getting import items from manifest."); List lst = importDataSource.getItemCategories(); if (lst != null && lst.size() > 0) { Iterator iter = lst.iterator(); while (iter.hasNext()) { ImportMetadata importdata = (ImportMetadata) iter .next(); // Log.info("chef","Preparing import // item '" + importdata.getId() + "'"); if ((!importdata.isMandatory()) && (importdata.getFileName() .endsWith(".xml"))) { allzipList.add(importdata); } else { directcopyList.add(importdata); } } } // set Attributes state.setAttribute(ALL_ZIP_IMPORT_SITES, allzipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, finalzipList); state.setAttribute(DIRECT_ZIP_IMPORT_SITES, directcopyList); state.setAttribute(CLASSIC_ZIP_FILE_NAME, fileName); state.setAttribute(IMPORT_DATA_SOURCE, importDataSource); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } else { // uploaded file is not a valid archive addAlert(state, rb.getString("importFile.invalidfile")); } } } } // doImportMtrlFrmFile /** * Handle addition to list request * * @param data */ public void doAdd_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("addImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); fnlList.add(removeItems(value, zipList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Helper class for Add and remove * * @param value * @param items * @return */ public ImportMetadata removeItems(String value, List items) { ImportMetadata result = null; for (int i = 0; i < items.size(); i++) { ImportMetadata item = (ImportMetadata) items.get(i); if (value.equals(item.getId())) { result = (ImportMetadata) items.remove(i); break; } } return result; } /** * Handle the request for remove * * @param data */ public void doRemove_MtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); List zipList = (List) state.getAttribute(ALL_ZIP_IMPORT_SITES); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List importSites = new ArrayList(Arrays.asList(params .getStrings("removeImportSelected"))); for (int i = 0; i < importSites.size(); i++) { String value = (String) importSites.get(i); zipList.add(removeItems(value, fnlList)); } state.setAttribute(ALL_ZIP_IMPORT_SITES, zipList); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "46"); } // doAdd_MtrlSite /** * Handle the request for copy * * @param data */ public void doCopyMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); state.setAttribute(FINAL_ZIP_IMPORT_SITES, fnlList); state.setAttribute(STATE_TEMPLATE_INDEX, "47"); } // doCopy_MtrlSite /** * Handle the request for Save * * @param data * @throws ImportException */ public void doSaveMtrlSite(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List fnlList = (List) state.getAttribute(FINAL_ZIP_IMPORT_SITES); List directList = (List) state.getAttribute(DIRECT_ZIP_IMPORT_SITES); ImportDataSource importDataSource = (ImportDataSource) state .getAttribute(IMPORT_DATA_SOURCE); // combine the selected import items with the mandatory import items fnlList.addAll(directList); Log.info("chef", "doSaveMtrlSite() about to import " + fnlList.size() + " top level items"); Log.info("chef", "doSaveMtrlSite() the importDataSource is " + importDataSource.getClass().getName()); if (importDataSource instanceof SakaiArchive) { Log.info("chef", "doSaveMtrlSite() our data source is a Sakai format"); ((SakaiArchive) importDataSource).buildSourceFolder(fnlList); Log.info("chef", "doSaveMtrlSite() source folder is " + ((SakaiArchive) importDataSource).getSourceFolder()); ArchiveService.merge(((SakaiArchive) importDataSource) .getSourceFolder(), siteId, null); } else { importService.doImportItems(importDataSource .getItemsForCategories(fnlList), siteId); } // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.removeAttribute(IMPORT_DATA_SOURCE); state.setAttribute(STATE_TEMPLATE_INDEX, "48"); // state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } // doSave_MtrlSite public void doSaveMtrlSiteMsg(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // remove attributes state.removeAttribute(ALL_ZIP_IMPORT_SITES); state.removeAttribute(FINAL_ZIP_IMPORT_SITES); state.removeAttribute(DIRECT_ZIP_IMPORT_SITES); state.removeAttribute(CLASSIC_ZIP_FILE_NAME); state.removeAttribute(SESSION_CONTEXT_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // htripath-end /** * Handle the site search request. */ public void doSite_search(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // read the search form field into the state object String search = StringUtil.trimToNull(data.getParameters().getString( FORM_SEARCH)); // set the flag to go to the prev page on the next list if (search == null) { state.removeAttribute(STATE_SEARCH); } else { state.setAttribute(STATE_SEARCH, search); } } // doSite_search /** * Handle a Search Clear request. */ public void doSite_search_clear(RunData data, Context context) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // clear the search state.removeAttribute(STATE_SEARCH); } // doSite_search_clear private void coursesIntoContext(SessionState state, Context context, Site site) { List providerCourseList = SiteParticipantHelper.getProviderCourseList((String) state.getAttribute(STATE_SITE_INSTANCE_ID)); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); String sectionTitleString = ""; for(int i = 0; i < providerCourseList.size(); i++) { String sectionId = (String) providerCourseList.get(i); try { Section s = cms.getSection(sectionId); sectionTitleString = (i>0)?sectionTitleString + "<br />" + s.getTitle():s.getTitle(); } catch (Exception e) { M_log.warn(this + ".coursesIntoContext " + e.getMessage() + " sectionId=" + sectionId, e); } } context.put("providedSectionTitle", sectionTitleString); context.put("providerCourseList", providerCourseList); } // put manual requested courses into context courseListFromStringIntoContext(state, context, site, STATE_CM_REQUESTED_SECTIONS, STATE_CM_REQUESTED_SECTIONS, "cmRequestedCourseList"); // put manual requested courses into context courseListFromStringIntoContext(state, context, site, PROP_SITE_REQUEST_COURSE, SITE_MANUAL_COURSE_LIST, "manualCourseList"); } private void courseListFromStringIntoContext(SessionState state, Context context, Site site, String site_prop_name, String state_attribute_string, String context_string) { String courseListString = StringUtil.trimToNull(site.getProperties().getProperty(site_prop_name)); if (courseListString != null) { List courseList = new Vector(); if (courseListString.indexOf("+") != -1) { courseList = new ArrayList(Arrays.asList(courseListString.split("\\+"))); } else { courseList.add(courseListString); } if (state_attribute_string.equals(STATE_CM_REQUESTED_SECTIONS)) { // need to construct the list of SectionObjects List<SectionObject> soList = new Vector(); for (int i=0; i<courseList.size();i++) { String courseEid = (String) courseList.get(i); try { Section s = cms.getSection(courseEid); if (s!=null) soList.add(new SectionObject(s)); } catch (Exception e) { M_log.warn(this + ".courseListFromStringIntoContext: cannot find section " + courseEid, e); } } if (soList.size() > 0) state.setAttribute(STATE_CM_REQUESTED_SECTIONS, soList); } else { // the list is of String objects state.setAttribute(state_attribute_string, courseList); } } context.put(context_string, state.getAttribute(state_attribute_string)); } /** * buildInstructorSectionsList Build the CourseListItem list for this * Instructor for the requested Term * */ private void buildInstructorSectionsList(SessionState state, ParameterParser params, Context context) { // Site information // The sections of the specified term having this person as Instructor context.put("providerCourseSectionList", state .getAttribute("providerCourseSectionList")); context.put("manualCourseSectionList", state .getAttribute("manualCourseSectionList")); context.put("term", (AcademicSession) state .getAttribute(STATE_TERM_SELECTED)); setTermListForContext(context, state, true); //-> future terms only context.put(STATE_TERM_COURSE_LIST, state .getAttribute(STATE_TERM_COURSE_LIST)); context.put("tlang", rb); } // buildInstructorSectionsList /** * {@inheritDoc} */ protected int sizeResources(SessionState state) { int size = 0; String search = ""; String userId = SessionManager.getCurrentSessionUserId(); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using // the criteria size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null); } else if (view.equals(rb.getString("java.my"))) { // search for a specific user site // for the particular user id in the // criteria - exact match only try { SiteService.getSite(SiteService .getUserSiteId(search)); size++; } catch (IdUnusedException e) { } } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size = SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, view, search, null); } } } else { Site userWorkspaceSite = null; try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "sizeResources, template index = 0: Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { size++; } } else { size++; } } size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null); } else { // search for specific type of sites size += SiteService .countSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null); } } } } // for SiteInfo list page else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { Collection l = (Collection) state.getAttribute(STATE_PARTICIPANT_LIST); size = (l != null) ? l.size() : 0; } return size; } // sizeResources /** * {@inheritDoc} */ protected List readResourcesPage(SessionState state, int first, int last) { String search = StringUtil.trimToNull((String) state .getAttribute(STATE_SEARCH)); // if called from the site list page if (((String) state.getAttribute(STATE_TEMPLATE_INDEX)).equals("0")) { // get sort type SortType sortType = null; String sortBy = (String) state.getAttribute(SORTED_BY); boolean sortAsc = (new Boolean((String) state .getAttribute(SORTED_ASC))).booleanValue(); if (sortBy.equals(SortType.TITLE_ASC.toString())) { sortType = sortAsc ? SortType.TITLE_ASC : SortType.TITLE_DESC; } else if (sortBy.equals(SortType.TYPE_ASC.toString())) { sortType = sortAsc ? SortType.TYPE_ASC : SortType.TYPE_DESC; } else if (sortBy.equals(SortType.CREATED_BY_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_BY_ASC : SortType.CREATED_BY_DESC; } else if (sortBy.equals(SortType.CREATED_ON_ASC.toString())) { sortType = sortAsc ? SortType.CREATED_ON_ASC : SortType.CREATED_ON_DESC; } else if (sortBy.equals(SortType.PUBLISHED_ASC.toString())) { sortType = sortAsc ? SortType.PUBLISHED_ASC : SortType.PUBLISHED_DESC; } if (SecurityService.isSuperUser()) { // admin-type of user String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { // search for non-user sites, using the // criteria return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, null, search, null, sortType, new PagingPosition(first, last)); } else if (view.equalsIgnoreCase(rb.getString("java.my"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only List rv = new Vector(); try { Site userSite = SiteService.getSite(SiteService .getUserSiteId(search)); rv.add(userSite); } catch (IdUnusedException e) { } return rv; } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for gradtools sites return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.NON_USER, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last)); } else { // search for a specific site return SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ANY, view, search, null, sortType, new PagingPosition(first, last)); } } } else { List rv = new Vector(); Site userWorkspaceSite = null; String userId = SessionManager.getCurrentSessionUserId(); try { userWorkspaceSite = SiteService.getSite(SiteService .getUserSiteId(userId)); } catch (IdUnusedException e) { M_log.warn(this + "readResourcesPage template index = 0 :Cannot find user " + SessionManager.getCurrentSessionUserId() + "'s My Workspace site.", e); } String view = (String) state.getAttribute(STATE_VIEW_SELECTED); if (view != null) { if (view.equals(rb.getString("java.allmy"))) { view = null; // add my workspace if any if (userWorkspaceSite != null) { if (search != null) { if (userId.indexOf(search) != -1) { rv.add(userWorkspaceSite); } } else { rv.add(userWorkspaceSite); } } rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, search, null, sortType, new PagingPosition(first, last))); } else if (view.equalsIgnoreCase(rb .getString("java.gradtools"))) { // search for a specific user site for // the particular user id in the // criteria - exact match only rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, state .getAttribute(GRADTOOLS_SITE_TYPES), search, null, sortType, new PagingPosition(first, last))); } else { rv .addAll(SiteService .getSites( org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, view, search, null, sortType, new PagingPosition(first, last))); } } return rv; } } // if in Site Info list view else if (state.getAttribute(STATE_TEMPLATE_INDEX).toString().equals( "12")) { List participants = (state.getAttribute(STATE_PARTICIPANT_LIST) != null) ? collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)): new Vector(); String sortedBy = (String) state.getAttribute(SORTED_BY); String sortedAsc = (String) state.getAttribute(SORTED_ASC); Iterator sortedParticipants = null; if (sortedBy != null) { sortedParticipants = new SortedIterator(participants .iterator(), new SiteComparator(sortedBy, sortedAsc)); participants.clear(); while (sortedParticipants.hasNext()) { participants.add(sortedParticipants.next()); } } PagingPosition page = new PagingPosition(first, last); page.validate(participants.size()); participants = participants.subList(page.getFirst() - 1, page.getLast()); return participants; } return null; } // readResourcesPage /** * get the selected tool ids from import sites */ private boolean select_import_tools(ParameterParser params, SessionState state) { // has the user selected any tool for importing? boolean anyToolSelected = false; Hashtable importTools = new Hashtable(); // the tools for current site List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // String // toolId's for (int i = 0; i < selectedTools.size(); i++) { // any tools chosen from import sites? String toolId = (String) selectedTools.get(i); if (params.getStrings(toolId) != null) { importTools.put(toolId, new ArrayList(Arrays.asList(params .getStrings(toolId)))); if (!anyToolSelected) { anyToolSelected = true; } } } state.setAttribute(STATE_IMPORT_SITE_TOOL, importTools); return anyToolSelected; } // select_import_tools /** * Is it from the ENW edit page? * * @return ture if the process went through the ENW page; false, otherwise */ private boolean fromENWModifyView(SessionState state) { boolean fromENW = false; List oTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); List toolList = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); for (int i = 0; i < toolList.size() && !fromENW; i++) { String toolId = (String) toolList.get(i); if (toolId.equals("sakai.mailbox") || isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { if (oTools == null) { // if during site creation proces fromENW = true; } else if (!oTools.contains(toolId)) { // if user is adding either EmailArchive tool, News tool or // Web Content tool, go to the Customize page for the tool fromENW = true; } } } return fromENW; } /** * doNew_site is called when the Site list tool bar New... button is clicked * */ public void doNew_site(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // start clean cleanState(state); List siteTypes = (List) state.getAttribute(STATE_SITE_TYPES); if (siteTypes != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } } // doNew_site /** * doMenu_site_delete is called when the Site list tool bar Delete button is * clicked * */ public void doMenu_site_delete(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } String[] removals = (String[]) params.getStrings("selectedMembers"); state.setAttribute(STATE_SITE_REMOVALS, removals); // present confirm delete template state.setAttribute(STATE_TEMPLATE_INDEX, "8"); } // doMenu_site_delete public void doSite_delete_confirmed(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (params.getStrings("selectedMembers") == null) { M_log .warn("SiteAction.doSite_delete_confirmed selectedMembers null"); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the // site list return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites if (!chosenList.isEmpty()) { for (ListIterator i = chosenList.listIterator(); i.hasNext();) { String id = (String) i.next(); String site_title = NULL_STRING; try { site_title = SiteService.getSite(id).getTitle(); } catch (IdUnusedException e) { M_log.warn(this + ".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + id + " " + rb.getString("java.couldnt") + " "); } if (SiteService.allowRemoveSite(id)) { try { Site site = SiteService.getSite(id); site_title = site.getTitle(); SiteService.removeSite(site); } catch (IdUnusedException e) { M_log.warn(this +".doSite_delete_confirmed - IdUnusedException " + id, e); addAlert(state, rb.getString("java.sitewith") + " " + site_title + "(" + id + ") " + rb.getString("java.couldnt") + " "); } catch (PermissionException e) { M_log.warn(this + ".doSite_delete_confirmed - PermissionException, site " + site_title + "(" + id + ").", e); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } else { M_log.warn(this + ".doSite_delete_confirmed - allowRemoveSite failed for site "+ id); addAlert(state, site_title + " " + rb.getString("java.dontperm") + " "); } } } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // return to the site // list // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); } // doSite_delete_confirmed /** * get the Site object based on SessionState attribute values * * @return Site object related to current state; null if no such Site object * could be found */ protected Site getStateSite(SessionState state) { Site site = null; if (state.getAttribute(STATE_SITE_INSTANCE_ID) != null) { try { site = SiteService.getSite((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); } catch (Exception ignore) { } } return site; } // getStateSite /** * do called when "eventSubmit_do" is in the request parameters to c is * called from site list menu entry Revise... to get a locked site as * editable and to go to the correct template to begin DB version of writes * changes to disk at site commit whereas XML version writes at server * shutdown */ public void doGet_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // check form filled out correctly if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } List chosenList = new ArrayList(Arrays.asList(params .getStrings("selectedMembers"))); // Site id's of checked // sites String siteId = ""; if (!chosenList.isEmpty()) { if (chosenList.size() != 1) { addAlert(state, rb.getString("java.please")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } siteId = (String) chosenList.get(0); getReviseSite(state, siteId); state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // reset the paging info resetPaging(state); if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_PAGESIZE_SITESETUP, state .getAttribute(STATE_PAGESIZE)); } Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // when first entered Site Info, set the participant list size to // 200 as default state.setAttribute(STATE_PAGESIZE, new Integer(200)); // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } else { // restore the page size in site info tool state.setAttribute(STATE_PAGESIZE, h.get(siteId)); } } // doGet_site /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_reuse(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // create a new Site object based on selected Site object and put in // state // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_reuse /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doMenu_site_revise(RunData data) throws Exception { // called from chef_site-list.vm after a site has been selected from // list // get site as Site object, check SiteCreationStatus and SiteType of // site, put in state, and set STATE_TEMPLATE_INDEX correctly // set mode to state_mode_site_type SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doMenu_site_revise /** * doView_sites is called when "eventSubmit_doView_sites" is in the request * parameters */ public void doView_sites(RunData data) throws Exception { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.setAttribute(STATE_VIEW_SELECTED, params.getString("view")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); resetPaging(state); } // doView_sites /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doView(RunData data) throws Exception { // called from chef_site-list.vm with a select option to build query of // sites // // SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } // doView /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doSite_type(RunData data) { /* * for measuring how long it takes to load sections java.util.Date date = * new java.util.Date(); M_log.debug("***1. start preparing * section:"+date); */ SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); String type = StringUtil.trimToNull(params.getString("itemType")); int totalSteps = 0; if (type == null) { addAlert(state, rb.getString("java.select") + " "); } else { state.setAttribute(STATE_TYPE_SELECTED, type); setNewSiteType(state, type); if (type.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { User user = UserDirectoryService.getCurrentUser(); String currentUserId = user.getEid(); String userId = params.getString("userId"); if (userId == null || "".equals(userId)) { userId = currentUserId; } else { // implies we are trying to pick sections owned by other // users. Currently "select section by user" page only // take one user per sitte request - daisy's note 1 ArrayList<String> list = new ArrayList(); list.add(userId); state.setAttribute(STATE_CM_AUTHORIZER_LIST, list); } state.setAttribute(STATE_INSTRUCTOR_SELECTED, userId); String academicSessionEid = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(academicSessionEid); state.setAttribute(STATE_TERM_SELECTED, t); if (t != null) { List sections = prepareCourseAndSectionListing(userId, t .getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) { state.setAttribute(STATE_TERM_COURSE_LIST, sections); state.setAttribute(STATE_TEMPLATE_INDEX, "36"); state.setAttribute(STATE_AUTO_ADD, Boolean.TRUE); } else { state.removeAttribute(STATE_TERM_COURSE_LIST); Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue() && courseManagementIsImplemented()) { state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } } else { // not course type state.setAttribute(STATE_TEMPLATE_INDEX, "37"); totalSteps = 5; } } else if (type.equals("project")) { totalSteps = 4; state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else if (type.equals(SITE_TYPE_GRADTOOLS_STUDENT)) { // if a GradTools site use pre-defined site info and exclude // from public listing SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } User currentUser = UserDirectoryService.getCurrentUser(); siteInfo.title = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.description = rb.getString("java.gradsite") + " " + currentUser.getDisplayName(); siteInfo.short_description = rb.getString("java.grad") + " - " + currentUser.getId(); siteInfo.include = false; state.setAttribute(STATE_SITE_INFO, siteInfo); // skip directly to confirm creation of site state.setAttribute(STATE_TEMPLATE_INDEX, "42"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } // get the user selected template getSelectedTemplate(state, params, type); } if (state.getAttribute(SITE_CREATE_TOTAL_STEPS) == null) { state.setAttribute(SITE_CREATE_TOTAL_STEPS, new Integer(totalSteps)); } if (state.getAttribute(SITE_CREATE_CURRENT_STEP) == null) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(1)); } redirectToQuestionVM(state, type); } // doSite_type /** * see whether user selected any template * @param state * @param params * @param type */ private void getSelectedTemplate(SessionState state, ParameterParser params, String type) { String templateSiteId = params.getString("selectTemplate" + type); if (templateSiteId != null) { Site templateSite = null; try { templateSite = SiteService.getSite(templateSiteId); // save the template site in state state.setAttribute(STATE_TEMPLATE_SITE, templateSite); // the new site type is based on the template site setNewSiteType(state, templateSite.getType()); }catch (Exception e) { // should never happened, as the list of templates are generated // from existing sites M_log.warn(this + ".doSite_type" + e.getClass().getName(), e); } // grab site info from template SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // copy information from template site siteInfo.description = templateSite.getDescription(); siteInfo.short_description = templateSite.getShortDescription(); siteInfo.iconUrl = templateSite.getIconUrl(); siteInfo.infoUrl = templateSite.getInfoUrl(); siteInfo.joinable = templateSite.isJoinable(); siteInfo.joinerRole = templateSite.getJoinerRole(); //siteInfo.include = false; List<String> toolIdsSelected = new Vector<String>(); List pageList = templateSite.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); if (pageToolList != null && pageToolList.size() > 0) { Tool tConfig = ((ToolConfiguration) pageToolList.get(0)).getTool(); if (tConfig != null) { toolIdsSelected.add(tConfig.getId()); } } } } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolIdsSelected); state.setAttribute(STATE_SITE_INFO, siteInfo); } } /** * Depend on the setup question setting, redirect the site setup flow * @param state * @param type */ private void redirectToQuestionVM(SessionState state, String type) { // SAK-12912: check whether there is any setup question defined SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions(type); if (siteTypeQuestions != null) { List questionList = siteTypeQuestions.getQuestions(); if (questionList != null && questionList.size() > 0) { // there is at least one question defined for this type if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE, state.getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, "54"); } } } } /** * Determine whether the selected term is considered of "future term" * @param state * @param t */ private void isFutureTermSelected(SessionState state) { AcademicSession t = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); int weeks = 0; Calendar c = (Calendar) Calendar.getInstance().clone(); try { weeks = Integer .parseInt(ServerConfigurationService .getString( "roster.available.weeks.before.term.start", "0")); c.add(Calendar.DATE, weeks * 7); } catch (Exception ignore) { } if (t.getStartDate() != null && c.getTimeInMillis() < t.getStartDate().getTime()) { // if a future term is selected state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.TRUE); } else { state.setAttribute(STATE_FUTURE_TERM_SELECTED, Boolean.FALSE); } } public void doChange_user(RunData data) { doSite_type(data); } // doChange_user /** * */ private void removeSection(SessionState state, ParameterParser params) { // v2.4 - added by daisyf // RemoveSection - remove any selected course from a list of // provider courses // check if any section need to be removed removeAnyFlagedSection(state, params); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerChosenList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); collectNewSiteInfo(siteInfo, state, params, providerChosenList); // next step //state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } /** * dispatch to different functions based on the option value in the * parameter */ public void doManual_add_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("change") || option.equalsIgnoreCase("add")) { readCourseSectionInfo(state, params); String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); updateSiteInfo(params, state); if (option.equalsIgnoreCase("add")) { if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(uniqname.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String eid = StringUtil.trimToZero((String) iInstructors.next()); try { UserDirectoryService.getUserByEid(eid); } catch (UserNotDefinedException e) { addAlert( state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService .getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doManual_add_course: cannot find user with eid=" + eid, e); } } } } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } updateCurrentStep(state, true); } } else if (option.equalsIgnoreCase("back")) { doBack(data); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doManual_add_course /** * dispatch to different functions based on the option value in the * parameter */ public void doSite_information(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); if (option.equalsIgnoreCase("continue")) { doContinue(data); // if create based on template, skip the feature selection Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (getStateSite(state) == null) { doCancel_create(data); } else { doCancel(data); } } else if (option.equalsIgnoreCase("removeSection")) { // remove selected section removeSection(state, params); } } // doSite_information /** * read the input information of subject, course and section in the manual * site creation page */ private void readCourseSectionInfo(SessionState state, ParameterParser params) { String option = params.getString("option"); int oldNumber = 1; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { oldNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(); } // read the user input int validInputSites = 0; boolean validInput = true; List multiCourseInputs = new Vector(); for (int i = 0; i < oldNumber; i++) { List requiredFields = sectionFieldProvider.getRequiredFields(); List aCourseInputs = new Vector(); int emptyInputNum = 0; // iterate through all required fields for (int k = 0; k < requiredFields.size(); k++) { SectionField sectionField = (SectionField) requiredFields .get(k); String fieldLabel = sectionField.getLabelKey(); String fieldInput = StringUtil.trimToZero(params .getString(fieldLabel + i)); sectionField.setValue(fieldInput); aCourseInputs.add(sectionField); if (fieldInput.length() == 0) { // is this an empty String input? emptyInputNum++; } } // is any input invalid? if (emptyInputNum == 0) { // valid if all the inputs are not empty multiCourseInputs.add(validInputSites++, aCourseInputs); } else if (emptyInputNum == requiredFields.size()) { // ignore if all inputs are empty if (option.equalsIgnoreCase("change")) { multiCourseInputs.add(validInputSites++, aCourseInputs); } } else { // input invalid validInput = false; } } // how many more course/section to include in the site? if (option.equalsIgnoreCase("change")) { if (params.getString("number") != null) { int newNumber = Integer.parseInt(params.getString("number")); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer(oldNumber + newNumber)); List requiredFields = sectionFieldProvider.getRequiredFields(); for (int j = 0; j < newNumber; j++) { // add a new course input List aCourseInputs = new Vector(); // iterate through all required fields for (int m = 0; m < requiredFields.size(); m++) { aCourseInputs = sectionFieldProvider.getRequiredFields(); } multiCourseInputs.add(aCourseInputs); } } } state.setAttribute(STATE_MANUAL_ADD_COURSE_FIELDS, multiCourseInputs); if (!option.equalsIgnoreCase("change")) { if (!validInput || validInputSites == 0) { // not valid input addAlert(state, rb.getString("java.miss")); } // valid input, adjust the add course number state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( validInputSites)); } // set state attributes state.setAttribute(FORM_ADDITIONAL, StringUtil.trimToZero(params .getString("additional"))); SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // store the manually requested sections in one site property if ((providerCourseList == null || providerCourseList.size() == 0) && multiCourseInputs.size() > 0) { AcademicSession t = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); String sectionEid = sectionFieldProvider.getSectionEid(t.getEid(), (List) multiCourseInputs.get(0)); // default title String title = sectionFieldProvider.getSectionTitle(t.getEid(), (List) multiCourseInputs.get(0)); try { title = cms.getSection(sectionEid).getTitle(); } catch (IdNotFoundException e) { // cannot find section, use the default title M_log.warn(this + ":readCourseSectionInfo: cannot find section with eid=" + sectionEid); } siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // readCourseSectionInfo /** * * @param state * @param type */ private void setNewSiteType(SessionState state, String type) { state.setAttribute(STATE_SITE_TYPE, type); // start out with fresh site information SiteInfo siteInfo = new SiteInfo(); siteInfo.site_type = type; siteInfo.published = true; state.setAttribute(STATE_SITE_INFO, siteInfo); // set tool registration list setToolRegistrationList(state, type); } /** * Set the state variables for tool registration list basd on site type * @param state * @param type */ private void setToolRegistrationList(SessionState state, String type) { state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the tool id set which allows for multiple instances Set multipleToolIdSet = new HashSet(); Hashtable multipleToolConfiguration = new Hashtable<String, Hashtable<String, String>>(); // get registered tools list Set categories = new HashSet(); categories.add(type); Set toolRegistrations = ToolManager.findTools(categories, null); if ((toolRegistrations == null || toolRegistrations.size() == 0) && state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // use default site type and try getting tools again type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); categories.clear(); categories.add(type); toolRegistrations = ToolManager.findTools(categories, null); } List tools = new Vector(); SortedIterator i = new SortedIterator(toolRegistrations.iterator(), new ToolComparator()); for (; i.hasNext();) { // form a new Tool Tool tr = (Tool) i.next(); MyTool newTool = new MyTool(); newTool.title = tr.getTitle(); newTool.id = tr.getId(); newTool.description = tr.getDescription(); tools.add(newTool); String originalToolId = findOriginalToolId(state, tr.getId()); if (isMultipleInstancesAllowed(originalToolId)) { // of a tool which allows multiple instances multipleToolIdSet.add(tr.getId()); // get the configuration for multiple instance Hashtable<String, String> toolConfigurations = getMultiToolConfiguration(originalToolId); multipleToolConfiguration.put(tr.getId(), toolConfigurations); } } state.setAttribute(STATE_TOOL_REGISTRATION_LIST, tools); state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); } /** * Set the field on which to sort the list of students * */ public void doSort_roster(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the field on which to sort the student list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } } // doSort_roster /** * Set the field on which to sort the list of sites * */ public void doSort_sites(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // call this method at the start of a sort for proper paging resetPaging(state); // get the field on which to sort the site list ParameterParser params = data.getParameters(); String criterion = params.getString("criterion"); // current sorting sequence String asc = ""; if (!criterion.equals(state.getAttribute(SORTED_BY))) { state.setAttribute(SORTED_BY, criterion); asc = Boolean.TRUE.toString(); state.setAttribute(SORTED_ASC, asc); } else { // current sorting sequence asc = (String) state.getAttribute(SORTED_ASC); // toggle between the ascending and descending sequence if (asc.equals(Boolean.TRUE.toString())) { asc = Boolean.FALSE.toString(); } else { asc = Boolean.TRUE.toString(); } state.setAttribute(SORTED_ASC, asc); } state.setAttribute(SORTED_BY, criterion); } // doSort_sites /** * doContinue is called when "eventSubmit_doContinue" is in the request * parameters */ public void doContinue(RunData data) { // Put current form data in state and continue to the next template, // make any permanent changes SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); // Let actionForTemplate know to make any permanent changes before // continuing to the next template String direction = "continue"; String option = params.getString("option"); actionForTemplate(direction, index, params, state); if (state.getAttribute(STATE_MESSAGE) == null) { if (index == 36 && ("add").equals(option)) { // this is the Add extra Roster(s) case after a site is created state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } else if (params.getString("continue") != null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } } }// doContinue /** * handle with continue add new course site options * */ public void doContinue_new_course(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = data.getParameters().getString("option"); if (option.equals("continue")) { doContinue(data); // if create based on template, skip the feature selection Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equalsIgnoreCase("change")) { // change term String termId = params.getString("selectTerm"); AcademicSession t = cms.getAcademicSession(termId); state.setAttribute(STATE_TERM_SELECTED, t); isFutureTermSelected(state); } else if (option.equalsIgnoreCase("cancel_edit")) { // cancel doCancel(data); } else if (option.equalsIgnoreCase("add")) { isFutureTermSelected(state); // continue doContinue(data); } } // doContinue_new_course /** * doBack is called when "eventSubmit_doBack" is in the request parameters * Pass parameter to actionForTemplate to request action for backward * direction */ public void doBack(RunData data) { // Put current form data in state and return to the previous template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); int currentIndex = Integer.parseInt((String) state .getAttribute(STATE_TEMPLATE_INDEX)); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("back")); // Let actionForTemplate know not to make any permanent changes before // continuing to the next template String direction = "back"; actionForTemplate(direction, currentIndex, params, state); // remove the last template index from the list removeLastIndexInStateVisitedTemplates(state); }// doBack /** * doFinish is called when a site has enough information to be saved as an * unpublished site */ public void doFinish(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); addNewSite(params, state); Site site = getStateSite(state); Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite == null) { // normal site creation: add the features. saveFeatures(params, state, site); } else { // create based on template: skip add features, and copying all the contents from the tools in template site importToolContent(site.getId(), templateSite.getId(), site, true); } // for course sites String siteType = (String) state.getAttribute(STATE_SITE_TYPE); if (siteType != null && siteType.equalsIgnoreCase((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { String siteId = site.getId(); ResourcePropertiesEdit rp = site.getPropertiesEdit(); AcademicSession term = null; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } // update the site and related realm based on the rosters chosen or requested updateCourseSiteSections(state, siteId, rp, term); } // commit site commitSite(site); // transfer site content from template site if (templateSite != null) { sendTemplateUseNotification(site, UserDirectoryService.getCurrentUser(), templateSite); } String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); // now that the site exists, we can set the email alias when an // Email Archive tool has been selected setSiteAlias(state, siteId); // save user answers saveSiteSetupQuestionUserAnswers(state, siteId); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); // clean state variables cleanState(state); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(SiteHelper.SITE_CREATE_SITE_ID, site.getId()); state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); } state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } }// doFinish /** * set site mail alias * @param state * @param siteId */ private void setSiteAlias(SessionState state, String siteId) { List oTools = (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); if (oTools == null || (oTools!=null && !oTools.contains("sakai.mailbox"))) { // set alias only if the email archive tool is newly added String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { String channelReference = mailArchiveChannelReference(siteId); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { addAlert(state, rb.getString("java.addalias") + " "); M_log.warn(this + ".setSiteAlias: " + rb.getString("java.addalias") + ee); } } } } /** * save user answers * @param state * @param siteId */ private void saveSiteSetupQuestionUserAnswers(SessionState state, String siteId) { // update the database with user answers to SiteSetup questions if (state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER) != null) { Set<SiteSetupUserAnswer> userAnswers = (Set<SiteSetupUserAnswer>) state.getAttribute(STATE_SITE_SETUP_QUESTION_ANSWER); for(Iterator<SiteSetupUserAnswer> aIterator = userAnswers.iterator(); aIterator.hasNext();) { SiteSetupUserAnswer userAnswer = aIterator.next(); userAnswer.setSiteId(siteId); // save to db questionService.saveSiteSetupUserAnswer(userAnswer); } } } /** * Update course site and related realm based on the roster chosen or requested * @param state * @param siteId * @param rp * @param term */ private void updateCourseSiteSections(SessionState state, String siteId, ResourcePropertiesEdit rp, AcademicSession term) { // whether this is in the process of editing a site? boolean editingSite = ((String)state.getAttribute(STATE_SITE_MODE)).equals(SITE_MODE_SITEINFO)?true:false; List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); int manualAddNumber = 0; if (state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { manualAddNumber = ((Integer) state .getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)) .intValue(); } List<SectionObject> cmRequestedSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); List<SectionObject> cmAuthorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); String realm = SiteService.siteReference(siteId); if ((providerCourseList != null) && (providerCourseList.size() != 0)) { try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realm); String providerRealm = buildExternalRealm(siteId, state, providerCourseList, StringUtil.trimToNull(realmEdit.getProviderGroupId())); realmEdit.setProviderGroupId(providerRealm); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseSiteSections: IdUnusedException, not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.realm")); } // catch (AuthzPermissionException e) // { // M_log.warn(this + " PermissionException, user does not // have permission to edit AuthzGroup object."); // addAlert(state, rb.getString("java.notaccess")); // return; // } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".updateCourseSiteSections: " + rb.getString("java.problem"), e); } sendSiteNotification(state, providerCourseList); } if (manualAddNumber != 0) { // set the manual sections to the site property String manualSections = rp.getProperty(PROP_SITE_REQUEST_COURSE) != null?rp.getProperty(PROP_SITE_REQUEST_COURSE)+"+":""; // manualCourseInputs is a list of a list of SectionField List manualCourseInputs = (List) state .getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < manualAddNumber; j++) { manualSections = manualSections.concat( sectionFieldProvider.getSectionEid( term.getEid(), (List) manualCourseInputs.get(j))) .concat("+"); } // trim the trailing plus sign manualSections = trimTrailingString(manualSections, "+"); rp.addProperty(PROP_SITE_REQUEST_COURSE, manualSections); // send request sendSiteRequest(state, "new", manualAddNumber, manualCourseInputs, "manual"); } if (cmRequestedSections != null && cmRequestedSections.size() > 0 || state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null) { // set the cmRequest sections to the site property String cmRequestedSectionString = ""; if (!editingSite) { // but we want to feed a list of a list of String (input of // the required fields) for (int j = 0; j < cmRequestedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmRequestedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmRequestedSections.size(), cmRequestedSections, "cmRequest"); } else { cmRequestedSectionString = rp.getProperty(STATE_CM_REQUESTED_SECTIONS) != null ? (String) rp.getProperty(STATE_CM_REQUESTED_SECTIONS):""; // get the selected cm section if (state.getAttribute(STATE_CM_SELECTED_SECTIONS) != null ) { List<SectionObject> cmSelectedSections = (List) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmRequestedSectionString.length() != 0) { cmRequestedSectionString = cmRequestedSectionString.concat("+"); } for (int j = 0; j < cmSelectedSections.size(); j++) { cmRequestedSectionString = cmRequestedSectionString.concat(( cmSelectedSections.get(j)).eid).concat("+"); } // trim the trailing plus sign cmRequestedSectionString = trimTrailingString(cmRequestedSectionString, "+"); sendSiteRequest(state, "new", cmSelectedSections.size(), cmSelectedSections, "cmRequest"); } } // update site property if (cmRequestedSectionString.length() > 0) { rp.addProperty(STATE_CM_REQUESTED_SECTIONS, cmRequestedSectionString); } else { rp.removeProperty(STATE_CM_REQUESTED_SECTIONS); } } } /** * Trim the trailing occurance of specified string * @param cmRequestedSectionString * @param trailingString * @return */ private String trimTrailingString(String cmRequestedSectionString, String trailingString) { if (cmRequestedSectionString.endsWith(trailingString)) { cmRequestedSectionString = cmRequestedSectionString.substring(0, cmRequestedSectionString.lastIndexOf(trailingString)); } return cmRequestedSectionString; } /** * buildExternalRealm creates a site/realm id in one of three formats, for a * single section, for multiple sections of the same course, or for a * cross-listing having multiple courses * * @param sectionList * is a Vector of CourseListItem * @param id * The site id */ private String buildExternalRealm(String id, SessionState state, List<String> providerIdList, String existingProviderIdString) { String realm = SiteService.siteReference(id); if (!AuthzGroupService.allowUpdate(realm)) { addAlert(state, rb.getString("java.rosters")); return null; } List<String> allProviderIdList = new Vector<String>(); // see if we need to keep existing provider settings if (existingProviderIdString != null) { allProviderIdList.addAll(Arrays.asList(groupProvider.unpackId(existingProviderIdString))); } // update the list with newly added providers allProviderIdList.addAll(providerIdList); if (allProviderIdList == null || allProviderIdList.size() == 0) return null; String[] providers = new String[allProviderIdList.size()]; providers = (String[]) allProviderIdList.toArray(providers); String providerId = groupProvider.packId(providers); return providerId; } // buildExternalRealm /** * Notification sent when a course site needs to be set up by Support * */ private void sendSiteRequest(SessionState state, String request, int requestListSize, List requestFields, String fromContext) { User cUser = UserDirectoryService.getCurrentUser(); String sendEmailToRequestee = null; StringBuilder buf = new StringBuilder(); // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { String officialAccountName = ServerConfigurationService .getString("officialAccountName", ""); SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); AcademicSession term = null; boolean termExist = false; if (state.getAttribute(STATE_TERM_SELECTED) != null) { termExist = true; term = (AcademicSession) state .getAttribute(STATE_TERM_SELECTED); } String productionSiteName = ServerConfigurationService .getServerName(); String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String message_subject = NULL_STRING; String content = NULL_STRING; String sessionUserName = cUser.getDisplayName(); String additional = NULL_STRING; if (request.equals("new")) { additional = siteInfo.getAdditional(); } else { additional = (String) state.getAttribute(FORM_ADDITIONAL); } boolean isFutureTerm = false; if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && ((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { isFutureTerm = true; } // message subject if (termExist) { message_subject = rb.getString("java.sitereqfrom") + " " + sessionUserName + " " + rb.getString("java.for") + " " + term.getEid(); } else { message_subject = rb.getString("java.official") + " " + sessionUserName; } // there is no offical instructor for future term sites String requestId = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (!isFutureTerm) { // To site quest account - the instructor of record's if (requestId != null) { // in case of multiple instructors List instructors = new ArrayList(Arrays.asList(requestId.split(","))); for (Iterator iInstructors = instructors.iterator(); iInstructors.hasNext();) { String instructorId = (String) iInstructors.next(); try { User instructor = UserDirectoryService.getUserByEid(instructorId); rb.setContextLocale(rb.getLocale(instructor.getId())); // reset buf.setLength(0); to = instructor.getEmail(); from = requestEmail; headerTo = to; replyTo = requestEmail; buf.append(rb.getString("java.hello") + " \n\n"); buf.append(rb.getString("java.receiv") + " " + sessionUserName + ", "); buf.append(rb.getString("java.who") + "\n"); if (termExist) { buf.append(term.getTitle()); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append("\n" + rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id); buf.append("\n\n" + rb.getString("java.according") + " " + sessionUserName + " " + rb.getString("java.record")); buf.append(" " + rb.getString("java.canyou") + " " + sessionUserName + " " + rb.getString("java.assoc") + "\n\n"); buf.append(rb.getString("java.respond") + " " + sessionUserName + rb.getString("java.appoint") + "\n\n"); buf.append(rb.getString("java.thanks") + "\n"); buf.append(productionSiteName + " " + rb.getString("java.support")); content = buf.toString(); // send the email EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert back the local setting to default rb.setContextLocale(Locale.getDefault()); } catch (Exception e) { sendEmailToRequestee = sendEmailToRequestee == null?instructorId:sendEmailToRequestee.concat(", ").concat(instructorId); } } } } // To Support from = cUser.getEmail(); // set locale to system default rb.setContextLocale(Locale.getDefault()); to = requestEmail; headerTo = requestEmail; replyTo = cUser.getEmail(); buf.setLength(0); buf.append(rb.getString("java.to") + "\t\t" + productionSiteName + " " + rb.getString("java.supp") + "\n"); buf.append("\n" + rb.getString("java.from") + "\t" + sessionUserName + "\n"); if (request.equals("new")) { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitereq") + "\n"); } else { buf.append(rb.getString("java.subj") + "\t" + rb.getString("java.sitechreq") + "\n"); } buf.append(rb.getString("java.date") + "\t" + local_date + " " + local_time + "\n\n"); if (request.equals("new")) { buf.append(rb.getString("java.approval") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } else { buf.append(rb.getString("java.approval2") + " " + productionSiteName + " " + rb.getString("java.coursesite") + " "); } if (termExist) { buf.append(term.getTitle()); } if (requestListSize > 1) { buf.append(" " + rb.getString("java.forthese") + " " + requestListSize + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.forthis") + "\n\n"); } // requested sections if (fromContext.equals("manual")) { addRequestedSectionIntoNotification(state, requestFields, buf); } else if (fromContext.equals("cmRequest")) { addRequestedCMSectionIntoNotification(state, requestFields, buf); } buf.append(rb.getString("java.name") + "\t" + sessionUserName + " (" + officialAccountName + " " + cUser.getEid() + ")\n"); buf.append(rb.getString("java.email") + "\t" + replyTo + "\n\n"); buf.append(rb.getString("java.sitetitle") + "\t" + title + "\n"); buf.append(rb.getString("java.siteid") + "\t" + id + "\n"); buf.append(rb.getString("java.siteinstr") + "\n" + additional + "\n\n"); if (!isFutureTerm) { if (sendEmailToRequestee == null) { buf.append(rb.getString("java.authoriz") + " " + requestId + " " + rb.getString("java.asreq")); } else { buf.append(rb.getString("java.thesiteemail") + " " + sendEmailToRequestee + " " + rb.getString("java.asreq")); } } content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // To the Instructor from = requestEmail; to = cUser.getEmail(); // set the locale to individual receipient's setting rb.setContextLocale(rb.getLocale(cUser.getId())); headerTo = to; replyTo = to; buf.setLength(0); buf.append(rb.getString("java.isbeing") + " "); buf.append(rb.getString("java.meantime") + "\n\n"); buf.append(rb.getString("java.copy") + "\n\n"); buf.append(content); buf.append("\n" + rb.getString("java.wish") + " " + requestEmail); content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); // revert the locale to system default rb.setContextLocale(Locale.getDefault()); state.setAttribute(REQUEST_SENT, new Boolean(true)); } // if } // sendSiteRequest private void addRequestedSectionIntoNotification(SessionState state, List requestFields, StringBuilder buf) { // what are the required fields shown in the UI List requiredFields = state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS) != null ?(List) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS):new Vector(); for (int i = 0; i < requiredFields.size(); i++) { List requiredFieldList = (List) requestFields .get(i); for (int j = 0; j < requiredFieldList.size(); j++) { SectionField requiredField = (SectionField) requiredFieldList .get(j); buf.append(requiredField.getLabelKey() + "\t" + requiredField.getValue() + "\n"); } } } private void addRequestedCMSectionIntoNotification(SessionState state, List cmRequestedSections, StringBuilder buf) { // what are the required fields shown in the UI for (int i = 0; i < cmRequestedSections.size(); i++) { SectionObject so = (SectionObject) cmRequestedSections.get(i); buf.append(so.getTitle() + "(" + so.getEid() + ")" + so.getCategory() + "\n"); } } /** * Notification sent when a course site is set up automatcally * */ private void sendSiteNotification(SessionState state, List notifySites) { // get the request email from configuration String requestEmail = getSetupRequestEmailAddress(); if (requestEmail != null) { // send emails Site site = getStateSite(state); String id = site.getId(); String title = site.getTitle(); Time time = TimeService.newTime(); String local_time = time.toStringLocalTime(); String local_date = time.toStringLocalDate(); String term_name = ""; if (state.getAttribute(STATE_TERM_SELECTED) != null) { term_name = ((AcademicSession) state .getAttribute(STATE_TERM_SELECTED)).getEid(); } String message_subject = rb.getString("java.official") + " " + UserDirectoryService.getCurrentUser().getDisplayName() + " " + rb.getString("java.for") + " " + term_name; String from = NULL_STRING; String to = NULL_STRING; String headerTo = NULL_STRING; String replyTo = NULL_STRING; String sender = UserDirectoryService.getCurrentUser() .getDisplayName(); String userId = StringUtil.trimToZero(SessionManager .getCurrentSessionUserId()); try { userId = UserDirectoryService.getUserEid(userId); } catch (UserNotDefinedException e) { M_log.warn(this + ".sendSiteNotification:" + rb.getString("user.notdefined") + " " + userId, e); } // To Support //set local to default rb.setContextLocale(Locale.getDefault()); from = UserDirectoryService.getCurrentUser().getEmail(); to = requestEmail; headerTo = requestEmail; replyTo = UserDirectoryService.getCurrentUser().getEmail(); StringBuilder buf = new StringBuilder(); buf.append("\n" + rb.getString("java.fromwork") + " " + ServerConfigurationService.getServerName() + " " + rb.getString("java.supp") + ":\n\n"); buf.append(rb.getString("java.off") + " '" + title + "' (id " + id + "), " + rb.getString("java.wasset") + " "); buf.append(sender + " (" + userId + ", " + rb.getString("java.email2") + " " + replyTo + ") "); buf.append(rb.getString("java.on") + " " + local_date + " " + rb.getString("java.at") + " " + local_time + " "); buf.append(rb.getString("java.for") + " " + term_name + ", "); int nbr_sections = notifySites.size(); if (nbr_sections > 1) { buf.append(rb.getString("java.withrost") + " " + Integer.toString(nbr_sections) + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.withrost2") + "\n\n"); } for (int i = 0; i < nbr_sections; i++) { String course = (String) notifySites.get(i); buf.append(rb.getString("java.course2") + " " + course + "\n"); } String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if } // sendSiteNotification /** * doCancel called when "eventSubmit_doCancel_create" is in the request * parameters to c */ public void doCancel_create(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); if (SITE_MODE_HELPER.equals(state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_SITE_MODE, SITE_MODE_HELPER_DONE); state.setAttribute(SiteHelper.SITE_CREATE_CANCELLED, Boolean.TRUE); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel_create /** * doCancel called when "eventSubmit_doCancel" is in the request parameters * to c int index = Integer.valueOf(params.getString * ("templateIndex")).intValue(); */ public void doCancel(RunData data) { // Don't put current form data in state, just return to the previous // template SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); state.removeAttribute(STATE_MESSAGE); String currentIndex = (String) state.getAttribute(STATE_TEMPLATE_INDEX); String backIndex = params.getString("back"); state.setAttribute(STATE_TEMPLATE_INDEX, backIndex); if (currentIndex.equals("3")) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); state.removeAttribute(STATE_MESSAGE); removeEditToolState(state); } else if (currentIndex.equals("5")) { // remove related state variables removeAddParticipantContext(state); params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("13") || currentIndex.equals("14")) { // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_ICON_URL); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("15")) { params = data.getParameters(); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("cancelIndex")); removeEditToolState(state); } // htripath: added 'currentIndex.equals("45")' for import from file // cancel else if (currentIndex.equals("19") || currentIndex.equals("20") || currentIndex.equals("21") || currentIndex.equals("22") || currentIndex.equals("45")) { // from adding participant pages // remove related state variables removeAddParticipantContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else if (currentIndex.equals("3")) { // from adding class if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } else if (currentIndex.equals("27") || currentIndex.equals("28") || currentIndex.equals("59") || currentIndex.equals("60")) { // from import if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP)) { // worksite setup if (getStateSite(state) == null) { // in creating new site process state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // in editing site process state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } else if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITEINFO)) { // site info state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } else if (currentIndex.equals("26")) { if (((String) state.getAttribute(STATE_SITE_MODE)) .equalsIgnoreCase(SITE_MODE_SITESETUP) && getStateSite(state) == null) { // from creating site state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else { // from revising site state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } removeEditToolState(state); } else if (currentIndex.equals("37") || currentIndex.equals("44") || currentIndex.equals("53") || currentIndex.equals("36")) { // cancel back to edit class view state.removeAttribute(STATE_TERM_SELECTED); removeAddClassContext(state); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // if all fails to match else if (isTemplateVisited(state, "12")) { // go to site info list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } else { // go to WSetup list view state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } resetVisitedTemplateListToIndex(state, (String) state.getAttribute(STATE_TEMPLATE_INDEX)); } // doCancel /** * doMenu_customize is called when "eventSubmit_doBack" is in the request * parameters Pass parameter to actionForTemplate to request action for * backward direction */ public void doMenu_customize(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "15"); }// doMenu_customize /** * doBack_to_list cancels an outstanding site edit, cleans state and returns * to the site list * */ public void doBack_to_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); if (site != null) { Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); h.put(site.getId(), state.getAttribute(STATE_PAGESIZE)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } // restore the page size for Worksite setup tool if (state.getAttribute(STATE_PAGESIZE_SITESETUP) != null) { state.setAttribute(STATE_PAGESIZE, state .getAttribute(STATE_PAGESIZE_SITESETUP)); state.removeAttribute(STATE_PAGESIZE_SITESETUP); } cleanState(state); setupFormNamesAndConstants(state); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_list /** * reset to sublist with index as the last item * @param state * @param index */ private void resetVisitedTemplateListToIndex(SessionState state, String index) { if (state.getAttribute(STATE_VISITED_TEMPLATES) != null) { List<String> l = (List<String>) state.getAttribute(STATE_VISITED_TEMPLATES); if (l != null && l.indexOf(index) >=0 && l.indexOf(index) < l.size()) { state.setAttribute(STATE_VISITED_TEMPLATES, l.subList(0, l.indexOf(index)+1)); } } } /** * do called when "eventSubmit_do" is in the request parameters to c */ public void doAdd_custom_link(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); if ((params.getString("name")) == null || (params.getString("url") == null)) { Tool tr = ToolManager.getTool("sakai.iframe"); Site site = getStateSite(state); SitePage page = site.addPage(); page.setTitle(params.getString("name")); // the visible label on // the tool menu ToolConfiguration tool = page.addTool(); tool.setTool("sakai.iframe", tr); tool.setTitle(params.getString("name")); commitSite(site); } else { addAlert(state, rb.getString("java.reqmiss")); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("templateIndex")); } } // doAdd_custom_link /** * toolId might be of form original tool id concatenated with number * find whether there is an counterpart in the the multipleToolIdSet * @param state * @param toolId * @return */ private String findOriginalToolId(SessionState state, String toolId) { // treat home tool differently if (toolId.equals(HOME_TOOL_ID)) { return toolId; } else { Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationList = ToolManager.findTools(categories, null); String rv = null; if (toolRegistrationList != null) { for (Iterator i=toolRegistrationList.iterator(); rv == null && i.hasNext();) { Tool tool = (Tool) i.next(); String tId = tool.getId(); rv = originalToolId(toolId, tId); } } return rv; } } private String originalToolId(String toolId, String toolRegistrationId) { String rv = null; if (toolId.indexOf(toolRegistrationId) != -1) { // the multiple tool id format is of TOOL_IDx, where x is an intger >= 1 if (toolId.endsWith(toolRegistrationId)) { rv = toolRegistrationId; } else { String suffix = toolId.substring(toolId.indexOf(toolRegistrationId) + toolRegistrationId.length()); try { Integer.parseInt(suffix); rv = toolRegistrationId; } catch (Exception e) { // not the right tool id M_log.debug(this + ".findOriginalToolId not matchign tool id = " + toolRegistrationId + " original tool id=" + toolId + e.getMessage(), e); } } } return rv; } /** * Read from tool registration whether multiple registration is allowed for this tool * @param toolId * @return */ private boolean isMultipleInstancesAllowed(String toolId) { Tool tool = ToolManager.getTool(toolId); if (tool != null) { Properties tProperties = tool.getRegisteredConfig(); return (tProperties.containsKey("allowMultipleInstances") && tProperties.getProperty("allowMultipleInstances").equalsIgnoreCase(Boolean.TRUE.toString()))?true:false; } return false; } private Hashtable<String, String> getMultiToolConfiguration(String toolId) { Hashtable<String, String> rv = new Hashtable<String, String>(); // read from configuration file ArrayList<String> attributes=new ArrayList<String>(); String attributesConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE + toolId); if ( attributesConfig != null && attributesConfig.length() > 0) { attributes = new ArrayList(Arrays.asList(attributesConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default setting for News tool attributes.add("channel-url"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool attributes.add("source"); } } ArrayList<String> defaultValues =new ArrayList<String>(); String defaultValueConfig = ServerConfigurationService.getString(CONFIG_TOOL_ATTRIBUTE_DEFAULT + toolId); if ( defaultValueConfig != null && defaultValueConfig.length() > 0) { defaultValues = new ArrayList(Arrays.asList(defaultValueConfig.split(","))); } else { if (toolId.equals("sakai.news")) { // default value defaultValues.add("http://www.sakaiproject.org/news-rss-feed"); } else if (toolId.equals("sakai.iframe")) { // default setting for Web Content tool defaultValues.add("http://"); } } if (attributes != null && attributes.size() > 0) { for (int i = 0; i<attributes.size();i++) { rv.put(attributes.get(i), defaultValues.get(i)); } } return rv; } /** * doSave_revised_features */ public void doSave_revised_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site site = getStateSite(state); saveFeatures(params, state, site); String id = site.getId(); // now that the site exists, we can set the email alias when an Email // Archive tool has been selected setSiteAlias(state, id); if (state.getAttribute(STATE_MESSAGE) == null) { // clean state variables state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); state.setAttribute(STATE_SITE_INSTANCE_ID, id); state.setAttribute(STATE_TEMPLATE_INDEX, params .getString("continue")); } // refresh the whole page scheduleTopRefresh(); } // doSave_revised_features /** * doMenu_add_participant */ public void doMenu_add_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // doMenu_add_participant /** * doMenu_siteInfo_addParticipant */ public void doMenu_siteInfo_addParticipant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } } // doMenu_siteInfo_addParticipant /** * doMenu_siteInfo_cancel_access */ public void doMenu_siteInfo_cancel_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // doMenu_siteInfo_cancel_access /** * doMenu_siteInfo_importSelection */ public void doMenu_siteInfo_importSelection(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "58"); } } // doMenu_siteInfo_importSelection /** * doMenu_siteInfo_import */ public void doMenu_siteInfo_import(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "28"); } } // doMenu_siteInfo_import public void doMenu_siteInfo_importMigrate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "59"); } } // doMenu_siteInfo_importMigrate /** * doMenu_siteInfo_editClass */ public void doMenu_siteInfo_editClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(STATE_TEMPLATE_INDEX, "43"); } // doMenu_siteInfo_editClass /** * doMenu_siteInfo_addClass */ public void doMenu_siteInfo_addClass(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site site = getStateSite(state); String termEid = site.getProperties().getProperty(PROP_SITE_TERM_EID); if (termEid == null) { // no term eid stored, need to get term eid from the term title String termTitle = site.getProperties().getProperty(PROP_SITE_TERM); List asList = cms.getAcademicSessions(); if (termTitle != null && asList != null) { boolean found = false; for (int i = 0; i<asList.size() && !found; i++) { AcademicSession as = (AcademicSession) asList.get(i); if (as.getTitle().equals(termTitle)) { termEid = as.getEid(); site.getPropertiesEdit().addProperty(PROP_SITE_TERM_EID, termEid); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + site.getId(), e); } found=true; } } } } state.setAttribute(STATE_TERM_SELECTED, cms.getAcademicSession(termEid)); try { List sections = prepareCourseAndSectionListing(UserDirectoryService.getCurrentUser().getEid(), cms.getAcademicSession(termEid).getEid(), state); isFutureTermSelected(state); if (sections != null && sections.size() > 0) state.setAttribute(STATE_TERM_COURSE_LIST, sections); } catch (Exception e) { M_log.warn(this + ".doMenu_siteinfo_addClass: " + e.getMessage() + termEid, e); } state.setAttribute(STATE_TEMPLATE_INDEX, "36"); } // doMenu_siteInfo_addClass /** * doMenu_siteInfo_duplicate */ public void doMenu_siteInfo_duplicate(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "29"); } } // doMenu_siteInfo_import /** * doMenu_edit_site_info * */ public void doMenu_edit_site_info(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourceProperties siteProperties = Site.getProperties(); state.setAttribute(FORM_SITEINFO_TITLE, Site.getTitle()); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (site_type != null && !site_type.equalsIgnoreCase("myworkspace")) { state.setAttribute(FORM_SITEINFO_INCLUDE, Boolean.valueOf( Site.isPubView()).toString()); } state.setAttribute(FORM_SITEINFO_DESCRIPTION, Site.getDescription()); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, Site .getShortDescription()); state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); if (Site.getIconUrl() != null) { state.setAttribute(FORM_SITEINFO_SKIN, Site.getIconUrl()); } // site contact information String contactName = siteProperties.getProperty(PROP_SITE_CONTACT_NAME); String contactEmail = siteProperties .getProperty(PROP_SITE_CONTACT_EMAIL); if (contactName == null && contactEmail == null) { String creatorId = siteProperties .getProperty(ResourceProperties.PROP_CREATOR); try { User u = UserDirectoryService.getUser(creatorId); String email = u.getEmail(); if (email != null) { contactEmail = u.getEmail(); } contactName = u.getDisplayName(); } catch (UserNotDefinedException e) { } } if (contactName != null) { state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); } if (contactEmail != null) { state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "13"); } } // doMenu_edit_site_info /** * doMenu_edit_site_tools * */ public void doMenu_edit_site_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); // get the tools siteToolsIntoState(state); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "3"); } } // doMenu_edit_site_tools /** * doMenu_edit_site_access * */ public void doMenu_edit_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doMenu_edit_site_access /** * Back to worksite setup's list view * */ public void doBack_to_site_list(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SITE_TYPE); state.removeAttribute(STATE_SITE_INSTANCE_ID); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // reset resetVisitedTemplateListToIndex(state, "0"); } // doBack_to_site_list /** * doSave_site_info * */ public void doSave_siteInfo(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site Site = getStateSite(state); ResourcePropertiesEdit siteProperties = Site.getPropertiesEdit(); String site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (siteTitleEditable(state, site_type)) { Site.setTitle((String) state.getAttribute(FORM_SITEINFO_TITLE)); } Site.setDescription((String) state .getAttribute(FORM_SITEINFO_DESCRIPTION)); Site.setShortDescription((String) state .getAttribute(FORM_SITEINFO_SHORT_DESCRIPTION)); if (site_type != null) { if (site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // set icon url for course String skin = (String) state.getAttribute(FORM_SITEINFO_SKIN); setAppearance(state, Site, skin); } else { // set icon url for others String iconUrl = (String) state .getAttribute(FORM_SITEINFO_ICON_URL); Site.setIconUrl(iconUrl); } } // site contact information String contactName = (String) state .getAttribute(FORM_SITEINFO_CONTACT_NAME); if (contactName != null) { siteProperties.addProperty(PROP_SITE_CONTACT_NAME, contactName); } String contactEmail = (String) state .getAttribute(FORM_SITEINFO_CONTACT_EMAIL); if (contactEmail != null) { siteProperties.addProperty(PROP_SITE_CONTACT_EMAIL, contactEmail); } if (state.getAttribute(STATE_MESSAGE) == null) { try { SiteService.save(Site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // clean state attributes state.removeAttribute(FORM_SITEINFO_TITLE); state.removeAttribute(FORM_SITEINFO_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SHORT_DESCRIPTION); state.removeAttribute(FORM_SITEINFO_SKIN); state.removeAttribute(FORM_SITEINFO_INCLUDE); state.removeAttribute(FORM_SITEINFO_CONTACT_NAME); state.removeAttribute(FORM_SITEINFO_CONTACT_EMAIL); // back to site info view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // refresh the whole page scheduleTopRefresh(); } } // doSave_siteInfo /** * Check to see whether the site's title is editable or not * @param state * @param site_type * @return */ private boolean siteTitleEditable(SessionState state, String site_type) { return site_type != null && (!site_type.equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE)) || (state.getAttribute(TITLE_EDITABLE_SITE_TYPE) != null && ((List) state.getAttribute(TITLE_EDITABLE_SITE_TYPE)).contains(site_type))); } /** * init * */ private void init(VelocityPortlet portlet, RunData data, SessionState state) { state.setAttribute(STATE_ACTION, "SiteAction"); setupFormNamesAndConstants(state); if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) { state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable()); } if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); } else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))){ String siteId = ToolManager.getCurrentPlacement().getContext(); getReviseSite(state, siteId); Hashtable h = (Hashtable) state .getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // update h.put(siteId, new Integer(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); state.setAttribute(STATE_PAGESIZE, new Integer(200)); } } if (state.getAttribute(STATE_SITE_TYPES) == null) { PortletConfig config = portlet.getPortletConfig(); // all site types (SITE_DEFAULT_LIST overrides tool config) String t = StringUtil.trimToNull(SITE_DEFAULT_LIST); if ( t == null ) t = StringUtil.trimToNull(config.getInitParameter("siteTypes")); if (t != null) { List types = new ArrayList(Arrays.asList(t.split(","))); if (cms == null) { // if there is no CourseManagementService, disable the process of creating course site String courseType = ServerConfigurationService.getString("courseSiteType", (String) state.getAttribute(STATE_COURSE_SITE_TYPE)); types.remove(courseType); } state.setAttribute(STATE_SITE_TYPES, types); } else { t = (String)state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES); if (t != null) { state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays .asList(t.split(",")))); } else { state.setAttribute(STATE_SITE_TYPES, new Vector()); } } } /*<p> * This is a change related to SAK-12912 * initialize the question list */ if (!questionService.hasAnySiteTypeQuestions()) { if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable()) { SiteSetupQuestionFileParser.updateConfig(); } } // show UI for adding non-official participant(s) or not // if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them. // the setting defaults to be true if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null) { state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true")); } if (state.getAttribute(STATE_VISITED_TEMPLATES) == null) { List<String> templates = new Vector<String>(); if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) { templates.add("0"); // the default page of WSetup tool } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { templates.add("12");// the default page of Site Info tool } state.setAttribute(STATE_VISITED_TEMPLATES, templates); } } // init public void doNavigate_to_site(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteId = StringUtil.trimToNull(data.getParameters().getString( "option")); if (siteId != null) { getReviseSite(state, siteId); } else { doBack_to_list(data); } } // doNavigate_to_site /** * Get site information for revise screen */ private void getReviseSite(SessionState state, String siteId) { if (state.getAttribute(STATE_SELECTED_USER_LIST) == null) { state.setAttribute(STATE_SELECTED_USER_LIST, new Vector()); } List sites = (List) state.getAttribute(STATE_SITES); try { Site site = SiteService.getSite(siteId); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); if (sites != null) { int pos = -1; for (int index = 0; index < sites.size() && pos == -1; index++) { if (((Site) sites.get(index)).getId().equals(siteId)) { pos = index; } } // has any previous site in the list? if (pos > 0) { state.setAttribute(STATE_PREV_SITE, sites.get(pos - 1)); } else { state.removeAttribute(STATE_PREV_SITE); } // has any next site in the list? if (pos < sites.size() - 1) { state.setAttribute(STATE_NEXT_SITE, sites.get(pos + 1)); } else { state.removeAttribute(STATE_NEXT_SITE); } } String type = site.getType(); if (type == null) { if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } state.setAttribute(STATE_SITE_TYPE, type); } catch (IdUnusedException e) { M_log.warn(this + ".getReviseSite: " + e.toString() + " site id = " + siteId, e); } // one site has been selected state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } // getReviseSite /** * doUpdate_participant * */ public void doUpdate_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); Site s = getStateSite(state); String realmId = SiteService.siteReference(s.getId()); if (AuthzGroupService.allowUpdate(realmId) || SiteService.allowUpdateSiteMembership(s.getId())) { try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId); // does the site has maintain type user(s) before updating // participants? String maintainRoleString = realmEdit.getMaintainRole(); boolean hadMaintainUser = !realmEdit.getUsersHasRole( maintainRoleString).isEmpty(); // update participant roles List participants = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); // remove all roles and then add back those that were checked for (int i = 0; i < participants.size(); i++) { String id = null; // added participant Participant participant = (Participant) participants.get(i); id = participant.getUniqname(); if (id != null) { // get the newly assigned role String inputRoleField = "role" + id; String roleId = params.getString(inputRoleField); // only change roles when they are different than before if (roleId != null) { // get the grant active status boolean activeGrant = true; String activeGrantField = "activeGrant" + id; if (params.getString(activeGrantField) != null) { activeGrant = params .getString(activeGrantField) .equalsIgnoreCase("true") ? true : false; } boolean fromProvider = !participant.isRemoveable(); if (fromProvider && !roleId.equals(participant.getRole())) { fromProvider = false; } realmEdit.addMember(id, roleId, activeGrant, fromProvider); } } } // remove selected users if (params.getStrings("selectedUser") != null) { List removals = new ArrayList(Arrays.asList(params .getStrings("selectedUser"))); state.setAttribute(STATE_SELECTED_USER_LIST, removals); for (int i = 0; i < removals.size(); i++) { String rId = (String) removals.get(i); try { User user = UserDirectoryService.getUser(rId); realmEdit.removeMember(user.getId()); } catch (UserNotDefinedException e) { M_log.warn(this + ".doUpdate_participant: IdUnusedException " + rId + ". ", e); } } } if (hadMaintainUser && realmEdit.getUsersHasRole(maintainRoleString) .isEmpty()) { // if after update, the "had maintain type user" status // changed, show alert message and don't save the update addAlert(state, rb .getString("sitegen.siteinfolist.nomaintainuser") + maintainRoleString + "."); } else { AuthzGroupService.save(realmEdit); // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); // then update all related group realms for the role doUpdate_related_group_participants(s, realmId); } } catch (GroupNotDefinedException e) { addAlert(state, rb.getString("java.problem2")); M_log.warn(this + ".doUpdate_participant: IdUnusedException " + s.getTitle() + "(" + realmId + "). ", e); } catch (AuthzPermissionException e) { addAlert(state, rb.getString("java.changeroles")); M_log.warn(this + ".doUpdate_participant: PermissionException " + s.getTitle() + "(" + realmId + "). ", e); } } } // doUpdate_participant /** * update realted group realm setting according to parent site realm changes * @param s * @param realmId */ private void doUpdate_related_group_participants(Site s, String realmId) { Collection groups = s.getGroups(); if (groups != null) { try { for (Iterator iGroups = groups.iterator(); iGroups.hasNext();) { Group g = (Group) iGroups.next(); try { Set gMembers = g.getMembers(); for (Iterator iGMembers = gMembers.iterator(); iGMembers.hasNext();) { Member gMember = (Member) iGMembers.next(); String gMemberId = gMember.getUserId(); Member siteMember = s.getMember(gMemberId); if ( siteMember == null) { // user has been removed from the site g.removeMember(gMemberId); } else { // if there is a difference between the role setting, remove the entry from group and add it back with correct role, all are marked "not provided" if (!g.getUserRole(gMemberId).equals(siteMember.getRole())) { g.removeMember(gMemberId); g.addMember(gMemberId, siteMember.getRole().getId(), siteMember.isActive(), false); } } } // post event about the participant update EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_GROUP_MEMBERSHIP, g.getId(),false)); } catch (Exception ee) { M_log.warn(this + ".doUpdate_related_group_participants: " + ee.getMessage() + g.getId(), ee); } } // commit, save the site SiteService.save(s); } catch (Exception e) { M_log.warn(this + ".doUpdate_related_group_participants: " + e.getMessage() + s.getId(), e); } } } /** * doUpdate_site_access * */ public void doUpdate_site_access(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site sEdit = getStateSite(state); ParameterParser params = data.getParameters(); String publishUnpublish = params.getString("publishunpublish"); String include = params.getString("include"); String joinable = params.getString("joinable"); if (sEdit != null) { // editing existing site // publish site or not if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { sEdit.setPublished(true); } else { sEdit.setPublished(false); } // site public choice if (include != null) { // if there is pubview input, use it sEdit.setPubView(include.equalsIgnoreCase("true") ? true : false); } else if (state.getAttribute(STATE_SITE_TYPE) != null) { String type = (String) state.getAttribute(STATE_SITE_TYPE); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public sEdit.setPubView(true); } else if (privateSiteTypes.contains(type)) { // site are always private sEdit.setPubView(false); } } else { sEdit.setPubView(false); } // publish site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { state.setAttribute(STATE_JOINABLE, Boolean.TRUE); sEdit.setJoinable(true); String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { state.setAttribute(STATE_JOINERROLE, joinerRole); sEdit.setJoinerRole(joinerRole); } else { state.setAttribute(STATE_JOINERROLE, ""); addAlert(state, rb.getString("java.joinsite") + " "); } } else { state.setAttribute(STATE_JOINABLE, Boolean.FALSE); state.removeAttribute(STATE_JOINERROLE); sEdit.setJoinable(false); sEdit.setJoinerRole(null); } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(sEdit); state.setAttribute(STATE_TEMPLATE_INDEX, "12"); // TODO: hard coding this frame id is fragile, portal dependent, // and needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.removeAttribute(STATE_JOINABLE); state.removeAttribute(STATE_JOINERROLE); } } else { // adding new site if (state.getAttribute(STATE_SITE_INFO) != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); if (publishUnpublish != null && publishUnpublish.equalsIgnoreCase("publish")) { siteInfo.published = true; } else { siteInfo.published = false; } // site public choice if (include != null) { siteInfo.include = include.equalsIgnoreCase("true") ? true : false; } else if (StringUtil.trimToNull(siteInfo.site_type) != null) { String type = StringUtil.trimToNull(siteInfo.site_type); List publicSiteTypes = (List) state .getAttribute(STATE_PUBLIC_SITE_TYPES); List privateSiteTypes = (List) state .getAttribute(STATE_PRIVATE_SITE_TYPES); if (publicSiteTypes.contains(type)) { // sites are always public siteInfo.include = true; } else if (privateSiteTypes.contains(type)) { // site are always private siteInfo.include = false; } } else { siteInfo.include = false; } // joinable site or not if (joinable != null && joinable.equalsIgnoreCase("true")) { siteInfo.joinable = true; String joinerRole = StringUtil.trimToNull(params .getString("joinerRole")); if (joinerRole != null) { siteInfo.joinerRole = joinerRole; } else { addAlert(state, rb.getString("java.joinsite") + " "); } } else { siteInfo.joinable = false; siteInfo.joinerRole = null; } state.setAttribute(STATE_SITE_INFO, siteInfo); } if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "10"); updateCurrentStep(state, true); } } } // doUpdate_site_access /** * /* Actions for vm templates under the "chef_site" root. This method is * called by doContinue. Each template has a hidden field with the value of * template-index that becomes the value of index for the switch statement * here. Some cases not implemented. */ private void actionForTemplate(String direction, int index, ParameterParser params, SessionState state) { // Continue - make any permanent changes, Back - keep any data entered // on the form boolean forward = direction.equals("continue") ? true : false; SiteInfo siteInfo = new SiteInfo(); switch (index) { case 0: /* * actionForTemplate chef_site-list.vm * */ break; case 1: /* * actionForTemplate chef_site-type.vm * */ break; case 2: /* * actionForTemplate chef_site-newSiteInformation.vm * */ if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // defaults to be true siteInfo.include = true; state.setAttribute(STATE_SITE_INFO, siteInfo); updateSiteInfo(params, state); // alerts after clicking Continue but not Back if (forward) { if (StringUtil.trimToNull(siteInfo.title) == null) { addAlert(state, rb.getString("java.reqfields")); state.setAttribute(STATE_TEMPLATE_INDEX, "2"); return; } } else { // removing previously selected template site state.removeAttribute(STATE_TEMPLATE_SITE); } updateSiteAttributes(state); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 3: /* * actionForTemplate chef_site-editFeatures.vm * */ if (forward) { // editing existing site or creating a new one? Site site = getStateSite(state); getFeatures(params, state, site==null?"18":"15"); if (state.getAttribute(STATE_MESSAGE) == null && site==null) { updateCurrentStep(state, forward); } } break; case 5: /* * actionForTemplate chef_site-addParticipant.vm * */ if (forward) { checkAddParticipant(params, state); } else { // remove related state variables removeAddParticipantContext(state); } break; case 8: /* * actionForTemplate chef_site-siteDeleteConfirm.vm * */ break; case 10: /* * actionForTemplate chef_site-newSiteConfirm.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } break; case 12: /* * actionForTemplate chef_site_siteInfo-list.vm * */ break; case 13: /* * actionForTemplate chef_site_siteInfo-editInfo.vm * */ if (forward) { Site Site = getStateSite(state); if (siteTitleEditable(state, Site.getType())) { // site titel is editable and could not be null String title = StringUtil.trimToNull(params .getString("title")); state.setAttribute(FORM_SITEINFO_TITLE, title); if (title == null) { addAlert(state, rb.getString("java.specify") + " "); } } String description = StringUtil.trimToNull(params .getString("description")); StringBuilder alertMsg = new StringBuilder(); state.setAttribute(FORM_SITEINFO_DESCRIPTION, FormattedText.processFormattedText(description, alertMsg)); String short_description = StringUtil.trimToNull(params .getString("short_description")); state.setAttribute(FORM_SITEINFO_SHORT_DESCRIPTION, short_description); String skin = params.getString("skin"); if (skin != null) { // if there is a skin input for course site skin = StringUtil.trimToNull(skin); state.setAttribute(FORM_SITEINFO_SKIN, skin); } else { // if ther is a icon input for non-course site String icon = StringUtil.trimToNull(params .getString("icon")); if (icon != null) { if (icon.endsWith(PROTOCOL_STRING)) { addAlert(state, rb.getString("alert.protocol")); } state.setAttribute(FORM_SITEINFO_ICON_URL, icon); } else { state.removeAttribute(FORM_SITEINFO_ICON_URL); } } // site contact information String contactName = StringUtil.trimToZero(params .getString("siteContactName")); state.setAttribute(FORM_SITEINFO_CONTACT_NAME, contactName); String email = StringUtil.trimToZero(params .getString("siteContactEmail")); String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } state.setAttribute(FORM_SITEINFO_CONTACT_EMAIL, email); if (state.getAttribute(STATE_MESSAGE) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "14"); } } break; case 14: /* * actionForTemplate chef_site_siteInfo-editInfoConfirm.vm * */ break; case 15: /* * actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm * */ break; case 18: /* * actionForTemplate chef_siteInfo-editAccess.vm * */ if (!forward) { if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, false); } } case 19: /* * actionForTemplate chef_site-addParticipant-sameRole.vm * */ String roleId = StringUtil.trimToNull(params .getString("selectRole")); if (roleId == null && forward) { addAlert(state, rb.getString("java.pleasesel") + " "); } else { state.setAttribute("form_selectedRole", params .getString("selectRole")); } break; case 20: /* * actionForTemplate chef_site-addParticipant-differentRole.vm * */ if (forward) { getSelectedRoles(state, params, STATE_ADD_PARTICIPANTS); } break; case 21: /* * actionForTemplate chef_site-addParticipant-notification.vm ' */ if (params.getString("notify") == null) { if (forward) addAlert(state, rb.getString("java.pleasechoice") + " "); } else { state.setAttribute("form_selectedNotify", new Boolean(params .getString("notify"))); } break; case 22: /* * actionForTemplate chef_site-addParticipant-confirm.vm * */ break; case 24: /* * actionForTemplate * chef_site-siteInfo-editAccess-globalAccess-confirm.vm * */ break; case 26: /* * actionForTemplate chef_site-modifyENW.vm * */ updateSelectedToolList(state, params, forward); if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 27: /* * actionForTemplate chef_site-importSites.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); importToolIntoSite(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 60: /* * actionForTemplate chef_site-importSitesMigrate.vm * */ if (forward) { Site existingSite = getStateSite(state); if (existingSite != null) { // revising a existing site's tool if (select_import_tools(params, state)) { Hashtable importTools = (Hashtable) state .getAttribute(STATE_IMPORT_SITE_TOOL); List selectedTools = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // Remove all old contents before importing contents from new site importToolIntoSiteMigrate(selectedTools, importTools, existingSite); existingSite = getStateSite(state); // refresh site for // WC and News if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(existingSite); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); } } else { // show alert and remain in current page addAlert(state, rb.getString("java.toimporttool")); } } else { // new site select_import_tools(params, state); } } else { // read form input about import tools select_import_tools(params, state); } if (state.getAttribute(STATE_MESSAGE) == null) { updateCurrentStep(state, forward); } break; case 28: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 58: /* * actionForTemplate chef_siteinfo-importSelection.vm * */ break; case 59: /* * actionForTemplate chef_siteinfo-import.vm * */ if (forward) { if (params.getStrings("importSites") == null) { addAlert(state, rb.getString("java.toimport") + " "); state.removeAttribute(STATE_IMPORT_SITES); } else { List importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); Hashtable sites = new Hashtable(); for (index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); sites.put(s, new Vector()); } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } break; case 29: /* * actionForTemplate chef_siteinfo-duplicate.vm * */ if (forward) { if (state.getAttribute(SITE_DUPLICATED) == null) { if (StringUtil.trimToNull(params.getString("title")) == null) { addAlert(state, rb.getString("java.dupli") + " "); } else { String title = params.getString("title"); state.setAttribute(SITE_DUPLICATED_NAME, title); String nSiteId = IdManager.createUuid(); try { String oSiteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); Site site = SiteService.addSite(nSiteId, getStateSite(state)); // get the new site icon url if (site.getIconUrl() != null) { site.setIconUrl(transferSiteResource(oSiteId, nSiteId, site.getIconUrl())); } try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } try { site = SiteService.getSite(nSiteId); // set title site.setTitle(title); // import tool content importToolContent(nSiteId, oSiteId, site, false); } catch (Exception e1) { // if goes here, IdService // or SiteService has done // something wrong. M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + e1 + ":" + nSiteId + "when duplicating site", e1); } if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // for course site, need to // read in the input for // term information String termId = StringUtil.trimToNull(params .getString("selectTerm")); if (termId != null) { AcademicSession term = cms.getAcademicSession(termId); if (term != null) { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(PROP_SITE_TERM, term.getTitle()); rp.addProperty(PROP_SITE_TERM_EID, term.getEid()); } else { M_log.warn("termId=" + termId + " not found"); } } } try { SiteService.save(site); if (site.getType().equals((String) state.getAttribute(STATE_COURSE_SITE_TYPE))) { // also remove the provider id attribute if any String realm = SiteService.siteReference(site.getId()); try { AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realm); realmEdit.setProviderGroupId(null); AuthzGroupService.save(realmEdit); } catch (GroupNotDefinedException e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "+ realm, e); addAlert(state, rb.getString("java.realm")); } catch (Exception e) { addAlert(state, this + rb.getString("java.problem")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.problem"), e); } } } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } // TODO: hard coding this frame id // is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); state.setAttribute(SITE_DUPLICATED, Boolean.TRUE); } catch (IdInvalidException e) { addAlert(state, rb.getString("java.siteinval")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.siteinval") + " site id = " + nSiteId, e); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitebeenused")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.sitebeenused") + " site id = " + nSiteId, e); } catch (PermissionException e) { addAlert(state, rb.getString("java.allowcreate")); M_log.warn(this + ".actionForTemplate chef_siteinfo-duplicate: " + rb.getString("java.allowcreate") + " site id = " + nSiteId, e); } } } if (state.getAttribute(STATE_MESSAGE) == null) { // site duplication confirmed state.removeAttribute(SITE_DUPLICATED); state.removeAttribute(SITE_DUPLICATED_NAME); // return to the list view state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } } break; case 33: break; case 36: /* * actionForTemplate chef_site-newSiteCourse.vm */ if (forward) { List providerChosenList = new Vector(); if (params.getStrings("providerCourseAdd") == null) { state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (params.getString("manualAdds") == null) { addAlert(state, rb.getString("java.manual") + " "); } } if (state.getAttribute(STATE_MESSAGE) == null) { // The list of courses selected from provider listing if (params.getStrings("providerCourseAdd") != null) { providerChosenList = new ArrayList(Arrays.asList(params .getStrings("providerCourseAdd"))); // list of // course // ids String userId = (String) state .getAttribute(STATE_INSTRUCTOR_SELECTED); String currentUserId = (String) state .getAttribute(STATE_CM_CURRENT_USERID); if (userId == null || (userId != null && userId .equals(currentUserId))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); state.removeAttribute(FORM_ADDITIONAL); state.removeAttribute(STATE_CM_AUTHORIZER_LIST); } else { // STATE_CM_AUTHORIZER_SECTIONS are SectionObject, // so need to prepare it // also in this page, u can pick either section from // current user OR // sections from another users but not both. - // daisy's note 1 for now // till we are ready to add more complexity List sectionObjectList = prepareSectionObject( providerChosenList, userId); state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS, sectionObjectList); state .removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); // set special instruction & we will keep // STATE_CM_AUTHORIZER_LIST String additional = StringUtil.trimToZero(params .getString("additional")); state.setAttribute(FORM_ADDITIONAL, additional); } } collectNewSiteInfo(siteInfo, state, params, providerChosenList); } // next step state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer(2)); } break; case 38: break; case 39: break; case 42: /* * actionForTemplate chef_site-gradtoolsConfirm.vm * */ break; case 43: /* * actionForTemplate chef_site-editClass.vm * */ if (forward) { if (params.getStrings("providerClassDeletes") == null && params.getStrings("manualClassDeletes") == null && params.getStrings("cmRequestedClassDeletes") == null && !direction.equals("back")) { addAlert(state, rb.getString("java.classes")); } if (params.getStrings("providerClassDeletes") != null) { // build the deletions list List providerCourseList = (List) state .getAttribute(SITE_PROVIDER_COURSE_LIST); List providerCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("providerClassDeletes"))); for (ListIterator i = providerCourseDeleteList .listIterator(); i.hasNext();) { providerCourseList.remove((String) i.next()); } state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } if (params.getStrings("manualClassDeletes") != null) { // build the deletions list List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); List manualCourseDeleteList = new ArrayList(Arrays .asList(params.getStrings("manualClassDeletes"))); for (ListIterator i = manualCourseDeleteList.listIterator(); i .hasNext();) { manualCourseList.remove((String) i.next()); } state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList); } if (params.getStrings("cmRequestedClassDeletes") != null) { // build the deletions list List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); List<String> cmRequestedCourseDeleteList = new ArrayList(Arrays.asList(params.getStrings("cmRequestedClassDeletes"))); for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i .hasNext();) { String sectionId = (String) i.next(); try { SectionObject so = new SectionObject(cms.getSection(sectionId)); SectionObject soFound = null; for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();) { SectionObject k = (SectionObject) j.next(); if (k.eid.equals(sectionId)) { soFound = k; } } if (soFound != null) cmRequestedCourseList.remove(soFound); } catch (Exception e) { M_log.warn( this + e.getMessage() + sectionId, e); } } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList); } updateCourseClasses(state, new Vector(), new Vector()); } break; case 44: if (forward) { AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED); Site site = getStateSite(state); ResourcePropertiesEdit pEdit = site.getPropertiesEdit(); // update the course site property and realm based on the selection updateCourseSiteSections(state, site.getId(), pEdit, a); try { SiteService.save(site); } catch (Exception e) { M_log.warn(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage() + site.getId(), e); } removeAddClassContext(state); } break; case 54: if (forward) { // store answers to site setup questions if (getAnswersToSetupQuestions(params, state)) { state.setAttribute(STATE_TEMPLATE_INDEX, state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE)); } } break; } }// actionFor Template /** * This is used to update exsiting site attributes with encoded site id in it. A new resource item is added to new site when needed * * @param oSiteId * @param nSiteId * @param siteAttribute * @return the new migrated resource url */ private String transferSiteResource(String oSiteId, String nSiteId, String siteAttribute) { String rv = ""; String accessUrl = ServerConfigurationService.getAccessUrl(); if (siteAttribute.indexOf(oSiteId) != -1 && accessUrl != null) { // stripe out the access url, get the relative form of "url" Reference ref = EntityManager.newReference(siteAttribute.replaceAll(accessUrl, "")); try { ContentResource resource = m_contentHostingService.getResource(ref.getId()); // the new resource ContentResource nResource = null; String nResourceId = resource.getId().replaceAll(oSiteId, nSiteId); try { nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n2Exception) { // copy the resource then try { nResourceId = m_contentHostingService.copy(resource.getId(), nResourceId); nResource = m_contentHostingService.getResource(nResourceId); } catch (Exception n3Exception) { } } // get the new resource url rv = nResource != null?nResource.getUrl(false):""; } catch (Exception refException) { M_log.warn(this + ":transferSiteResource: cannot find resource with ref=" + ref.getReference() + " " + refException.getMessage()); } } return rv; } /** * * @param nSiteId * @param oSiteId * @param site */ private void importToolContent(String nSiteId, String oSiteId, Site site, boolean bypassSecurity) { // import tool content if (bypassSecurity) { // importing from template, bypass the permission checking: // temporarily allow the user to read and write from assignments (asn.revise permission) SecurityService.pushAdvisor(new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }); } List pageList = site.getPages(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList .listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); List pageToolList = page.getTools(); Tool tool = ((ToolConfiguration) pageToolList.get(0)).getTool(); String toolId = tool != null?tool.getId():""; if (toolId.equalsIgnoreCase("sakai.resources")) { // handle // resource // tool // specially transferCopyEntities( toolId, m_contentHostingService .getSiteCollection(oSiteId), m_contentHostingService .getSiteCollection(nSiteId)); } else if (toolId.equalsIgnoreCase(SITE_INFORMATION_TOOL)) { // handle Home tool specially, need to update the site infomration display url if needed String newSiteInfoUrl = transferSiteResource(oSiteId, nSiteId, site.getInfoUrl()); site.setInfoUrl(newSiteInfoUrl); } else { // other // tools transferCopyEntities(toolId, oSiteId, nSiteId); } } } if (bypassSecurity) { SecurityService.clearAdvisors(); } } /** * get user answers to setup questions * @param params * @param state * @return */ protected boolean getAnswersToSetupQuestions(ParameterParser params, SessionState state) { boolean rv = true; String answerString = null; String answerId = null; Set userAnswers = new HashSet(); SiteTypeQuestions siteTypeQuestions = questionService.getSiteTypeQuestions((String) state.getAttribute(STATE_SITE_TYPE)); if (siteTypeQuestions != null) { List<SiteSetupQuestion> questions = siteTypeQuestions.getQuestions(); for (Iterator i = questions.iterator(); i.hasNext();) { SiteSetupQuestion question = (SiteSetupQuestion) i.next(); // get the selected answerId answerId = params.get(question.getId()); if (question.isRequired() && answerId == null) { rv = false; addAlert(state, rb.getString("sitesetupquestion.alert")); } else if (answerId != null) { SiteSetupQuestionAnswer answer = questionService.getSiteSetupQuestionAnswer(answerId); if (answer != null) { if (answer.getIsFillInBlank()) { // need to read the text input instead answerString = params.get("fillInBlank_" + answerId); } SiteSetupUserAnswer uAnswer = questionService.newSiteSetupUserAnswer(); uAnswer.setAnswerId(answerId); uAnswer.setAnswerString(answerString); uAnswer.setQuestionId(question.getId()); uAnswer.setUserId(SessionManager.getCurrentSessionUserId()); //update the state variable userAnswers.add(uAnswer); } } } state.setAttribute(STATE_SITE_SETUP_QUESTION_ANSWER, userAnswers); } return rv; } /** * get user answers to setup questions * @param params * @return */ protected void saveAnswersToSetupQuestions(SessionState state) { String answerFolderReference = SiteSetupQuestionFileParser.getAnswerFolderReference(); try { contentHostingService.addResource(answerFolderReference + ""); } catch (Exception e) { M_log.warn(this + e.getMessage()); } } /** * update current step index within the site creation wizard * * @param state * The SessionState object * @param forward * Moving forward or backward? */ private void updateCurrentStep(SessionState state, boolean forward) { if (state.getAttribute(SITE_CREATE_CURRENT_STEP) != null) { int currentStep = ((Integer) state .getAttribute(SITE_CREATE_CURRENT_STEP)).intValue(); if (forward) { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep + 1)); } else { state.setAttribute(SITE_CREATE_CURRENT_STEP, new Integer( currentStep - 1)); } } } /** * remove related state variable for adding class * * @param state * SessionState object */ private void removeAddClassContext(SessionState state) { // remove related state variables state.removeAttribute(STATE_ADD_CLASS_MANUAL); state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); state.removeAttribute(STATE_AUTO_ADD); state.removeAttribute(SITE_CREATE_TOTAL_STEPS); state.removeAttribute(SITE_CREATE_CURRENT_STEP); state.removeAttribute(STATE_IMPORT_SITE_TOOL); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); state.removeAttribute(STATE_CM_SELECTED_SECTIONS); sitePropertiesIntoState(state); } // removeAddClassContext private void updateCourseClasses(SessionState state, List notifyClasses, List requestClasses) { List providerCourseSectionList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST); List manualCourseSectionList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST); List<SectionObject> cmRequestedCourseList = (List) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); Site site = getStateSite(state); String id = site.getId(); String realmId = SiteService.siteReference(id); if ((providerCourseSectionList == null) || (providerCourseSectionList.size() == 0)) { // no section access so remove Provider Id try { AuthzGroup realmEdit1 = AuthzGroupService .getAuthzGroup(realmId); realmEdit1.setProviderGroupId(NULL_STRING); AuthzGroupService.save(realmEdit1); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotedit")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } if ((providerCourseSectionList != null) && (providerCourseSectionList.size() != 0)) { // section access so rewrite Provider Id, don't need the current realm provider String String externalRealm = buildExternalRealm(id, state, providerCourseSectionList, null); try { AuthzGroup realmEdit2 = AuthzGroupService .getAuthzGroup(realmId); realmEdit2.setProviderGroupId(externalRealm); AuthzGroupService.save(realmEdit2); } catch (GroupNotDefinedException e) { M_log.warn(this + ".updateCourseClasses: IdUnusedException, " + site.getTitle() + "(" + realmId + ") not found, or not an AuthzGroup object", e); addAlert(state, rb.getString("java.cannotclasses")); return; } catch (AuthzPermissionException e) { M_log.warn(this + ".updateCourseClasses: PermissionException, user does not have permission to edit AuthzGroup object " + site.getTitle() + "(" + realmId + "). ", e); addAlert(state, rb.getString("java.notaccess")); return; } } // the manual request course into properties setSiteSectionProperty(manualCourseSectionList, site, PROP_SITE_REQUEST_COURSE); // the cm request course into properties setSiteSectionProperty(cmRequestedCourseList, site, STATE_CM_REQUESTED_SECTIONS); // clean the related site groups // if the group realm provider id is not listed for the site, remove the related group for (Iterator iGroups = site.getGroups().iterator(); iGroups.hasNext();) { Group group = (Group) iGroups.next(); try { AuthzGroup gRealm = AuthzGroupService.getAuthzGroup(group.getReference()); String gProviderId = StringUtil.trimToNull(gRealm.getProviderGroupId()); if (gProviderId != null) { if ((manualCourseSectionList== null && cmRequestedCourseList == null) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList == null) || (manualCourseSectionList == null && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId)) || (manualCourseSectionList != null && !manualCourseSectionList.contains(gProviderId) && cmRequestedCourseList != null && !cmRequestedCourseList.contains(gProviderId))) { AuthzGroupService.removeAuthzGroup(group.getReference()); } } } catch (Exception e) { M_log.warn(this + ".updateCourseClasses: cannot remove authzgroup : " + group.getReference(), e); } } if (state.getAttribute(STATE_MESSAGE) == null) { commitSite(site); } else { } if (requestClasses != null && requestClasses.size() > 0 && state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER) != null) { try { // send out class request notifications sendSiteRequest(state, "change", ((Integer) state.getAttribute(STATE_MANUAL_ADD_COURSE_NUMBER)).intValue(), (List<SectionObject>) state.getAttribute(STATE_MANUAL_ADD_COURSE_FIELDS), "manual"); } catch (Exception e) { M_log.warn(this +".updateCourseClasses:" + e.toString(), e); } } if (notifyClasses != null && notifyClasses.size() > 0) { try { // send out class access confirmation notifications sendSiteNotification(state, notifyClasses); } catch (Exception e) { M_log.warn(this + ".updateCourseClasses:" + e.toString(), e); } } } // updateCourseClasses private void setSiteSectionProperty(List courseSectionList, Site site, String propertyName) { if ((courseSectionList != null) && (courseSectionList.size() != 0)) { // store the requested sections in one site property String sections = ""; for (int j = 0; j < courseSectionList.size();) { sections = sections + (String) courseSectionList.get(j); j++; if (j < courseSectionList.size()) { sections = sections + "+"; } } ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.addProperty(propertyName, sections); } else { ResourcePropertiesEdit rp = site.getPropertiesEdit(); rp.removeProperty(propertyName); } } /** * Sets selected roles for multiple users * * @param params * The ParameterParser object * @param listName * The state variable */ private void getSelectedRoles(SessionState state, ParameterParser params, String listName) { Hashtable pSelectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); if (pSelectedRoles == null) { pSelectedRoles = new Hashtable(); } List userList = (List) state.getAttribute(listName); for (int i = 0; i < userList.size(); i++) { String userId = null; if (listName.equalsIgnoreCase(STATE_ADD_PARTICIPANTS)) { userId = ((Participant) userList.get(i)).getUniqname(); } else if (listName.equalsIgnoreCase(STATE_SELECTED_USER_LIST)) { userId = (String) userList.get(i); } if (userId != null) { String rId = StringUtil.trimToNull(params.getString("role" + userId)); if (rId == null) { addAlert(state, rb.getString("java.rolefor") + " " + userId + ". "); pSelectedRoles.remove(userId); } else { pSelectedRoles.put(userId, rId); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, pSelectedRoles); } // getSelectedRoles /** * dispatch function for changing participants roles */ public void doSiteinfo_edit_role(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("same_role_true")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.TRUE); state.setAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE, params .getString("role_to_all")); } else if (option.equalsIgnoreCase("same_role_false")) { state.setAttribute(STATE_CHANGEROLE_SAMEROLE, Boolean.FALSE); state.removeAttribute(STATE_CHANGEROLE_SAMEROLE_ROLE); if (state.getAttribute(STATE_SELECTED_PARTICIPANT_ROLES) == null) { state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, new Hashtable()); } } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("back")) { doBack(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * dispatch function for changing site global access */ public void doSiteinfo_edit_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // dispatch if (option.equalsIgnoreCase("joinable")) { state.setAttribute("form_joinable", Boolean.TRUE); state.setAttribute("form_joinerRole", getStateSite(state) .getJoinerRole()); } else if (option.equalsIgnoreCase("unjoinable")) { state.setAttribute("form_joinable", Boolean.FALSE); state.removeAttribute("form_joinerRole"); } else if (option.equalsIgnoreCase("continue")) { doContinue(data); } else if (option.equalsIgnoreCase("cancel")) { doCancel(data); } } // doSiteinfo_edit_globalAccess /** * save changes to site global access */ public void doSiteinfo_save_globalAccess(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); Site s = getStateSite(state); boolean joinable = ((Boolean) state.getAttribute("form_joinable")) .booleanValue(); s.setJoinable(joinable); if (joinable) { // set the joiner role String joinerRole = (String) state.getAttribute("form_joinerRole"); s.setJoinerRole(joinerRole); } if (state.getAttribute(STATE_MESSAGE) == null) { // release site edit commitSite(s); state.setAttribute(STATE_TEMPLATE_INDEX, "18"); } } // doSiteinfo_save_globalAccess /** * updateSiteAttributes * */ private void updateSiteAttributes(SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } else { M_log .warn("SiteAction.updateSiteAttributes STATE_SITE_INFO == null"); return; } Site site = getStateSite(state); if (site != null) { if (StringUtil.trimToNull(siteInfo.title) != null) { site.setTitle(siteInfo.title); } if (siteInfo.description != null) { site.setDescription(siteInfo.description); } site.setPublished(siteInfo.published); setAppearance(state, site, siteInfo.iconUrl); site.setJoinable(siteInfo.joinable); if (StringUtil.trimToNull(siteInfo.joinerRole) != null) { site.setJoinerRole(siteInfo.joinerRole); } // Make changes and then put changed site back in state String id = site.getId(); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } if (SiteService.allowUpdateSite(id)) { try { SiteService.getSite(id); state.setAttribute(STATE_SITE_INSTANCE_ID, id); } catch (IdUnusedException e) { M_log.warn(this + ".updateSiteAttributes: IdUnusedException " + siteInfo.getTitle() + "(" + id + ") not found", e); } } // no permission else { addAlert(state, rb.getString("java.makechanges")); M_log.warn(this + ".updateSiteAttributes: PermissionException " + siteInfo.getTitle() + "(" + id + ")"); } } } // updateSiteAttributes /** * %%% legacy properties, to be removed */ private void updateSiteInfo(ParameterParser params, SessionState state) { SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } siteInfo.site_type = (String) state.getAttribute(STATE_SITE_TYPE); if (params.getString("title") != null) { siteInfo.title = params.getString("title"); } if (params.getString("description") != null) { StringBuilder alertMsg = new StringBuilder(); String description = params.getString("description"); siteInfo.description = FormattedText.processFormattedText(description, alertMsg); } if (params.getString("short_description") != null) { siteInfo.short_description = params.getString("short_description"); } if (params.getString("additional") != null) { siteInfo.additional = params.getString("additional"); } if (params.getString("iconUrl") != null) { siteInfo.iconUrl = params.getString("iconUrl"); } else { siteInfo.iconUrl = params.getString("skin"); } if (params.getString("joinerRole") != null) { siteInfo.joinerRole = params.getString("joinerRole"); } if (params.getString("joinable") != null) { boolean joinable = params.getBoolean("joinable"); siteInfo.joinable = joinable; if (!joinable) siteInfo.joinerRole = NULL_STRING; } if (params.getString("itemStatus") != null) { siteInfo.published = Boolean .valueOf(params.getString("itemStatus")).booleanValue(); } // site contact information String name = StringUtil .trimToZero(params.getString("siteContactName")); siteInfo.site_contact_name = name; String email = StringUtil.trimToZero(params .getString("siteContactEmail")); if (email != null) { String[] parts = email.split("@"); if (email.length() > 0 && (email.indexOf("@") == -1 || parts.length != 2 || parts[0].length() == 0 || !Validator .checkEmailLocal(parts[0]))) { // invalid email addAlert(state, email + " " + rb.getString("java.invalid") + rb.getString("java.theemail")); } siteInfo.site_contact_email = email; } state.setAttribute(STATE_SITE_INFO, siteInfo); } // updateSiteInfo /** * getParticipantList * */ private Collection getParticipantList(SessionState state) { List members = new Vector(); String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); List providerCourseList = null; providerCourseList = SiteParticipantHelper.getProviderCourseList(siteId); if (providerCourseList != null && providerCourseList.size() > 0) { state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList); } Collection participants = SiteParticipantHelper.prepareParticipants(siteId, providerCourseList); state.setAttribute(STATE_PARTICIPANT_LIST, participants); return participants; } // getParticipantList /** * getRoles * */ private List getRoles(SessionState state) { List roles = new Vector(); String realmId = SiteService.siteReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); try { AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId); roles.addAll(realm.getRoles()); Collections.sort(roles); } catch (GroupNotDefinedException e) { M_log.warn( this + ".getRoles: IdUnusedException " + realmId, e); } return roles; } // getRoles private void addSynopticTool(SitePage page, String toolId, String toolTitle, String layoutHint) { // Add synoptic announcements tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(toolId); tool.setTool(toolId, reg); tool.setTitle(toolTitle); tool.setLayoutHints(layoutHint); } private void saveFeatures(ParameterParser params, SessionState state, Site site) { // get the list of Worksite Setup configured pages List wSetupPageList = state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST)!=null?(List) state.getAttribute(STATE_WORKSITE_SETUP_PAGE_LIST):new Vector(); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); WorksiteSetupPage wSetupHome = new WorksiteSetupPage(); List pageList = new Vector(); // declare some flags used in making decisions about Home, whether to // add, remove, or do nothing boolean hasHome = false; boolean homeInWSetupPageList = false; List chosenList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // if features were selected, diff wSetupPageList and chosenList to get // page adds and removes // boolean values for adding synoptic views boolean hasAnnouncement = false; boolean hasSchedule = false; boolean hasChat = false; boolean hasDiscussion = false; boolean hasEmail = false; boolean hasSiteInfo = false; boolean hasMessageCenter = false; // tools to be imported from other sites? Hashtable importTools = null; if (state.getAttribute(STATE_IMPORT_SITE_TOOL) != null) { importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL); } // Home tool chosen? if (chosenList.contains(HOME_TOOL_ID)) { // add home tool later hasHome = true; } // order the id list chosenList = orderToolIds(state, site.getType(), chosenList); // Special case - Worksite Setup Home comes from a hardcoded checkbox on // the vm template rather than toolRegistrationList // see if Home was chosen for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String choice = (String) j.next(); if (choice.equals("sakai.mailbox")) { hasEmail = true; String alias = StringUtil.trimToNull((String) state .getAttribute(STATE_TOOL_EMAIL_ADDRESS)); if (alias != null) { if (!Validator.checkEmailLocal(alias)) { addAlert(state, rb.getString("java.theemail")); } else { try { String channelReference = mailArchiveChannelReference(site .getId()); // first, clear any alias set to this channel AliasService.removeTargetAliases(channelReference); // check // to // see // whether // the // alias // has // been // used try { String target = AliasService.getTarget(alias); if (target != null) { addAlert(state, rb .getString("java.emailinuse") + " "); } } catch (IdUnusedException ee) { try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException exception) { } catch (IdInvalidException exception) { } catch (PermissionException exception) { } } } catch (PermissionException exception) { } } } } else if (choice.equals("sakai.announcements")) { hasAnnouncement = true; } else if (choice.equals("sakai.schedule")) { hasSchedule = true; } else if (choice.equals("sakai.chat")) { hasChat = true; } else if (choice.equals("sakai.discussion")) { hasDiscussion = true; } else if (choice.equals("sakai.messages") || choice.equals("sakai.forums") || choice.equals("sakai.messagecenter")) { hasMessageCenter = true; } else if (choice.equals("sakai.siteinfo")) { hasSiteInfo = true; } } // see if Home and/or Help in the wSetupPageList (can just check title // here, because we checked patterns before adding to the list) for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { wSetupPage = (WorksiteSetupPage) i.next(); if (wSetupPage.getToolId().equals(HOME_TOOL_ID)) { homeInWSetupPageList = true; } } if (hasHome) { SitePage page = null; // Were the synoptic views of Announcement, Discussioin, Chat // existing before the editing boolean hadAnnouncement = false, hadDiscussion = false, hadChat = false, hadSchedule = false, hadMessageCenter = false; if (homeInWSetupPageList) { if (!SiteService.isUserSite(site.getId())) { // for non-myworkspace site, if Home is chosen and Home is // in the wSetupPageList, remove synoptic tools WorksiteSetupPage homePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i .hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i .next(); if ((comparePage.getToolId()).equals(HOME_TOOL_ID)) { homePage = comparePage; } } page = site.getPage(homePage.getPageId()); List toolList = page.getTools(); List removeToolList = new Vector(); // get those synoptic tools for (ListIterator iToolList = toolList.listIterator(); iToolList .hasNext();) { ToolConfiguration tool = (ToolConfiguration) iToolList .next(); Tool t = tool.getTool(); if (t!= null) { if (t.getId().equals("sakai.synoptic.announcement")) { hadAnnouncement = true; if (!hasAnnouncement) { removeToolList.add(tool);// if Announcement // tool isn't // selected, remove // the synotic // Announcement } } else if (t.getId().equals(TOOL_ID_SUMMARY_CALENDAR)) { hadSchedule = true; if (!hasSchedule || !notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) { // if Schedule tool isn't selected, or the summary calendar tool is stealthed or hidden, remove the synotic Schedule removeToolList.add(tool); } } else if (t.getId().equals("sakai.synoptic.discussion")) { hadDiscussion = true; if (!hasDiscussion) { removeToolList.add(tool);// if Discussion // tool isn't // selected, remove // the synoptic // Discussion } } else if (t.getId().equals("sakai.synoptic.chat")) { hadChat = true; if (!hasChat) { removeToolList.add(tool);// if Chat tool // isn't selected, // remove the // synoptic Chat } } else if (t.getId().equals("sakai.synoptic.messagecenter")) { hadMessageCenter = true; if (!hasMessageCenter) { removeToolList.add(tool);// if Messages and/or Forums tools // isn't selected, // remove the // synoptic Message Center tool } } } } // remove those synoptic tools for (ListIterator rToolList = removeToolList.listIterator(); rToolList .hasNext();) { page.removeTool((ToolConfiguration) rToolList.next()); } } } else { // if Home is chosen and Home is not in wSetupPageList, add Home // to site and wSetupPageList page = site.addPage(); page.setTitle(rb.getString("java.home")); wSetupHome.pageId = page.getId(); wSetupHome.pageTitle = page.getTitle(); wSetupHome.toolId = HOME_TOOL_ID; wSetupPageList.add(wSetupHome); // Add worksite information tool ToolConfiguration tool = page.addTool(); Tool reg = ToolManager.getTool(SITE_INFORMATION_TOOL); tool.setTool(SITE_INFORMATION_TOOL, reg); tool.setTitle(reg.getTitle()); tool.setLayoutHints("0,0"); } if (!SiteService.isUserSite(site.getId())) { // add synoptical tools to home tool in non-myworkspace site try { if (hasAnnouncement && !hadAnnouncement) { // Add synoptic announcements tool addSynopticTool(page, "sakai.synoptic.announcement", rb .getString("java.recann"), "0,1"); } if (hasDiscussion && !hadDiscussion) { // Add synoptic discussion tool addSynopticTool(page, "sakai.synoptic.discussion", rb .getString("java.recdisc"), "1,1"); } if (hasChat && !hadChat) { // Add synoptic chat tool addSynopticTool(page, "sakai.synoptic.chat", rb .getString("java.recent"), "2,1"); } if (hasSchedule && !hadSchedule) { // Add synoptic schedule tool if not stealth or hidden if (notStealthOrHiddenTool(TOOL_ID_SUMMARY_CALENDAR)) addSynopticTool(page, TOOL_ID_SUMMARY_CALENDAR, rb .getString("java.reccal"), "3,1"); } if (hasMessageCenter && !hadMessageCenter) { // Add synoptic Message Center addSynopticTool(page, "sakai.synoptic.messagecenter", rb .getString("java.recmsg"), "4,1"); } if (hasAnnouncement || hasDiscussion || hasChat || hasSchedule || hasMessageCenter) { page.setLayout(SitePage.LAYOUT_DOUBLE_COL); } else { page.setLayout(SitePage.LAYOUT_SINGLE_COL); } } catch (Exception e) { M_log.warn(this + ".saveFeatures: " + e.getMessage() + " site id = " + site.getId(), e); } } } // add Home // if Home is in wSetupPageList and not chosen, remove Home feature from // wSetupPageList and site if (!hasHome && homeInWSetupPageList) { // remove Home from wSetupPageList WorksiteSetupPage removePage = new WorksiteSetupPage(); for (ListIterator i = wSetupPageList.listIterator(); i.hasNext();) { WorksiteSetupPage comparePage = (WorksiteSetupPage) i.next(); if (comparePage.getToolId().equals(HOME_TOOL_ID)) { removePage = comparePage; } } SitePage siteHome = site.getPage(removePage.getPageId()); site.removePage(siteHome); wSetupPageList.remove(removePage); } // declare flags used in making decisions about whether to add, remove, // or do nothing boolean inChosenList; boolean inWSetupPageList; Set categories = new HashSet(); categories.add((String) state.getAttribute(STATE_SITE_TYPE)); Set toolRegistrationSet = ToolManager.findTools(categories, null); // first looking for any tool for removal Vector removePageIds = new Vector(); for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page id + tool id for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } inChosenList = false; for (ListIterator j = chosenList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); if (pageToolId.equals(toolId)) { inChosenList = true; } } if (!inChosenList) { removePageIds.add(wSetupPage.getPageId()); } } for (int i = 0; i < removePageIds.size(); i++) { // if the tool exists in the wSetupPageList, remove it from the site String removeId = (String) removePageIds.get(i); SitePage sitePage = site.getPage(removeId); site.removePage(sitePage); // and remove it from wSetupPageList for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); if (!wSetupPage.getPageId().equals(removeId)) { wSetupPage = null; } } if (wSetupPage != null) { wSetupPageList.remove(wSetupPage); } } // then looking for any tool to add for (ListIterator j = orderToolIds(state, (String) state.getAttribute(STATE_SITE_TYPE), chosenList) .listIterator(); j.hasNext();) { String toolId = (String) j.next(); // Is the tool in the wSetupPageList? inWSetupPageList = false; for (ListIterator k = wSetupPageList.listIterator(); k.hasNext();) { wSetupPage = (WorksiteSetupPage) k.next(); String pageToolId = wSetupPage.getToolId(); // use page Id + toolId for multiple tool instances if (isMultipleInstancesAllowed(findOriginalToolId(state, pageToolId))) { pageToolId = wSetupPage.getPageId() + pageToolId; } if (pageToolId.equals(toolId)) { inWSetupPageList = true; // but for tool of multiple instances, need to change the title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { SitePage pEdit = (SitePage) site .getPage(wSetupPage.pageId); pEdit.setTitle((String) multipleToolIdTitleMap.get(toolId)); List toolList = pEdit.getTools(); for (ListIterator jTool = toolList.listIterator(); jTool .hasNext();) { ToolConfiguration tool = (ToolConfiguration) jTool .next(); String tId = tool.getTool().getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, tId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } } } } } if (inWSetupPageList) { // if the tool already in the list, do nothing so to save the // option settings } else { // if in chosen list but not in wSetupPageList, add it to the // site (one tool on a page) Tool toolRegFound = null; for (Iterator i = toolRegistrationSet.iterator(); i.hasNext();) { Tool toolReg = (Tool) i.next(); if (toolId.indexOf(toolReg.getId()) != -1) { toolRegFound = toolReg; } } if (toolRegFound != null) { // we know such a tool, so add it WorksiteSetupPage addPage = new WorksiteSetupPage(); SitePage page = site.addPage(); addPage.pageId = page.getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title page.setTitle((String) multipleToolIdTitleMap.get(toolId)); } else { // other tools with default title page.setTitle(toolRegFound.getTitle()); } page.setLayout(SitePage.LAYOUT_SINGLE_COL); ToolConfiguration tool = page.addTool(); tool.setTool(toolRegFound.getId(), toolRegFound); addPage.toolId = toolId; wSetupPageList.add(addPage); // set tool title if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // set tool title tool.setTitle((String) multipleToolIdTitleMap.get(toolId)); // save tool configuration saveMultipleToolConfiguration(state, tool, toolId); } else { tool.setTitle(toolRegFound.getTitle()); } } } } // for // reorder Home and Site Info only if the site has not been customized order before if (!site.isCustomPageOrdered()) { // the steps for moving page within the list int moves = 0; if (hasHome) { SitePage homePage = null; // Order tools - move Home to the top - first find it pageList = site.getPages(); if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); if (rb.getString("java.home").equals(page.getTitle())) { homePage = page; break; } } } if (homePage != null) { moves = pageList.indexOf(homePage); for (int n = 0; n < moves; n++) { homePage.moveUp(); } } } // if Site Info is newly added, more it to the last if (hasSiteInfo) { SitePage siteInfoPage = null; pageList = site.getPages(); String[] toolIds = { "sakai.siteinfo" }; if (pageList != null && pageList.size() != 0) { for (ListIterator i = pageList.listIterator(); siteInfoPage == null && i.hasNext();) { SitePage page = (SitePage) i.next(); int s = page.getTools(toolIds).size(); if (s > 0) { siteInfoPage = page; break; } } if (siteInfoPage != null) { // move home from it's index to the first position moves = pageList.indexOf(siteInfoPage); for (int n = moves; n < pageList.size(); n++) { siteInfoPage.moveDown(); } } } } } // if there is no email tool chosen if (!hasEmail) { state.removeAttribute(STATE_TOOL_EMAIL_ADDRESS); } // commit commitSite(site); // import importToolIntoSite(chosenList, importTools, site); } // saveFeatures /** * Save configuration values for multiple tool instances */ private void saveMultipleToolConfiguration(SessionState state, ToolConfiguration tool, String toolId) { // get the configuration of multiple tool instance Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); // set tool attributes Hashtable<String, String> attributes = multipleToolConfiguration.get(toolId); if (attributes != null) { for(String attribute : attributes.keySet()) { String attributeValue = attributes.get(attribute); // if we have a value if (attributeValue != null) { // if this value is not the same as the tool's registered, set it in the placement if (!attributeValue.equals(tool.getTool().getRegisteredConfig().getProperty(attribute))) { tool.getPlacementConfig().setProperty(attribute, attributeValue); } // otherwise clear it else { tool.getPlacementConfig().remove(attribute); } } // if no value else { tool.getPlacementConfig().remove(attribute); } } } } /** * Is the tool stealthed or hidden * @param toolId * @return */ private boolean notStealthOrHiddenTool(String toolId) { return (ToolManager.getTool(toolId) != null && !ServerConfigurationService .getString( "stealthTools@org.sakaiproject.tool.api.ActiveToolManager") .contains(toolId) && !ServerConfigurationService .getString( "hiddenTools@org.sakaiproject.tool.api.ActiveToolManager") .contains(toolId)); } /** * getFeatures gets features for a new site * */ private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) { List idsSelected = new Vector(); List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); boolean goToToolConfigPage = false; boolean homeSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); // toolId's & titles of // chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals(HOME_TOOL_ID)) { homeSelected = true; } else if (isMultipleInstancesAllowed(findOriginalToolId(state, toolId))) { // if user is adding either EmailArchive tool, News tool // or Web Content tool, go to the Customize page for the // tool if (!existTools.contains(toolId)) { goToToolConfigPage = true; multipleToolIdSet.add(toolId); multipleToolIdTitleMap.put(toolId, ToolManager.getTool(toolId).getTitle()); } } else if (toolId.equals("sakai.mailbox") && !existTools.contains(toolId)) { // get the email alias when an Email Archive tool // has been selected goToToolConfigPage = true; String channelReference = mailArchiveChannelReference((String) state .getAttribute(STATE_SITE_INSTANCE_ID)); List aliases = AliasService.getAliases( channelReference, 1, 1); if (aliases.size() > 0) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, ((Alias) aliases.get(0)).getId()); } } idsSelected.add(toolId); } state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean( homeSelected)); } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's // in case of import String importString = params.getString("import"); if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); List importSites = new Vector(); if (params.getStrings("importSites") != null) { importSites = new ArrayList(Arrays.asList(params .getStrings("importSites"))); } if (importSites.size() == 0) { addAlert(state, rb.getString("java.toimport") + " "); } else { Hashtable sites = new Hashtable(); for (int index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites .get(index)); if (!sites.containsKey(s)) { sites.put(s, new Vector()); } } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } else { state.removeAttribute(STATE_IMPORT); } // of // ToolRegistration // toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (state.getAttribute(STATE_IMPORT) != null) { // go to import tool page state.setAttribute(STATE_TEMPLATE_INDEX, "27"); } else if (goToToolConfigPage) { // go to the configuration page for multiple instances of tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to next page state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex); } state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); } } // getFeatures // import tool content into site private void importToolIntoSite(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntities(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntities(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSite private void importToolIntoSiteMigrate(List toolIds, Hashtable importTools, Site site) { if (importTools != null) { // import resources first boolean resourcesImported = false; for (int i = 0; i < toolIds.size() && !resourcesImported; i++) { String toolId = (String) toolIds.get(i); if (toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); String fromSiteCollectionId = m_contentHostingService .getSiteCollection(fromSiteId); String toSiteCollectionId = m_contentHostingService .getSiteCollection(toSiteId); transferCopyEntitiesMigrate(toolId, fromSiteCollectionId, toSiteCollectionId); resourcesImported = true; } } } // import other tools then for (int i = 0; i < toolIds.size(); i++) { String toolId = (String) toolIds.get(i); if (!toolId.equalsIgnoreCase("sakai.resources") && importTools.containsKey(toolId)) { List importSiteIds = (List) importTools.get(toolId); for (int k = 0; k < importSiteIds.size(); k++) { String fromSiteId = (String) importSiteIds.get(k); String toSiteId = site.getId(); transferCopyEntitiesMigrate(toolId, fromSiteId, toSiteId); } } } } } // importToolIntoSiteMigrate public void saveSiteStatus(SessionState state, boolean published) { Site site = getStateSite(state); site.setPublished(published); } // saveSiteStatus public void commitSite(Site site, boolean published) { site.setPublished(published); try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } } // commitSite public void commitSite(Site site) { try { SiteService.save(site); } catch (IdUnusedException e) { // TODO: } catch (PermissionException e) { // TODO: } }// commitSite private boolean isValidDomain(String email) { String invalidNonOfficialAccountString = ServerConfigurationService .getString("invalidNonOfficialAccountString", null); if (invalidNonOfficialAccountString != null) { String[] invalidDomains = invalidNonOfficialAccountString.split(","); for (int i = 0; i < invalidDomains.length; i++) { String domain = invalidDomains[i].trim(); if (email.toLowerCase().indexOf(domain.toLowerCase()) != -1) { return false; } } } return true; } private void checkAddParticipant(ParameterParser params, SessionState state) { // get the participants to be added int i; Vector pList = new Vector(); HashSet existingUsers = new HashSet(); Site site = null; String siteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID); try { site = SiteService.getSite(siteId); } catch (IdUnusedException e) { addAlert(state, rb.getString("java.specif") + " " + siteId); M_log.warn(this + ".checkAddParticipant: "+ rb.getString("java.specif") + " " + siteId, e); } // accept officialAccounts and/or nonOfficialAccount account names String officialAccounts = ""; String nonOfficialAccounts = ""; // check that there is something with which to work officialAccounts = StringUtil.trimToNull((params .getString("officialAccount"))); nonOfficialAccounts = StringUtil.trimToNull(params .getString("nonOfficialAccount")); state.setAttribute("officialAccountValue", officialAccounts); state.setAttribute("nonOfficialAccountValue", nonOfficialAccounts); // if there is no uniquname or nonOfficialAccount entered if (officialAccounts == null && nonOfficialAccounts == null) { addAlert(state, rb.getString("java.guest")); state.setAttribute(STATE_TEMPLATE_INDEX, "5"); return; } String at = "@"; if (officialAccounts != null) { // adding officialAccounts String[] officialAccountArray = officialAccounts .split("\r\n"); for (i = 0; i < officialAccountArray.length; i++) { String officialAccount = StringUtil.trimToNull(officialAccountArray[i].replaceAll("[\t\r\n]", "")); // if there is some text, try to use it if (officialAccount != null) { // automaticially add nonOfficialAccount account Participant participant = new Participant(); User u = null; try { // look for user based on eid first u = UserDirectoryService.getUserByEid(officialAccount); } catch (UserNotDefinedException e) { M_log.warn(this + ".checkAddParticipant: " + officialAccount + " " + rb.getString("java.username") + " ", e); //Changed user lookup to satisfy BSP-1010 (jholtzman) // continue to look for the user by their email address Collection usersWithEmail = UserDirectoryService.findUsersByEmail(officialAccount); if(usersWithEmail != null) { if(usersWithEmail.size() == 0) { // If the collection is empty, we didn't find any users with this email address M_log.info("Unable to find users with email " + officialAccount); } else if (usersWithEmail.size() == 1) { // We found one user with this email address. Use it. u = (User)usersWithEmail.iterator().next(); } else if (usersWithEmail.size() > 1) { // If we have multiple users with this email address, pick one and log this error condition // TODO Should we not pick a user? Throw an exception? M_log.warn("Found multiple user with email " + officialAccount); u = (User)usersWithEmail.iterator().next(); } } } if (u != null) { M_log.info("found user with eid " + officialAccount); if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be added // again existingUsers.add(officialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = u.getEid(); participant.active = true; pList.add(participant); } } } } } // officialAccounts if (nonOfficialAccounts != null) { String[] nonOfficialAccountArray = nonOfficialAccounts.split("\r\n"); for (i = 0; i < nonOfficialAccountArray.length; i++) { String nonOfficialAccount = StringUtil.trimToNull(nonOfficialAccountArray[i].replaceAll("[ \t\r\n]", "")); // remove the trailing dots while (nonOfficialAccount != null && nonOfficialAccount.endsWith(".")) { nonOfficialAccount = nonOfficialAccount.substring(0, nonOfficialAccount.length() - 1); } if (nonOfficialAccount != null && nonOfficialAccount.length() > 0) { String[] parts = nonOfficialAccount.split(at); if (nonOfficialAccount.indexOf(at) == -1) { // must be a valid email address addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress")); } else if ((parts.length != 2) || (parts[0].length() == 0)) { // must have both id and address part addAlert(state, nonOfficialAccount + " " + rb.getString("java.notemailid")); } else if (!Validator.checkEmailLocal(parts[0])) { addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + rb.getString("java.theemail")); } else if (nonOfficialAccount != null && !isValidDomain(nonOfficialAccount)) { // wrong string inside nonOfficialAccount id addAlert(state, nonOfficialAccount + " " + rb.getString("java.emailaddress") + " "); } else { Participant participant = new Participant(); try { // if the nonOfficialAccount user already exists User u = UserDirectoryService .getUserByEid(nonOfficialAccount); if (site != null && site.getUserRole(u.getId()) != null) { // user already exists in the site, cannot be // added again existingUsers.add(nonOfficialAccount); } else { participant.name = u.getDisplayName(); participant.uniqname = nonOfficialAccount; participant.active = true; pList.add(participant); } } catch (UserNotDefinedException e) { // if the nonOfficialAccount user is not in the system // yet participant.name = nonOfficialAccount; participant.uniqname = nonOfficialAccount; // TODO: // what // would // the // UDS // case // this // name // to? // -ggolden participant.active = true; pList.add(participant); } } } // if } // } // nonOfficialAccounts boolean same_role = true; if (params.getString("same_role") == null) { addAlert(state, rb.getString("java.roletype") + " "); } else { same_role = params.getString("same_role").equals("true") ? true : false; state.setAttribute("form_same_role", new Boolean(same_role)); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } else { if (same_role) { state.setAttribute(STATE_TEMPLATE_INDEX, "19"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "20"); } } // remove duplicate or existing user from participant list pList = removeDuplicateParticipants(pList, state); state.setAttribute(STATE_ADD_PARTICIPANTS, pList); // if the add participant list is empty after above removal, stay in the // current page if (pList.size() == 0) { state.setAttribute(STATE_TEMPLATE_INDEX, "5"); } // add alert for attempting to add existing site user(s) if (!existingUsers.isEmpty()) { int count = 0; String accounts = ""; for (Iterator eIterator = existingUsers.iterator(); eIterator .hasNext();) { if (count == 0) { accounts = (String) eIterator.next(); } else { accounts = accounts + ", " + (String) eIterator.next(); } count++; } addAlert(state, rb.getString("add.existingpart.1") + accounts + rb.getString("add.existingpart.2")); } return; } // checkAddParticipant private Vector removeDuplicateParticipants(List pList, SessionState state) { // check the uniqness of list member Set s = new HashSet(); Set uniqnameSet = new HashSet(); Vector rv = new Vector(); for (int i = 0; i < pList.size(); i++) { Participant p = (Participant) pList.get(i); if (!uniqnameSet.contains(p.getUniqname())) { // no entry for the account yet rv.add(p); uniqnameSet.add(p.getUniqname()); } else { // found duplicates s.add(p.getUniqname()); } } if (!s.isEmpty()) { int count = 0; String accounts = ""; for (Iterator i = s.iterator(); i.hasNext();) { if (count == 0) { accounts = (String) i.next(); } else { accounts = accounts + ", " + (String) i.next(); } count++; } if (count == 1) { addAlert(state, rb.getString("add.duplicatedpart.single") + accounts + "."); } else { addAlert(state, rb.getString("add.duplicatedpart") + accounts + "."); } } return rv; } public void doAdd_participant(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); String siteTitle = getStateSite(state).getTitle(); String nonOfficialAccountLabel = ServerConfigurationService.getString( "nonOfficialAccountLabel", ""); Hashtable selectedRoles = (Hashtable) state .getAttribute(STATE_SELECTED_PARTICIPANT_ROLES); boolean notify = false; if (state.getAttribute("form_selectedNotify") != null) { notify = ((Boolean) state.getAttribute("form_selectedNotify")) .booleanValue(); } boolean same_role = ((Boolean) state.getAttribute("form_same_role")) .booleanValue(); Hashtable eIdRoles = new Hashtable(); List addParticipantList = (List) state .getAttribute(STATE_ADD_PARTICIPANTS); for (int i = 0; i < addParticipantList.size(); i++) { Participant p = (Participant) addParticipantList.get(i); String eId = p.getEid(); // role defaults to same role String role = (String) state.getAttribute("form_selectedRole"); if (!same_role) { // if all added participants have different role role = (String) selectedRoles.get(eId); } if (isOfficialAccount(eId)) { // if this is a officialAccount // update the hashtable eIdRoles.put(eId, role); } else { // if this is an nonOfficialAccount try { UserDirectoryService.getUserByEid(eId); } catch (UserNotDefinedException e) { // if there is no such user yet, add the user try { UserEdit uEdit = UserDirectoryService .addUser(null, eId); // set email address uEdit.setEmail(eId); // set the guest user type uEdit.setType("guest"); // set password to a positive random number Random generator = new Random(System .currentTimeMillis()); Integer num = new Integer(generator .nextInt(Integer.MAX_VALUE)); if (num.intValue() < 0) num = new Integer(num.intValue() * -1); String pw = num.toString(); uEdit.setPassword(pw); // and save UserDirectoryService.commitEdit(uEdit); boolean notifyNewUserEmail = (ServerConfigurationService .getString("notifyNewUserEmail", Boolean.TRUE .toString())) .equalsIgnoreCase(Boolean.TRUE.toString()); if (notifyNewUserEmail) { userNotificationProvider.notifyNewUserEmail(uEdit, pw, siteTitle); } } catch (UserIdInvalidException ee) { addAlert(state, nonOfficialAccountLabel + " id " + eId + " " + rb.getString("java.isinval")); M_log.warn(this + ".doAdd_participant: " + nonOfficialAccountLabel + " id " + eId + " " + rb.getString("java.isinval"), ee); } catch (UserAlreadyDefinedException ee) { addAlert(state, "The " + nonOfficialAccountLabel + " " + eId + " " + rb.getString("java.beenused")); M_log.warn(this + ".doAdd_participant: The " + nonOfficialAccountLabel + " " + eId + " " + rb.getString("java.beenused"), ee); } catch (UserPermissionException ee) { addAlert(state, rb.getString("java.haveadd") + " " + eId); M_log.warn(this + ".doAdd_participant: " + rb.getString("java.haveadd") + " " + eId, ee); } } if (state.getAttribute(STATE_MESSAGE) == null) { eIdRoles.put(eId, role); } } } // batch add and updates the successful added list List addedParticipantEIds = addUsersRealm(state, eIdRoles, notify); // update the not added user list String notAddedOfficialAccounts = NULL_STRING; String notAddedNonOfficialAccounts = NULL_STRING; for (Iterator iEIds = eIdRoles.keySet().iterator(); iEIds.hasNext();) { String iEId = (String) iEIds.next(); if (!addedParticipantEIds.contains(iEId)) { if (isOfficialAccount(iEId)) { // no email in eid notAddedOfficialAccounts = notAddedOfficialAccounts .concat(iEId + "\n"); } else { // email in eid notAddedNonOfficialAccounts = notAddedNonOfficialAccounts .concat(iEId + "\n"); } } } if (addedParticipantEIds.size() != 0 && (!notAddedOfficialAccounts.equals(NULL_STRING) || !notAddedNonOfficialAccounts.equals(NULL_STRING))) { // at lease one officialAccount account or an nonOfficialAccount // account added, and there are also failures addAlert(state, rb.getString("java.allusers")); } if (notAddedOfficialAccounts.equals(NULL_STRING) && notAddedNonOfficialAccounts.equals(NULL_STRING)) { // all account has been added successfully removeAddParticipantContext(state); } else { state.setAttribute("officialAccountValue", notAddedOfficialAccounts); state.setAttribute("nonOfficialAccountValue", notAddedNonOfficialAccounts); } if (state.getAttribute(STATE_MESSAGE) != null) { state.setAttribute(STATE_TEMPLATE_INDEX, "22"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "12"); } return; } // doAdd_participant /** * whether the eId is considered of official account * @param eId * @return */ private boolean isOfficialAccount(String eId) { return eId.indexOf(EMAIL_CHAR) == -1; } /** * remove related state variable for adding participants * * @param state * SessionState object */ private void removeAddParticipantContext(SessionState state) { // remove related state variables state.removeAttribute("form_selectedRole"); state.removeAttribute("officialAccountValue"); state.removeAttribute("nonOfficialAccountValue"); state.removeAttribute("form_same_role"); state.removeAttribute("form_selectedNotify"); state.removeAttribute(STATE_ADD_PARTICIPANTS); state.removeAttribute(STATE_SELECTED_USER_LIST); state.removeAttribute(STATE_SELECTED_PARTICIPANT_ROLES); } // removeAddParticipantContext private String getSetupRequestEmailAddress() { String from = ServerConfigurationService.getString("setup.request", null); if (from == null) { from = "postmaster@".concat(ServerConfigurationService .getServerName()); M_log.warn(this + " - no 'setup.request' in configuration, using: "+ from); } return from; } /* * Given a list of user eids, add users to realm If the user account does * not exist yet inside the user directory, assign role to it @return A list * of eids for successfully added users */ private List addUsersRealm(SessionState state, Hashtable eIdRoles, boolean notify) { // return the list of user eids for successfully added user List addedUserEIds = new Vector(); StringBuilder message = new StringBuilder(); if (eIdRoles != null && !eIdRoles.isEmpty()) { // get the current site Site sEdit = getStateSite(state); if (sEdit != null) { // get realm object String realmId = sEdit.getReference(); try { AuthzGroup realmEdit = AuthzGroupService .getAuthzGroup(realmId); for (Iterator eIds = eIdRoles.keySet().iterator(); eIds .hasNext();) { String eId = (String) eIds.next(); String role = (String) eIdRoles.get(eId); try { User user = UserDirectoryService.getUserByEid(eId); if (AuthzGroupService.allowUpdate(realmId) || SiteService .allowUpdateSiteMembership(sEdit .getId())) { realmEdit.addMember(user.getId(), role, true, false); addedUserEIds.add(eId); // send notification if (notify) { String emailId = user.getEmail(); String userName = user.getDisplayName(); // send notification email if (this.userNotificationProvider == null) { M_log.warn("notification provider is null!"); } else { userNotificationProvider.notifyAddedParticipant(!isOfficialAccount(eId), user, sEdit.getTitle()); } } } } catch (UserNotDefinedException e) { message.append(eId + " " + rb.getString("java.account") + " \n"); M_log.warn(this + ".addUsersRealm: " + eId + " "+ rb.getString("java.account"), e); } // try } // for try { AuthzGroupService.save(realmEdit); // post event about adding participant EventTrackingService.post(EventTrackingService.newEvent(SiteService.SECURE_UPDATE_SITE_MEMBERSHIP, realmEdit.getId(),false)); } catch (GroupNotDefinedException ee) { message.append(rb.getString("java.realm") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.realm") + realmId, ee); } catch (AuthzPermissionException ee) { message.append(rb.getString("java.permeditsite") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.permeditsite") + realmId, ee); } } catch (GroupNotDefinedException eee) { message.append(rb.getString("java.realm") + realmId); M_log.warn(this + ".addUsersRealm: " + rb.getString("java.realm") + realmId, eee); } catch (Exception eee) { M_log.warn(this + ".addUsersRealm: " + eee.getMessage() + " realmId=" + realmId, eee); } } } if (message.length() != 0) { addAlert(state, message.toString()); } // if return addedUserEIds; } // addUsersRealm /** * addNewSite is called when the site has enough information to create a new * site * */ private void addNewSite(ParameterParser params, SessionState state) { if (getStateSite(state) != null) { // There is a Site in state already, so use it rather than creating // a new Site return; } // If cleanState() has removed SiteInfo, get a new instance into state SiteInfo siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } String id = StringUtil.trimToNull(siteInfo.getSiteId()); if (id == null) { // get id id = IdManager.createUuid(); siteInfo.site_id = id; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (state.getAttribute(STATE_MESSAGE) == null) { try { Site site = null; // if create based on template, Site templateSite = (Site) state.getAttribute(STATE_TEMPLATE_SITE); if (templateSite != null) { site = SiteService.addSite(id, templateSite); } else { site = SiteService.addSite(id, siteInfo.site_type); } // add current user as the maintainer site.addMember(UserDirectoryService.getCurrentUser().getId(), site.getMaintainRole(), true, false); String title = StringUtil.trimToNull(siteInfo.title); String description = siteInfo.description; setAppearance(state, site, siteInfo.iconUrl); site.setDescription(description); if (title != null) { site.setTitle(title); } site.setType(siteInfo.site_type); ResourcePropertiesEdit rp = site.getPropertiesEdit(); site.setShortDescription(siteInfo.short_description); site.setPubView(siteInfo.include); site.setJoinable(siteInfo.joinable); site.setJoinerRole(siteInfo.joinerRole); site.setPublished(siteInfo.published); // site contact information rp.addProperty(PROP_SITE_CONTACT_NAME, siteInfo.site_contact_name); rp.addProperty(PROP_SITE_CONTACT_EMAIL, siteInfo.site_contact_email); state.setAttribute(STATE_SITE_INSTANCE_ID, site.getId()); // commit newly added site in order to enable related realm commitSite(site); } catch (IdUsedException e) { addAlert(state, rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists")); M_log.warn(this + ".addNewSite: " + rb.getString("java.sitewithid") + " " + id + " " + rb.getString("java.exists"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (IdInvalidException e) { addAlert(state, rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid")); M_log.warn(this + ".addNewSite: " + rb.getString("java.thesiteid") + " " + id + " " + rb.getString("java.notvalid"), e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } catch (PermissionException e) { addAlert(state, rb.getString("java.permission") + " " + id + "."); M_log.warn(this + ".addNewSite: " + rb.getString("java.permission") + " " + id + ".", e); state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("templateIndex")); return; } } } // addNewSite private void sendTemplateUseNotification(Site site, User currentUser, Site templateSite) { // send an email to track who are using the template String from = getSetupRequestEmailAddress(); // send it to the email archive of the template site // TODO: need a better way to get the email archive address //String domain = from.substring(from.indexOf('@')); String templateEmailArchive = templateSite.getId() + "@" + ServerConfigurationService.getServerName(); String to = templateEmailArchive; String headerTo = templateEmailArchive; String replyTo = templateEmailArchive; String message_subject = templateSite.getId() + ": copied by " + currentUser.getDisplayId (); if (from != null && templateEmailArchive != null) { StringBuffer buf = new StringBuffer(); buf.setLength(0); // email body buf.append("Dear template maintainer,\n\n"); buf.append("Congratulations!\n\n"); buf.append("The following user just created a new site based on your template.\n\n"); buf.append("Template name: " + templateSite.getTitle() + "\n"); buf.append("User : " + currentUser.getDisplayName() + " (" + currentUser.getDisplayId () + ")\n"); buf.append("Date : " + new java.util.Date() + "\n"); buf.append("New site Id : " + site.getId() + "\n"); buf.append("New site name: " + site.getTitle() + "\n\n"); buf.append("Cheers,\n"); buf.append("Alliance Team\n"); String content = buf.toString(); EmailService.send(from, to, message_subject, content, headerTo, replyTo, null); } } /** * created based on setTermListForContext - Denny * @param context * @param state */ private void setTemplateListForContext(Context context, SessionState state) { Hashtable<String, List<Site>> templateList = new Hashtable<String, List<Site>>(); // find all template sites. String[] siteTemplates = null; if (ServerConfigurationService.getString("site.templates") != null) { siteTemplates = StringUtil.split(ServerConfigurationService.getString("site.templates"), ","); } for (String siteTemplateId:siteTemplates) { try { Site siteTemplate = SiteService.getSite(siteTemplateId); if (siteTemplate != null) { // get the type of template String type = siteTemplate.getType(); if (type != null) { // populate the list according to template site type List<Site> subTemplateList = new Vector<Site>(); if (templateList.containsKey(type)) { subTemplateList = templateList.get(type); } subTemplateList.add(siteTemplate); templateList.put(type, subTemplateList); } } } catch (IdUnusedException e) { M_log.warn(this + ".setTemplateListForContext: cannot find site with id " + siteTemplateId, e); } } context.put("templateList", templateList); } // setTemplateListForContext /** * %%% legacy properties, to be cleaned up * */ private void sitePropertiesIntoState(SessionState state) { try { Site site = getStateSite(state); SiteInfo siteInfo = new SiteInfo(); if (site != null) { // set from site attributes siteInfo.title = site.getTitle(); siteInfo.description = site.getDescription(); siteInfo.iconUrl = site.getIconUrl(); siteInfo.infoUrl = site.getInfoUrl(); siteInfo.joinable = site.isJoinable(); siteInfo.joinerRole = site.getJoinerRole(); siteInfo.published = site.isPublished(); siteInfo.include = site.isPubView(); siteInfo.short_description = site.getShortDescription(); } siteInfo.additional = ""; state.setAttribute(STATE_SITE_TYPE, siteInfo.site_type); state.setAttribute(STATE_SITE_INFO, siteInfo); } catch (Exception e) { M_log.warn(this + ".sitePropertiesIntoState: " + e.getMessage(), e); } } // sitePropertiesIntoState /** * pageMatchesPattern returns true if a SitePage matches a WorkSite Setup * pattern * */ private boolean pageMatchesPattern(SessionState state, SitePage page) { List pageToolList = page.getTools(); // if no tools on the page, return false if (pageToolList == null || pageToolList.size() == 0) { return false; } // for the case where the page has one tool ToolConfiguration toolConfiguration = (ToolConfiguration) pageToolList .get(0); // don't compare tool properties, which may be changed using Options List toolList = new Vector(); int count = pageToolList.size(); boolean match = false; // check Worksite Setup Home pattern if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.home"))) { return true; } // Home else if (page.getTitle() != null && page.getTitle().equals(rb.getString("java.help"))) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if tooId isn't sakai.contactSupport, return false if (!(toolConfiguration.getTool().getId()) .equals("sakai.contactSupport")) { return false; } return true; } // Help else if (page.getTitle() != null && page.getTitle().equals("Chat")) { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } // if the tool doesn't match, return false if (!(toolConfiguration.getTool().getId()).equals("sakai.chat")) { return false; } // if the channel doesn't match value for main channel, return false String channel = toolConfiguration.getPlacementConfig() .getProperty("channel"); if (channel == null) { return false; } if (!(channel.equals(NULL_STRING))) { return false; } return true; } // Chat else { // if the count of tools on the page doesn't match, return false if (count != 1) { return false; } // if the page layout doesn't match, return false if (page.getLayout() != SitePage.LAYOUT_SINGLE_COL) { return false; } toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); if (pageToolList != null || pageToolList.size() != 0) { // if tool attributes don't match, return false match = false; for (ListIterator i = toolList.listIterator(); i.hasNext();) { MyTool tool = (MyTool) i.next(); if (toolConfiguration.getTitle() != null) { if (toolConfiguration.getTool() != null && toolConfiguration.getTool().getId().indexOf( tool.getId()) != -1) { match = true; } } } if (!match) { return false; } } } // Others return true; } // pageMatchesPattern /** * siteToolsIntoState is the replacement for siteToolsIntoState_ Make a list * of pages and tools that match WorkSite Setup configurations into state */ private void siteToolsIntoState(SessionState state) { // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); String wSetupTool = NULL_STRING; List wSetupPageList = new Vector(); Site site = getStateSite(state); List pageList = site.getPages(); // Put up tool lists filtered by category String type = site.getType(); if (type == null) { if (SiteService.isUserSite(site.getId())) { type = "myworkspace"; } else if (state.getAttribute(STATE_DEFAULT_SITE_TYPE) != null) { // for those sites without type, use the tool set for default // site type type = (String) state.getAttribute(STATE_DEFAULT_SITE_TYPE); } } if (type == null) { M_log.warn(this + ": - unknown STATE_SITE_TYPE"); } else { state.setAttribute(STATE_SITE_TYPE, type); } // set tool registration list setToolRegistrationList(state, type); List toolRegList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); // for the selected tools boolean check_home = false; Vector idSelected = new Vector(); if (!((pageList == null) || (pageList.size() == 0))) { for (ListIterator i = pageList.listIterator(); i.hasNext();) { SitePage page = (SitePage) i.next(); // collect the pages consistent with Worksite Setup patterns if (pageMatchesPattern(state, page)) { if (page.getTitle().equals(rb.getString("java.home"))) { wSetupTool = HOME_TOOL_ID; check_home = true; } else { List pageToolList = page.getTools(); wSetupTool = ((ToolConfiguration) pageToolList.get(0)).getTool().getId(); if (isMultipleInstancesAllowed(findOriginalToolId(state, wSetupTool))) { String mId = page.getId() + wSetupTool; idSelected.add(mId); multipleToolIdTitleMap.put(mId, page.getTitle()); MyTool newTool = new MyTool(); newTool.title = ToolManager.getTool(wSetupTool).getTitle(); newTool.id = mId; newTool.selected = false; boolean hasThisMultipleTool = false; int j = 0; for (; j < toolRegList.size() && !hasThisMultipleTool; j++) { MyTool t = (MyTool) toolRegList.get(j); if (t.getId().equals(wSetupTool)) { hasThisMultipleTool = true; newTool.description = t.getDescription(); } } if (hasThisMultipleTool) { toolRegList.add(j - 1, newTool); } else { toolRegList.add(newTool); } } else { idSelected.add(wSetupTool); } } WorksiteSetupPage wSetupPage = new WorksiteSetupPage(); wSetupPage.pageId = page.getId(); wSetupPage.pageTitle = page.getTitle(); wSetupPage.toolId = wSetupTool; wSetupPageList.add(wSetupPage); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(check_home)); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idSelected); // List state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolRegList); // of // ToolRegistration // toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST,idSelected); // List of ToolRegistration toolId's state.setAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME, Boolean.valueOf(check_home)); state.setAttribute(STATE_WORKSITE_SETUP_PAGE_LIST, wSetupPageList); } // siteToolsIntoState /** * reset the state variables used in edit tools mode * * @state The SessionState object */ private void removeEditToolState(SessionState state) { state.removeAttribute(STATE_TOOL_HOME_SELECTED); state.removeAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // List // of // ToolRegistration // toolId's state.removeAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_HOME); state.removeAttribute(STATE_WORKSITE_SETUP_PAGE_LIST); state.removeAttribute(STATE_MULTIPLE_TOOL_ID_SET); //state.removeAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP); } private List orderToolIds(SessionState state, String type, List toolIdList) { List rv = new Vector(); if (state.getAttribute(STATE_TOOL_HOME_SELECTED) != null && ((Boolean) state.getAttribute(STATE_TOOL_HOME_SELECTED)) .booleanValue()) { rv.add(HOME_TOOL_ID); } // look for null site type if (type != null && toolIdList != null) { Set categories = new HashSet(); categories.add(type); Set tools = ToolManager.findTools(categories, null); SortedIterator i = new SortedIterator(tools.iterator(), new ToolComparator()); for (; i.hasNext();) { String tool_id = ((Tool) i.next()).getId(); for (ListIterator j = toolIdList.listIterator(); j.hasNext();) { String toolId = (String) j.next(); String rToolId = originalToolId(toolId, tool_id); if (rToolId != null) { rv.add(toolId); } } } } return rv; } // orderToolIds private void setupFormNamesAndConstants(SessionState state) { TimeBreakdown timeBreakdown = (TimeService.newTime()).breakdownLocal(); String mycopyright = COPYRIGHT_SYMBOL + " " + timeBreakdown.getYear() + ", " + UserDirectoryService.getCurrentUser().getDisplayName() + ". All Rights Reserved. "; state.setAttribute(STATE_MY_COPYRIGHT, mycopyright); state.setAttribute(STATE_SITE_INSTANCE_ID, null); state.setAttribute(STATE_INITIALIZED, Boolean.TRUE.toString()); SiteInfo siteInfo = new SiteInfo(); Participant participant = new Participant(); participant.name = NULL_STRING; participant.uniqname = NULL_STRING; participant.active = true; state.setAttribute(STATE_SITE_INFO, siteInfo); state.setAttribute("form_participantToAdd", participant); state.setAttribute(FORM_ADDITIONAL, NULL_STRING); // legacy state.setAttribute(FORM_HONORIFIC, "0"); state.setAttribute(FORM_REUSE, "0"); state.setAttribute(FORM_RELATED_CLASS, "0"); state.setAttribute(FORM_RELATED_PROJECT, "0"); state.setAttribute(FORM_INSTITUTION, "0"); // sundry form variables state.setAttribute(FORM_PHONE, ""); state.setAttribute(FORM_EMAIL, ""); state.setAttribute(FORM_SUBJECT, ""); state.setAttribute(FORM_DESCRIPTION, ""); state.setAttribute(FORM_TITLE, ""); state.setAttribute(FORM_NAME, ""); state.setAttribute(FORM_SHORT_DESCRIPTION, ""); } // setupFormNamesAndConstants /** * setupSkins * */ private void setupIcons(SessionState state) { List icons = new Vector(); String[] iconNames = null; String[] iconUrls = null; String[] iconSkins = null; // get icon information if (ServerConfigurationService.getStrings("iconNames") != null) { iconNames = ServerConfigurationService.getStrings("iconNames"); } if (ServerConfigurationService.getStrings("iconUrls") != null) { iconUrls = ServerConfigurationService.getStrings("iconUrls"); } if (ServerConfigurationService.getStrings("iconSkins") != null) { iconSkins = ServerConfigurationService.getStrings("iconSkins"); } if ((iconNames != null) && (iconUrls != null) && (iconSkins != null) && (iconNames.length == iconUrls.length) && (iconNames.length == iconSkins.length)) { for (int i = 0; i < iconNames.length; i++) { MyIcon s = new MyIcon(StringUtil.trimToNull((String) iconNames[i]), StringUtil.trimToNull((String) iconUrls[i]), StringUtil .trimToNull((String) iconSkins[i])); icons.add(s); } } state.setAttribute(STATE_ICONS, icons); } private void setAppearance(SessionState state, Site edit, String iconUrl) { // set the icon edit.setIconUrl(iconUrl); if (iconUrl == null) { // this is the default case - no icon, no (default) skin edit.setSkin(null); return; } // if this icon is in the config appearance list, find a skin to set List icons = (List) state.getAttribute(STATE_ICONS); for (Iterator i = icons.iterator(); i.hasNext();) { Object icon = (Object) i.next(); if (icon instanceof MyIcon && !StringUtil.different(((MyIcon) icon).getUrl(), iconUrl)) { edit.setSkin(((MyIcon) icon).getSkin()); return; } } } /** * A dispatch funtion when selecting course features */ public void doAdd_features(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); String option = params.getString("option"); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET):new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // editing existing site or creating a new one? Site site = getStateSite(state); // dispatch if (option.startsWith("add_")) { // this could be format of originalToolId plus number of multiplication String addToolId = option.substring("add_".length(), option.length()); // find the original tool id String originToolId = findOriginalToolId(state, addToolId); if (originToolId != null) { Tool tool = ToolManager.getTool(originToolId); if (tool != null) { insertTool(state, originToolId, tool.getTitle(), tool.getDescription(), Integer.parseInt(params.getString("num_"+ addToolId))); updateSelectedToolList(state, params, false); state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } } } else if (option.equalsIgnoreCase("import")) { // import or not updateSelectedToolList(state, params, false); String importSites = params.getString("import"); if (importSites != null && importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); if (importSites.equalsIgnoreCase(Boolean.TRUE.toString())) { state.removeAttribute(STATE_IMPORT); state.removeAttribute(STATE_IMPORT_SITES); state.removeAttribute(STATE_IMPORT_SITE_TOOL); } } else { state.removeAttribute(STATE_IMPORT); } } else if (option.equalsIgnoreCase("continue")) { // continue updateSelectedToolList(state, params, false); doContinue(data); } else if (option.equalsIgnoreCase("back")) { // back doBack(data); } else if (option.equalsIgnoreCase("cancel")) { if (site == null) { // cancel doCancel_create(data); } else { // cancel editing doCancel(data); } } } // doAdd_features /** * update the selected tool list * * @param params * The ParameterParser object * @param verifyData * Need to verify input data or not */ private void updateSelectedToolList(SessionState state, ParameterParser params, boolean verifyData) { List selectedTools = new ArrayList(Arrays.asList(params .getStrings("selectedTools"))); Set multipleToolIdSet = (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET); Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); Vector<String> idSelected = (Vector<String>) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); boolean has_home = false; String emailId = null; for (int i = 0; i < selectedTools.size(); i++) { String id = (String) selectedTools.get(i); if (id.equalsIgnoreCase(HOME_TOOL_ID)) { has_home = true; } else if (id.equalsIgnoreCase("sakai.mailbox")) { // if Email archive tool is selected, check the email alias emailId = StringUtil.trimToNull(params.getString("emailId")); if (verifyData) { if (emailId == null) { addAlert(state, rb.getString("java.emailarchive") + " "); } else { if (!Validator.checkEmailLocal(emailId)) { addAlert(state, rb.getString("java.theemail")); } else { // check to see whether the alias has been used by // other sites try { String target = AliasService.getTarget(emailId); if (target != null) { if (state .getAttribute(STATE_SITE_INSTANCE_ID) != null) { String siteId = (String) state .getAttribute(STATE_SITE_INSTANCE_ID); String channelReference = mailArchiveChannelReference(siteId); if (!target.equals(channelReference)) { // the email alias is not used by // current site addAlert(state, rb.getString("java.emailinuse") + " "); } } else { addAlert(state, rb.getString("java.emailinuse") + " "); } } } catch (IdUnusedException ee) { } } } } } else if (isMultipleInstancesAllowed(findOriginalToolId(state, id)) && (idSelected != null && !idSelected.contains(id) || idSelected == null)) { // newly added mutliple instances String title = StringUtil.trimToNull(params.getString("title_" + id)); if (title != null) { // save the titles entered multipleToolIdTitleMap.put(id, title); } // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(id); if (attributes == null) { // if missing, get the default setting for original id attributes = multipleToolConfiguration.get(findOriginalToolId(state, id)); } if (attributes != null) { for(Enumeration<String> e = attributes.keys(); e.hasMoreElements();) { String attribute = e.nextElement(); String attributeInput = StringUtil.trimToNull(params.getString(attribute + "_" + id)); if (attributeInput != null) { // save the attribute input attributes.put(attribute, attributeInput); } } multipleToolConfiguration.put(id, attributes); } } } // update the state objects state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); state.setAttribute(STATE_TOOL_HOME_SELECTED, new Boolean(has_home)); state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, emailId); } // updateSelectedToolList /** * find the tool in the tool list and insert another tool instance to the list * @param state * @param toolId * @param defaultTitle * @param defaultDescription * @param insertTimes */ private void insertTool(SessionState state, String toolId, String defaultTitle, String defaultDescription, int insertTimes) { // the list of available tools List toolList = (List) state.getAttribute(STATE_TOOL_REGISTRATION_LIST); List oTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null? new Vector():(List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP):new HashMap(); // get the attributes of multiple tool instances Hashtable<String, Hashtable<String, String>> multipleToolConfiguration = state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION) != null?(Hashtable<String, Hashtable<String, String>>) state.getAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION):new Hashtable<String, Hashtable<String, String>>(); int toolListedTimes = 0; int index = 0; int insertIndex = 0; while (index < toolList.size()) { MyTool tListed = (MyTool) toolList.get(index); if (tListed.getId().indexOf(toolId) != -1 && !oTools.contains(tListed.getId())) { toolListedTimes++; } if (toolListedTimes > 0 && insertIndex == 0) { // update the insert index insertIndex = index; } index++; } List toolSelected = (List) state .getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST); // insert multiple tools for (int i = 0; i < insertTimes; i++) { toolSelected.add(toolId + toolListedTimes); // We need to insert a specific tool entry only if all the specific // tool entries have been selected String newToolId = toolId + toolListedTimes; MyTool newTool = new MyTool(); newTool.title = defaultTitle; newTool.id = newToolId; newTool.description = defaultDescription; toolList.add(insertIndex, newTool); toolListedTimes++; // add title multipleToolIdTitleMap.put(newTool.id, defaultTitle); // get the attribute input Hashtable<String, String> attributes = multipleToolConfiguration.get(newToolId); if (attributes == null) { // if missing, get the default setting for original id attributes = new Hashtable<String, String>(); Hashtable<String, String> oAttributes = multipleToolConfiguration.get(findOriginalToolId(state, newToolId)); // add the entry for the newly added tool if (attributes != null) { attributes = (Hashtable<String, String>) oAttributes.clone(); multipleToolConfiguration.put(newToolId, attributes); } } } state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); state.setAttribute(STATE_MULTIPLE_TOOL_CONFIGURATION, multipleToolConfiguration); state.setAttribute(STATE_TOOL_REGISTRATION_LIST, toolList); state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, toolSelected); } // insertTool /** * * set selected participant role Hashtable */ private void setSelectedParticipantRoles(SessionState state) { List selectedUserIds = (List) state .getAttribute(STATE_SELECTED_USER_LIST); List participantList = collectionToList((Collection) state.getAttribute(STATE_PARTICIPANT_LIST)); List selectedParticipantList = new Vector(); Hashtable selectedParticipantRoles = new Hashtable(); if (!selectedUserIds.isEmpty() && participantList != null) { for (int i = 0; i < participantList.size(); i++) { String id = ""; Object o = (Object) participantList.get(i); if (o.getClass().equals(Participant.class)) { // get participant roles id = ((Participant) o).getUniqname(); selectedParticipantRoles.put(id, ((Participant) o) .getRole()); } if (selectedUserIds.contains(id)) { selectedParticipantList.add(participantList.get(i)); } } } state.setAttribute(STATE_SELECTED_PARTICIPANT_ROLES, selectedParticipantRoles); state .setAttribute(STATE_SELECTED_PARTICIPANTS, selectedParticipantList); } // setSelectedParticipantRol3es public class MyIcon { protected String m_name = null; protected String m_url = null; protected String m_skin = null; public MyIcon(String name, String url, String skin) { m_name = name; m_url = url; m_skin = skin; } public String getName() { return m_name; } public String getUrl() { return m_url; } public String getSkin() { return m_skin; } } // a utility class for working with ToolConfigurations and ToolRegistrations // %%% convert featureList from IdAndText to Tool so getFeatures item.id = // chosen-feature.id is a direct mapping of data public class MyTool { public String id = NULL_STRING; public String title = NULL_STRING; public String description = NULL_STRING; public boolean selected = false; public String getId() { return id; } public String getTitle() { return title; } public String getDescription() { return description; } public boolean getSelected() { return selected; } } /* * WorksiteSetupPage is a utility class for working with site pages * configured by Worksite Setup * */ public class WorksiteSetupPage { public String pageId = NULL_STRING; public String pageTitle = NULL_STRING; public String toolId = NULL_STRING; public String getPageId() { return pageId; } public String getPageTitle() { return pageTitle; } public String getToolId() { return toolId; } } // WorksiteSetupPage public class SiteInfo { public String site_id = NULL_STRING; // getId of Resource public String external_id = NULL_STRING; // if matches site_id // connects site with U-M // course information public String site_type = ""; public String iconUrl = NULL_STRING; public String infoUrl = NULL_STRING; public boolean joinable = false; public String joinerRole = NULL_STRING; public String title = NULL_STRING; // the short name of the site public String short_description = NULL_STRING; // the short (20 char) // description of the // site public String description = NULL_STRING; // the longer description of // the site public String additional = NULL_STRING; // additional information on // crosslists, etc. public boolean published = false; public boolean include = true; // include the site in the Sites index; // default is true. public String site_contact_name = NULL_STRING; // site contact name public String site_contact_email = NULL_STRING; // site contact email public String getSiteId() { return site_id; } public String getSiteType() { return site_type; } public String getTitle() { return title; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } public String getInfoUrll() { return infoUrl; } public boolean getJoinable() { return joinable; } public String getJoinerRole() { return joinerRole; } public String getAdditional() { return additional; } public boolean getPublished() { return published; } public boolean getInclude() { return include; } public String getSiteContactName() { return site_contact_name; } public String getSiteContactEmail() { return site_contact_email; } } // SiteInfo // dissertation tool related /** * doFinish_grad_tools is called when creation of a Grad Tools site is * confirmed */ public void doFinish_grad_tools(RunData data) { SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // set up for the coming template state.setAttribute(STATE_TEMPLATE_INDEX, params.getString("continue")); int index = Integer.valueOf(params.getString("templateIndex")) .intValue(); actionForTemplate("continue", index, params, state); // add the pre-configured Grad Tools tools to a new site addGradToolsFeatures(state); // TODO: hard coding this frame id is fragile, portal dependent, and // needs to be fixed -ggolden // schedulePeerFrameRefresh("sitenav"); scheduleTopRefresh(); resetPaging(state); }// doFinish_grad_tools /** * addGradToolsFeatures adds features to a new Grad Tools student site * */ private void addGradToolsFeatures(SessionState state) { Site edit = null; Site template = null; // get a unique id String id = IdManager.createUuid(); // get the Grad Tools student site template try { template = SiteService.getSite(SITE_GTS_TEMPLATE); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + e.getMessage() + SITE_GTS_TEMPLATE, e); } if (template != null) { // create a new site based on the template try { edit = SiteService.addSite(id, template); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " add/edit site id=" + id, e); } // set the tab, etc. if (edit != null) { SiteInfo siteInfo = (SiteInfo) state .getAttribute(STATE_SITE_INFO); edit.setShortDescription(siteInfo.short_description); edit.setTitle(siteInfo.title); edit.setPublished(true); edit.setPubView(false); edit.setType(SITE_TYPE_GRADTOOLS_STUDENT); // ResourcePropertiesEdit rpe = edit.getPropertiesEdit(); try { SiteService.save(edit); } catch (Exception e) { M_log.warn(this + ".addGradToolsFeatures:" + " commitEdit site id=" + id, e); } // now that the site and realm exist, we can set the email alias // set the GradToolsStudent site alias as: // gradtools-uniqname@servername String alias = "gradtools-" + SessionManager.getCurrentSessionUserId(); String channelReference = mailArchiveChannelReference(id); try { AliasService.setAlias(alias, channelReference); } catch (IdUsedException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.exists"), ee); } catch (IdInvalidException ee) { addAlert(state, rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval")); M_log.warn(this + ".addGradToolsFeatures:" + rb.getString("java.alias") + " " + alias + " " + rb.getString("java.isinval"), ee); } catch (PermissionException ee) { M_log.warn(this + ".addGradToolsFeatures:" + SessionManager.getCurrentSessionUserId() + " does not have permission to add alias. ", ee); } } } } // addGradToolsFeatures /** * handle with add site options * */ public void doAdd_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("finish")) { doFinish(data); } else if (option.equals("cancel")) { doCancel_create(data); } else if (option.equals("back")) { doBack(data); } } // doAdd_site_option /** * handle with duplicate site options * */ public void doDuplicate_site_option(RunData data) { String option = data.getParameters().getString("option"); if (option.equals("duplicate")) { doContinue(data); } else if (option.equals("cancel")) { doCancel(data); } else if (option.equals("finish")) { doContinue(data); } } // doDuplicate_site_option /** * Special check against the Dissertation service, which might not be * here... * * @return */ protected boolean isGradToolsCandidate(String userId) { // DissertationService.isCandidate(userId) - but the hard way Object service = ComponentManager .get("org.sakaiproject.api.app.dissertation.DissertationService"); if (service == null) return false; // the method signature Class[] signature = new Class[1]; signature[0] = String.class; // the method name String methodName = "isCandidate"; // find a method of this class with this name and signature try { Method method = service.getClass().getMethod(methodName, signature); // the parameters Object[] args = new Object[1]; args[0] = userId; // make the call Boolean rv = (Boolean) method.invoke(service, args); return rv.booleanValue(); } catch (Throwable t) { } return false; } /** * User has a Grad Tools student site * * @return */ protected boolean hasGradToolsStudentSite(String userId) { boolean has = false; int n = 0; try { n = SiteService.countSites( org.sakaiproject.site.api.SiteService.SelectionType.UPDATE, SITE_TYPE_GRADTOOLS_STUDENT, null, null); if (n > 0) has = true; } catch (Exception e) { M_log.warn(this + ".addGradToolsStudentSite:" + e.getMessage(), e); } return has; }// hasGradToolsStudentSite /** * Get the mail archive channel reference for the main container placement * for this site. * * @param siteId * The site id. * @return The mail archive channel reference for this site. */ protected String mailArchiveChannelReference(String siteId) { Object m = ComponentManager .get("org.sakaiproject.mailarchive.api.MailArchiveService"); if (m != null) { return "/mailarchive"+Entity.SEPARATOR+"channel"+Entity.SEPARATOR+siteId+Entity.SEPARATOR+SiteService.MAIN_CONTAINER; } else { return ""; } } /** * Transfer a copy of all entites from another context for any entity * producer that claims this tool id. * * @param toolId * The tool id. * @param fromContext * The context to import from. * @param toContext * The context to import into. */ protected void transferCopyEntities(String toolId, String fromContext, String toContext) { // TODO: used to offer to resources first - why? still needed? -ggolden // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector()); } } catch (Throwable t) { M_log.warn(this + ".transferCopyEntities: Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } protected void transferCopyEntitiesMigrate(String toolId, String fromContext, String toContext) { for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { try { EntityTransferrer et = (EntityTransferrer) ep; // if this producer claims this tool id if (ArrayUtil.contains(et.myToolIds(), toolId)) { et.transferCopyEntities(fromContext, toContext, new Vector(), true); } } catch (Throwable t) { M_log.warn( "Error encountered while asking EntityTransfer to transferCopyEntities from: " + fromContext + " to: " + toContext, t); } } } } /** * @return Get a list of all tools that support the import (transfer copy) * option */ protected Set importTools() { HashSet rv = new HashSet(); // offer to all EntityProducers for (Iterator i = EntityManager.getEntityProducers().iterator(); i .hasNext();) { EntityProducer ep = (EntityProducer) i.next(); if (ep instanceof EntityTransferrer) { EntityTransferrer et = (EntityTransferrer) ep; String[] tools = et.myToolIds(); if (tools != null) { for (int t = 0; t < tools.length; t++) { rv.add(tools[t]); } } } } return rv; } /** * @param state * @return Get a list of all tools that should be included as options for * import */ protected List getToolsAvailableForImport(SessionState state, List<String> toolIdList) { // The Web Content and News tools do not follow the standard rules for // import // Even if the current site does not contain the tool, News and WC will // be // an option if the imported site contains it boolean displayWebContent = false; boolean displayNews = false; Set importSites = ((Hashtable) state.getAttribute(STATE_IMPORT_SITES)) .keySet(); Iterator sitesIter = importSites.iterator(); while (sitesIter.hasNext()) { Site site = (Site) sitesIter.next(); if (site.getToolForCommonId("sakai.iframe") != null) displayWebContent = true; if (site.getToolForCommonId("sakai.news") != null) displayNews = true; } if (displayWebContent && !toolIdList.contains("sakai.iframe")) toolIdList.add("sakai.iframe"); if (displayNews && !toolIdList.contains("sakai.news")) toolIdList.add("sakai.news"); return toolIdList; } // getToolsAvailableForImport private void setTermListForContext(Context context, SessionState state, boolean upcomingOnly) { List terms; if (upcomingOnly) { terms = cms != null?cms.getCurrentAcademicSessions():null; } else { // get all terms = cms != null?cms.getAcademicSessions():null; } if (terms != null && terms.size() > 0) { context.put("termList", terms); } } // setTermListForContext private void setSelectedTermForContext(Context context, SessionState state, String stateAttribute) { if (state.getAttribute(stateAttribute) != null) { context.put("selectedTerm", state.getAttribute(stateAttribute)); } } // setSelectedTermForContext /** * rewrote for 2.4 * * @param userId * @param academicSessionEid * @param courseOfferingHash * @param sectionHash */ private void prepareCourseAndSectionMap(String userId, String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash) { // looking for list of courseOffering and sections that should be // included in // the selection list. The course offering must be offered // 1. in the specific academic Session // 2. that the specified user has right to attach its section to a // course site // map = (section.eid, sakai rolename) if (groupProvider == null) { M_log.warn("Group provider not found"); return; } Map map = groupProvider.getGroupRolesForUser(userId); if (map == null) return; Set keys = map.keySet(); Set roleSet = getRolesAllowedToAttachSection(); for (Iterator i = keys.iterator(); i.hasNext();) { String sectionEid = (String) i.next(); String role = (String) map.get(sectionEid); if (includeRole(role, roleSet)) { Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } // now consider those user with affiliated sections List affiliatedSectionEids = affiliatedSectionProvider.getAffiliatedSectionEids(userId, academicSessionEid); if (affiliatedSectionEids != null) { for (int k = 0; k < affiliatedSectionEids.size(); k++) { String sectionEid = (String) affiliatedSectionEids.get(k); Section section = null; getCourseOfferingAndSectionMap(academicSessionEid, courseOfferingHash, sectionHash, sectionEid, section); } } } // prepareCourseAndSectionMap private void getCourseOfferingAndSectionMap(String academicSessionEid, HashMap courseOfferingHash, HashMap sectionHash, String sectionEid, Section section) { try { section = cms.getSection(sectionEid); } catch (IdNotFoundException e) { M_log.warn(this + ".getCourseOfferingAndSectionMap:" + " cannot find section id=" + sectionEid, e); } if (section != null) { String courseOfferingEid = section.getCourseOfferingEid(); CourseOffering courseOffering = cms .getCourseOffering(courseOfferingEid); String sessionEid = courseOffering.getAcademicSession() .getEid(); if (academicSessionEid.equals(sessionEid)) { // a long way to the conclusion that yes, this course // offering // should be included in the selected list. Sigh... // -daisyf ArrayList sectionList = (ArrayList) sectionHash .get(courseOffering.getEid()); if (sectionList == null) { sectionList = new ArrayList(); } sectionList.add(new SectionObject(section)); sectionHash.put(courseOffering.getEid(), sectionList); courseOfferingHash.put(courseOffering.getEid(), courseOffering); } } } /** * for 2.4 * * @param role * @return */ private boolean includeRole(String role, Set roleSet) { boolean includeRole = false; for (Iterator i = roleSet.iterator(); i.hasNext();) { String r = (String) i.next(); if (r.equals(role)) { includeRole = true; break; } } return includeRole; } // includeRole protected Set getRolesAllowedToAttachSection() { // Use !site.template.[site_type] String azgId = "!site.template.course"; AuthzGroup azgTemplate; try { azgTemplate = AuthzGroupService.getAuthzGroup(azgId); } catch (GroupNotDefinedException e) { M_log.warn(this + ".getRolesAllowedToAttachSection: Could not find authz group " + azgId, e); return new HashSet(); } Set roles = azgTemplate.getRolesIsAllowed("site.upd"); roles.addAll(azgTemplate.getRolesIsAllowed("realm.upd")); return roles; } // getRolesAllowedToAttachSection /** * Here, we will preapre two HashMap: 1. courseOfferingHash stores * courseOfferingId and CourseOffering 2. sectionHash stores * courseOfferingId and a list of its Section We sorted the CourseOffering * by its eid & title and went through them one at a time to construct the * CourseObject that is used for the displayed in velocity. Each * CourseObject will contains a list of CourseOfferingObject(again used for * vm display). Usually, a CourseObject would only contain one * CourseOfferingObject. A CourseObject containing multiple * CourseOfferingObject implies that this is a cross-listing situation. * * @param userId * @param academicSessionEid * @return */ private List prepareCourseAndSectionListing(String userId, String academicSessionEid, SessionState state) { // courseOfferingHash = (courseOfferingEid, vourseOffering) // sectionHash = (courseOfferingEid, list of sections) HashMap courseOfferingHash = new HashMap(); HashMap sectionHash = new HashMap(); prepareCourseAndSectionMap(userId, academicSessionEid, courseOfferingHash, sectionHash); // courseOfferingHash & sectionHash should now be filled with stuffs // put section list in state for later use state.setAttribute(STATE_PROVIDER_SECTION_LIST, getSectionList(sectionHash)); ArrayList offeringList = new ArrayList(); Set keys = courseOfferingHash.keySet(); for (Iterator i = keys.iterator(); i.hasNext();) { CourseOffering o = (CourseOffering) courseOfferingHash .get((String) i.next()); offeringList.add(o); } Collection offeringListSorted = sortOffering(offeringList); ArrayList resultedList = new ArrayList(); // use this to keep track of courseOffering that we have dealt with // already // this is important 'cos cross-listed offering is dealt with together // with its // equivalents ArrayList dealtWith = new ArrayList(); for (Iterator j = offeringListSorted.iterator(); j.hasNext();) { CourseOffering o = (CourseOffering) j.next(); if (!dealtWith.contains(o.getEid())) { // 1. construct list of CourseOfferingObject for CourseObject ArrayList l = new ArrayList(); CourseOfferingObject coo = new CourseOfferingObject(o, (ArrayList) sectionHash.get(o.getEid())); l.add(coo); // 2. check if course offering is cross-listed Set set = cms.getEquivalentCourseOfferings(o.getEid()); if (set != null) { for (Iterator k = set.iterator(); k.hasNext();) { CourseOffering eo = (CourseOffering) k.next(); if (courseOfferingHash.containsKey(eo.getEid())) { // => cross-listed, then list them together CourseOfferingObject coo_equivalent = new CourseOfferingObject( eo, (ArrayList) sectionHash.get(eo.getEid())); l.add(coo_equivalent); dealtWith.add(eo.getEid()); } } } CourseObject co = new CourseObject(o, l); dealtWith.add(o.getEid()); resultedList.add(co); } } return resultedList; } // prepareCourseAndSectionListing /** * Sort CourseOffering by order of eid, title uisng velocity SortTool * * @param offeringList * @return */ private Collection sortOffering(ArrayList offeringList) { return sortCmObject(offeringList); /* * List propsList = new ArrayList(); propsList.add("eid"); * propsList.add("title"); SortTool sort = new SortTool(); return * sort.sort(offeringList, propsList); */ } // sortOffering /** * sort any Cm object such as CourseOffering, CourseOfferingObject, * SectionObject provided object has getter & setter for eid & title * * @param list * @return */ private Collection sortCmObject(List list) { if (list != null) { List propsList = new ArrayList(); propsList.add("eid"); propsList.add("title"); SortTool sort = new SortTool(); return sort.sort(list, propsList); } else { return list; } } // sortCmObject /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class SectionObject { public Section section; public String eid; public String title; public String category; public String categoryDescription; public boolean isLecture; public boolean attached; public String authorizer; public SectionObject(Section section) { this.section = section; this.eid = section.getEid(); this.title = section.getTitle(); this.category = section.getCategory(); this.categoryDescription = cms .getSectionCategoryDescription(section.getCategory()); if ("01.lct".equals(section.getCategory())) { this.isLecture = true; } else { this.isLecture = false; } Set set = authzGroupService.getAuthzGroupIds(section.getEid()); if (set != null && !set.isEmpty()) { this.attached = true; } else { this.attached = false; } } public Section getSection() { return section; } public String getEid() { return eid; } public String getTitle() { return title; } public String getCategory() { return category; } public String getCategoryDescription() { return categoryDescription; } public boolean getIsLecture() { return isLecture; } public boolean getAttached() { return attached; } public String getAuthorizer() { return authorizer; } public void setAuthorizer(String authorizer) { this.authorizer = authorizer; } } // SectionObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseObject { public String eid; public String title; public List courseOfferingObjects; public CourseObject(CourseOffering offering, List courseOfferingObjects) { this.eid = offering.getEid(); this.title = offering.getTitle(); this.courseOfferingObjects = courseOfferingObjects; } public String getEid() { return eid; } public String getTitle() { return title; } public List getCourseOfferingObjects() { return courseOfferingObjects; } } // CourseObject constructor /** * this object is used for displaying purposes in chef_site-newSiteCourse.vm */ public class CourseOfferingObject { public String eid; public String title; public List sections; public CourseOfferingObject(CourseOffering offering, List unsortedSections) { List propsList = new ArrayList(); propsList.add("category"); propsList.add("eid"); SortTool sort = new SortTool(); this.sections = new ArrayList(); if (unsortedSections != null) { this.sections = (List) sort.sort(unsortedSections, propsList); } this.eid = offering.getEid(); this.title = offering.getTitle(); } public String getEid() { return eid; } public String getTitle() { return title; } public List getSections() { return sections; } } // CourseOfferingObject constructor /** * get campus user directory for dispaly in chef_newSiteCourse.vm * * @return */ private String getCampusDirectory() { return ServerConfigurationService.getString( "site-manage.campusUserDirectory", null); } // getCampusDirectory private void removeAnyFlagedSection(SessionState state, ParameterParser params) { List all = new ArrayList(); List providerCourseList = (List) state .getAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN); if (providerCourseList != null && providerCourseList.size() > 0) { all.addAll(providerCourseList); } List manualCourseList = (List) state .getAttribute(SITE_MANUAL_COURSE_LIST); if (manualCourseList != null && manualCourseList.size() > 0) { all.addAll(manualCourseList); } for (int i = 0; i < all.size(); i++) { String eid = (String) all.get(i); String field = "removeSection" + eid; String toRemove = params.getString(field); if ("true".equals(toRemove)) { // eid is in either providerCourseList or manualCourseList // either way, just remove it if (providerCourseList != null) providerCourseList.remove(eid); if (manualCourseList != null) manualCourseList.remove(eid); } } List<SectionObject> requestedCMSections = (List<SectionObject>) state .getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedCMSections != null) { for (int i = 0; i < requestedCMSections.size(); i++) { SectionObject so = (SectionObject) requestedCMSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { requestedCMSections.remove(so); } } if (requestedCMSections.size() == 0) state.removeAttribute(STATE_CM_REQUESTED_SECTIONS); } List<SectionObject> authorizerSections = (List<SectionObject>) state .getAttribute(STATE_CM_AUTHORIZER_SECTIONS); if (authorizerSections != null) { for (int i = 0; i < authorizerSections.size(); i++) { SectionObject so = (SectionObject) authorizerSections.get(i); String field = "removeSection" + so.getEid(); String toRemove = params.getString(field); if ("true".equals(toRemove)) { authorizerSections.remove(so); } } if (authorizerSections.size() == 0) state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS); } // if list is empty, set to null. This is important 'cos null is // the indication that the list is empty in the code. See case 2 on line // 1081 if (manualCourseList != null && manualCourseList.size() == 0) manualCourseList = null; if (providerCourseList != null && providerCourseList.size() == 0) providerCourseList = null; } private void collectNewSiteInfo(SiteInfo siteInfo, SessionState state, ParameterParser params, List providerChosenList) { if (state.getAttribute(STATE_MESSAGE) == null) { siteInfo = new SiteInfo(); if (state.getAttribute(STATE_SITE_INFO) != null) { siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); } // site title is the title of the 1st section selected - // daisyf's note if (providerChosenList != null && providerChosenList.size() >= 1) { String title = prepareTitle((List) state .getAttribute(STATE_PROVIDER_SECTION_LIST), providerChosenList); siteInfo.title = title; } state.setAttribute(STATE_SITE_INFO, siteInfo); if (params.getString("manualAdds") != null && ("true").equals(params.getString("manualAdds"))) { // if creating a new site state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); } else if (params.getString("findCourse") != null && ("true").equals(params.getString("findCourse"))) { state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList); prepFindPage(state); } else { // no manual add state.removeAttribute(STATE_MANUAL_ADD_COURSE_NUMBER); state.removeAttribute(STATE_MANUAL_ADD_COURSE_FIELDS); state.removeAttribute(STATE_SITE_QUEST_UNIQNAME); if (getStateSite(state) != null) { // if revising a site, go to the confirmation // page of adding classes //state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } else { // if creating a site, go the the site // information entry page state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } } } } /** * By default, courseManagement is implemented * * @return */ private boolean courseManagementIsImplemented() { boolean returnValue = true; String isImplemented = ServerConfigurationService.getString( "site-manage.courseManagementSystemImplemented", "true"); if (("false").equals(isImplemented)) returnValue = false; return returnValue; } private List getCMSections(String offeringEid) { if (offeringEid == null || offeringEid.trim().length() == 0) return null; if (cms != null) { Set sections = cms.getSections(offeringEid); Collection c = sortCmObject(new ArrayList(sections)); return (List) c; } return new ArrayList(0); } private List getCMCourseOfferings(String subjectEid, String termID) { if (subjectEid == null || subjectEid.trim().length() == 0 || termID == null || termID.trim().length() == 0) return null; if (cms != null) { Set offerings = cms.getCourseOfferingsInCourseSet(subjectEid);// , // termID); ArrayList returnList = new ArrayList(); Iterator coIt = offerings.iterator(); while (coIt.hasNext()) { CourseOffering co = (CourseOffering) coIt.next(); AcademicSession as = co.getAcademicSession(); if (as != null && as.getEid().equals(termID)) returnList.add(co); } Collection c = sortCmObject(returnList); return (List) c; } return new ArrayList(0); } private List<String> getCMLevelLabels() { List<String> rv = new Vector<String>(); Set courseSets = cms.getCourseSets(); String currentLevel = ""; rv = addCategories(rv, courseSets); // course and section exist in the CourseManagementService rv.add(rb.getString("cm.level.course")); rv.add(rb.getString("cm.level.section")); return rv; } /** * a recursive function to add courseset categories * @param rv * @param courseSets */ private List<String> addCategories(List<String> rv, Set courseSets) { if (courseSets != null) { for (Iterator i = courseSets.iterator(); i.hasNext();) { // get the CourseSet object level CourseSet cs = (CourseSet) i.next(); String level = cs.getCategory(); if (!rv.contains(level)) { rv.add(level); } try { // recursively add child categories rv = addCategories(rv, cms.getChildCourseSets(cs.getEid())); } catch (IdNotFoundException e) { // current CourseSet not found } } } return rv; } private void prepFindPage(SessionState state) { final List cmLevels = getCMLevelLabels(), selections = (List) state .getAttribute(STATE_CM_LEVEL_SELECTIONS); int lvlSz = 0; if (cmLevels == null || (lvlSz = cmLevels.size()) < 1) { // TODO: no cm levels configured, redirect to manual add return; } if (selections != null && selections.size() == lvlSz) { Section sect = cms.getSection((String) selections.get(selections .size() - 1)); SectionObject so = new SectionObject(sect); state.setAttribute(STATE_CM_SELECTED_SECTION, so); } else state.removeAttribute(STATE_CM_SELECTED_SECTION); state.setAttribute(STATE_CM_LEVELS, cmLevels); state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); // check the configuration setting for choosing next screen Boolean skipCourseSectionSelection = ServerConfigurationService.getBoolean("wsetup.skipCourseSectionSelection", Boolean.FALSE); if (!skipCourseSectionSelection.booleanValue()) { // go to the course/section selection page state.setAttribute(STATE_TEMPLATE_INDEX, "53"); } else { // skip the course/section selection page, go directly into the manually create course page state.setAttribute(STATE_TEMPLATE_INDEX, "37"); } } private void addRequestedSection(SessionState state) { SectionObject so = (SectionObject) state .getAttribute(STATE_CM_SELECTED_SECTION); String uniqueName = (String) state .getAttribute(STATE_SITE_QUEST_UNIQNAME); if (so == null) return; so.setAuthorizer(uniqueName); if (getStateSite(state) == null) { // creating new site List<SectionObject> requestedSections = (List<SectionObject>) state.getAttribute(STATE_CM_REQUESTED_SECTIONS); if (requestedSections == null) { requestedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!requestedSections.contains(so)) requestedSections.add(so); // if the title has not yet been set and there is just // one section, set the title to that section's EID if (requestedSections.size() == 1) { SiteInfo siteInfo = (SiteInfo) state.getAttribute(STATE_SITE_INFO); if (siteInfo == null) { siteInfo = new SiteInfo(); } if (siteInfo.title == null || siteInfo.title.trim().length() == 0) { siteInfo.title = so.getEid(); } state.setAttribute(STATE_SITE_INFO, siteInfo); } state.setAttribute(STATE_CM_REQUESTED_SECTIONS, requestedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } else { // editing site state.setAttribute(STATE_CM_SELECTED_SECTION, so); List<SectionObject> cmSelectedSections = (List<SectionObject>) state.getAttribute(STATE_CM_SELECTED_SECTIONS); if (cmSelectedSections == null) { cmSelectedSections = new ArrayList<SectionObject>(); } // don't add duplicates if (!cmSelectedSections.contains(so)) cmSelectedSections.add(so); state.setAttribute(STATE_CM_SELECTED_SECTIONS, cmSelectedSections); state.removeAttribute(STATE_CM_SELECTED_SECTION); } state.removeAttribute(STATE_CM_LEVEL_SELECTIONS); } public void doFind_course(RunData data) { final SessionState state = ((JetspeedRunData) data) .getPortletSessionState(((JetspeedRunData) data).getJs_peid()); final ParameterParser params = data.getParameters(); final String option = params.get("option"); if (option != null) { if ("continue".equals(option)) { String uniqname = StringUtil.trimToNull(params .getString("uniqname")); state.setAttribute(STATE_SITE_QUEST_UNIQNAME, uniqname); if (state.getAttribute(STATE_FUTURE_TERM_SELECTED) != null && !((Boolean) state .getAttribute(STATE_FUTURE_TERM_SELECTED)) .booleanValue()) { // if a future term is selected, do not check authorization // uniqname if (uniqname == null) { addAlert(state, rb.getString("java.author") + " " + ServerConfigurationService .getString("officialAccountName") + ". "); } else { try { UserDirectoryService.getUserByEid(uniqname); addRequestedSection(state); } catch (UserNotDefinedException e) { addAlert(state, rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2")); M_log.warn(this + ".doFind_course:" + rb.getString("java.validAuthor1") + " " + ServerConfigurationService.getString("officialAccountName") + " " + rb.getString("java.validAuthor2"), e); } } } else { addRequestedSection(state); } if (state.getAttribute(STATE_MESSAGE) == null) { if (getStateSite(state) == null) { state.setAttribute(STATE_TEMPLATE_INDEX, "2"); } else { state.setAttribute(STATE_TEMPLATE_INDEX, "44"); } } doContinue(data); return; } else if ("back".equals(option)) { doBack(data); return; } else if ("cancel".equals(option)) { if (getStateSite(state) == null) { doCancel_create(data);// cancel from new site creation } else { doCancel(data);// cancel from site info editing } return; } else if (option.equals("add")) { addRequestedSection(state); return; } else if (option.equals("manual")) { // TODO: send to case 37 state.setAttribute(STATE_TEMPLATE_INDEX, "37"); state.setAttribute(STATE_MANUAL_ADD_COURSE_NUMBER, new Integer( 1)); return; } else if (option.equals("remove")) removeAnyFlagedSection(state, params); } final List selections = new ArrayList(3); int cmLevel = getCMLevelLabels().size(); String deptChanged = params.get("deptChanged"); if ("true".equals(deptChanged)) { // when dept changes, remove selection on courseOffering and // courseSection cmLevel = 1; } for (int i = 0; i < cmLevel; i++) { String val = params.get("idField_" + i); if (val == null || val.trim().length() < 1) { break; } selections.add(val); } state.setAttribute(STATE_CM_LEVEL_SELECTIONS, selections); prepFindPage(state); } /** * return the title of the 1st section in the chosen list that has an * enrollment set. No discrimination on section category * * @param sectionList * @param chosenList * @return */ private String prepareTitle(List sectionList, List chosenList) { String title = null; HashMap map = new HashMap(); for (Iterator i = sectionList.iterator(); i.hasNext();) { SectionObject o = (SectionObject) i.next(); map.put(o.getEid(), o.getSection()); } for (int j = 0; j < chosenList.size(); j++) { String eid = (String) chosenList.get(j); Section s = (Section) map.get(eid); // we will always has a title regardless but we prefer it to be the // 1st section on the chosen list that has an enrollment set if (j == 0) { title = s.getTitle(); } if (s.getEnrollmentSet() != null) { title = s.getTitle(); break; } } return title; } // prepareTitle /** * return an ArrayList of SectionObject * * @param sectionHash * contains an ArrayList collection of SectionObject * @return */ private ArrayList getSectionList(HashMap sectionHash) { ArrayList list = new ArrayList(); // values is an ArrayList of section Collection c = sectionHash.values(); for (Iterator i = c.iterator(); i.hasNext();) { ArrayList l = (ArrayList) i.next(); list.addAll(l); } return list; } private String getAuthorizers(SessionState state) { String authorizers = ""; ArrayList list = (ArrayList) state .getAttribute(STATE_CM_AUTHORIZER_LIST); if (list != null) { for (int i = 0; i < list.size(); i++) { if (i == 0) { authorizers = (String) list.get(i); } else { authorizers = authorizers + ", " + list.get(i); } } } return authorizers; } private List prepareSectionObject(List sectionList, String userId) { ArrayList list = new ArrayList(); if (sectionList != null) { for (int i = 0; i < sectionList.size(); i++) { String sectionEid = (String) sectionList.get(i); Section s = cms.getSection(sectionEid); SectionObject so = new SectionObject(s); so.setAuthorizer(userId); list.add(so); } } return list; } /** * change collection object to list object * @param c * @return */ private List collectionToList(Collection c) { List rv = new Vector(); if (c!=null) { for (Iterator i = c.iterator(); i.hasNext();) { rv.add(i.next()); } } return rv; } protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { ToolSession toolSession = SessionManager.getCurrentToolSession(); SessionState state = getState(req); if (SITE_MODE_HELPER_DONE.equals(state.getAttribute(STATE_SITE_MODE))) { String url = (String) SessionManager.getCurrentToolSession().getAttribute(Tool.HELPER_DONE_URL); SessionManager.getCurrentToolSession().removeAttribute(Tool.HELPER_DONE_URL); // TODO: Implement cleanup. cleanState(state); // Helper cleanup. cleanStateHelper(state); if (M_log.isDebugEnabled()) { M_log.debug("Sending redirect to: "+ url); } try { res.sendRedirect(url); } catch (IOException e) { M_log.warn("Problem sending redirect to: "+ url, e); } return; } else { super.toolModeDispatch(methodBase, methodExt, req, res); } } private void cleanStateHelper(SessionState state) { state.removeAttribute(STATE_SITE_MODE); state.removeAttribute(STATE_TEMPLATE_INDEX); state.removeAttribute(STATE_INITIALIZED); } }
fix to SAK-3566:Setting in sakai.properties to make the display of Edit Class Roster optional git-svn-id: 19a9fd284f7506c72ea2840aac2b5d740703d7e8@52017 66ffb92e-73f9-0310-93c1-f5514f145a0a
site-manage/site-manage-tool/tool/src/java/org/sakaiproject/site/tool/SiteAction.java
fix to SAK-3566:Setting in sakai.properties to make the display of Edit Class Roster optional
Java
apache-2.0
bfb7c80505acde8e20f9985a87e01e67538d9c41
0
juhalindfors/bazel-patches,snnn/bazel,werkt/bazel,spxtr/bazel,twitter-forks/bazel,dropbox/bazel,damienmg/bazel,ButterflyNetwork/bazel,dropbox/bazel,akira-baruah/bazel,akira-baruah/bazel,katre/bazel,juhalindfors/bazel-patches,meteorcloudy/bazel,spxtr/bazel,bazelbuild/bazel,variac/bazel,werkt/bazel,dslomov/bazel-windows,cushon/bazel,ulfjack/bazel,dslomov/bazel,perezd/bazel,ulfjack/bazel,bazelbuild/bazel,cushon/bazel,safarmer/bazel,katre/bazel,aehlig/bazel,meteorcloudy/bazel,safarmer/bazel,meteorcloudy/bazel,aehlig/bazel,katre/bazel,damienmg/bazel,ButterflyNetwork/bazel,juhalindfors/bazel-patches,ulfjack/bazel,davidzchen/bazel,akira-baruah/bazel,akira-baruah/bazel,meteorcloudy/bazel,variac/bazel,ulfjack/bazel,variac/bazel,akira-baruah/bazel,spxtr/bazel,dropbox/bazel,werkt/bazel,aehlig/bazel,ulfjack/bazel,snnn/bazel,aehlig/bazel,spxtr/bazel,damienmg/bazel,aehlig/bazel,damienmg/bazel,snnn/bazel,davidzchen/bazel,cushon/bazel,twitter-forks/bazel,safarmer/bazel,katre/bazel,davidzchen/bazel,meteorcloudy/bazel,variac/bazel,perezd/bazel,dslomov/bazel-windows,safarmer/bazel,variac/bazel,bazelbuild/bazel,bazelbuild/bazel,variac/bazel,dslomov/bazel,cushon/bazel,dslomov/bazel,dslomov/bazel-windows,werkt/bazel,snnn/bazel,aehlig/bazel,aehlig/bazel,werkt/bazel,safarmer/bazel,snnn/bazel,perezd/bazel,juhalindfors/bazel-patches,dslomov/bazel,juhalindfors/bazel-patches,dropbox/bazel,bazelbuild/bazel,akira-baruah/bazel,damienmg/bazel,dslomov/bazel,dslomov/bazel,cushon/bazel,dslomov/bazel-windows,ulfjack/bazel,ButterflyNetwork/bazel,dropbox/bazel,twitter-forks/bazel,werkt/bazel,dslomov/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,spxtr/bazel,dslomov/bazel-windows,dropbox/bazel,perezd/bazel,davidzchen/bazel,ulfjack/bazel,katre/bazel,twitter-forks/bazel,dslomov/bazel-windows,snnn/bazel,katre/bazel,meteorcloudy/bazel,perezd/bazel,davidzchen/bazel,twitter-forks/bazel,juhalindfors/bazel-patches,bazelbuild/bazel,meteorcloudy/bazel,cushon/bazel,spxtr/bazel,perezd/bazel,damienmg/bazel,davidzchen/bazel,variac/bazel,davidzchen/bazel,perezd/bazel,safarmer/bazel,juhalindfors/bazel-patches,damienmg/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,spxtr/bazel,snnn/bazel
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.rules.android; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.syntax.Type.INTEGER; import static com.google.devtools.build.lib.syntax.Type.STRING; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpls; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule; import com.google.devtools.build.lib.rules.repository.WorkspaceConfiguredTargetFactory; import java.util.Map; import javax.annotation.Nullable; /** * Definition of the {@code android_ndk_repository} rule. */ public class AndroidNdkRepositoryRule implements RuleDefinition { public static final String NAME = "android_ndk_repository"; private static final Function<? super Rule, Map<String, Label>> BINDINGS_FUNCTION = new Function< Rule, Map<String, Label>>() { @Nullable @Override public Map<String, Label> apply(Rule rule) { String defaultToolchainName = AndroidNdkRepositoryFunction.createToolchainName(StlImpls.DEFAULT_STL_NAME); return ImmutableMap.of( "android/crosstool", Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:" + defaultToolchainName), "android_ndk_for_testing", Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:files")); } }; @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { return builder .setWorkspaceOnly() .setExternalBindingsFunction(BINDINGS_FUNCTION) /* <!-- #BLAZE_RULE(android_ndk_repository).ATTRIBUTE(path) --> An absolute or relative path to an Android NDK. Either this attribute or the <code>$ANDROID_NDK_HOME</code> environment variable must be set. <p>The Android NDK can be downloaded from <a href='https://developer.android.com/ndk/downloads/index.html'>the Android developer site </a>. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("path", STRING).nonconfigurable("WORKSPACE rule")) /* <!-- #BLAZE_RULE(android_ndk_repository).ATTRIBUTE(api_level) --> The Android API level to build against. If not specified, the highest API level installed will be used. <!-- #END_BLAZE_RULE.ATTRIBUTE --> */ .add(attr("api_level", INTEGER).nonconfigurable("WORKSPACE rule")) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name(AndroidNdkRepositoryRule.NAME) .type(RuleClassType.WORKSPACE) .ancestors(WorkspaceBaseRule.class) .factoryClass(WorkspaceConfiguredTargetFactory.class) .build(); } } /*<!-- #BLAZE_RULE (NAME=android_ndk_repository, TYPE=OTHER, FAMILY=Workspace)[GENERIC_RULE] --> <p>Configures Bazel to use an Android NDK to support building Android targets with native code. NDK versions 10, 11, 12, 13 and 14 are currently supported. <p>Note that building for Android also requires an <code>android_sdk_repository</code> rule in your <code>WORKSPACE</code> file. <h4 id="android_ndk_repository_examples">Examples</h4> <pre class="code"> android_ndk_repository( name = "androidndk", ) </pre> <p>The above example will locate your Android NDK from <code>$ANDROID_NDK_HOME</code> and detect the highest API level that it supports. <pre class="code"> android_ndk_repository( name = "androidndk", path = "./android-ndk-r12b", api_level = 24, ) </pre> <p>The above example will use the Android NDK located inside your workspace in <code>./android-ndk-r12b</code>. It will use the API level 24 libraries when compiling your JNI code. <h4 id="android_ndk_repository_cpufeatures">cpufeatures</h4> <p>The Android NDK contains the <a href="https://developer.android.com/ndk/guides/cpu-features.html">cpufeatures library</a> which can be used to detect a device's CPU at runtime. The following example demonstrates how to use cpufeatures with Bazel. <pre class="code"> # jni.cc #include "ndk/sources/android/cpufeatures/cpu-features.h" ... </pre> <pre class="code"> # BUILD cc_library( name = "jni", srcs = ["jni.cc"], deps = ["@androidndk//:cpufeatures"], ) </pre> <!-- #END_BLAZE_RULE -->*/
src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.bazel.rules.android; import static com.google.devtools.build.lib.packages.Attribute.attr; import static com.google.devtools.build.lib.syntax.Type.INTEGER; import static com.google.devtools.build.lib.syntax.Type.STRING; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.analysis.RuleDefinition; import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment; import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpls; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.packages.Rule; import com.google.devtools.build.lib.packages.RuleClass; import com.google.devtools.build.lib.packages.RuleClass.Builder; import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType; import com.google.devtools.build.lib.rules.repository.WorkspaceBaseRule; import com.google.devtools.build.lib.rules.repository.WorkspaceConfiguredTargetFactory; import java.util.Map; import javax.annotation.Nullable; /** * Definition of the {@code android_ndk_repository} rule. */ public class AndroidNdkRepositoryRule implements RuleDefinition { public static final String NAME = "android_ndk_repository"; private static final Function<? super Rule, Map<String, Label>> BINDINGS_FUNCTION = new Function< Rule, Map<String, Label>>() { @Nullable @Override public Map<String, Label> apply(Rule rule) { String defaultToolchainName = AndroidNdkRepositoryFunction.createToolchainName(StlImpls.DEFAULT_STL_NAME); return ImmutableMap.of( "android/crosstool", Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:" + defaultToolchainName), "android_ndk_for_testing", Label.parseAbsoluteUnchecked("@" + rule.getName() + "//:files")); } }; @Override public RuleClass build(Builder builder, RuleDefinitionEnvironment environment) { return builder .setUndocumented() .setWorkspaceOnly() .setExternalBindingsFunction(BINDINGS_FUNCTION) .add(attr("path", STRING).nonconfigurable("WORKSPACE rule")) .add(attr("api_level", INTEGER).nonconfigurable("WORKSPACE rule")) .build(); } @Override public Metadata getMetadata() { return RuleDefinition.Metadata.builder() .name(AndroidNdkRepositoryRule.NAME) .type(RuleClassType.WORKSPACE) .ancestors(WorkspaceBaseRule.class) .factoryClass(WorkspaceConfiguredTargetFactory.class) .build(); } }
Document android_ndk_repository. One step towards https://github.com/bazelbuild/bazel/issues/1272. RELNOTES: None PiperOrigin-RevId: 156082858
src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryRule.java
Document android_ndk_repository.
Java
apache-2.0
f66343050f5157a5ade09ed219f3158141975f29
0
ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,ultratendency/hbase,Apache9/hbase,ndimiduk/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,Eshcar/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ndimiduk/hbase,bijugs/hbase,mahak/hbase,ultratendency/hbase,Apache9/hbase,apurtell/hbase,Eshcar/hbase,Apache9/hbase,bijugs/hbase,mahak/hbase,bijugs/hbase,mahak/hbase,ultratendency/hbase,apurtell/hbase,mahak/hbase,Eshcar/hbase,ndimiduk/hbase,apurtell/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,ultratendency/hbase,Eshcar/hbase,ndimiduk/hbase,apurtell/hbase,Apache9/hbase,francisliu/hbase,apurtell/hbase,Eshcar/hbase,Eshcar/hbase,Eshcar/hbase,ultratendency/hbase,ndimiduk/hbase,francisliu/hbase,ultratendency/hbase,mahak/hbase,francisliu/hbase,Apache9/hbase,bijugs/hbase,ndimiduk/hbase,Apache9/hbase,apurtell/hbase,Eshcar/hbase,bijugs/hbase,ndimiduk/hbase,ultratendency/hbase,francisliu/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,francisliu/hbase,ndimiduk/hbase,apurtell/hbase,ultratendency/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,bijugs/hbase,bijugs/hbase,bijugs/hbase,francisliu/hbase,francisliu/hbase,mahak/hbase,francisliu/hbase,Eshcar/hbase,ChinmaySKulkarni/hbase,bijugs/hbase,ultratendency/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,mahak/hbase,Apache9/hbase,Eshcar/hbase,mahak/hbase,Apache9/hbase,ndimiduk/hbase,ultratendency/hbase,apurtell/hbase
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.namespace; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.Waiter; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.DoNotRetryRegionException; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.MasterObserver; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionObserver; import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionServerObserver; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.master.MasterCoprocessorHost; import org.apache.hadoop.hbase.master.TableNamespaceManager; import org.apache.hadoop.hbase.quotas.MasterQuotaManager; import org.apache.hadoop.hbase.quotas.QuotaExceededException; import org.apache.hadoop.hbase.quotas.QuotaUtil; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.util.Threads; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Category(MediumTests.class) public class TestNamespaceAuditor { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestNamespaceAuditor.class); private static final Logger LOG = LoggerFactory.getLogger(TestNamespaceAuditor.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static Admin ADMIN; private String prefix = "TestNamespaceAuditor"; @BeforeClass public static void before() throws Exception { Configuration conf = UTIL.getConfiguration(); conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, CustomObserver.class.getName()); conf.setStrings( CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, MasterSyncObserver.class.getName(), CPMasterObserver.class.getName()); conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5); conf.setBoolean(QuotaUtil.QUOTA_CONF_KEY, true); conf.setClass("hbase.coprocessor.regionserver.classes", CPRegionServerObserver.class, RegionServerObserver.class); UTIL.startMiniCluster(1, 1); waitForQuotaInitialize(UTIL); ADMIN = UTIL.getAdmin(); } @AfterClass public static void tearDown() throws Exception { UTIL.shutdownMiniCluster(); } @After public void cleanup() throws Exception, KeeperException { for (HTableDescriptor table : ADMIN.listTables()) { ADMIN.disableTable(table.getTableName()); deleteTable(table.getTableName()); } for (NamespaceDescriptor ns : ADMIN.listNamespaceDescriptors()) { if (ns.getName().startsWith(prefix)) { ADMIN.deleteNamespace(ns.getName()); } } assertTrue("Quota manager not initialized", UTIL.getHBaseCluster().getMaster() .getMasterQuotaManager().isQuotaInitialized()); } @Test public void testTableOperations() throws Exception { String nsp = prefix + "_np2"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "5") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); assertEquals(3, ADMIN.listNamespaceDescriptors().length); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); HTableDescriptor tableDescThree = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table3")); tableDescThree.addFamily(fam1); ADMIN.createTable(tableDescOne); boolean constraintViolated = false; try { ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5); } catch (Exception exp) { assertTrue(exp instanceof IOException); constraintViolated = true; } finally { assertTrue("Constraint not violated for table " + tableDescTwo.getTableName(), constraintViolated); } ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nspState = getQuotaManager().getState(nsp); assertNotNull(nspState); assertTrue(nspState.getTables().size() == 2); assertTrue(nspState.getRegionCount() == 5); constraintViolated = false; try { ADMIN.createTable(tableDescThree); } catch (Exception exp) { assertTrue(exp instanceof IOException); constraintViolated = true; } finally { assertTrue("Constraint not violated for table " + tableDescThree.getTableName(), constraintViolated); } } @Test public void testValidQuotas() throws Exception { boolean exceptionCaught = false; FileSystem fs = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem(); Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir(); NamespaceDescriptor nspDesc = NamespaceDescriptor.create(prefix + "vq1") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "hihdufh") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq2") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "-456") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq3") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "sciigd").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq4") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "-1500").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } } @Test public void testDeleteTable() throws Exception { String namespace = prefix + "_dummy"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(namespace) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "100") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "3").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(namespace)); NamespaceTableAndRegionInfo stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found null for " + namespace, stateInfo); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); ADMIN.createTable(tableDescOne); ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5); stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found to be null.", stateInfo); assertEquals(2, stateInfo.getTables().size()); assertEquals(5, stateInfo.getRegionCountOfTable(tableDescTwo.getTableName())); assertEquals(6, stateInfo.getRegionCount()); ADMIN.disableTable(tableDescOne.getTableName()); deleteTable(tableDescOne.getTableName()); stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found to be null.", stateInfo); assertEquals(5, stateInfo.getRegionCount()); assertEquals(1, stateInfo.getTables().size()); ADMIN.disableTable(tableDescTwo.getTableName()); deleteTable(tableDescTwo.getTableName()); ADMIN.deleteNamespace(namespace); stateInfo = getNamespaceState(namespace); assertNull("Namespace state not found to be null.", stateInfo); } public static class CPRegionServerObserver implements RegionServerCoprocessor, RegionServerObserver { private volatile boolean shouldFailMerge = false; public void failMerge(boolean fail) { shouldFailMerge = fail; } private boolean triggered = false; public synchronized void waitUtilTriggered() throws InterruptedException { while (!triggered) { wait(); } } @Override public Optional<RegionServerObserver> getRegionServerObserver() { return Optional.of(this); } } public static class CPMasterObserver implements MasterCoprocessor, MasterObserver { private volatile boolean shouldFailMerge = false; public void failMerge(boolean fail) { shouldFailMerge = fail; } @Override public Optional<MasterObserver> getMasterObserver() { return Optional.of(this); } @Override public synchronized void preMergeRegionsAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, final RegionInfo[] regionsToMerge) throws IOException { notifyAll(); if (shouldFailMerge) { throw new IOException("fail merge"); } } } @Test public void testRegionMerge() throws Exception { String nsp1 = prefix + "_regiontest"; final int initialRegions = 3; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "" + initialRegions) .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); ADMIN.createNamespace(nspDesc); final TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2"); byte[] columnFamily = Bytes.toBytes("info"); HTableDescriptor tableDescOne = new HTableDescriptor(tableTwo); tableDescOne.addFamily(new HColumnDescriptor(columnFamily)); ADMIN.createTable(tableDescOne, Bytes.toBytes("0"), Bytes.toBytes("9"), initialRegions); Connection connection = ConnectionFactory.createConnection(UTIL.getConfiguration()); try (Table table = connection.getTable(tableTwo)) { UTIL.loadNumericRows(table, Bytes.toBytes("info"), 1000, 1999); } ADMIN.flush(tableTwo); List<RegionInfo> hris = ADMIN.getRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris, RegionInfo.COMPARATOR); Future<?> f = ADMIN.mergeRegionsAsync( hris.get(0).getEncodedNameAsBytes(), hris.get(1).getEncodedNameAsBytes(), false); f.get(10, TimeUnit.SECONDS); hris = ADMIN.getRegions(tableTwo); assertEquals(initialRegions - 1, hris.size()); Collections.sort(hris, RegionInfo.COMPARATOR); UTIL.compact(tableTwo, true); ADMIN.splitRegionAsync(hris.get(0).getRegionName(), Bytes.toBytes("3")).get(10, TimeUnit.SECONDS); hris = ADMIN.getRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris, RegionInfo.COMPARATOR); // Fail region merge through Coprocessor hook MiniHBaseCluster cluster = UTIL.getHBaseCluster(); MasterCoprocessorHost cpHost = cluster.getMaster().getMasterCoprocessorHost(); Coprocessor coprocessor = cpHost.findCoprocessor(CPMasterObserver.class); CPMasterObserver masterObserver = (CPMasterObserver) coprocessor; masterObserver.failMerge(true); f = ADMIN.mergeRegionsAsync( hris.get(1).getEncodedNameAsBytes(), hris.get(2).getEncodedNameAsBytes(), false); try { f.get(10, TimeUnit.SECONDS); fail("Merge was supposed to fail!"); } catch (ExecutionException ee) { // Expected. } hris = ADMIN.getRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris, RegionInfo.COMPARATOR); // verify that we cannot split try { ADMIN.split(tableTwo, Bytes.toBytes("6")); fail(); } catch (DoNotRetryRegionException e) { // Expected } Thread.sleep(2000); assertEquals(initialRegions, ADMIN.getRegions(tableTwo).size()); } /* * Create a table and make sure that the table creation fails after adding this table entry into * namespace quota cache. Now correct the failure and recreate the table with same name. * HBASE-13394 */ @Test public void testRecreateTableWithSameNameAfterFirstTimeFailure() throws Exception { String nsp1 = prefix + "_testRecreateTable"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1").build(); ADMIN.createNamespace(nspDesc); final TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1"); byte[] columnFamily = Bytes.toBytes("info"); HTableDescriptor tableDescOne = new HTableDescriptor(tableOne); tableDescOne.addFamily(new HColumnDescriptor(columnFamily)); MasterSyncObserver.throwExceptionInPreCreateTableAction = true; try { try { ADMIN.createTable(tableDescOne); fail("Table " + tableOne.toString() + "creation should fail."); } catch (Exception exp) { LOG.error(exp.toString(), exp); } assertFalse(ADMIN.tableExists(tableOne)); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp1); assertEquals("First table creation failed in namespace so number of tables in namespace " + "should be 0.", 0, nstate.getTables().size()); MasterSyncObserver.throwExceptionInPreCreateTableAction = false; try { ADMIN.createTable(tableDescOne); } catch (Exception e) { fail("Table " + tableOne.toString() + "creation should succeed."); LOG.error(e.toString(), e); } assertTrue(ADMIN.tableExists(tableOne)); nstate = getNamespaceState(nsp1); assertEquals("First table was created successfully so table size in namespace should " + "be one now.", 1, nstate.getTables().size()); } finally { MasterSyncObserver.throwExceptionInPreCreateTableAction = false; if (ADMIN.tableExists(tableOne)) { ADMIN.disableTable(tableOne); deleteTable(tableOne); } ADMIN.deleteNamespace(nsp1); } } private NamespaceTableAndRegionInfo getNamespaceState(String namespace) throws KeeperException, IOException { return getQuotaManager().getState(namespace); } byte[] getSplitKey(byte[] startKey, byte[] endKey) { String skey = Bytes.toString(startKey); int key; if (StringUtils.isBlank(skey)) { key = Integer.parseInt(Bytes.toString(endKey))/2 ; } else { key = (int) (Integer.parseInt(skey) * 1.5); } return Bytes.toBytes("" + key); } public static class CustomObserver implements RegionCoprocessor, RegionObserver { volatile CountDownLatch postCompact; @Override public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, StoreFile resultFile, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { postCompact.countDown(); } @Override public void start(CoprocessorEnvironment e) throws IOException { postCompact = new CountDownLatch(1); } @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } } @Test public void testStatePreserve() throws Exception { final String nsp1 = prefix + "_testStatePreserve"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "10").build(); ADMIN.createNamespace(nspDesc); TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1"); TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2"); TableName tableThree = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table3"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableOne); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(tableTwo); tableDescTwo.addFamily(fam1); HTableDescriptor tableDescThree = new HTableDescriptor(tableThree); tableDescThree.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3); ADMIN.createTable(tableDescTwo, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3); ADMIN.createTable(tableDescThree, Bytes.toBytes("1"), Bytes.toBytes("1000"), 4); ADMIN.disableTable(tableThree); deleteTable(tableThree); // wait for chore to complete UTIL.waitFor(1000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { return (getNamespaceState(nsp1).getTables().size() == 2); } }); NamespaceTableAndRegionInfo before = getNamespaceState(nsp1); restartMaster(); NamespaceTableAndRegionInfo after = getNamespaceState(nsp1); assertEquals("Expected: " + before.getTables() + " Found: " + after.getTables(), before .getTables().size(), after.getTables().size()); } public static void waitForQuotaInitialize(final HBaseTestingUtility util) throws Exception { util.waitFor(60000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { HMaster master = util.getHBaseCluster().getMaster(); if (master == null) { return false; } MasterQuotaManager quotaManager = master.getMasterQuotaManager(); return quotaManager != null && quotaManager.isQuotaInitialized(); } }); } private void restartMaster() throws Exception { UTIL.getHBaseCluster().getMaster(0).stop("Stopping to start again"); UTIL.getHBaseCluster().waitOnMaster(0); UTIL.getHBaseCluster().startMaster(); waitForQuotaInitialize(UTIL); } private NamespaceAuditor getQuotaManager() { return UTIL.getHBaseCluster().getMaster() .getMasterQuotaManager().getNamespaceQuotaManager(); } public static class MasterSyncObserver implements MasterCoprocessor, MasterObserver { volatile CountDownLatch tableDeletionLatch; static boolean throwExceptionInPreCreateTableAction; @Override public Optional<MasterObserver> getMasterObserver() { return Optional.of(this); } @Override public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException { tableDeletionLatch = new CountDownLatch(1); } @Override public void postCompletedDeleteTableAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, final TableName tableName) throws IOException { tableDeletionLatch.countDown(); } @Override public void preCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx, TableDescriptor desc, RegionInfo[] regions) throws IOException { if (throwExceptionInPreCreateTableAction) { throw new IOException("Throw exception as it is demanded."); } } } private void deleteTable(final TableName tableName) throws Exception { // NOTE: We need a latch because admin is not sync, // so the postOp coprocessor method may be called after the admin operation returned. MasterSyncObserver observer = UTIL.getHBaseCluster().getMaster() .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class); ADMIN.deleteTable(tableName); observer.tableDeletionLatch.await(); } @Test(expected = QuotaExceededException.class) public void testExceedTableQuotaInNamespace() throws Exception { String nsp = prefix + "_testExceedTableQuotaInNamespace"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1") .build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); assertEquals(3, ADMIN.listNamespaceDescriptors().length); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); ADMIN.createTable(tableDescOne); ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); } @Test(expected = QuotaExceededException.class) public void testCloneSnapshotQuotaExceed() throws Exception { String nsp = prefix + "_testTableQuotaExceedWithCloneSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1") .build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne); String snapshot = "snapshot_testTableQuotaExceedWithCloneSnapshot"; ADMIN.snapshot(snapshot, tableName); ADMIN.cloneSnapshot(snapshot, cloneTableName); ADMIN.deleteSnapshot(snapshot); } @Test public void testCloneSnapshot() throws Exception { String nsp = prefix + "_testCloneSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); String snapshot = "snapshot_testCloneSnapshot"; ADMIN.snapshot(snapshot, tableName); ADMIN.cloneSnapshot(snapshot, cloneTableName); int tableLength; try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(tableName)) { tableLength = locator.getStartKeys().length; } assertEquals(tableName.getNameAsString() + " should have four regions.", 4, tableLength); try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(cloneTableName)) { tableLength = locator.getStartKeys().length; } assertEquals(cloneTableName.getNameAsString() + " should have four regions.", 4, tableLength); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Total tables count should be 2.", 2, nstate.getTables().size()); assertEquals("Total regions count should be.", 8, nstate.getRegionCount()); ADMIN.deleteSnapshot(snapshot); } @Test public void testRestoreSnapshot() throws Exception { String nsp = prefix + "_testRestoreSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName1); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount()); String snapshot = "snapshot_testRestoreSnapshot"; ADMIN.snapshot(snapshot, tableName1); List<HRegionInfo> regions = ADMIN.getTableRegions(tableName1); Collections.sort(regions); ADMIN.split(tableName1, Bytes.toBytes("JJJ")); Thread.sleep(2000); assertEquals("Total regions count should be 5.", 5, nstate.getRegionCount()); ADMIN.disableTable(tableName1); ADMIN.restoreSnapshot(snapshot); assertEquals("Total regions count should be 4 after restore.", 4, nstate.getRegionCount()); ADMIN.enableTable(tableName1); ADMIN.deleteSnapshot(snapshot); } @Test public void testRestoreSnapshotQuotaExceed() throws Exception { String nsp = prefix + "_testRestoreSnapshotQuotaExceed"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build(); ADMIN.createNamespace(nspDesc); NamespaceDescriptor ndesc = ADMIN.getNamespaceDescriptor(nsp); assertNotNull("Namespace descriptor found null.", ndesc); TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName1); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount()); String snapshot = "snapshot_testRestoreSnapshotQuotaExceed"; // snapshot has 4 regions ADMIN.snapshot(snapshot, tableName1); // recreate table with 1 region and set max regions to 3 for namespace ADMIN.disableTable(tableName1); ADMIN.deleteTable(tableName1); ADMIN.createTable(tableDescOne); ndesc.setConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "3"); ADMIN.modifyNamespace(ndesc); ADMIN.disableTable(tableName1); try { ADMIN.restoreSnapshot(snapshot); fail("Region quota is exceeded so QuotaExceededException should be thrown but HBaseAdmin" + " wraps IOException into RestoreSnapshotException"); } catch (RestoreSnapshotException ignore) { assertTrue(ignore.getCause() instanceof QuotaExceededException); } assertEquals(1, getNamespaceState(nsp).getRegionCount()); ADMIN.enableTable(tableName1); ADMIN.deleteSnapshot(snapshot); } }
hbase-server/src/test/java/org/apache/hadoop/hbase/namespace/TestNamespaceAuditor.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.namespace; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.Waiter; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.DoNotRetryRegionException; import org.apache.hadoop.hbase.client.RegionInfo; import org.apache.hadoop.hbase.client.RegionLocator; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptor; import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.MasterObserver; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.coprocessor.RegionObserver; import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor; import org.apache.hadoop.hbase.coprocessor.RegionServerObserver; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.master.MasterCoprocessorHost; import org.apache.hadoop.hbase.master.TableNamespaceManager; import org.apache.hadoop.hbase.quotas.MasterQuotaManager; import org.apache.hadoop.hbase.quotas.QuotaExceededException; import org.apache.hadoop.hbase.quotas.QuotaUtil; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.StoreFile; import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.util.Threads; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Category(MediumTests.class) public class TestNamespaceAuditor { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestNamespaceAuditor.class); private static final Logger LOG = LoggerFactory.getLogger(TestNamespaceAuditor.class); private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static Admin ADMIN; private String prefix = "TestNamespaceAuditor"; @BeforeClass public static void before() throws Exception { Configuration conf = UTIL.getConfiguration(); conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, CustomObserver.class.getName()); conf.setStrings( CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, MasterSyncObserver.class.getName(), CPMasterObserver.class.getName()); conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5); conf.setBoolean(QuotaUtil.QUOTA_CONF_KEY, true); conf.setClass("hbase.coprocessor.regionserver.classes", CPRegionServerObserver.class, RegionServerObserver.class); UTIL.startMiniCluster(1, 1); waitForQuotaInitialize(UTIL); ADMIN = UTIL.getAdmin(); } @AfterClass public static void tearDown() throws Exception { UTIL.shutdownMiniCluster(); } @After public void cleanup() throws Exception, KeeperException { for (HTableDescriptor table : ADMIN.listTables()) { ADMIN.disableTable(table.getTableName()); deleteTable(table.getTableName()); } for (NamespaceDescriptor ns : ADMIN.listNamespaceDescriptors()) { if (ns.getName().startsWith(prefix)) { ADMIN.deleteNamespace(ns.getName()); } } assertTrue("Quota manager not initialized", UTIL.getHBaseCluster().getMaster() .getMasterQuotaManager().isQuotaInitialized()); } @Test public void testTableOperations() throws Exception { String nsp = prefix + "_np2"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "5") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); assertEquals(3, ADMIN.listNamespaceDescriptors().length); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); HTableDescriptor tableDescThree = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table3")); tableDescThree.addFamily(fam1); ADMIN.createTable(tableDescOne); boolean constraintViolated = false; try { ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5); } catch (Exception exp) { assertTrue(exp instanceof IOException); constraintViolated = true; } finally { assertTrue("Constraint not violated for table " + tableDescTwo.getTableName(), constraintViolated); } ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nspState = getQuotaManager().getState(nsp); assertNotNull(nspState); assertTrue(nspState.getTables().size() == 2); assertTrue(nspState.getRegionCount() == 5); constraintViolated = false; try { ADMIN.createTable(tableDescThree); } catch (Exception exp) { assertTrue(exp instanceof IOException); constraintViolated = true; } finally { assertTrue("Constraint not violated for table " + tableDescThree.getTableName(), constraintViolated); } } @Test public void testValidQuotas() throws Exception { boolean exceptionCaught = false; FileSystem fs = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem(); Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir(); NamespaceDescriptor nspDesc = NamespaceDescriptor.create(prefix + "vq1") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "hihdufh") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq2") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "-456") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq3") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "sciigd").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } nspDesc = NamespaceDescriptor.create(prefix + "vq4") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "-1500").build(); try { ADMIN.createNamespace(nspDesc); } catch (Exception exp) { LOG.warn(exp.toString(), exp); exceptionCaught = true; } finally { assertTrue(exceptionCaught); assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName()))); } } @Test public void testDeleteTable() throws Exception { String namespace = prefix + "_dummy"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(namespace) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "100") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "3").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(namespace)); NamespaceTableAndRegionInfo stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found null for " + namespace, stateInfo); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); ADMIN.createTable(tableDescOne); ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5); stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found to be null.", stateInfo); assertEquals(2, stateInfo.getTables().size()); assertEquals(5, stateInfo.getRegionCountOfTable(tableDescTwo.getTableName())); assertEquals(6, stateInfo.getRegionCount()); ADMIN.disableTable(tableDescOne.getTableName()); deleteTable(tableDescOne.getTableName()); stateInfo = getNamespaceState(nspDesc.getName()); assertNotNull("Namespace state found to be null.", stateInfo); assertEquals(5, stateInfo.getRegionCount()); assertEquals(1, stateInfo.getTables().size()); ADMIN.disableTable(tableDescTwo.getTableName()); deleteTable(tableDescTwo.getTableName()); ADMIN.deleteNamespace(namespace); stateInfo = getNamespaceState(namespace); assertNull("Namespace state not found to be null.", stateInfo); } public static class CPRegionServerObserver implements RegionServerCoprocessor, RegionServerObserver { private volatile boolean shouldFailMerge = false; public void failMerge(boolean fail) { shouldFailMerge = fail; } private boolean triggered = false; public synchronized void waitUtilTriggered() throws InterruptedException { while (!triggered) { wait(); } } @Override public Optional<RegionServerObserver> getRegionServerObserver() { return Optional.of(this); } } public static class CPMasterObserver implements MasterCoprocessor, MasterObserver { private volatile boolean shouldFailMerge = false; public void failMerge(boolean fail) { shouldFailMerge = fail; } @Override public Optional<MasterObserver> getMasterObserver() { return Optional.of(this); } @Override public synchronized void preMergeRegionsAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, final RegionInfo[] regionsToMerge) throws IOException { notifyAll(); if (shouldFailMerge) { throw new IOException("fail merge"); } } } @Test public void testRegionMerge() throws Exception { String nsp1 = prefix + "_regiontest"; final int initialRegions = 3; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "" + initialRegions) .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); ADMIN.createNamespace(nspDesc); final TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2"); byte[] columnFamily = Bytes.toBytes("info"); HTableDescriptor tableDescOne = new HTableDescriptor(tableTwo); tableDescOne.addFamily(new HColumnDescriptor(columnFamily)); ADMIN.createTable(tableDescOne, Bytes.toBytes("0"), Bytes.toBytes("9"), initialRegions); Connection connection = ConnectionFactory.createConnection(UTIL.getConfiguration()); try (Table table = connection.getTable(tableTwo)) { UTIL.loadNumericRows(table, Bytes.toBytes("info"), 1000, 1999); } ADMIN.flush(tableTwo); List<HRegionInfo> hris = ADMIN.getTableRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris); Future<?> f = ADMIN.mergeRegionsAsync( hris.get(0).getEncodedNameAsBytes(), hris.get(1).getEncodedNameAsBytes(), false); f.get(10, TimeUnit.SECONDS); hris = ADMIN.getTableRegions(tableTwo); assertEquals(initialRegions - 1, hris.size()); Collections.sort(hris); ADMIN.split(tableTwo, Bytes.toBytes("3")); // Not much we can do here until we have split return a Future. Threads.sleep(5000); hris = ADMIN.getTableRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris); // Fail region merge through Coprocessor hook MiniHBaseCluster cluster = UTIL.getHBaseCluster(); MasterCoprocessorHost cpHost = cluster.getMaster().getMasterCoprocessorHost(); Coprocessor coprocessor = cpHost.findCoprocessor(CPMasterObserver.class); CPMasterObserver masterObserver = (CPMasterObserver) coprocessor; masterObserver.failMerge(true); f = ADMIN.mergeRegionsAsync( hris.get(1).getEncodedNameAsBytes(), hris.get(2).getEncodedNameAsBytes(), false); try { f.get(10, TimeUnit.SECONDS); fail("Merge was supposed to fail!"); } catch (ExecutionException ee) { // Expected. } hris = ADMIN.getTableRegions(tableTwo); assertEquals(initialRegions, hris.size()); Collections.sort(hris); // verify that we cannot split HRegionInfo hriToSplit2 = hris.get(1); try { ADMIN.split(tableTwo, Bytes.toBytes("6")); fail(); } catch (DoNotRetryRegionException e) { // Expected } Thread.sleep(2000); assertEquals(initialRegions, ADMIN.getTableRegions(tableTwo).size()); } /* * Create a table and make sure that the table creation fails after adding this table entry into * namespace quota cache. Now correct the failure and recreate the table with same name. * HBASE-13394 */ @Test public void testRecreateTableWithSameNameAfterFirstTimeFailure() throws Exception { String nsp1 = prefix + "_testRecreateTable"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1").build(); ADMIN.createNamespace(nspDesc); final TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1"); byte[] columnFamily = Bytes.toBytes("info"); HTableDescriptor tableDescOne = new HTableDescriptor(tableOne); tableDescOne.addFamily(new HColumnDescriptor(columnFamily)); MasterSyncObserver.throwExceptionInPreCreateTableAction = true; try { try { ADMIN.createTable(tableDescOne); fail("Table " + tableOne.toString() + "creation should fail."); } catch (Exception exp) { LOG.error(exp.toString(), exp); } assertFalse(ADMIN.tableExists(tableOne)); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp1); assertEquals("First table creation failed in namespace so number of tables in namespace " + "should be 0.", 0, nstate.getTables().size()); MasterSyncObserver.throwExceptionInPreCreateTableAction = false; try { ADMIN.createTable(tableDescOne); } catch (Exception e) { fail("Table " + tableOne.toString() + "creation should succeed."); LOG.error(e.toString(), e); } assertTrue(ADMIN.tableExists(tableOne)); nstate = getNamespaceState(nsp1); assertEquals("First table was created successfully so table size in namespace should " + "be one now.", 1, nstate.getTables().size()); } finally { MasterSyncObserver.throwExceptionInPreCreateTableAction = false; if (ADMIN.tableExists(tableOne)) { ADMIN.disableTable(tableOne); deleteTable(tableOne); } ADMIN.deleteNamespace(nsp1); } } private NamespaceTableAndRegionInfo getNamespaceState(String namespace) throws KeeperException, IOException { return getQuotaManager().getState(namespace); } byte[] getSplitKey(byte[] startKey, byte[] endKey) { String skey = Bytes.toString(startKey); int key; if (StringUtils.isBlank(skey)) { key = Integer.parseInt(Bytes.toString(endKey))/2 ; } else { key = (int) (Integer.parseInt(skey) * 1.5); } return Bytes.toBytes("" + key); } public static class CustomObserver implements RegionCoprocessor, RegionObserver { volatile CountDownLatch postCompact; @Override public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store, StoreFile resultFile, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { postCompact.countDown(); } @Override public void start(CoprocessorEnvironment e) throws IOException { postCompact = new CountDownLatch(1); } @Override public Optional<RegionObserver> getRegionObserver() { return Optional.of(this); } } @Test public void testStatePreserve() throws Exception { final String nsp1 = prefix + "_testStatePreserve"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "10").build(); ADMIN.createNamespace(nspDesc); TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1"); TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2"); TableName tableThree = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table3"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableOne); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(tableTwo); tableDescTwo.addFamily(fam1); HTableDescriptor tableDescThree = new HTableDescriptor(tableThree); tableDescThree.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3); ADMIN.createTable(tableDescTwo, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3); ADMIN.createTable(tableDescThree, Bytes.toBytes("1"), Bytes.toBytes("1000"), 4); ADMIN.disableTable(tableThree); deleteTable(tableThree); // wait for chore to complete UTIL.waitFor(1000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { return (getNamespaceState(nsp1).getTables().size() == 2); } }); NamespaceTableAndRegionInfo before = getNamespaceState(nsp1); restartMaster(); NamespaceTableAndRegionInfo after = getNamespaceState(nsp1); assertEquals("Expected: " + before.getTables() + " Found: " + after.getTables(), before .getTables().size(), after.getTables().size()); } public static void waitForQuotaInitialize(final HBaseTestingUtility util) throws Exception { util.waitFor(60000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { HMaster master = util.getHBaseCluster().getMaster(); if (master == null) { return false; } MasterQuotaManager quotaManager = master.getMasterQuotaManager(); return quotaManager != null && quotaManager.isQuotaInitialized(); } }); } private void restartMaster() throws Exception { UTIL.getHBaseCluster().getMaster(0).stop("Stopping to start again"); UTIL.getHBaseCluster().waitOnMaster(0); UTIL.getHBaseCluster().startMaster(); waitForQuotaInitialize(UTIL); } private NamespaceAuditor getQuotaManager() { return UTIL.getHBaseCluster().getMaster() .getMasterQuotaManager().getNamespaceQuotaManager(); } public static class MasterSyncObserver implements MasterCoprocessor, MasterObserver { volatile CountDownLatch tableDeletionLatch; static boolean throwExceptionInPreCreateTableAction; @Override public Optional<MasterObserver> getMasterObserver() { return Optional.of(this); } @Override public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName) throws IOException { tableDeletionLatch = new CountDownLatch(1); } @Override public void postCompletedDeleteTableAction( final ObserverContext<MasterCoprocessorEnvironment> ctx, final TableName tableName) throws IOException { tableDeletionLatch.countDown(); } @Override public void preCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx, TableDescriptor desc, RegionInfo[] regions) throws IOException { if (throwExceptionInPreCreateTableAction) { throw new IOException("Throw exception as it is demanded."); } } } private void deleteTable(final TableName tableName) throws Exception { // NOTE: We need a latch because admin is not sync, // so the postOp coprocessor method may be called after the admin operation returned. MasterSyncObserver observer = UTIL.getHBaseCluster().getMaster() .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class); ADMIN.deleteTable(tableName); observer.tableDeletionLatch.await(); } @Test(expected = QuotaExceededException.class) public void testExceedTableQuotaInNamespace() throws Exception { String nsp = prefix + "_testExceedTableQuotaInNamespace"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1") .build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); assertEquals(3, ADMIN.listNamespaceDescriptors().length); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1")); tableDescOne.addFamily(fam1); HTableDescriptor tableDescTwo = new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2")); tableDescTwo.addFamily(fam1); ADMIN.createTable(tableDescOne); ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); } @Test(expected = QuotaExceededException.class) public void testCloneSnapshotQuotaExceed() throws Exception { String nsp = prefix + "_testTableQuotaExceedWithCloneSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1") .build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne); String snapshot = "snapshot_testTableQuotaExceedWithCloneSnapshot"; ADMIN.snapshot(snapshot, tableName); ADMIN.cloneSnapshot(snapshot, cloneTableName); ADMIN.deleteSnapshot(snapshot); } @Test public void testCloneSnapshot() throws Exception { String nsp = prefix + "_testCloneSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2") .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); String snapshot = "snapshot_testCloneSnapshot"; ADMIN.snapshot(snapshot, tableName); ADMIN.cloneSnapshot(snapshot, cloneTableName); int tableLength; try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(tableName)) { tableLength = locator.getStartKeys().length; } assertEquals(tableName.getNameAsString() + " should have four regions.", 4, tableLength); try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(cloneTableName)) { tableLength = locator.getStartKeys().length; } assertEquals(cloneTableName.getNameAsString() + " should have four regions.", 4, tableLength); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Total tables count should be 2.", 2, nstate.getTables().size()); assertEquals("Total regions count should be.", 8, nstate.getRegionCount()); ADMIN.deleteSnapshot(snapshot); } @Test public void testRestoreSnapshot() throws Exception { String nsp = prefix + "_testRestoreSnapshot"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build(); ADMIN.createNamespace(nspDesc); assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp)); TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName1); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount()); String snapshot = "snapshot_testRestoreSnapshot"; ADMIN.snapshot(snapshot, tableName1); List<HRegionInfo> regions = ADMIN.getTableRegions(tableName1); Collections.sort(regions); ADMIN.split(tableName1, Bytes.toBytes("JJJ")); Thread.sleep(2000); assertEquals("Total regions count should be 5.", 5, nstate.getRegionCount()); ADMIN.disableTable(tableName1); ADMIN.restoreSnapshot(snapshot); assertEquals("Total regions count should be 4 after restore.", 4, nstate.getRegionCount()); ADMIN.enableTable(tableName1); ADMIN.deleteSnapshot(snapshot); } @Test public void testRestoreSnapshotQuotaExceed() throws Exception { String nsp = prefix + "_testRestoreSnapshotQuotaExceed"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build(); ADMIN.createNamespace(nspDesc); NamespaceDescriptor ndesc = ADMIN.getNamespaceDescriptor(nsp); assertNotNull("Namespace descriptor found null.", ndesc); TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"); HTableDescriptor tableDescOne = new HTableDescriptor(tableName1); HColumnDescriptor fam1 = new HColumnDescriptor("fam1"); tableDescOne.addFamily(fam1); ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4); NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp); assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount()); String snapshot = "snapshot_testRestoreSnapshotQuotaExceed"; // snapshot has 4 regions ADMIN.snapshot(snapshot, tableName1); // recreate table with 1 region and set max regions to 3 for namespace ADMIN.disableTable(tableName1); ADMIN.deleteTable(tableName1); ADMIN.createTable(tableDescOne); ndesc.setConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "3"); ADMIN.modifyNamespace(ndesc); ADMIN.disableTable(tableName1); try { ADMIN.restoreSnapshot(snapshot); fail("Region quota is exceeded so QuotaExceededException should be thrown but HBaseAdmin" + " wraps IOException into RestoreSnapshotException"); } catch (RestoreSnapshotException ignore) { assertTrue(ignore.getCause() instanceof QuotaExceededException); } assertEquals(1, getNamespaceState(nsp).getRegionCount()); ADMIN.enableTable(tableName1); ADMIN.deleteSnapshot(snapshot); } }
HBASE-20363 TestNamespaceAuditor.testRegionMerge is flaky
hbase-server/src/test/java/org/apache/hadoop/hbase/namespace/TestNamespaceAuditor.java
HBASE-20363 TestNamespaceAuditor.testRegionMerge is flaky
Java
apache-2.0
8765c955be60df8c079d9a4f3e390986a0c09967
0
FuckBoilerplate/base_app_android
/* * Copyright 2016 FuckBoilerplate * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.presentation.sections; import android.content.Intent; import android.os.Bundle; import org.base_app_android.R; import javax.inject.Inject; import app.presentation.foundation.BaseApp; import app.presentation.foundation.views.BaseActivity; import app.presentation.foundation.views.SingleActivity; import app.presentation.sections.dashboard.DashBoardActivity; import app.presentation.sections.user_demo.detail.UserFragment; import app.presentation.sections.user_demo.search.SearchUserFragment; /** * Provides the routing for the application screens. */ public class Wireframe { private final BaseApp baseApp; @Inject public Wireframe(BaseApp baseApp) { this.baseApp = baseApp; } public void dashboard() { baseApp.getLiveActivity().startActivity(new Intent(baseApp, DashBoardActivity.class)); } public void userScreen() { Bundle bundle = new Bundle(); bundle.putString(BaseActivity.Behaviour.TITLE_KEY, baseApp.getString(R.string.user)); bundle.putSerializable(BaseActivity.Behaviour.FRAGMENT_CLASS_KEY, UserFragment.class); Intent intent = new Intent(baseApp, SingleActivity.class); intent.putExtras(bundle); baseApp.getLiveActivity().startActivity(intent); } public void searchUserScreen() { Bundle bundleFragment = new Bundle(); bundleFragment.putString(SearchUserFragment.HELLO_FROM_BUNDLE_WIREFRAME_KEY, "Hi from wireframe bundle"); Bundle bundle = new Bundle(); bundle.putString(BaseActivity.Behaviour.TITLE_KEY, baseApp.getString(R.string.find_user)); bundle.putSerializable(BaseActivity.Behaviour.FRAGMENT_CLASS_KEY, SearchUserFragment.class); bundle.putBundle(BaseActivity.Behaviour.BUNDLE_FOR_FRAGMENT, bundleFragment); Intent intent = new Intent(baseApp, SingleActivity.class); intent.putExtras(bundle); baseApp.getLiveActivity().startActivity(intent); } public void popCurrentScreen() { baseApp.getLiveActivity().onBackPressed(); } }
app/src/main/java/app/presentation/sections/Wireframe.java
/* * Copyright 2016 FuckBoilerplate * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.presentation.sections; import android.content.Intent; import android.os.Bundle; import org.base_app_android.R; import javax.inject.Inject; import app.presentation.foundation.BaseApp; import app.presentation.foundation.views.BaseActivity; import app.presentation.foundation.views.SingleActivity; import app.presentation.sections.dashboard.DashBoardActivity; import app.presentation.sections.user_demo.detail.UserFragment; import app.presentation.sections.user_demo.search.SearchUserFragment; /** * Provides the routing for the application screens. */ public class Wireframe { private final BaseApp baseApp; @Inject public Wireframe(BaseApp baseApp) { this.baseApp = baseApp; } public void dashboard() { baseApp.getLiveActivity().startActivity(new Intent(baseApp, DashBoardActivity.class)); } public void userScreen() { Bundle bundle = new Bundle(); bundle.putString(BaseActivity.Behaviour.TITLE_KEY, baseApp.getString(R.string.user)); bundle.putSerializable(BaseActivity.Behaviour.FRAGMENT_CLASS_KEY, UserFragment.class); Intent intent = new Intent(baseApp, SingleActivity.class); intent.putExtras(bundle); baseApp.getLiveActivity().startActivity(intent); } public void searchUserScreen() { Bundle bundleFragment = new Bundle(); bundleFragment.putString(SearchUserFragment.HELLO_FROM_BUNDLE_WIREFRAME_KEY, "Hi from wireframe bundle"); Bundle bundle = new Bundle(); bundle.putString(BaseActivity.Behaviour.TITLE_KEY, baseApp.getString(R.string.find_user)); bundle.putSerializable(BaseActivity.Behaviour.FRAGMENT_CLASS_KEY, SearchUserFragment.class); bundle.putBundle(BaseActivity.Behaviour.BUNDLE_FOR_FRAGMENT, bundleFragment); Intent intent = new Intent(baseApp, SingleActivity.class); intent.putExtras(bundle); baseApp.getLiveActivity().startActivity(intent); } public void popCurrentScreen() { baseApp.getLiveActivity().finish(); } }
changed finish call by onBackPressed on popCurrentScreen method implementation
app/src/main/java/app/presentation/sections/Wireframe.java
changed finish call by onBackPressed on popCurrentScreen method implementation
Java
apache-2.0
28f1fb894a590957281b51d8ff37c32535bac487
0
marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api,marklogic/java-client-api
/* * Copyright (c) 2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.datamovement.impl; import com.marklogic.client.datamovement.QueryBatch; import com.marklogic.client.datamovement.QueryBatchListener; import com.marklogic.client.datamovement.DataMovementManager; import com.marklogic.client.datamovement.DataMovementException; import com.marklogic.client.datamovement.QueryFailureListener; import com.marklogic.client.datamovement.Forest; import com.marklogic.client.datamovement.ForestConfiguration; import com.marklogic.client.datamovement.JobTicket; import com.marklogic.client.datamovement.QueryBatcher; import com.marklogic.client.datamovement.QueryBatchException; import com.marklogic.client.datamovement.QueryEvent; import com.marklogic.client.datamovement.QueryBatcherListener; import com.marklogic.client.impl.HandleAccessor; import com.marklogic.client.impl.HandleImplementation; import com.marklogic.client.io.Format; import com.marklogic.client.io.StringHandle; import com.marklogic.client.io.marker.StructureWriteHandle; import com.marklogic.client.query.RawQueryDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.marklogic.client.DatabaseClient; import com.marklogic.client.ResourceNotFoundException; import com.marklogic.client.query.QueryDefinition; import com.marklogic.client.impl.QueryManagerImpl; import com.marklogic.client.impl.UrisHandle; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /* For implementation explanation, see the comments below above startQuerying, * startIterating, withForestConfig, and retry. */ public class QueryBatcherImpl extends BatcherImpl implements QueryBatcher { private static Logger logger = LoggerFactory.getLogger(QueryBatcherImpl.class); private String queryMethod; private QueryDefinition query; private QueryDefinition originalQuery; private Boolean filtered; private Iterator<String> iterator; private boolean threadCountSet = false; private List<QueryBatchListener> urisReadyListeners = new ArrayList<>(); private List<QueryFailureListener> failureListeners = new ArrayList<>(); private List<QueryBatcherListener> jobCompletionListeners = new ArrayList<>(); private QueryThreadPoolExecutor threadPool; private boolean consistentSnapshot = false; private final AtomicLong batchNumber = new AtomicLong(0); private final AtomicLong resultsSoFar = new AtomicLong(0); private final AtomicLong serverTimestamp = new AtomicLong(-1); private final AtomicReference<List<DatabaseClient>> clientList = new AtomicReference<>(); private Map<Forest,AtomicLong> forestResults = new HashMap<>(); private Map<Forest,AtomicBoolean> forestIsDone = new HashMap<>(); private Map<Forest, AtomicInteger> retryForestMap = new HashMap<>(); private AtomicBoolean runJobCompletionListeners = new AtomicBoolean(false); private final Object lock = new Object(); private final Map<Forest,List<QueryTask>> blackListedTasks = new HashMap<>(); private boolean isSingleThreaded = false; private long maxUris = Long.MAX_VALUE; private long maxBatches = Long.MAX_VALUE; QueryBatcherImpl( QueryDefinition originalQuery, DataMovementManager moveMgr, ForestConfiguration forestConfig, String serializedCtsQuery, Boolean filtered ) { this(moveMgr, forestConfig); QueryManagerImpl queryMgr = (QueryManagerImpl) getPrimaryClient().newQueryManager(); if (serializedCtsQuery != null && serializedCtsQuery.length() > 0) { this.queryMethod = "POST"; this.query = queryMgr.newRawCtsQueryDefinition(new StringHandle(serializedCtsQuery).withFormat(Format.JSON)); this.originalQuery = originalQuery; if (filtered != null) { this.filtered = filtered; } } else { initQuery(originalQuery); } } public QueryBatcherImpl(QueryDefinition query, DataMovementManager moveMgr, ForestConfiguration forestConfig) { this(moveMgr, forestConfig); initQuery(query); } public QueryBatcherImpl(Iterator<String> iterator, DataMovementManager moveMgr, ForestConfiguration forestConfig) { this(moveMgr, forestConfig); this.iterator = iterator; } private QueryBatcherImpl(DataMovementManager moveMgr, ForestConfiguration forestConfig) { super(moveMgr); withForestConfig(forestConfig); withBatchSize(1000); } private void initQuery(QueryDefinition query) { if (query == null) { throw new IllegalArgumentException("Cannot create QueryBatcher with null query"); } // post if the effective version is at least 10.0-5 this.queryMethod = (Long.compareUnsigned(getMoveMgr().getServerVersion(), Long.parseUnsignedLong("10000500")) >= 0) ? "POST" : "GET"; this.query = query; if (query instanceof RawQueryDefinition) { RawQueryDefinition rawQuery = (RawQueryDefinition) query; StructureWriteHandle handle = rawQuery.getHandle(); @SuppressWarnings("rawtypes") HandleImplementation baseHandle = HandleAccessor.checkHandle(handle, "queryBatcher"); Format inputFormat = baseHandle.getFormat(); switch(inputFormat) { case UNKNOWN: baseHandle.setFormat(Format.XML); break; case JSON: case XML: break; default: throw new UnsupportedOperationException("Only XML and JSON raw query definitions are possible."); } } } @Override public QueryBatcherImpl onUrisReady(QueryBatchListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); urisReadyListeners.add(listener); return this; } @Override public QueryBatcherImpl onQueryFailure(QueryFailureListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); failureListeners.add(listener); return this; } /* Accepts a QueryEvent (usually a QueryBatchException sent to a * onQueryFailure listener) and retries that task. If the task succeeds, it * will spawn the task for the next page in the result set, which will spawn * the task for the next page, etc. A failure in this attempt will not call * onQueryFailure listeners (as that might lead to infinite recursion since * this is usually called by an onQueryFailure listener), but instead will * directly throw the Exception. In order to use the latest * ForestConfiguration yet still query the correct forest for this * QueryEvent, we look for a forest from the current ForestConfiguration * which has the same forest id, then we use the preferred host for the * forest from the current ForestConfiguration. If the current * ForestConfiguration does not have a matching forest, this method throws * IllegalStateException. This works perfectly with the approach used by * HostAvailabilityListener of black-listing unavailable hosts then retrying * the QueryEvent that failed. */ @Override public void retry(QueryEvent queryEvent) { retry(queryEvent, false); } @Override public void retryWithFailureListeners(QueryEvent queryEvent) { retry(queryEvent, true); } private void retry(QueryEvent queryEvent, boolean callFailListeners) { if ( isStopped() == true ) { logger.warn("Job is now stopped, aborting the retry"); return; } Forest retryForest = null; for ( Forest forest : getForestConfig().listForests() ) { if ( forest.equals(queryEvent.getForest()) ) { // while forest and queryEvent.getForest() have equivalent forest id, // we expect forest to have the currently available host info retryForest = forest; break; } } if ( retryForest == null ) { throw new IllegalStateException("Forest for queryEvent (" + queryEvent.getForest().getForestName() + ") is not in current getForestConfig()"); } // we're obviously not done with this forest forestIsDone.get(retryForest).set(false); retryForestMap.get(retryForest).incrementAndGet(); long start = queryEvent.getForestResultsSoFar() + 1; logger.trace("retryForest {} on retryHost {} at start {}", retryForest.getForestName(), retryForest.getPreferredHost(), start); QueryTask runnable = new QueryTask(getMoveMgr(), this, retryForest, queryMethod, query, filtered, queryEvent.getForestBatchNumber(), start, queryEvent.getLastUriForForest(), queryEvent.getJobBatchNumber(), callFailListeners); runnable.run(); } /* * Accepts a QueryBatch which was successfully retrieved from the server and a * QueryBatchListener which was failed to apply and retry that listener on the batch. * */ @Override public void retryListener(QueryBatch batch, QueryBatchListener queryBatchListener) { // We get the batch and modify the client alone in order to make use // of the new forest client in case if the original host is unavailable. DatabaseClient client = null; Forest[] forests = batch.getBatcher().getForestConfig().listForests(); for(Forest forest : forests) { if(forest.equals(batch.getForest())) client = getMoveMgr().getForestClient(forest); } QueryBatchImpl retryBatch = new QueryBatchImpl() .withClient( client ) .withBatcher( batch.getBatcher() ) .withTimestamp( batch.getTimestamp() ) .withServerTimestamp( batch.getServerTimestamp() ) .withItems( batch.getItems() ) .withJobTicket( batch.getJobTicket() ) .withJobBatchNumber( batch.getJobBatchNumber() ) .withJobResultsSoFar( batch.getJobResultsSoFar() ) .withForestBatchNumber( batch.getForestBatchNumber() ) .withForestResultsSoFar( batch.getForestResultsSoFar() ) .withForest( batch.getForest() ) .withJobTicket( batch.getJobTicket() ); queryBatchListener.processEvent(retryBatch); } @Override public QueryBatchListener[] getQuerySuccessListeners() { return getUrisReadyListeners(); } @Override public QueryBatchListener[] getUrisReadyListeners() { return urisReadyListeners.toArray(new QueryBatchListener[urisReadyListeners.size()]); } @Override public QueryFailureListener[] getQueryFailureListeners() { return failureListeners.toArray(new QueryFailureListener[failureListeners.size()]); } @Override public void setUrisReadyListeners(QueryBatchListener... listeners) { requireNotStarted(); urisReadyListeners.clear(); if ( listeners != null ) { for ( QueryBatchListener listener : listeners ) { urisReadyListeners.add(listener); } } } @Override public void setQueryFailureListeners(QueryFailureListener... listeners) { requireNotStarted(); failureListeners.clear(); if ( listeners != null ) { for ( QueryFailureListener listener : listeners ) { failureListeners.add(listener); } } } @Override public QueryBatcher withJobName(String jobName) { requireNotStarted(); super.withJobName(jobName); return this; } @Override public QueryBatcher withJobId(String jobId) { requireNotStarted(); setJobId(jobId); return this; } @Override public QueryBatcher withBatchSize(int batchSize) { requireNotStarted(); super.withBatchSize(batchSize); return this; } @Override public QueryBatcher withThreadCount(int threadCount) { requireNotStarted(); if ( getThreadCount() <= 0 ) { throw new IllegalArgumentException("threadCount must be 1 or greater"); } threadCountSet = true; super.withThreadCount(threadCount); return this; } @Override public QueryBatcher withConsistentSnapshot() { requireNotStarted(); consistentSnapshot = true; return this; } @Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { requireJobStarted(); return threadPool.awaitTermination(timeout, unit); } @Override public boolean awaitCompletion() { try { return awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); } catch(InterruptedException e) { return false; } } @Override public boolean isStopped() { return threadPool != null && threadPool.isTerminated(); } @Override public JobTicket getJobTicket() { requireJobStarted(); return super.getJobTicket(); } private void requireJobStarted() { if ( threadPool == null ) { throw new IllegalStateException("Job not started. First call DataMovementManager.startJob(QueryBatcher)"); } } private void requireNotStarted() { if ( threadPool != null ) { throw new IllegalStateException("Configuration cannot be changed after startJob has been called"); } } @Override public synchronized void start(JobTicket ticket) { if ( threadPool != null ) { logger.warn("startJob called more than once"); return; } if ( getBatchSize() <= 0 ) { withBatchSize(1); logger.warn("batchSize should be 1 or greater--setting batchSize to 1"); } super.setJobTicket(ticket); initialize(); for (QueryBatchListener urisReadyListener : urisReadyListeners) { urisReadyListener.initializeListener(this); } super.setJobStartTime(); super.getStarted().set(true); if(this.maxBatches < Long.MAX_VALUE) { setMaxUris(getMaxBatches()); } if (query != null) { startQuerying(); } else if (iterator != null) { startIterating(); } else { throw new IllegalStateException("Cannot start QueryBatcher without query or iterator"); } } private synchronized void initialize() { if ( threadCountSet == false ) { if ( query != null ) { Forest[] forests = getForestConfig().listForests(); logger.warn("threadCount not set--defaulting to number of forests ({})", forests.length); withThreadCount(forests.length); } else { int hostCount = clientList.get().size(); logger.warn("threadCount not set--defaulting to number of hosts ({})", hostCount); withThreadCount( hostCount ); } // now we've set the threadCount threadCountSet = true; } // If we are iterating and if we have the thread count to 1, we have a single thread acting as both // consumer and producer of the ThreadPoolExecutor queue. Hence, we produce till the maximum and start // consuming and produce again. Since the thread count is 1, there is no worry about thread utilization. if(getThreadCount() == 1) { isSingleThreaded = true; } logger.info("Starting job batchSize={}, threadCount={}, onUrisReady listeners={}, failure listeners={}", getBatchSize(), getThreadCount(), urisReadyListeners.size(), failureListeners.size()); threadPool = new QueryThreadPoolExecutor(getThreadCount(), this); } /* When withForestConfig is called before the job starts, it just provides * the list of forests (and thus hosts) to talk to. When withForestConfig is * called mid-job, every attempt is made to switch any queued or future task * to use the new ForestConfiguration. This allows monitoring listeners like * HostAvailabilityListener to black-list hosts immediately when a host is * detected to be unavailable. In theory customer listeners could do even * more advanced monitoring. By decoupling the monitoring from the task * management, all a listener has to do is inform us what forests and what * hosts to talk to (by calling withForestConfig), and we'll manage ensuring * any queued or future tasks only talk to those forests and hosts. We * update clientList with a DatabaseClient per host which is used for * round-robin communication by startIterating (the version of QueryBatcher * that accepts an Iterator<String>). We also loop through any queued tasks * and point them to hosts and forests that are in the new * ForestConfiguration. If any queued tasks point to forests that are * missing from the new ForestConfiguration, those tasks are held in * blackListedTasks on the assumption that those tasks can be restarted once * those forests come back online. If withForestConfig is called later with * those forests back online, those tasks will be restarted. If the job * finishes before those forests come back online (and are provided this job * by a call to withForestConfig), then any blackListedTasks are left * unfinished and it's likely that not all documents that should have matched * the query will be processed. The only solution to this is to have a * cluster that is available during the job run (or if there's an outage, it * gets resolved during the job run). Simply put, there's no way for a job to * get documents from unavailable forests. * * If the ForestConfiguration provides new forests, jobs will be started to * get documenst from those forests (the code is in cleanupExistingTasks). */ @Override public synchronized QueryBatcher withForestConfig(ForestConfiguration forestConfig) { super.withForestConfig(forestConfig); Forest[] forests = forests(forestConfig); Set<Forest> oldForests = new HashSet<>(forestResults.keySet()); Map<String,Forest> hosts = new HashMap<>(); for ( Forest forest : forests ) { if ( forest.getPreferredHost() == null ) throw new IllegalStateException("Hostname must not be null for any forest"); hosts.put(forest.getPreferredHost(), forest); if ( forestResults.get(forest) == null ) forestResults.put(forest, new AtomicLong()); if ( forestIsDone.get(forest) == null ) forestIsDone.put(forest, new AtomicBoolean(false)); if ( retryForestMap.get(forest) == null ) retryForestMap.put(forest, new AtomicInteger(0)); } Set<String> hostNames = hosts.keySet(); logger.info("(withForestConfig) Using forests on {} hosts for \"{}\"", hostNames, forests[0].getDatabaseName()); List<DatabaseClient> newClientList = clients(hostNames); clientList.set(newClientList); boolean started = (threadPool != null); if ( started == true && oldForests.size() > 0 ) calculateDeltas(oldForests, forests); return this; } private synchronized void calculateDeltas(Set<Forest> oldForests, Forest[] forests) { // the forests we haven't known about yet Set<Forest> addedForests = new HashSet<>(); // the forests that we knew about but they were black-listed and are no longer black-listed Set<Forest> restartedForests = new HashSet<>(); // any known forest might now be black-listed Set<Forest> blackListedForests = new HashSet<>(oldForests); for ( Forest forest : forests ) { if ( ! oldForests.contains(forest) ) { // we need to do special handling since we're adding this new forest after we're started addedForests.add(forest); } // if we have blackListedTasks for this forest, let's restart them if ( blackListedTasks.get(forest) != null ) restartedForests.add(forest); // this forest is not black-listed blackListedForests.remove(forest); } if ( blackListedForests.size() > 0 ) { DataMovementManagerImpl moveMgrImpl = getMoveMgr(); String primaryHost = moveMgrImpl.getPrimaryClient().getHost(); if ( getHostNames(blackListedForests).contains(primaryHost) ) { int randomPos = new Random().nextInt(clientList.get().size()); moveMgrImpl.setPrimaryClient(clientList.get().get(randomPos)); } } cleanupExistingTasks(addedForests, restartedForests, blackListedForests); } private synchronized void cleanupExistingTasks(Set<Forest> addedForests, Set<Forest> restartedForests, Set<Forest> blackListedForests) { if ( blackListedForests.size() > 0 ) { logger.warn("removing jobs related to hosts [{}] from the queue", getHostNames(blackListedForests)); // since some forests have been removed, let's remove from the queue any jobs that were targeting that forest List<Runnable> tasks = new ArrayList<>(); threadPool.getQueue().drainTo(tasks); for ( Runnable task : tasks ) { if ( task instanceof QueryTask ) { QueryTask queryTask = (QueryTask) task; if ( blackListedForests.contains(queryTask.forest) ) { // this batch was targeting a forest that's no longer on the list // so keep track of it in case this forest comes back on-line List<QueryTask> blackListedTaskList = blackListedTasks.get(queryTask.forest); if ( blackListedTaskList == null ) { blackListedTaskList = new ArrayList<QueryTask>(); blackListedTasks.put(queryTask.forest, blackListedTaskList); } blackListedTaskList.add(queryTask); // jump to the next task continue; } } // this task is still valid so add it back to the queue threadPool.execute(task); } } if ( addedForests.size() > 0 ) { logger.warn("adding jobs for forests [{}] to the queue", getForestNames(addedForests)); } for ( Forest forest : addedForests ) { // we don't need to worry about consistentSnapshotFirstQueryHasRun because that's already done // or we wouldn't be here because we wouldn't have a synchronized lock on this threadPool.execute(new QueryTask( getMoveMgr(), this, forest, queryMethod, query, filtered, 1, 1 )); } if ( restartedForests.size() > 0 ) { logger.warn("re-adding jobs related to forests [{}] to the queue", getForestNames(restartedForests)); } for ( Forest forest : restartedForests ) { List<QueryTask> blackListedTaskList = blackListedTasks.get(forest); if ( blackListedTaskList != null ) { // let's start back up where we left off for ( QueryTask task : blackListedTaskList ) { threadPool.execute(task); } // we can clear blackListedTaskList because we have a synchronized lock blackListedTaskList.clear(); } } } private List<String> getForestNames(Collection<Forest> forests) { return forests.stream().map((forest)->forest.getForestName()).collect(Collectors.toList()); } private List<String> getHostNames(Collection<Forest> forests) { return forests.stream().map((forest)->forest.getPreferredHost()).distinct().collect(Collectors.toList()); } /* All we do to startQuerying is create a task per forest that queries that * forest for the first page of results, then spawns a new task to query for * the next page of results, etc. Tasks are handled by threadPool which is a * slightly modified ThreadPoolExecutor with threadCount threads. We don't * know whether we're at the end of the result set from a forest until we get * the last batch that isn't full (batch size != batchSize). Therefore, any * error to retrieve a batch might prevent us from getting the next batch and * all remaining batches. To mitigate the risk of one error effectively * cancelling the rest of the pagination for that forest, * HostAvailabilityListener is configured to retry any batch that encounters * a "host unavailable" error (see HostAvailabilityListener for more * details). HostAvailabilityListener is also intended to act as an example * so comparable client-specific listeners can be built to handle other * failure scenarios and retry those batches. */ private synchronized void startQuerying() { boolean consistentSnapshotFirstQueryHasRun = false; for ( Forest forest : getForestConfig().listForests() ) { QueryTask runnable = new QueryTask( getMoveMgr(), this, forest, queryMethod, query, filtered, 1, 1 ); if ( consistentSnapshot == true && consistentSnapshotFirstQueryHasRun == false ) { // let's run this first time in-line so we'll have the serverTimestamp set // before we launch all the parallel threads runnable.run(); consistentSnapshotFirstQueryHasRun = true; } else { threadPool.execute(runnable); } } } private class QueryTask implements Runnable { private DataMovementManager moveMgr; private QueryBatcherImpl batcher; private Forest forest; private String queryMethod; private QueryDefinition query; private Boolean filtered; private long forestBatchNum; private long start; private long retryBatchNumber; private boolean callFailListeners; private String afterUri; private String nextAfterUri; QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start ) { this(moveMgr, batcher, forest, queryMethod, query, filtered, forestBatchNum, start, null, -1, true); } QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start, String afterUri ) { this(moveMgr, batcher, forest, queryMethod, query, filtered, forestBatchNum, start, afterUri, -1, true); } QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start, String afterUri, long retryBatchNumber, boolean callFailListeners ) { this.moveMgr = moveMgr; this.batcher = batcher; this.forest = forest; this.queryMethod = queryMethod; this.query = query; this.filtered = filtered; this.forestBatchNum = forestBatchNum; this.start = start; this.retryBatchNumber = retryBatchNumber; this.callFailListeners = callFailListeners; // ignore the afterUri if the effective version is less than 9.0-9 if (Long.compareUnsigned(getMoveMgr().getServerVersion(), Long.parseUnsignedLong("9000900")) >= 0) { this.afterUri = afterUri; } } public void run() { // don't proceed if this forest is marked as done (because we already got the last batch) AtomicBoolean isDone = forestIsDone.get(forest); if ( isDone.get() == true) { logger.error("Attempt to query forest '{}' forestBatchNum {} with start {} after the last batch " + "for that forest has already been retrieved", forest.getForestName(), forestBatchNum, start); return; } // don't proceed if this job is stopped (because dataMovementManager.stopJob was called) if (batcher.getStopped().get() == true ) { logger.warn("Cancelling task to query forest '{}' forestBatchNum {} with start {} after the job is stopped", forest.getForestName(), forestBatchNum, start); return; } DatabaseClient client = getMoveMgr().getForestClient(forest); Calendar queryStart = Calendar.getInstance(); QueryBatchImpl batch = new QueryBatchImpl() .withBatcher(batcher) .withClient(client) .withTimestamp(queryStart) .withJobTicket(getJobTicket()) .withForestBatchNumber(forestBatchNum) .withForest(forest); if ( retryBatchNumber != -1 ) { batch = batch.withJobBatchNumber(retryBatchNumber); } else { batch = batch.withJobBatchNumber(batchNumber.incrementAndGet()); } try { QueryManagerImpl queryMgr = (QueryManagerImpl) client.newQueryManager(); queryMgr.setPageLength(getBatchSize()); UrisHandle handle = new UrisHandle(); if ( consistentSnapshot == true && serverTimestamp.get() > -1 ) { handle.setPointInTimeQueryTimestamp(serverTimestamp.get()); } // this try-with-resources block will call results.close() once the block is done // here we call the /v1/internal/uris endpoint to get the text/uri-list of documents // matching this structured or string query try (UrisHandle results = queryMgr.uris(queryMethod, query, filtered, handle, start, afterUri, forest.getForestName())) { // if we're doing consistentSnapshot and this is the first result set, let's capture the // serverTimestamp so we can use it for all future queries if ( consistentSnapshot == true && serverTimestamp.get() == -1 ) { if (serverTimestamp.compareAndSet(-1, results.getServerTimestamp())) { logger.info("Consistent snapshot timestamp=[{}]", serverTimestamp); } } List<String> uris = new ArrayList<>(); for ( String uri : results ) { uris.add( uri ); } batch = batch .withItems(uris.toArray(new String[uris.size()])) .withServerTimestamp(serverTimestamp.get()) .withJobResultsSoFar(resultsSoFar.addAndGet(uris.size())) .withForestResultsSoFar(forestResults.get(forest).addAndGet(uris.size())); if(maxUris <= (resultsSoFar.longValue())) { isDone.set(true); } else if ( uris.size() == getBatchSize() ) { nextAfterUri = uris.get(getBatchSize() - 1); // this is a full batch launchNextTask(); } logger.trace("batch size={}, jobBatchNumber={}, jobResultsSoFar={}, forest={}", uris.size(), batch.getJobBatchNumber(), batch.getJobResultsSoFar(), forest.getForestName()); // now that we have the QueryBatch, let's send it to each onUrisReady listener for (QueryBatchListener listener : urisReadyListeners) { try { listener.processEvent(batch); } catch (Throwable t) { logger.error("Exception thrown by an onUrisReady listener", t); } } if ( uris.size() != getBatchSize() ) { // we're done if we get a partial batch (always the last) isDone.set(true); } } } catch (ResourceNotFoundException e) { // we're done if we get a 404 NOT FOUND which throws ResourceNotFoundException // this should only happen if the last query retrieved a full batch so it thought // there would be more and queued this task which retrieved 0 results isDone.set(true); } catch (Throwable t) { // any error outside listeners is grounds for stopping queries to this forest if ( callFailListeners == true ) { batch = batch .withJobResultsSoFar(resultsSoFar.get()) .withForestResultsSoFar(forestResults.get(forest).get()); for ( QueryFailureListener listener : failureListeners ) { try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e2) { logger.error("Exception thrown by an onQueryFailure listener", e2); } } if(retryForestMap.get(forest).get() == 0) { isDone.set(true); } else { retryForestMap.get(forest).decrementAndGet(); } } else if ( t instanceof RuntimeException ) { throw (RuntimeException) t; } else { throw new DataMovementException("Failed to retry batch", t); } } if(isDone.get()) { shutdownIfAllForestsAreDone(); } } private void launchNextTask() { if (batcher.getStopped().get() == true ) { // we're stopping, so don't do anything more return; } AtomicBoolean isDone = forestIsDone.get(forest); // we made it to the end, so don't launch anymore tasks if ( isDone.get() == true ) { shutdownIfAllForestsAreDone(); return; } long nextStart = start + getBatchSize(); threadPool.execute(new QueryTask( moveMgr, batcher, forest, QueryBatcherImpl.this.queryMethod, query, filtered, forestBatchNum + 1, nextStart, nextAfterUri )); } }; private void shutdownIfAllForestsAreDone() { for ( AtomicBoolean isDone : forestIsDone.values() ) { // if even one isn't done, short-circuit out of this method and don't shutdown if ( isDone.get() == false ) return; } // if we made it this far, all forests are done. let's run the Job // completion listeners and shutdown. if(runJobCompletionListeners.compareAndSet(false, true)) runJobCompletionListeners(); threadPool.shutdown(); } private void runJobCompletionListeners() { for (QueryBatcherListener listener : jobCompletionListeners) { try { listener.processEvent(QueryBatcherImpl.this); } catch (Throwable e) { logger.error("Exception thrown by an onJobCompletion listener", e); } } super.setJobEndTime(); } private class IteratorTask implements Runnable { private QueryBatcher batcher; IteratorTask(QueryBatcher batcher) { this.batcher = batcher; } @Override public void run() { try { boolean lastBatch = false; List<String> uriQueue = new ArrayList<>(getBatchSize()); while (iterator.hasNext() && !lastBatch) { uriQueue.add(iterator.next()); if(!iterator.hasNext()) lastBatch = true; // if we've hit batchSize or the end of the iterator if (uriQueue.size() == getBatchSize() || !iterator.hasNext() || lastBatch) { final List<String> uris = uriQueue; final boolean finalLastBatch = lastBatch; final long results = resultsSoFar.addAndGet(uris.size()); if(maxUris <= results) lastBatch = true; uriQueue = new ArrayList<>(getBatchSize()); Runnable processBatch = new Runnable() { public void run() { QueryBatchImpl batch = new QueryBatchImpl() .withBatcher(batcher) .withTimestamp(Calendar.getInstance()) .withJobTicket(getJobTicket()); try { long currentBatchNumber = batchNumber.incrementAndGet(); // round-robin from client 0 to (clientList.size() - 1); List<DatabaseClient> currentClientList = clientList.get(); int clientIndex = (int) (currentBatchNumber % currentClientList.size()); DatabaseClient client = currentClientList.get(clientIndex); batch = batch.withJobBatchNumber(currentBatchNumber) .withClient(client) .withJobResultsSoFar(results) .withItems(uris.toArray(new String[uris.size()])); logger.trace("batch size={}, jobBatchNumber={}, jobResultsSoFar={}", uris.size(), batch.getJobBatchNumber(), batch.getJobResultsSoFar()); for (QueryBatchListener listener : urisReadyListeners) { try { listener.processEvent(batch); } catch (Throwable e) { logger.error("Exception thrown by an onUrisReady listener", e); } } } catch (Throwable t) { batch = batch.withItems(uris.toArray(new String[uris.size()])); for (QueryFailureListener listener : failureListeners) { try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e) { logger.error("Exception thrown by an onQueryFailure listener", e); } } logger.warn("Error iterating to queue uris: {}", t.toString()); } if(finalLastBatch) { runJobCompletionListeners(); } } }; threadPool.execute(processBatch); // If the queue is almost full, stop producing and add a task to continue later if (isSingleThreaded && threadPool.getQueue().remainingCapacity() <= 2 && iterator.hasNext()) { threadPool.execute(new IteratorTask(batcher)); return; } } } } catch (Throwable t) { for (QueryFailureListener listener : failureListeners) { QueryBatchImpl batch = new QueryBatchImpl() .withItems(new String[0]) .withClient(clientList.get().get(0)) .withBatcher(batcher) .withTimestamp(Calendar.getInstance()) .withJobResultsSoFar(0); try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e) { logger.error("Exception thrown by an onQueryFailure listener", e); } } logger.warn("Error iterating to queue uris: {}", t.toString()); } threadPool.shutdown(); } } /* startIterating launches in a separate thread (actually a task handled by * threadPool) and just loops through the Iterator<String>, batching uris of * batchSize, and queueing tasks to process each batch via onUrisReady * listeners. Therefore, this method doesn't talk directly to MarkLogic * Server. Only the registered onUrisReady listeners can talk to the server, * using the DatabaseClient provided by QueryBatch.getClient(). In order to * fully utilize the cluster, we provide DatabaseClient instances to batches * in round-robin fashion, looping through the hosts provided to * withForestConfig and cached in clientList. Errors calling * iterator.hasNext() or iterator.next() are handled by onQueryFailure * listeners. Errors calling listeners (onUrisReady or onQueryFailure) are * logged by our slf4j lgoger at level "error". If customers want errors in * their listeners handled, they should use try-catch and handle them. */ private void startIterating() { threadPool.execute(new IteratorTask(this)); } @Override public void stop() { super.getStopped().set(true); if ( threadPool != null ) threadPool.shutdownNow(); super.setJobEndTime(); if ( query != null ) { for ( AtomicBoolean isDone : forestIsDone.values() ) { // if even one isn't done, log a warning if ( isDone.get() == false ) { logger.warn("QueryBatcher instance \"{}\" stopped before all results were retrieved", getJobName()); break; } } } else { if ( iterator != null && iterator.hasNext() ) { logger.warn("QueryBatcher instance \"{}\" stopped before all results were processed", getJobName()); } } closeAllListeners(); } private void closeAllListeners() { for (QueryBatchListener listener : getUrisReadyListeners()) { if ( listener instanceof AutoCloseable ) { try { ((AutoCloseable) listener).close(); } catch (Exception e) { logger.error("onUrisReady listener cannot be closed", e); } } } for (QueryFailureListener listener : getQueryFailureListeners()) { if ( listener instanceof AutoCloseable ) { try { ((AutoCloseable) listener).close(); } catch (Exception e) { logger.error("onQueryFailure listener cannot be closed", e); } } } } protected void finalize() { if (this.getStopped().get() == false ) { logger.warn("QueryBatcher instance \"{}\" was never cleanly stopped. You should call dataMovementManager.stopJob.", getJobName()); } } /** * A handler for rejected tasks that waits for the work queue to * become empty and then submits the rejected task */ private class BlockingRunsPolicy implements RejectedExecutionHandler { /** * Waits for the work queue to become empty and then submits the rejected task, * unless the executor has been shut down, in which case the task is discarded. * * @param runnable the runnable task requested to be executed * @param executor the executor attempting to execute this task */ public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { if (executor.isShutdown()) { return; } try { synchronized ( lock ) { while (executor.getQueue().remainingCapacity() == 0) { lock.wait(); } if (!executor.isShutdown()) executor.execute(runnable); } } catch ( InterruptedException e ) { logger.warn("Thread interrupted while waiting for the work queue to become empty" + e); } } } private class QueryThreadPoolExecutor extends ThreadPoolExecutor { private Object objectToNotifyFrom; QueryThreadPoolExecutor(int threadCount, Object objectToNotifyFrom) { super(threadCount, threadCount, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(threadCount * 25), new BlockingRunsPolicy()); this.objectToNotifyFrom = objectToNotifyFrom; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { boolean returnValue = super.awaitTermination(timeout, unit); logger.info("Job complete, jobBatchNumber={}, jobResultsSoFar={}", batchNumber.get(), resultsSoFar.get()); return returnValue; } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); synchronized ( lock ) { lock.notify(); } } @Override protected void terminated() { super.terminated(); synchronized(objectToNotifyFrom) { objectToNotifyFrom.notifyAll(); } synchronized ( lock ) { lock.notify(); } } } @Override public QueryBatcher onJobCompletion(QueryBatcherListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); jobCompletionListeners.add(listener); return this; } @Override public QueryBatcherListener[] getQueryJobCompletionListeners() { return jobCompletionListeners.toArray(new QueryBatcherListener[jobCompletionListeners.size()]); } @Override public void setQueryJobCompletionListeners(QueryBatcherListener... listeners) { requireNotStarted(); jobCompletionListeners.clear(); if ( listeners != null ) { for (QueryBatcherListener listener : listeners) { jobCompletionListeners.add(listener); } } } @Override public Calendar getJobStartTime() { if(! this.isStarted()) { return null; } else { return super.getJobStartTime(); } } @Override public Calendar getJobEndTime() { if(! this.isStopped()) { return null; } else { return super.getJobEndTime(); } } @Override public void setMaxBatches(long maxBatches) { Long max_limit = Long.MAX_VALUE/getBatchSize(); if(maxBatches > max_limit) throw new IllegalArgumentException("Number of batches cannot be more than "+ max_limit); this.maxBatches = maxBatches; if(isStarted()) setMaxUris(maxBatches); } private void setMaxUris(long maxBatches) { this.maxUris = (maxBatches * getBatchSize()); } @Override public long getMaxBatches() { return this.maxBatches; } @Override public void setMaxBatches() { this.maxBatches = -1L; if(isStarted()) setMaxUris(getMaxBatches()); } }
marklogic-client-api/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java
/* * Copyright (c) 2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.datamovement.impl; import com.marklogic.client.datamovement.QueryBatch; import com.marklogic.client.datamovement.QueryBatchListener; import com.marklogic.client.datamovement.DataMovementManager; import com.marklogic.client.datamovement.DataMovementException; import com.marklogic.client.datamovement.QueryFailureListener; import com.marklogic.client.datamovement.Forest; import com.marklogic.client.datamovement.ForestConfiguration; import com.marklogic.client.datamovement.JobTicket; import com.marklogic.client.datamovement.QueryBatcher; import com.marklogic.client.datamovement.QueryBatchException; import com.marklogic.client.datamovement.QueryEvent; import com.marklogic.client.datamovement.QueryBatcherListener; import com.marklogic.client.impl.HandleAccessor; import com.marklogic.client.impl.HandleImplementation; import com.marklogic.client.io.Format; import com.marklogic.client.io.StringHandle; import com.marklogic.client.io.marker.StructureWriteHandle; import com.marklogic.client.query.RawQueryDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.marklogic.client.DatabaseClient; import com.marklogic.client.ResourceNotFoundException; import com.marklogic.client.query.QueryDefinition; import com.marklogic.client.impl.QueryManagerImpl; import com.marklogic.client.impl.UrisHandle; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /* For implementation explanation, see the comments below above startQuerying, * startIterating, withForestConfig, and retry. */ public class QueryBatcherImpl extends BatcherImpl implements QueryBatcher { private static Logger logger = LoggerFactory.getLogger(QueryBatcherImpl.class); private String queryMethod; private QueryDefinition query; private QueryDefinition originalQuery; private Boolean filtered; private Iterator<String> iterator; private boolean threadCountSet = false; private List<QueryBatchListener> urisReadyListeners = new ArrayList<>(); private List<QueryFailureListener> failureListeners = new ArrayList<>(); private List<QueryBatcherListener> jobCompletionListeners = new ArrayList<>(); private QueryThreadPoolExecutor threadPool; private boolean consistentSnapshot = false; private final AtomicLong batchNumber = new AtomicLong(0); private final AtomicLong resultsSoFar = new AtomicLong(0); private final AtomicLong serverTimestamp = new AtomicLong(-1); private final AtomicReference<List<DatabaseClient>> clientList = new AtomicReference<>(); private Map<Forest,AtomicLong> forestResults = new HashMap<>(); private Map<Forest,AtomicBoolean> forestIsDone = new HashMap<>(); private Map<Forest, AtomicInteger> retryForestMap = new HashMap<>(); private AtomicBoolean runJobCompletionListeners = new AtomicBoolean(false); private final Object lock = new Object(); private final Map<Forest,List<QueryTask>> blackListedTasks = new HashMap<>(); private boolean isSingleThreaded = false; private long maxUris = Long.MAX_VALUE; private long maxBatches = Long.MAX_VALUE; QueryBatcherImpl( QueryDefinition originalQuery, DataMovementManager moveMgr, ForestConfiguration forestConfig, String serializedCtsQuery, Boolean filtered ) { this(moveMgr, forestConfig); QueryManagerImpl queryMgr = (QueryManagerImpl) getPrimaryClient().newQueryManager(); if (serializedCtsQuery != null && serializedCtsQuery.length() > 0) { this.queryMethod = "POST"; this.query = queryMgr.newRawCtsQueryDefinition(new StringHandle(serializedCtsQuery).withFormat(Format.JSON)); this.originalQuery = originalQuery; if (filtered != null) { this.filtered = filtered; } } else { initQuery(query); } } public QueryBatcherImpl(QueryDefinition query, DataMovementManager moveMgr, ForestConfiguration forestConfig) { this(moveMgr, forestConfig); initQuery(query); } public QueryBatcherImpl(Iterator<String> iterator, DataMovementManager moveMgr, ForestConfiguration forestConfig) { this(moveMgr, forestConfig); this.iterator = iterator; } private QueryBatcherImpl(DataMovementManager moveMgr, ForestConfiguration forestConfig) { super(moveMgr); withForestConfig(forestConfig); withBatchSize(1000); } private void initQuery(QueryDefinition query) { // post if the effective version is at least 10.0-5 this.queryMethod = (Long.compareUnsigned(getMoveMgr().getServerVersion(), Long.parseUnsignedLong("10000500")) >= 0) ? "POST" : "GET"; this.query = query; if (query instanceof RawQueryDefinition) { RawQueryDefinition rawQuery = (RawQueryDefinition) query; StructureWriteHandle handle = rawQuery.getHandle(); @SuppressWarnings("rawtypes") HandleImplementation baseHandle = HandleAccessor.checkHandle(handle, "queryBatcher"); Format inputFormat = baseHandle.getFormat(); switch(inputFormat) { case UNKNOWN: baseHandle.setFormat(Format.XML); break; case JSON: case XML: break; default: throw new UnsupportedOperationException("Only XML and JSON raw query definitions are possible."); } } } @Override public QueryBatcherImpl onUrisReady(QueryBatchListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); urisReadyListeners.add(listener); return this; } @Override public QueryBatcherImpl onQueryFailure(QueryFailureListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); failureListeners.add(listener); return this; } /* Accepts a QueryEvent (usually a QueryBatchException sent to a * onQueryFailure listener) and retries that task. If the task succeeds, it * will spawn the task for the next page in the result set, which will spawn * the task for the next page, etc. A failure in this attempt will not call * onQueryFailure listeners (as that might lead to infinite recursion since * this is usually called by an onQueryFailure listener), but instead will * directly throw the Exception. In order to use the latest * ForestConfiguration yet still query the correct forest for this * QueryEvent, we look for a forest from the current ForestConfiguration * which has the same forest id, then we use the preferred host for the * forest from the current ForestConfiguration. If the current * ForestConfiguration does not have a matching forest, this method throws * IllegalStateException. This works perfectly with the approach used by * HostAvailabilityListener of black-listing unavailable hosts then retrying * the QueryEvent that failed. */ @Override public void retry(QueryEvent queryEvent) { retry(queryEvent, false); } @Override public void retryWithFailureListeners(QueryEvent queryEvent) { retry(queryEvent, true); } private void retry(QueryEvent queryEvent, boolean callFailListeners) { if ( isStopped() == true ) { logger.warn("Job is now stopped, aborting the retry"); return; } Forest retryForest = null; for ( Forest forest : getForestConfig().listForests() ) { if ( forest.equals(queryEvent.getForest()) ) { // while forest and queryEvent.getForest() have equivalent forest id, // we expect forest to have the currently available host info retryForest = forest; break; } } if ( retryForest == null ) { throw new IllegalStateException("Forest for queryEvent (" + queryEvent.getForest().getForestName() + ") is not in current getForestConfig()"); } // we're obviously not done with this forest forestIsDone.get(retryForest).set(false); retryForestMap.get(retryForest).incrementAndGet(); long start = queryEvent.getForestResultsSoFar() + 1; logger.trace("retryForest {} on retryHost {} at start {}", retryForest.getForestName(), retryForest.getPreferredHost(), start); QueryTask runnable = new QueryTask(getMoveMgr(), this, retryForest, queryMethod, query, filtered, queryEvent.getForestBatchNumber(), start, queryEvent.getLastUriForForest(), queryEvent.getJobBatchNumber(), callFailListeners); runnable.run(); } /* * Accepts a QueryBatch which was successfully retrieved from the server and a * QueryBatchListener which was failed to apply and retry that listener on the batch. * */ @Override public void retryListener(QueryBatch batch, QueryBatchListener queryBatchListener) { // We get the batch and modify the client alone in order to make use // of the new forest client in case if the original host is unavailable. DatabaseClient client = null; Forest[] forests = batch.getBatcher().getForestConfig().listForests(); for(Forest forest : forests) { if(forest.equals(batch.getForest())) client = getMoveMgr().getForestClient(forest); } QueryBatchImpl retryBatch = new QueryBatchImpl() .withClient( client ) .withBatcher( batch.getBatcher() ) .withTimestamp( batch.getTimestamp() ) .withServerTimestamp( batch.getServerTimestamp() ) .withItems( batch.getItems() ) .withJobTicket( batch.getJobTicket() ) .withJobBatchNumber( batch.getJobBatchNumber() ) .withJobResultsSoFar( batch.getJobResultsSoFar() ) .withForestBatchNumber( batch.getForestBatchNumber() ) .withForestResultsSoFar( batch.getForestResultsSoFar() ) .withForest( batch.getForest() ) .withJobTicket( batch.getJobTicket() ); queryBatchListener.processEvent(retryBatch); } @Override public QueryBatchListener[] getQuerySuccessListeners() { return getUrisReadyListeners(); } @Override public QueryBatchListener[] getUrisReadyListeners() { return urisReadyListeners.toArray(new QueryBatchListener[urisReadyListeners.size()]); } @Override public QueryFailureListener[] getQueryFailureListeners() { return failureListeners.toArray(new QueryFailureListener[failureListeners.size()]); } @Override public void setUrisReadyListeners(QueryBatchListener... listeners) { requireNotStarted(); urisReadyListeners.clear(); if ( listeners != null ) { for ( QueryBatchListener listener : listeners ) { urisReadyListeners.add(listener); } } } @Override public void setQueryFailureListeners(QueryFailureListener... listeners) { requireNotStarted(); failureListeners.clear(); if ( listeners != null ) { for ( QueryFailureListener listener : listeners ) { failureListeners.add(listener); } } } @Override public QueryBatcher withJobName(String jobName) { requireNotStarted(); super.withJobName(jobName); return this; } @Override public QueryBatcher withJobId(String jobId) { requireNotStarted(); setJobId(jobId); return this; } @Override public QueryBatcher withBatchSize(int batchSize) { requireNotStarted(); super.withBatchSize(batchSize); return this; } @Override public QueryBatcher withThreadCount(int threadCount) { requireNotStarted(); if ( getThreadCount() <= 0 ) { throw new IllegalArgumentException("threadCount must be 1 or greater"); } threadCountSet = true; super.withThreadCount(threadCount); return this; } @Override public QueryBatcher withConsistentSnapshot() { requireNotStarted(); consistentSnapshot = true; return this; } @Override public boolean awaitCompletion(long timeout, TimeUnit unit) throws InterruptedException { requireJobStarted(); return threadPool.awaitTermination(timeout, unit); } @Override public boolean awaitCompletion() { try { return awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); } catch(InterruptedException e) { return false; } } @Override public boolean isStopped() { return threadPool != null && threadPool.isTerminated(); } @Override public JobTicket getJobTicket() { requireJobStarted(); return super.getJobTicket(); } private void requireJobStarted() { if ( threadPool == null ) { throw new IllegalStateException("Job not started. First call DataMovementManager.startJob(QueryBatcher)"); } } private void requireNotStarted() { if ( threadPool != null ) { throw new IllegalStateException("Configuration cannot be changed after startJob has been called"); } } @Override public synchronized void start(JobTicket ticket) { if ( threadPool != null ) { logger.warn("startJob called more than once"); return; } if ( getBatchSize() <= 0 ) { withBatchSize(1); logger.warn("batchSize should be 1 or greater--setting batchSize to 1"); } super.setJobTicket(ticket); initialize(); for (QueryBatchListener urisReadyListener : urisReadyListeners) { urisReadyListener.initializeListener(this); } super.setJobStartTime(); super.getStarted().set(true); if(this.maxBatches < Long.MAX_VALUE) { setMaxUris(getMaxBatches()); } if ( query != null ) { startQuerying(); } else { startIterating(); } } private synchronized void initialize() { if ( threadCountSet == false ) { if ( query != null ) { Forest[] forests = getForestConfig().listForests(); logger.warn("threadCount not set--defaulting to number of forests ({})", forests.length); withThreadCount(forests.length); } else { int hostCount = clientList.get().size(); logger.warn("threadCount not set--defaulting to number of hosts ({})", hostCount); withThreadCount( hostCount ); } // now we've set the threadCount threadCountSet = true; } // If we are iterating and if we have the thread count to 1, we have a single thread acting as both // consumer and producer of the ThreadPoolExecutor queue. Hence, we produce till the maximum and start // consuming and produce again. Since the thread count is 1, there is no worry about thread utilization. if(getThreadCount() == 1) { isSingleThreaded = true; } logger.info("Starting job batchSize={}, threadCount={}, onUrisReady listeners={}, failure listeners={}", getBatchSize(), getThreadCount(), urisReadyListeners.size(), failureListeners.size()); threadPool = new QueryThreadPoolExecutor(getThreadCount(), this); } /* When withForestConfig is called before the job starts, it just provides * the list of forests (and thus hosts) to talk to. When withForestConfig is * called mid-job, every attempt is made to switch any queued or future task * to use the new ForestConfiguration. This allows monitoring listeners like * HostAvailabilityListener to black-list hosts immediately when a host is * detected to be unavailable. In theory customer listeners could do even * more advanced monitoring. By decoupling the monitoring from the task * management, all a listener has to do is inform us what forests and what * hosts to talk to (by calling withForestConfig), and we'll manage ensuring * any queued or future tasks only talk to those forests and hosts. We * update clientList with a DatabaseClient per host which is used for * round-robin communication by startIterating (the version of QueryBatcher * that accepts an Iterator<String>). We also loop through any queued tasks * and point them to hosts and forests that are in the new * ForestConfiguration. If any queued tasks point to forests that are * missing from the new ForestConfiguration, those tasks are held in * blackListedTasks on the assumption that those tasks can be restarted once * those forests come back online. If withForestConfig is called later with * those forests back online, those tasks will be restarted. If the job * finishes before those forests come back online (and are provided this job * by a call to withForestConfig), then any blackListedTasks are left * unfinished and it's likely that not all documents that should have matched * the query will be processed. The only solution to this is to have a * cluster that is available during the job run (or if there's an outage, it * gets resolved during the job run). Simply put, there's no way for a job to * get documents from unavailable forests. * * If the ForestConfiguration provides new forests, jobs will be started to * get documenst from those forests (the code is in cleanupExistingTasks). */ @Override public synchronized QueryBatcher withForestConfig(ForestConfiguration forestConfig) { super.withForestConfig(forestConfig); Forest[] forests = forests(forestConfig); Set<Forest> oldForests = new HashSet<>(forestResults.keySet()); Map<String,Forest> hosts = new HashMap<>(); for ( Forest forest : forests ) { if ( forest.getPreferredHost() == null ) throw new IllegalStateException("Hostname must not be null for any forest"); hosts.put(forest.getPreferredHost(), forest); if ( forestResults.get(forest) == null ) forestResults.put(forest, new AtomicLong()); if ( forestIsDone.get(forest) == null ) forestIsDone.put(forest, new AtomicBoolean(false)); if ( retryForestMap.get(forest) == null ) retryForestMap.put(forest, new AtomicInteger(0)); } Set<String> hostNames = hosts.keySet(); logger.info("(withForestConfig) Using forests on {} hosts for \"{}\"", hostNames, forests[0].getDatabaseName()); List<DatabaseClient> newClientList = clients(hostNames); clientList.set(newClientList); boolean started = (threadPool != null); if ( started == true && oldForests.size() > 0 ) calculateDeltas(oldForests, forests); return this; } private synchronized void calculateDeltas(Set<Forest> oldForests, Forest[] forests) { // the forests we haven't known about yet Set<Forest> addedForests = new HashSet<>(); // the forests that we knew about but they were black-listed and are no longer black-listed Set<Forest> restartedForests = new HashSet<>(); // any known forest might now be black-listed Set<Forest> blackListedForests = new HashSet<>(oldForests); for ( Forest forest : forests ) { if ( ! oldForests.contains(forest) ) { // we need to do special handling since we're adding this new forest after we're started addedForests.add(forest); } // if we have blackListedTasks for this forest, let's restart them if ( blackListedTasks.get(forest) != null ) restartedForests.add(forest); // this forest is not black-listed blackListedForests.remove(forest); } if ( blackListedForests.size() > 0 ) { DataMovementManagerImpl moveMgrImpl = getMoveMgr(); String primaryHost = moveMgrImpl.getPrimaryClient().getHost(); if ( getHostNames(blackListedForests).contains(primaryHost) ) { int randomPos = new Random().nextInt(clientList.get().size()); moveMgrImpl.setPrimaryClient(clientList.get().get(randomPos)); } } cleanupExistingTasks(addedForests, restartedForests, blackListedForests); } private synchronized void cleanupExistingTasks(Set<Forest> addedForests, Set<Forest> restartedForests, Set<Forest> blackListedForests) { if ( blackListedForests.size() > 0 ) { logger.warn("removing jobs related to hosts [{}] from the queue", getHostNames(blackListedForests)); // since some forests have been removed, let's remove from the queue any jobs that were targeting that forest List<Runnable> tasks = new ArrayList<>(); threadPool.getQueue().drainTo(tasks); for ( Runnable task : tasks ) { if ( task instanceof QueryTask ) { QueryTask queryTask = (QueryTask) task; if ( blackListedForests.contains(queryTask.forest) ) { // this batch was targeting a forest that's no longer on the list // so keep track of it in case this forest comes back on-line List<QueryTask> blackListedTaskList = blackListedTasks.get(queryTask.forest); if ( blackListedTaskList == null ) { blackListedTaskList = new ArrayList<QueryTask>(); blackListedTasks.put(queryTask.forest, blackListedTaskList); } blackListedTaskList.add(queryTask); // jump to the next task continue; } } // this task is still valid so add it back to the queue threadPool.execute(task); } } if ( addedForests.size() > 0 ) { logger.warn("adding jobs for forests [{}] to the queue", getForestNames(addedForests)); } for ( Forest forest : addedForests ) { // we don't need to worry about consistentSnapshotFirstQueryHasRun because that's already done // or we wouldn't be here because we wouldn't have a synchronized lock on this threadPool.execute(new QueryTask( getMoveMgr(), this, forest, queryMethod, query, filtered, 1, 1 )); } if ( restartedForests.size() > 0 ) { logger.warn("re-adding jobs related to forests [{}] to the queue", getForestNames(restartedForests)); } for ( Forest forest : restartedForests ) { List<QueryTask> blackListedTaskList = blackListedTasks.get(forest); if ( blackListedTaskList != null ) { // let's start back up where we left off for ( QueryTask task : blackListedTaskList ) { threadPool.execute(task); } // we can clear blackListedTaskList because we have a synchronized lock blackListedTaskList.clear(); } } } private List<String> getForestNames(Collection<Forest> forests) { return forests.stream().map((forest)->forest.getForestName()).collect(Collectors.toList()); } private List<String> getHostNames(Collection<Forest> forests) { return forests.stream().map((forest)->forest.getPreferredHost()).distinct().collect(Collectors.toList()); } /* All we do to startQuerying is create a task per forest that queries that * forest for the first page of results, then spawns a new task to query for * the next page of results, etc. Tasks are handled by threadPool which is a * slightly modified ThreadPoolExecutor with threadCount threads. We don't * know whether we're at the end of the result set from a forest until we get * the last batch that isn't full (batch size != batchSize). Therefore, any * error to retrieve a batch might prevent us from getting the next batch and * all remaining batches. To mitigate the risk of one error effectively * cancelling the rest of the pagination for that forest, * HostAvailabilityListener is configured to retry any batch that encounters * a "host unavailable" error (see HostAvailabilityListener for more * details). HostAvailabilityListener is also intended to act as an example * so comparable client-specific listeners can be built to handle other * failure scenarios and retry those batches. */ private synchronized void startQuerying() { boolean consistentSnapshotFirstQueryHasRun = false; for ( Forest forest : getForestConfig().listForests() ) { QueryTask runnable = new QueryTask( getMoveMgr(), this, forest, queryMethod, query, filtered, 1, 1 ); if ( consistentSnapshot == true && consistentSnapshotFirstQueryHasRun == false ) { // let's run this first time in-line so we'll have the serverTimestamp set // before we launch all the parallel threads runnable.run(); consistentSnapshotFirstQueryHasRun = true; } else { threadPool.execute(runnable); } } } private class QueryTask implements Runnable { private DataMovementManager moveMgr; private QueryBatcherImpl batcher; private Forest forest; private String queryMethod; private QueryDefinition query; private Boolean filtered; private long forestBatchNum; private long start; private long retryBatchNumber; private boolean callFailListeners; private String afterUri; private String nextAfterUri; QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start ) { this(moveMgr, batcher, forest, queryMethod, query, filtered, forestBatchNum, start, null, -1, true); } QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start, String afterUri ) { this(moveMgr, batcher, forest, queryMethod, query, filtered, forestBatchNum, start, afterUri, -1, true); } QueryTask(DataMovementManager moveMgr, QueryBatcherImpl batcher, Forest forest, String queryMethod, QueryDefinition query, Boolean filtered, long forestBatchNum, long start, String afterUri, long retryBatchNumber, boolean callFailListeners ) { this.moveMgr = moveMgr; this.batcher = batcher; this.forest = forest; this.queryMethod = queryMethod; this.query = query; this.filtered = filtered; this.forestBatchNum = forestBatchNum; this.start = start; this.retryBatchNumber = retryBatchNumber; this.callFailListeners = callFailListeners; // ignore the afterUri if the effective version is less than 9.0-9 if (Long.compareUnsigned(getMoveMgr().getServerVersion(), Long.parseUnsignedLong("9000900")) >= 0) { this.afterUri = afterUri; } } public void run() { // don't proceed if this forest is marked as done (because we already got the last batch) AtomicBoolean isDone = forestIsDone.get(forest); if ( isDone.get() == true) { logger.error("Attempt to query forest '{}' forestBatchNum {} with start {} after the last batch " + "for that forest has already been retrieved", forest.getForestName(), forestBatchNum, start); return; } // don't proceed if this job is stopped (because dataMovementManager.stopJob was called) if (batcher.getStopped().get() == true ) { logger.warn("Cancelling task to query forest '{}' forestBatchNum {} with start {} after the job is stopped", forest.getForestName(), forestBatchNum, start); return; } DatabaseClient client = getMoveMgr().getForestClient(forest); Calendar queryStart = Calendar.getInstance(); QueryBatchImpl batch = new QueryBatchImpl() .withBatcher(batcher) .withClient(client) .withTimestamp(queryStart) .withJobTicket(getJobTicket()) .withForestBatchNumber(forestBatchNum) .withForest(forest); if ( retryBatchNumber != -1 ) { batch = batch.withJobBatchNumber(retryBatchNumber); } else { batch = batch.withJobBatchNumber(batchNumber.incrementAndGet()); } try { QueryManagerImpl queryMgr = (QueryManagerImpl) client.newQueryManager(); queryMgr.setPageLength(getBatchSize()); UrisHandle handle = new UrisHandle(); if ( consistentSnapshot == true && serverTimestamp.get() > -1 ) { handle.setPointInTimeQueryTimestamp(serverTimestamp.get()); } // this try-with-resources block will call results.close() once the block is done // here we call the /v1/internal/uris endpoint to get the text/uri-list of documents // matching this structured or string query try (UrisHandle results = queryMgr.uris(queryMethod, query, filtered, handle, start, afterUri, forest.getForestName())) { // if we're doing consistentSnapshot and this is the first result set, let's capture the // serverTimestamp so we can use it for all future queries if ( consistentSnapshot == true && serverTimestamp.get() == -1 ) { if (serverTimestamp.compareAndSet(-1, results.getServerTimestamp())) { logger.info("Consistent snapshot timestamp=[{}]", serverTimestamp); } } List<String> uris = new ArrayList<>(); for ( String uri : results ) { uris.add( uri ); } batch = batch .withItems(uris.toArray(new String[uris.size()])) .withServerTimestamp(serverTimestamp.get()) .withJobResultsSoFar(resultsSoFar.addAndGet(uris.size())) .withForestResultsSoFar(forestResults.get(forest).addAndGet(uris.size())); if(maxUris <= (resultsSoFar.longValue())) { isDone.set(true); } else if ( uris.size() == getBatchSize() ) { nextAfterUri = uris.get(getBatchSize() - 1); // this is a full batch launchNextTask(); } logger.trace("batch size={}, jobBatchNumber={}, jobResultsSoFar={}, forest={}", uris.size(), batch.getJobBatchNumber(), batch.getJobResultsSoFar(), forest.getForestName()); // now that we have the QueryBatch, let's send it to each onUrisReady listener for (QueryBatchListener listener : urisReadyListeners) { try { listener.processEvent(batch); } catch (Throwable t) { logger.error("Exception thrown by an onUrisReady listener", t); } } if ( uris.size() != getBatchSize() ) { // we're done if we get a partial batch (always the last) isDone.set(true); } } } catch (ResourceNotFoundException e) { // we're done if we get a 404 NOT FOUND which throws ResourceNotFoundException // this should only happen if the last query retrieved a full batch so it thought // there would be more and queued this task which retrieved 0 results isDone.set(true); } catch (Throwable t) { // any error outside listeners is grounds for stopping queries to this forest if ( callFailListeners == true ) { batch = batch .withJobResultsSoFar(resultsSoFar.get()) .withForestResultsSoFar(forestResults.get(forest).get()); for ( QueryFailureListener listener : failureListeners ) { try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e2) { logger.error("Exception thrown by an onQueryFailure listener", e2); } } if(retryForestMap.get(forest).get() == 0) { isDone.set(true); } else { retryForestMap.get(forest).decrementAndGet(); } } else if ( t instanceof RuntimeException ) { throw (RuntimeException) t; } else { throw new DataMovementException("Failed to retry batch", t); } } if(isDone.get()) { shutdownIfAllForestsAreDone(); } } private void launchNextTask() { if (batcher.getStopped().get() == true ) { // we're stopping, so don't do anything more return; } AtomicBoolean isDone = forestIsDone.get(forest); // we made it to the end, so don't launch anymore tasks if ( isDone.get() == true ) { shutdownIfAllForestsAreDone(); return; } long nextStart = start + getBatchSize(); threadPool.execute(new QueryTask( moveMgr, batcher, forest, QueryBatcherImpl.this.queryMethod, query, filtered, forestBatchNum + 1, nextStart, nextAfterUri )); } }; private void shutdownIfAllForestsAreDone() { for ( AtomicBoolean isDone : forestIsDone.values() ) { // if even one isn't done, short-circuit out of this method and don't shutdown if ( isDone.get() == false ) return; } // if we made it this far, all forests are done. let's run the Job // completion listeners and shutdown. if(runJobCompletionListeners.compareAndSet(false, true)) runJobCompletionListeners(); threadPool.shutdown(); } private void runJobCompletionListeners() { for (QueryBatcherListener listener : jobCompletionListeners) { try { listener.processEvent(QueryBatcherImpl.this); } catch (Throwable e) { logger.error("Exception thrown by an onJobCompletion listener", e); } } super.setJobEndTime(); } private class IteratorTask implements Runnable { private QueryBatcher batcher; IteratorTask(QueryBatcher batcher) { this.batcher = batcher; } @Override public void run() { try { boolean lastBatch = false; List<String> uriQueue = new ArrayList<>(getBatchSize()); while (iterator.hasNext() && !lastBatch) { uriQueue.add(iterator.next()); if(!iterator.hasNext()) lastBatch = true; // if we've hit batchSize or the end of the iterator if (uriQueue.size() == getBatchSize() || !iterator.hasNext() || lastBatch) { final List<String> uris = uriQueue; final boolean finalLastBatch = lastBatch; final long results = resultsSoFar.addAndGet(uris.size()); if(maxUris <= results) lastBatch = true; uriQueue = new ArrayList<>(getBatchSize()); Runnable processBatch = new Runnable() { public void run() { QueryBatchImpl batch = new QueryBatchImpl() .withBatcher(batcher) .withTimestamp(Calendar.getInstance()) .withJobTicket(getJobTicket()); try { long currentBatchNumber = batchNumber.incrementAndGet(); // round-robin from client 0 to (clientList.size() - 1); List<DatabaseClient> currentClientList = clientList.get(); int clientIndex = (int) (currentBatchNumber % currentClientList.size()); DatabaseClient client = currentClientList.get(clientIndex); batch = batch.withJobBatchNumber(currentBatchNumber) .withClient(client) .withJobResultsSoFar(results) .withItems(uris.toArray(new String[uris.size()])); logger.trace("batch size={}, jobBatchNumber={}, jobResultsSoFar={}", uris.size(), batch.getJobBatchNumber(), batch.getJobResultsSoFar()); for (QueryBatchListener listener : urisReadyListeners) { try { listener.processEvent(batch); } catch (Throwable e) { logger.error("Exception thrown by an onUrisReady listener", e); } } } catch (Throwable t) { batch = batch.withItems(uris.toArray(new String[uris.size()])); for (QueryFailureListener listener : failureListeners) { try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e) { logger.error("Exception thrown by an onQueryFailure listener", e); } } logger.warn("Error iterating to queue uris: {}", t.toString()); } if(finalLastBatch) { runJobCompletionListeners(); } } }; threadPool.execute(processBatch); // If the queue is almost full, stop producing and add a task to continue later if (isSingleThreaded && threadPool.getQueue().remainingCapacity() <= 2 && iterator.hasNext()) { threadPool.execute(new IteratorTask(batcher)); return; } } } } catch (Throwable t) { for (QueryFailureListener listener : failureListeners) { QueryBatchImpl batch = new QueryBatchImpl() .withItems(new String[0]) .withClient(clientList.get().get(0)) .withBatcher(batcher) .withTimestamp(Calendar.getInstance()) .withJobResultsSoFar(0); try { listener.processFailure(new QueryBatchException(batch, t)); } catch (Throwable e) { logger.error("Exception thrown by an onQueryFailure listener", e); } } logger.warn("Error iterating to queue uris: {}", t.toString()); } threadPool.shutdown(); } } /* startIterating launches in a separate thread (actually a task handled by * threadPool) and just loops through the Iterator<String>, batching uris of * batchSize, and queueing tasks to process each batch via onUrisReady * listeners. Therefore, this method doesn't talk directly to MarkLogic * Server. Only the registered onUrisReady listeners can talk to the server, * using the DatabaseClient provided by QueryBatch.getClient(). In order to * fully utilize the cluster, we provide DatabaseClient instances to batches * in round-robin fashion, looping through the hosts provided to * withForestConfig and cached in clientList. Errors calling * iterator.hasNext() or iterator.next() are handled by onQueryFailure * listeners. Errors calling listeners (onUrisReady or onQueryFailure) are * logged by our slf4j lgoger at level "error". If customers want errors in * their listeners handled, they should use try-catch and handle them. */ private void startIterating() { threadPool.execute(new IteratorTask(this)); } @Override public void stop() { super.getStopped().set(true); if ( threadPool != null ) threadPool.shutdownNow(); super.setJobEndTime(); if ( query != null ) { for ( AtomicBoolean isDone : forestIsDone.values() ) { // if even one isn't done, log a warning if ( isDone.get() == false ) { logger.warn("QueryBatcher instance \"{}\" stopped before all results were retrieved", getJobName()); break; } } } else { if ( iterator != null && iterator.hasNext() ) { logger.warn("QueryBatcher instance \"{}\" stopped before all results were processed", getJobName()); } } closeAllListeners(); } private void closeAllListeners() { for (QueryBatchListener listener : getUrisReadyListeners()) { if ( listener instanceof AutoCloseable ) { try { ((AutoCloseable) listener).close(); } catch (Exception e) { logger.error("onUrisReady listener cannot be closed", e); } } } for (QueryFailureListener listener : getQueryFailureListeners()) { if ( listener instanceof AutoCloseable ) { try { ((AutoCloseable) listener).close(); } catch (Exception e) { logger.error("onQueryFailure listener cannot be closed", e); } } } } protected void finalize() { if (this.getStopped().get() == false ) { logger.warn("QueryBatcher instance \"{}\" was never cleanly stopped. You should call dataMovementManager.stopJob.", getJobName()); } } /** * A handler for rejected tasks that waits for the work queue to * become empty and then submits the rejected task */ private class BlockingRunsPolicy implements RejectedExecutionHandler { /** * Waits for the work queue to become empty and then submits the rejected task, * unless the executor has been shut down, in which case the task is discarded. * * @param runnable the runnable task requested to be executed * @param executor the executor attempting to execute this task */ public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { if (executor.isShutdown()) { return; } try { synchronized ( lock ) { while (executor.getQueue().remainingCapacity() == 0) { lock.wait(); } if (!executor.isShutdown()) executor.execute(runnable); } } catch ( InterruptedException e ) { logger.warn("Thread interrupted while waiting for the work queue to become empty" + e); } } } private class QueryThreadPoolExecutor extends ThreadPoolExecutor { private Object objectToNotifyFrom; QueryThreadPoolExecutor(int threadCount, Object objectToNotifyFrom) { super(threadCount, threadCount, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(threadCount * 25), new BlockingRunsPolicy()); this.objectToNotifyFrom = objectToNotifyFrom; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { boolean returnValue = super.awaitTermination(timeout, unit); logger.info("Job complete, jobBatchNumber={}, jobResultsSoFar={}", batchNumber.get(), resultsSoFar.get()); return returnValue; } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); synchronized ( lock ) { lock.notify(); } } @Override protected void terminated() { super.terminated(); synchronized(objectToNotifyFrom) { objectToNotifyFrom.notifyAll(); } synchronized ( lock ) { lock.notify(); } } } @Override public QueryBatcher onJobCompletion(QueryBatcherListener listener) { if ( listener == null ) throw new IllegalArgumentException("listener must not be null"); jobCompletionListeners.add(listener); return this; } @Override public QueryBatcherListener[] getQueryJobCompletionListeners() { return jobCompletionListeners.toArray(new QueryBatcherListener[jobCompletionListeners.size()]); } @Override public void setQueryJobCompletionListeners(QueryBatcherListener... listeners) { requireNotStarted(); jobCompletionListeners.clear(); if ( listeners != null ) { for (QueryBatcherListener listener : listeners) { jobCompletionListeners.add(listener); } } } @Override public Calendar getJobStartTime() { if(! this.isStarted()) { return null; } else { return super.getJobStartTime(); } } @Override public Calendar getJobEndTime() { if(! this.isStopped()) { return null; } else { return super.getJobEndTime(); } } @Override public void setMaxBatches(long maxBatches) { Long max_limit = Long.MAX_VALUE/getBatchSize(); if(maxBatches > max_limit) throw new IllegalArgumentException("Number of batches cannot be more than "+ max_limit); this.maxBatches = maxBatches; if(isStarted()) setMaxUris(maxBatches); } private void setMaxUris(long maxBatches) { this.maxUris = (maxBatches * getBatchSize()); } @Override public long getMaxBatches() { return this.maxBatches; } @Override public void setMaxBatches() { this.maxBatches = -1L; if(isStarted()) setMaxUris(getMaxBatches()); } }
fallback to original query instead of null query field #1242 #1163
marklogic-client-api/src/main/java/com/marklogic/client/datamovement/impl/QueryBatcherImpl.java
fallback to original query instead of null query field #1242 #1163
Java
apache-2.0
df108fb3c87fb9f10012b794bb384193acb8f600
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.SpaceShip.ShipFlag; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2016-2018 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GravityFloat extends StdAbility { @Override public String ID() { return "GravityFloat"; } private final static String localizedName = CMLib.lang().L("GravityFloat"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Floating)"); private volatile boolean flyingAllowed = false; @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return CAN_ITEMS | Ability.CAN_MOBS; } @Override protected int canTargetCode() { return 0; } private class PossiblyFloater implements Runnable { private final Physical P; private final boolean hasGrav; public PossiblyFloater(final Physical possFloater, final boolean hasGravity) { this.P = possFloater; this.hasGrav = hasGravity; } @Override public void run() { final boolean hasGravity = confirmGravity(P,hasGrav); final Ability gravA=P.fetchEffect("GravityFloat"); if(hasGravity) { if((gravA!=null)&&(!gravA.isSavable())) { gravA.unInvoke(); P.delEffect(gravA); P.recoverPhyStats(); } } else { if(gravA==null) { Ability gravityA=(Ability)copyOf(); if(gravityA != null) { final Room R=CMLib.map().roomLocation(P); if(R!=null) { final CMMsg msg=CMClass.getMsg(CMClass.getFactoryMOB("gravity", 1, R),P,gravityA,CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,null); if(P.okMessage(P, msg)) { P.executeMsg(P, msg); R.showHappens(CMMsg.MSG_OK_VISUAL, P,L("<S-NAME> start(s) floating around.")); P.addNonUninvokableEffect(gravityA); gravityA.setSavable(false); P.recoverPhyStats(); } } } } } } } private final Runnable checkStopFloating() { return new Runnable() { @Override public void run() { final Physical P = affected; if(P!=null) { if(confirmGravity(P, false)) { unInvoke(); P.delEffect(GravityFloat.this); P.recoverPhyStats(); } } } }; } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(affected == null) return false; if(tickID!=Tickable.TICKID_MOB) return true; checkStopFloating().run(); return (affected != null); } @Override public void affectPhyStats(Physical affected, PhyStats affectableStats) { super.affectPhyStats(affected, affectableStats); affectableStats.setWeight(1); affectableStats.addAmbiance(L("Floating")); affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_FLYING); affectableStats.addAmbiance("-FLYING"); } public void showFailedToMove(final MOB mob) { if(mob != null) { final Room R=mob.location(); if(R!=null) { switch(CMLib.dice().roll(1, 10, 0)) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: default: case 10: R.show(mob, null,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around trying to go somewhere, but make(s) no progress.")); break; } } } } public void showFailedToTouch(final MOB mob, Physical P) { if(mob != null) { final Room R=mob.location(); if(R!=null) { switch(CMLib.dice().roll(1, 10, 0)) { case 1: case 2: case 3: case 4: case 5: R.show(mob, P,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around reaching for <T-NAME>, but <S-HE-SHE> float(s) away from it.")); break; case 6: case 7: case 8: case 9: default: case 10: R.show(mob, P,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around trying reach for <T-NAME>, but <T-HE-SHE> float(s) away.")); break; } } } } @Override public boolean okMessage(Environmental host, CMMsg msg) { if(!super.okMessage(host, msg)) return false; if((affected instanceof MOB) &&(msg.source()==affected)) { switch(msg.targetMinor()) { case CMMsg.TYP_GET: case CMMsg.TYP_PUT: case CMMsg.TYP_OPEN: case CMMsg.TYP_CLOSE: case CMMsg.TYP_QUIETMOVEMENT: case CMMsg.TYP_NOISYMOVEMENT: case CMMsg.TYP_HANDS: if(!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS)) { if((msg.target() instanceof Item) &&(!msg.source().isMine(msg.target())) &&(CMLib.dice().rollPercentage()>20) &&(msg.source().phyStats().isAmbiance(L("Floating")))) { showFailedToTouch(msg.source(),(Physical)msg.target()); return false; } if((msg.target() instanceof MOB) &&(CMLib.dice().rollPercentage()>20) &&(msg.source().phyStats().isAmbiance(L("Floating")))) { showFailedToTouch(msg.source(),(Physical)msg.target()); return false; } } break; case CMMsg.TYP_ENTER: case CMMsg.TYP_LEAVE: case CMMsg.TYP_MOUNT: case CMMsg.TYP_SIT: { if(msg.source().phyStats().isAmbiance(L("Floating")) && (!flyingAllowed) &&(!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS)) &&(msg.target()!=null)) { if(CMLib.flags().isSwimming(affected)) { if(CMLib.dice().rollPercentage()>60) { showFailedToMove(msg.source()); return false; } } else if(CMLib.dice().rollPercentage()>20) { showFailedToMove(msg.source()); return false; } } break; } } } return true; } @Override public void executeMsg(Environmental host, CMMsg msg) { // IDEA: gravity legs should develop over time...this turns into a saved ability with a score? if((affected instanceof Item) &&(msg.target()==affected)) { switch(msg.targetMinor()) { case CMMsg.TYP_GET: msg.addTrailerRunnable(checkStopFloating()); break; } } else if((affected instanceof MOB) &&(msg.source()==affected)) { switch(msg.sourceMinor()) { case CMMsg.TYP_PUSH: if((msg.target() instanceof Item) &&(msg.source().location().isHere(msg.target()))) { final Item pushedI=(Item)msg.target(); if((pushedI instanceof Rideable) ||(!CMLib.flags().isGettable(pushedI)) ||(pushedI.phyStats().weight()>msg.source().phyStats().weight())) { // it will work } else { break; // won't work. } } else { break; // won't work. } //$FALL-THROUGH$ case CMMsg.TYP_THROW: if(msg.source().phyStats().isAmbiance(L("Floating"))) { final String sourceMessage = CMStrings.removeColors(CMLib.english().stripPunctuation(msg.sourceMessage())); final List<String> words=CMParms.parseSpaces(sourceMessage, true); final Room R=msg.source().location(); if(R==null) break; final boolean useShip =((R instanceof BoardableShip)||(R.getArea() instanceof BoardableShip))?true:false; int floatDir = -1; for(int i=words.size()-1;(i>=0) && (floatDir<0);i--) { for(int dir : Directions.DISPLAY_CODES()) { if(words.get(i).equals(CMLib.directions().getUpperDirectionName(dir, useShip))) { floatDir = Directions.getOpDirectionCode(dir); break; } } } if(floatDir >=0) { final Room newRoom=R.getRoomInDir(floatDir); final Exit E=R.getExitInDir(floatDir); if((newRoom!=null)&&(E!=null)&&(E.isOpen())) { try { flyingAllowed=true; CMLib.tracking().walk(msg.source(),floatDir,msg.source().isInCombat(),false,false,false); } finally { flyingAllowed=false; } } } } break; } } } protected boolean confirmGravity(final Physical P, boolean hasGravity) { if(P instanceof Item) { final Item I=(Item)P; if((I.container()!=null) ||(!CMLib.flags().isGettable(I)) ||(I instanceof Rideable) ||(I.owner() instanceof MOB) ||(I instanceof TechComponent)) { if(!hasGravity) hasGravity=true; } } else if(P instanceof MOB) { final MOB M=(MOB)P; if((M.riding() != null) || (CMLib.flags().isBound(M))) { if(!hasGravity) hasGravity=true; } final Area A=CMLib.map().areaLocation(M); if(A instanceof SpaceShip) { if(!((SpaceShip)A).getShipFlag(ShipFlag.NO_GRAVITY)) { if(!hasGravity) hasGravity=true; } } else { SpaceObject o=null; if(A instanceof SpaceObject) o=(SpaceObject)A; else o=CMLib.map().getSpaceObject(A,true); if(o==null) hasGravity=true; else hasGravity=o.getMass() > SpaceObject.MULTIPLIER_PLANET_MASS; } } return hasGravity; } @Override public boolean invoke(final MOB mob, List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { if(givenTarget==null) return false; final Physical P = givenTarget; new PossiblyFloater(P, auto).run(); return true; } }
com/planet_ink/coffee_mud/Abilities/Misc/GravityFloat.java
package com.planet_ink.coffee_mud.Abilities.Misc; import com.planet_ink.coffee_mud.Abilities.StdAbility; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.SpaceShip.ShipFlag; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2016-2018 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GravityFloat extends StdAbility { @Override public String ID() { return "GravityFloat"; } private final static String localizedName = CMLib.lang().L("GravityFloat"); @Override public String name() { return localizedName; } private final static String localizedStaticDisplay = CMLib.lang().L("(Floating)"); private volatile boolean flyingAllowed = false; @Override public String displayText() { return localizedStaticDisplay; } @Override protected int canAffectCode() { return CAN_ITEMS | Ability.CAN_MOBS; } @Override protected int canTargetCode() { return 0; } private class PossiblyFloater implements Runnable { private final Physical P; private final boolean hasGrav; public PossiblyFloater(final Physical possFloater, final boolean hasGravity) { this.P = possFloater; this.hasGrav = hasGravity; } @Override public void run() { final boolean hasGravity = confirmGravity(P,hasGrav); final Ability gravA=P.fetchEffect("GravityFloat"); if(hasGravity) { if((gravA!=null)&&(!gravA.isSavable())) { gravA.unInvoke(); P.delEffect(gravA); P.recoverPhyStats(); } } else { if(gravA==null) { Ability gravityA=(Ability)copyOf(); if(gravityA != null) { final Room R=CMLib.map().roomLocation(P); if(R!=null) { final CMMsg msg=CMClass.getMsg(CMClass.getFactoryMOB("gravity", 1, R),P,gravityA,CMMsg.MASK_ALWAYS|CMMsg.TYP_JUSTICE,null); if(P.okMessage(P, msg)) { P.executeMsg(P, msg); R.showHappens(CMMsg.MSG_OK_VISUAL, P,L("<S-NAME> start(s) floating around.")); P.addNonUninvokableEffect(gravityA); gravityA.setSavable(false); P.recoverPhyStats(); } } } } } } } private final Runnable checkStopFloating() { return new Runnable() { @Override public void run() { final Physical P = affected; if(P!=null) { if(confirmGravity(P, false)) { unInvoke(); P.delEffect(GravityFloat.this); P.recoverPhyStats(); } } } }; } @Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(affected == null) return false; if(tickID!=Tickable.TICKID_MOB) return true; checkStopFloating().run(); return (affected != null); } @Override public void affectPhyStats(Physical affected, PhyStats affectableStats) { super.affectPhyStats(affected, affectableStats); affectableStats.setWeight(1); affectableStats.addAmbiance(L("Floating")); affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_FLYING); affectableStats.addAmbiance("-FLYING"); } public void showFailedToMove(final MOB mob) { if(mob != null) { final Room R=mob.location(); if(R!=null) { switch(CMLib.dice().roll(1, 10, 0)) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: default: case 10: R.show(mob, null,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around trying to go somewhere, but make(s) no progress.")); break; } } } } public void showFailedToTouch(final MOB mob, Physical P) { if(mob != null) { final Room R=mob.location(); if(R!=null) { switch(CMLib.dice().roll(1, 10, 0)) { case 1: case 2: case 3: case 4: case 5: R.show(mob, P,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around reaching for <T-NAME>, but <S-HE-SHE> float(s) away from it.")); break; case 6: case 7: case 8: case 9: default: case 10: R.show(mob, P,CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> flap(s) around trying reach for <T-NAME>, but <T-HE-SHE> float(s) away.")); break; } } } } @Override public boolean okMessage(Environmental host, CMMsg msg) { if(!super.okMessage(host, msg)) return false; if((affected instanceof MOB) &&(msg.source()==affected)) { switch(msg.targetMinor()) { case CMMsg.TYP_GET: case CMMsg.TYP_PUT: case CMMsg.TYP_OPEN: case CMMsg.TYP_CLOSE: case CMMsg.TYP_QUIETMOVEMENT: case CMMsg.TYP_NOISYMOVEMENT: case CMMsg.TYP_HANDS: if(!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS)) { if((msg.target() instanceof Item) &&(!msg.source().isMine(msg.target())) &&(CMLib.dice().rollPercentage()>20) &&(msg.source().phyStats().isAmbiance(L("Floating")))) { showFailedToTouch(msg.source(),(Physical)msg.target()); return false; } if((msg.target() instanceof MOB) &&(CMLib.dice().rollPercentage()>20) &&(msg.source().phyStats().isAmbiance(L("Floating")))) { showFailedToTouch(msg.source(),(Physical)msg.target()); return false; } } break; case CMMsg.TYP_ENTER: case CMMsg.TYP_LEAVE: case CMMsg.TYP_MOUNT: case CMMsg.TYP_SIT: { if(msg.source().phyStats().isAmbiance(L("Floating")) && (!flyingAllowed) &&(!CMath.bset(msg.sourceMajor(), CMMsg.MASK_ALWAYS)) &&(msg.target()!=null)) { if(CMLib.flags().isSwimming(affected)) { if(CMLib.dice().rollPercentage()>60) { showFailedToMove(msg.source()); return false; } } else if(CMLib.dice().rollPercentage()>20) { showFailedToMove(msg.source()); return false; } } break; } } } return true; } @Override public void executeMsg(Environmental host, CMMsg msg) { // IDEA: gravity legs should develop over time...this turns into a saved ability with a score? if((affected instanceof Item) &&(msg.target()==affected)) { switch(msg.targetMinor()) { case CMMsg.TYP_GET: msg.addTrailerRunnable(checkStopFloating()); break; } } else if((affected instanceof MOB) &&(msg.source()==affected)) { switch(msg.sourceMinor()) { case CMMsg.TYP_PUSH: if((msg.target() instanceof Item) &&(msg.source().location().isHere(msg.target()))) { final Item pushedI=(Item)msg.target(); if((pushedI instanceof Rideable) ||(!CMLib.flags().isGettable(pushedI)) ||(pushedI.phyStats().weight()>msg.source().phyStats().weight())) { // it will work } else { break; // won't work. } } else { break; // won't work. } //$FALL-THROUGH$ case CMMsg.TYP_THROW: if(msg.source().phyStats().isAmbiance(L("Floating"))) { final String sourceMessage = CMStrings.removeColors(CMLib.english().stripPunctuation(msg.sourceMessage())); final List<String> words=CMParms.parseSpaces(sourceMessage, true); final Room R=msg.source().location(); if(R==null) break; final boolean useShip =((R instanceof BoardableShip)||(R.getArea() instanceof BoardableShip))?true:false; int floatDir = -1; for(int i=words.size()-1;(i>=0) && (floatDir<0);i--) { for(int dir : Directions.DISPLAY_CODES()) { if(words.get(i).equals(CMLib.directions().getUpperDirectionName(dir, useShip))) { floatDir = Directions.getOpDirectionCode(dir); break; } } } if(floatDir >=0) { final Room newRoom=R.getRoomInDir(floatDir); final Exit E=R.getExitInDir(floatDir); if((newRoom!=null)&&(E!=null)&&(E.isOpen())) { try { flyingAllowed=true; CMLib.tracking().walk(msg.source(),floatDir,msg.source().isInCombat(),false,false,false); } finally { flyingAllowed=false; } } } } break; } } } protected boolean confirmGravity(final Physical P, boolean hasGravity) { if(P instanceof Item) { final Item I=(Item)P; if((I.container()!=null) ||(!CMLib.flags().isGettable(I)) ||(I instanceof Rideable) ||(I.owner() instanceof MOB) ||(I instanceof TechComponent)) { if(!hasGravity) hasGravity=true; } } else if(P instanceof MOB) { final MOB M=(MOB)P; if((M.riding() != null) || (CMLib.flags().isBound(M))) { if(!hasGravity) hasGravity=true; } final Area A=CMLib.map().areaLocation(M); if(A instanceof SpaceShip) { if(!((SpaceShip)A).getShipFlag(ShipFlag.NO_GRAVITY)) { if(!hasGravity) hasGravity=true; } } else hasGravity=true; } return hasGravity; } @Override public boolean invoke(final MOB mob, List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel) { if(givenTarget==null) return false; final Physical P = givenTarget; new PossiblyFloater(P, auto).run(); return true; } }
Can transfer from space back to earth. git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@16249 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Abilities/Misc/GravityFloat.java
Can transfer from space back to earth.
Java
apache-2.0
5fa1935c52f3866f0675e9fd64bd04d153b9f225
0
apache/commons-configuration,apache/commons-configuration,apache/commons-configuration
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.configuration2.interpol; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.text.StringSubstitutor; import org.apache.commons.text.lookup.StringLookup; /** * <p> * A class that handles interpolation (variable substitution) for configuration * objects. * </p> * <p> * Each instance of {@code AbstractConfiguration} is associated with an object * of this class. All interpolation tasks are delegated to this object. * </p> * <p> * {@code ConfigurationInterpolator} internally uses the {@code StringSubstitutor} * class from <a href="http://commons.apache.org/text">Commons Text</a>. Thus it * supports the same syntax of variable expressions. * </p> * <p> * The basic idea of this class is that it can maintain a set of primitive * {@link Lookup} objects, each of which is identified by a special prefix. The * variables to be processed have the form <code>${prefix:name}</code>. * {@code ConfigurationInterpolator} will extract the prefix and determine, * which primitive lookup object is registered for it. Then the name of the * variable is passed to this object to obtain the actual value. It is also * possible to define an arbitrary number of default lookup objects, which are * used for variables that do not have a prefix or that cannot be resolved by * their associated lookup object. When adding default lookup objects their * order matters; they are queried in this order, and the first non-<b>null</b> * variable value is used. * </p> * <p> * After an instance has been created it does not contain any {@code Lookup} * objects. The current set of lookup objects can be modified using the * {@code registerLookup()} and {@code deregisterLookup()} methods. Default * lookup objects (that are invoked for variables without a prefix) can be added * or removed with the {@code addDefaultLookup()} and * {@code removeDefaultLookup()} methods respectively. (When a * {@code ConfigurationInterpolator} instance is created by a configuration * object, a default lookup object is added pointing to the configuration * itself, so that variables are resolved using the configuration's properties.) * </p> * <p> * The default usage scenario is that on a fully initialized instance the * {@code interpolate()} method is called. It is passed an object value which * may contain variables. All these variables are substituted if they can be * resolved. The result is the passed in value with variables replaced. * Alternatively, the {@code resolve()} method can be called to obtain the * values of specific variables without performing interpolation. * </p> * <p> * Implementation node: This class is thread-safe. Lookup objects can be added * or removed at any time concurrent to interpolation operations. * </p> * * @version $Id$ * @since 1.4 * @author <a * href="http://commons.apache.org/configuration/team-list.html">Commons * Configuration team</a> */ public class ConfigurationInterpolator { /** Constant for the prefix separator. */ private static final char PREFIX_SEPARATOR = ':'; /** The variable prefix. */ private static final String VAR_START = "${"; /** The length of {@link #VAR_START}. */ private static final int VAR_START_LENGTH = VAR_START.length(); /** The variable suffix. */ private static final String VAR_END = "}"; /** The length of {@link #VAR_END}. */ private static final int VAR_END_LENGTH = VAR_END.length(); /** A map containing the default prefix lookups. */ private static final Map<String, Lookup> DEFAULT_PREFIX_LOOKUPS; /** A map with the currently registered lookup objects. */ private final Map<String, Lookup> prefixLookups; /** Stores the default lookup objects. */ private final List<Lookup> defaultLookups; /** The helper object performing variable substitution. */ private final StringSubstitutor substitutor; /** Stores a parent interpolator objects if the interpolator is nested hierarchically. */ private volatile ConfigurationInterpolator parentInterpolator; /** * Creates a new instance of {@code ConfigurationInterpolator}. */ public ConfigurationInterpolator() { prefixLookups = new ConcurrentHashMap<>(); defaultLookups = new CopyOnWriteArrayList<>(); substitutor = initSubstitutor(); } /** * Creates a new {@code ConfigurationInterpolator} instance based on the * passed in specification object. If the {@code InterpolatorSpecification} * already contains a {@code ConfigurationInterpolator} object, it is used * directly. Otherwise, a new instance is created and initialized with the * properties stored in the specification. * * @param spec the {@code InterpolatorSpecification} (must not be * <b>null</b>) * @return the {@code ConfigurationInterpolator} obtained or created based * on the given specification * @throws IllegalArgumentException if the specification is <b>null</b> * @since 2.0 */ public static ConfigurationInterpolator fromSpecification( InterpolatorSpecification spec) { if (spec == null) { throw new IllegalArgumentException( "InterpolatorSpecification must not be null!"); } return (spec.getInterpolator() != null) ? spec.getInterpolator() : createInterpolator(spec); } /** * Returns a map containing the default prefix lookups. Every configuration * object derived from {@code AbstractConfiguration} is by default * initialized with a {@code ConfigurationInterpolator} containing these * {@code Lookup} objects and their prefixes. The map cannot be modified * * @return a map with the default prefix {@code Lookup} objects and their * prefixes * @since 2.0 */ public static Map<String, Lookup> getDefaultPrefixLookups() { return DEFAULT_PREFIX_LOOKUPS; } /** * Utility method for obtaining a {@code Lookup} object in a safe way. This * method always returns a non-<b>null</b> {@code Lookup} object. If the * passed in {@code Lookup} is not <b>null</b>, it is directly returned. * Otherwise, result is a dummy {@code Lookup} which does not provide any * values. * * @param lookup the {@code Lookup} to check * @return a non-<b>null</b> {@code Lookup} object * @since 2.0 */ public static Lookup nullSafeLookup(Lookup lookup) { if (lookup == null) { lookup = DummyLookup.INSTANCE; } return lookup; } /** * Returns a map with the currently registered {@code Lookup} objects and * their prefixes. This is a snapshot copy of the internally used map. So * modifications of this map do not effect this instance. * * @return a copy of the map with the currently registered {@code Lookup} * objects */ public Map<String, Lookup> getLookups() { return new HashMap<>(prefixLookups); } /** * Registers the given {@code Lookup} object for the specified prefix at * this instance. From now on this lookup object will be used for variables * that have the specified prefix. * * @param prefix the variable prefix (must not be <b>null</b>) * @param lookup the {@code Lookup} object to be used for this prefix (must * not be <b>null</b>) * @throws IllegalArgumentException if either the prefix or the * {@code Lookup} object is <b>null</b> */ public void registerLookup(String prefix, Lookup lookup) { if (prefix == null) { throw new IllegalArgumentException( "Prefix for lookup object must not be null!"); } if (lookup == null) { throw new IllegalArgumentException( "Lookup object must not be null!"); } prefixLookups.put(prefix, lookup); } /** * Registers all {@code Lookup} objects in the given map with their prefixes * at this {@code ConfigurationInterpolator}. Using this method multiple * {@code Lookup} objects can be registered at once. If the passed in map is * <b>null</b>, this method does not have any effect. * * @param lookups the map with lookups to register (may be <b>null</b>) * @throws IllegalArgumentException if the map contains <b>entries</b> */ public void registerLookups(Map<String, ? extends Lookup> lookups) { if (lookups != null) { prefixLookups.putAll(lookups); } } /** * Deregisters the {@code Lookup} object for the specified prefix at this * instance. It will be removed from this instance. * * @param prefix the variable prefix * @return a flag whether for this prefix a lookup object had been * registered */ public boolean deregisterLookup(String prefix) { return prefixLookups.remove(prefix) != null; } /** * Returns an unmodifiable set with the prefixes, for which {@code Lookup} * objects are registered at this instance. This means that variables with * these prefixes can be processed. * * @return a set with the registered variable prefixes */ public Set<String> prefixSet() { return Collections.unmodifiableSet(prefixLookups.keySet()); } /** * Returns a collection with the default {@code Lookup} objects * added to this {@code ConfigurationInterpolator}. These objects are not * associated with a variable prefix. The returned list is a snapshot copy * of the internal collection of default lookups; so manipulating it does * not affect this instance. * * @return the default lookup objects */ public List<Lookup> getDefaultLookups() { return new ArrayList<>(defaultLookups); } /** * Adds a default {@code Lookup} object. Default {@code Lookup} objects are * queried (in the order they were added) for all variables without a * special prefix. If no default {@code Lookup} objects are present, such * variables won't be processed. * * @param defaultLookup the default {@code Lookup} object to be added (must * not be <b>null</b>) * @throws IllegalArgumentException if the {@code Lookup} object is * <b>null</b> */ public void addDefaultLookup(Lookup defaultLookup) { defaultLookups.add(defaultLookup); } /** * Adds all {@code Lookup} objects in the given collection as default * lookups. The collection can be <b>null</b>, then this method has no * effect. It must not contain <b>null</b> entries. * * @param lookups the {@code Lookup} objects to be added as default lookups * @throws IllegalArgumentException if the collection contains a <b>null</b> * entry */ public void addDefaultLookups(Collection<? extends Lookup> lookups) { if (lookups != null) { defaultLookups.addAll(lookups); } } /** * Removes the specified {@code Lookup} object from the list of default * {@code Lookup}s. * * @param lookup the {@code Lookup} object to be removed * @return a flag whether this {@code Lookup} object actually existed and * was removed */ public boolean removeDefaultLookup(Lookup lookup) { return defaultLookups.remove(lookup); } /** * Sets the parent {@code ConfigurationInterpolator}. This object is used if * the {@code Lookup} objects registered at this object cannot resolve a * variable. * * @param parentInterpolator the parent {@code ConfigurationInterpolator} * object (can be <b>null</b>) */ public void setParentInterpolator( ConfigurationInterpolator parentInterpolator) { this.parentInterpolator = parentInterpolator; } /** * Returns the parent {@code ConfigurationInterpolator}. * * @return the parent {@code ConfigurationInterpolator} (can be <b>null</b>) */ public ConfigurationInterpolator getParentInterpolator() { return this.parentInterpolator; } /** * Sets a flag that variable names can contain other variables. If enabled, * variable substitution is also done in variable names. * * @return the substitution in variables flag */ public boolean isEnableSubstitutionInVariables() { return substitutor.isEnableSubstitutionInVariables(); } /** * Sets the flag whether variable names can contain other variables. This * flag corresponds to the {@code enableSubstitutionInVariables} property of * the underlying {@code StrSubstitutor} object. * * @param f the new value of the flag */ public void setEnableSubstitutionInVariables(boolean f) { substitutor.setEnableSubstitutionInVariables(f); } /** * Performs interpolation of the passed in value. If the value is of type * String, this method checks whether it contains variables. If so, all * variables are replaced by their current values (if possible). For non * string arguments, the value is returned without changes. * * @param value the value to be interpolated * @return the interpolated value */ public Object interpolate(Object value) { if (value instanceof String) { String strValue = (String) value; if (looksLikeSingleVariable(strValue)) { Object resolvedValue = resolveSingleVariable(strValue); if (resolvedValue != null && !(resolvedValue instanceof String)) { // If the value is again a string, it needs no special // treatment; it may also contain further variables which // must be resolved; therefore, the default mechanism is // applied. return resolvedValue; } } return substitutor.replace(strValue); } return value; } /** * Resolves the specified variable. This implementation tries to extract * a variable prefix from the given variable name (the first colon (':') is * used as prefix separator). It then passes the name of the variable with * the prefix stripped to the lookup object registered for this prefix. If * no prefix can be found or if the associated lookup object cannot resolve * this variable, the default lookup objects are used. If this is not * successful either and a parent {@code ConfigurationInterpolator} is * available, this object is asked to resolve the variable. * * @param var the name of the variable whose value is to be looked up * @return the value of this variable or <b>null</b> if it cannot be * resolved */ public Object resolve(String var) { if (var == null) { return null; } int prefixPos = var.indexOf(PREFIX_SEPARATOR); if (prefixPos >= 0) { String prefix = var.substring(0, prefixPos); String name = var.substring(prefixPos + 1); Object value = fetchLookupForPrefix(prefix).lookup(name); if (value != null) { return value; } } for (Lookup l : defaultLookups) { Object value = l.lookup(var); if (value != null) { return value; } } ConfigurationInterpolator parent = getParentInterpolator(); if (parent != null) { return getParentInterpolator().resolve(var); } return null; } /** * Obtains the lookup object for the specified prefix. This method is called * by the {@code lookup()} method. This implementation will check * whether a lookup object is registered for the given prefix. If not, a * <b>null</b> lookup object will be returned (never <b>null</b>). * * @param prefix the prefix * @return the lookup object to be used for this prefix */ protected Lookup fetchLookupForPrefix(String prefix) { return nullSafeLookup(prefixLookups.get(prefix)); } /** * Creates and initializes a {@code StrSubstitutor} object which is used for * variable substitution. This {@code StrSubstitutor} is assigned a * specialized lookup object implementing the correct variable resolving * algorithm. * * @return the {@code StrSubstitutor} used by this object */ private StringSubstitutor initSubstitutor() { return new StringSubstitutor(new StringLookup() { @Override public String lookup(String key) { Object result = resolve(key); return result != null ? result.toString() : null; } }); } /** * Interpolates a string value that seems to be a single variable. * * @param strValue the string to be interpolated * @return the resolved value or <b>null</b> if resolving failed */ private Object resolveSingleVariable(String strValue) { return resolve(extractVariableName(strValue)); } /** * Checks whether a value to be interpolated seems to be a single variable. * In this case, it is resolved directly without using the * {@code StrSubstitutor}. Note that it is okay if this method returns a * false positive: In this case, resolving is going to fail, and standard * mechanism is used. * * @param strValue the value to be interpolated * @return a flag whether this value seems to be a single variable */ private static boolean looksLikeSingleVariable(String strValue) { return strValue.startsWith(VAR_START) && strValue.endsWith(VAR_END); } /** * Extracts the variable name from a value that consists of a single * variable. * * @param strValue the value * @return the extracted variable name */ private static String extractVariableName(String strValue) { return strValue.substring(VAR_START_LENGTH, strValue.length() - VAR_END_LENGTH); } /** * Creates a new instance based on the properties in the given specification * object. * * @param spec the {@code InterpolatorSpecification} * @return the newly created instance */ private static ConfigurationInterpolator createInterpolator( InterpolatorSpecification spec) { ConfigurationInterpolator ci = new ConfigurationInterpolator(); ci.addDefaultLookups(spec.getDefaultLookups()); ci.registerLookups(spec.getPrefixLookups()); ci.setParentInterpolator(spec.getParentInterpolator()); return ci; } static { Map<String, Lookup> lookups = new HashMap<>(); for (DefaultLookups l : DefaultLookups.values()) { lookups.put(l.getPrefix(), l.getLookup()); } DEFAULT_PREFIX_LOOKUPS = Collections.unmodifiableMap(lookups); } }
src/main/java/org/apache/commons/configuration2/interpol/ConfigurationInterpolator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.configuration2.interpol; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.text.StringSubstitutor; import org.apache.commons.text.lookup.StringLookup; /** * <p> * A class that handles interpolation (variable substitution) for configuration * objects. * </p> * <p> * Each instance of {@code AbstractConfiguration} is associated with an object * of this class. All interpolation tasks are delegated to this object. * </p> * <p> * {@code ConfigurationInterpolator} internally uses the {@code StringSubstitutor} * class from <a href="http://commons.apache.org/text">Commons Text</a>. Thus it * supports the same syntax of variable expressions. * </p> * <p> * The basic idea of this class is that it can maintain a set of primitive * {@link Lookup} objects, each of which is identified by a special prefix. The * variables to be processed have the form <code>${prefix:name}</code>. * {@code ConfigurationInterpolator} will extract the prefix and determine, * which primitive lookup object is registered for it. Then the name of the * variable is passed to this object to obtain the actual value. It is also * possible to define an arbitrary number of default lookup objects, which are * used for variables that do not have a prefix or that cannot be resolved by * their associated lookup object. When adding default lookup objects their * order matters; they are queried in this order, and the first non-<b>null</b> * variable value is used. * </p> * <p> * After an instance has been created it does not contain any {@code Lookup} * objects. The current set of lookup objects can be modified using the * {@code registerLookup()} and {@code deregisterLookup()} methods. Default * lookup objects (that are invoked for variables without a prefix) can be added * or removed with the {@code addDefaultLookup()} and * {@code removeDefaultLookup()} methods respectively. (When a * {@code ConfigurationInterpolator} instance is created by a configuration * object, a default lookup object is added pointing to the configuration * itself, so that variables are resolved using the configuration's properties.) * </p> * <p> * The default usage scenario is that on a fully initialized instance the * {@code interpolate()} method is called. It is passed an object value which * may contain variables. All these variables are substituted if they can be * resolved. The result is the passed in value with variables replaced. * Alternatively, the {@code resolve()} method can be called to obtain the * values of specific variables without performing interpolation. * </p> * <p> * Implementation node: This class is thread-safe. Lookup objects can be added * or removed at any time concurrent to interpolation operations. * </p> * * @version $Id$ * @since 1.4 * @author <a * href="http://commons.apache.org/configuration/team-list.html">Commons * Configuration team</a> */ public class ConfigurationInterpolator { /** Constant for the prefix separator. */ private static final char PREFIX_SEPARATOR = ':'; /** The variable prefix. */ private static final String VAR_START = "${"; /** The variable suffix. */ private static final String VAR_END = "}"; /** A map containing the default prefix lookups. */ private static final Map<String, Lookup> DEFAULT_PREFIX_LOOKUPS; /** A map with the currently registered lookup objects. */ private final Map<String, Lookup> prefixLookups; /** Stores the default lookup objects. */ private final List<Lookup> defaultLookups; /** The helper object performing variable substitution. */ private final StringSubstitutor substitutor; /** Stores a parent interpolator objects if the interpolator is nested hierarchically. */ private volatile ConfigurationInterpolator parentInterpolator; /** * Creates a new instance of {@code ConfigurationInterpolator}. */ public ConfigurationInterpolator() { prefixLookups = new ConcurrentHashMap<>(); defaultLookups = new CopyOnWriteArrayList<>(); substitutor = initSubstitutor(); } /** * Creates a new {@code ConfigurationInterpolator} instance based on the * passed in specification object. If the {@code InterpolatorSpecification} * already contains a {@code ConfigurationInterpolator} object, it is used * directly. Otherwise, a new instance is created and initialized with the * properties stored in the specification. * * @param spec the {@code InterpolatorSpecification} (must not be * <b>null</b>) * @return the {@code ConfigurationInterpolator} obtained or created based * on the given specification * @throws IllegalArgumentException if the specification is <b>null</b> * @since 2.0 */ public static ConfigurationInterpolator fromSpecification( InterpolatorSpecification spec) { if (spec == null) { throw new IllegalArgumentException( "InterpolatorSpecification must not be null!"); } return (spec.getInterpolator() != null) ? spec.getInterpolator() : createInterpolator(spec); } /** * Returns a map containing the default prefix lookups. Every configuration * object derived from {@code AbstractConfiguration} is by default * initialized with a {@code ConfigurationInterpolator} containing these * {@code Lookup} objects and their prefixes. The map cannot be modified * * @return a map with the default prefix {@code Lookup} objects and their * prefixes * @since 2.0 */ public static Map<String, Lookup> getDefaultPrefixLookups() { return DEFAULT_PREFIX_LOOKUPS; } /** * Utility method for obtaining a {@code Lookup} object in a safe way. This * method always returns a non-<b>null</b> {@code Lookup} object. If the * passed in {@code Lookup} is not <b>null</b>, it is directly returned. * Otherwise, result is a dummy {@code Lookup} which does not provide any * values. * * @param lookup the {@code Lookup} to check * @return a non-<b>null</b> {@code Lookup} object * @since 2.0 */ public static Lookup nullSafeLookup(Lookup lookup) { if (lookup == null) { lookup = DummyLookup.INSTANCE; } return lookup; } /** * Returns a map with the currently registered {@code Lookup} objects and * their prefixes. This is a snapshot copy of the internally used map. So * modifications of this map do not effect this instance. * * @return a copy of the map with the currently registered {@code Lookup} * objects */ public Map<String, Lookup> getLookups() { return new HashMap<>(prefixLookups); } /** * Registers the given {@code Lookup} object for the specified prefix at * this instance. From now on this lookup object will be used for variables * that have the specified prefix. * * @param prefix the variable prefix (must not be <b>null</b>) * @param lookup the {@code Lookup} object to be used for this prefix (must * not be <b>null</b>) * @throws IllegalArgumentException if either the prefix or the * {@code Lookup} object is <b>null</b> */ public void registerLookup(String prefix, Lookup lookup) { if (prefix == null) { throw new IllegalArgumentException( "Prefix for lookup object must not be null!"); } if (lookup == null) { throw new IllegalArgumentException( "Lookup object must not be null!"); } prefixLookups.put(prefix, lookup); } /** * Registers all {@code Lookup} objects in the given map with their prefixes * at this {@code ConfigurationInterpolator}. Using this method multiple * {@code Lookup} objects can be registered at once. If the passed in map is * <b>null</b>, this method does not have any effect. * * @param lookups the map with lookups to register (may be <b>null</b>) * @throws IllegalArgumentException if the map contains <b>entries</b> */ public void registerLookups(Map<String, ? extends Lookup> lookups) { if (lookups != null) { prefixLookups.putAll(lookups); } } /** * Deregisters the {@code Lookup} object for the specified prefix at this * instance. It will be removed from this instance. * * @param prefix the variable prefix * @return a flag whether for this prefix a lookup object had been * registered */ public boolean deregisterLookup(String prefix) { return prefixLookups.remove(prefix) != null; } /** * Returns an unmodifiable set with the prefixes, for which {@code Lookup} * objects are registered at this instance. This means that variables with * these prefixes can be processed. * * @return a set with the registered variable prefixes */ public Set<String> prefixSet() { return Collections.unmodifiableSet(prefixLookups.keySet()); } /** * Returns a collection with the default {@code Lookup} objects * added to this {@code ConfigurationInterpolator}. These objects are not * associated with a variable prefix. The returned list is a snapshot copy * of the internal collection of default lookups; so manipulating it does * not affect this instance. * * @return the default lookup objects */ public List<Lookup> getDefaultLookups() { return new ArrayList<>(defaultLookups); } /** * Adds a default {@code Lookup} object. Default {@code Lookup} objects are * queried (in the order they were added) for all variables without a * special prefix. If no default {@code Lookup} objects are present, such * variables won't be processed. * * @param defaultLookup the default {@code Lookup} object to be added (must * not be <b>null</b>) * @throws IllegalArgumentException if the {@code Lookup} object is * <b>null</b> */ public void addDefaultLookup(Lookup defaultLookup) { defaultLookups.add(defaultLookup); } /** * Adds all {@code Lookup} objects in the given collection as default * lookups. The collection can be <b>null</b>, then this method has no * effect. It must not contain <b>null</b> entries. * * @param lookups the {@code Lookup} objects to be added as default lookups * @throws IllegalArgumentException if the collection contains a <b>null</b> * entry */ public void addDefaultLookups(Collection<? extends Lookup> lookups) { if (lookups != null) { defaultLookups.addAll(lookups); } } /** * Removes the specified {@code Lookup} object from the list of default * {@code Lookup}s. * * @param lookup the {@code Lookup} object to be removed * @return a flag whether this {@code Lookup} object actually existed and * was removed */ public boolean removeDefaultLookup(Lookup lookup) { return defaultLookups.remove(lookup); } /** * Sets the parent {@code ConfigurationInterpolator}. This object is used if * the {@code Lookup} objects registered at this object cannot resolve a * variable. * * @param parentInterpolator the parent {@code ConfigurationInterpolator} * object (can be <b>null</b>) */ public void setParentInterpolator( ConfigurationInterpolator parentInterpolator) { this.parentInterpolator = parentInterpolator; } /** * Returns the parent {@code ConfigurationInterpolator}. * * @return the parent {@code ConfigurationInterpolator} (can be <b>null</b>) */ public ConfigurationInterpolator getParentInterpolator() { return this.parentInterpolator; } /** * Sets a flag that variable names can contain other variables. If enabled, * variable substitution is also done in variable names. * * @return the substitution in variables flag */ public boolean isEnableSubstitutionInVariables() { return substitutor.isEnableSubstitutionInVariables(); } /** * Sets the flag whether variable names can contain other variables. This * flag corresponds to the {@code enableSubstitutionInVariables} property of * the underlying {@code StrSubstitutor} object. * * @param f the new value of the flag */ public void setEnableSubstitutionInVariables(boolean f) { substitutor.setEnableSubstitutionInVariables(f); } /** * Performs interpolation of the passed in value. If the value is of type * String, this method checks whether it contains variables. If so, all * variables are replaced by their current values (if possible). For non * string arguments, the value is returned without changes. * * @param value the value to be interpolated * @return the interpolated value */ public Object interpolate(Object value) { if (value instanceof String) { String strValue = (String) value; if (looksLikeSingleVariable(strValue)) { Object resolvedValue = resolveSingleVariable(strValue); if (resolvedValue != null && !(resolvedValue instanceof String)) { // If the value is again a string, it needs no special // treatment; it may also contain further variables which // must be resolved; therefore, the default mechanism is // applied. return resolvedValue; } } return substitutor.replace(strValue); } return value; } /** * Resolves the specified variable. This implementation tries to extract * a variable prefix from the given variable name (the first colon (':') is * used as prefix separator). It then passes the name of the variable with * the prefix stripped to the lookup object registered for this prefix. If * no prefix can be found or if the associated lookup object cannot resolve * this variable, the default lookup objects are used. If this is not * successful either and a parent {@code ConfigurationInterpolator} is * available, this object is asked to resolve the variable. * * @param var the name of the variable whose value is to be looked up * @return the value of this variable or <b>null</b> if it cannot be * resolved */ public Object resolve(String var) { if (var == null) { return null; } int prefixPos = var.indexOf(PREFIX_SEPARATOR); if (prefixPos >= 0) { String prefix = var.substring(0, prefixPos); String name = var.substring(prefixPos + 1); Object value = fetchLookupForPrefix(prefix).lookup(name); if (value != null) { return value; } } for (Lookup l : defaultLookups) { Object value = l.lookup(var); if (value != null) { return value; } } ConfigurationInterpolator parent = getParentInterpolator(); if (parent != null) { return getParentInterpolator().resolve(var); } return null; } /** * Obtains the lookup object for the specified prefix. This method is called * by the {@code lookup()} method. This implementation will check * whether a lookup object is registered for the given prefix. If not, a * <b>null</b> lookup object will be returned (never <b>null</b>). * * @param prefix the prefix * @return the lookup object to be used for this prefix */ protected Lookup fetchLookupForPrefix(String prefix) { return nullSafeLookup(prefixLookups.get(prefix)); } /** * Creates and initializes a {@code StrSubstitutor} object which is used for * variable substitution. This {@code StrSubstitutor} is assigned a * specialized lookup object implementing the correct variable resolving * algorithm. * * @return the {@code StrSubstitutor} used by this object */ private StringSubstitutor initSubstitutor() { return new StringSubstitutor(new StringLookup() { @Override public String lookup(String key) { Object result = resolve(key); return result != null ? result.toString() : null; } }); } /** * Interpolates a string value that seems to be a single variable. * * @param strValue the string to be interpolated * @return the resolved value or <b>null</b> if resolving failed */ private Object resolveSingleVariable(String strValue) { return resolve(extractVariableName(strValue)); } /** * Checks whether a value to be interpolated seems to be a single variable. * In this case, it is resolved directly without using the * {@code StrSubstitutor}. Note that it is okay if this method returns a * false positive: In this case, resolving is going to fail, and standard * mechanism is used. * * @param strValue the value to be interpolated * @return a flag whether this value seems to be a single variable */ private static boolean looksLikeSingleVariable(String strValue) { return strValue.startsWith(VAR_START) && strValue.endsWith(VAR_END); } /** * Extracts the variable name from a value that consists of a single * variable. * * @param strValue the value * @return the extracted variable name */ private static String extractVariableName(String strValue) { return strValue.substring(VAR_START.length(), strValue.length() - VAR_END.length()); } /** * Creates a new instance based on the properties in the given specification * object. * * @param spec the {@code InterpolatorSpecification} * @return the newly created instance */ private static ConfigurationInterpolator createInterpolator( InterpolatorSpecification spec) { ConfigurationInterpolator ci = new ConfigurationInterpolator(); ci.addDefaultLookups(spec.getDefaultLookups()); ci.registerLookups(spec.getPrefixLookups()); ci.setParentInterpolator(spec.getParentInterpolator()); return ci; } static { Map<String, Lookup> lookups = new HashMap<>(); for (DefaultLookups l : DefaultLookups.values()) { lookups.put(l.getPrefix(), l.getLookup()); } DEFAULT_PREFIX_LOOKUPS = Collections.unmodifiableMap(lookups); } }
Extract constants. git-svn-id: 0d31da9e303333003508381311333cf78a25d41b@1842192 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/configuration2/interpol/ConfigurationInterpolator.java
Extract constants.
Java
apache-2.0
8568e90e12a66f3844db495c2da44f5069d66785
0
sangramjadhav/testrs
2047f154-2ece-11e5-905b-74de2bd44bed
hello.java
20476360-2ece-11e5-905b-74de2bd44bed
2047f154-2ece-11e5-905b-74de2bd44bed
hello.java
2047f154-2ece-11e5-905b-74de2bd44bed
Java
apache-2.0
ea578d22d41cf5856663077393a6cfb4c75cce7e
0
isandlaTech/cohorte-devtools,isandlaTech/cohorte-devtools,isandlaTech/cohorte-devtools,isandlaTech/cohorte-devtools,isandlaTech/cohorte-devtools
package org.cohorte.eclipse.runner.basic.jython; /** * * Object Factory that is used to coerce python module into a * Java class */ import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.python.core.PyBoolean; import org.python.core.PyFloat; import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class CPythonFactory implements IPythonFactory { static final String PROP_JYTHON_ENV = "org.cohorte.eclipse.runner.basic.jython.env"; /** * <pre> * define the level of the log for python call by default INFO * -Dorg.cohorte.eclipse.runner.basic.jython.level=INFO * </pre> */ static final String PROP_JYTHON_LEVEL = "org.cohorte.eclipse.runner.basic.jython.level"; public static PyObject getPyObject(final Object aJavaObj) { if (aJavaObj instanceof List<?>) { return new PyList((List<?>) aJavaObj); } else if (aJavaObj instanceof Integer) { return new PyInteger((Integer) aJavaObj); } else if (aJavaObj instanceof String) { return new PyString((String) aJavaObj); } else if (aJavaObj instanceof Float) { return new PyFloat((Float) aJavaObj); } else if (aJavaObj instanceof Boolean) { return new PyBoolean((Boolean) aJavaObj); } else if (aJavaObj instanceof PyObject) { return (PyObject) aJavaObj; } else { // to to get an invocation handler InvocationHandler wHandler = Proxy.getInvocationHandler(aJavaObj); if (wHandler instanceof CPyObjectHandler) { return ((CPyObjectHandler) wHandler).getPyObject(); } return null; } } // base directory where to lookup the python module private final List<String> pBaseDirs; /** * Create a new PythonInterpreter object, then use it to execute some python * code. In this case, we want to import the python module that we will * coerce. * * Once the module is imported than we obtain a reference to it and assign * the reference to a Java variable */ private final PythonInterpreter pInterpreter; private final List<String> pLoadedFile; /** * allow to retrieve from a pyObject the proxy */ private final Map<Integer, Integer> pMapHashCode; private final Map<Integer, WeakReference<Object>> pMapProxy; public CPythonFactory() { this(null, null); } public CPythonFactory(final List<String> aPythonPath, final String aLib) { pBaseDirs = aPythonPath; pLoadedFile = new ArrayList<>(); Properties wProps = new Properties(); wProps.put("python.home", aLib); wProps.put("python.console.encoding", "UTF-8"); wProps.put("python.security.respectJavaAccessibility", "false"); wProps.put("python.import.site", "false"); PythonInterpreter.initialize(System.getProperties(), wProps, new String[0]); pInterpreter = new PythonInterpreter(); pInterpreter.exec("import sys"); pInterpreter.exec("import logging"); pInterpreter.exec("import os"); String wLevel = System.getProperty(PROP_JYTHON_LEVEL); if (wLevel == null || wLevel.isEmpty()) { wLevel = "INFO"; } pInterpreter.exec(String.format( "logging.basicConfig(level=logging.%s)", wLevel)); initEnvironnementVariable(); if (aPythonPath != null) { addPythonPath(aPythonPath); } pMapHashCode = new HashMap<>(); pMapProxy = new HashMap<>(); } @Override public void addPythonPath(final List<String> aPythonPath) { for (String wPath : aPythonPath) { String wAppend = "sys.path.append('" + wPath + "')"; pInterpreter.exec(wAppend); } } /** * The create method is responsible for performing the actual coercion of * the referenced python module into Java bytecode * * @throws IOException */ public PyObject classForName(final String aModuleName, final String aClassName, final Object... aArguments) throws IOException { // import module String wFoundFullPath = null; // check existance of the file for (int i = 0; i < pBaseDirs.size() && wFoundFullPath == null; i++) { String wBaseDir = pBaseDirs.get(i); String path = wBaseDir + File.separatorChar + aModuleName; if (new File(path).exists()) { wFoundFullPath = path; } } if (wFoundFullPath != null) { if (!new File(wFoundFullPath).exists()) { throw new IOException(String.format("file {0} doesn't exists", wFoundFullPath)); } if (!pLoadedFile.contains(wFoundFullPath)) { pInterpreter.execfile(wFoundFullPath); pLoadedFile.add(wFoundFullPath); } // construct the argument return pInterpreter.get(aClassName); } else { throw new IOException(String.format("can't find module [%s]", aModuleName)); } } @Override public void clear() { pMapProxy.clear(); pMapHashCode.clear(); pLoadedFile.clear(); pInterpreter.cleanup(); pInterpreter.close(); } public PyObject[] convertToPyObject(final Object[] aObjects) { if (aObjects != null && aObjects.length > 0) { List<PyObject> wListArg = new ArrayList<>(); for (Object wArg : aObjects) { wListArg.add(getPyObject(wArg)); } // get the class PyObject[] wPyObjectArr = new PyObject[wListArg.size()]; wListArg.toArray(wPyObjectArr); return wPyObjectArr; } return null; } public Object getObject(final PyObject aPyObject) { if (aPyObject instanceof PyInteger) { return ((PyInteger) aPyObject).getValue(); } else if (aPyObject instanceof PyString) { return ((PyString) aPyObject).toString(); } else if (aPyObject instanceof PyFloat) { return ((PyFloat) aPyObject).getValue(); } else if (aPyObject instanceof PyBoolean) { return ((PyBoolean) aPyObject).getBooleanValue(); } else { if (pMapHashCode.get(aPyObject.hashCode()) != null) { WeakReference<Object> wRef = pMapProxy.get(pMapHashCode .get(aPyObject.hashCode())); return wRef.get(); } // not supported return aPyObject; } } private void initEnvironnementVariable() { String wEnvToAdd = System.getProperty(PROP_JYTHON_ENV); // read relevant environment variable setEnvironnementVariable("COHORTE_HOME", System.getProperty("cohorte.home")); setEnvironnementVariable( "COHORTE_DEV", System.getProperty("org.cohorte.eclipse.runner.basic.cohorte.dev")); setEnvironnementVariable("COHORTE_BASE", System.getProperty("cohorte.base")); setEnvironnementVariable("data-dir", System.getProperty("cohorte.node.data.dir")); // TODO add cohorte_home.... // set cohorte-dev environment variable if (wEnvToAdd != null && !wEnvToAdd.isEmpty()) { List<String> wSplitEnv = Arrays.asList(wEnvToAdd.split(";")); wSplitEnv.stream().forEach(wEnv -> { if (wEnv != null && wEnv.contains("=")) { String[] wEnvSpl = wEnv.split("="); setEnvironnementVariable(wEnvSpl[0], wEnvSpl[1]); } }); } } @Override public Object newInstance(final Class<?> aInterface, final Object... aArgs) throws IOException { PythonClass wAnn = aInterface.getAnnotation(PythonClass.class); if (wAnn != null) { String wmodulePath = wAnn.modulepath().replaceAll("\\.", File.separatorChar + "") + ".py"; String className = wAnn.classname(); PyObject wPyClass = classForName(wmodulePath, className); PyObject wPyObject = newInstance(wPyClass, aArgs); Object wInstance = Proxy.newProxyInstance( aInterface.getClassLoader(), new Class[] { aInterface }, new CPyObjectHandler(wPyObject, this)); // assign the hasCode betwwen proxy and pyObject pMapHashCode.put(wPyObject.hashCode(), wInstance.hashCode()); pMapProxy.put(wInstance.hashCode(), new WeakReference<>(wInstance)); return wInstance; } return null; } public PyObject newInstance(final PyObject aPythonClass, final Object... aArguments) { PyObject wPythonObject; PyObject[] wPyObjectArr = convertToPyObject(aArguments); if (wPyObjectArr != null && wPyObjectArr.length > 0) { wPythonObject = aPythonClass.__call__(wPyObjectArr); } else { wPythonObject = aPythonClass.__call__(); } return wPythonObject; } private void setEnvironnementVariable(final String aKey, final String aValue) { // read relevant environment variable pInterpreter.exec(String.format("os.environ['%s']='%s'", aKey, aValue)); pInterpreter.exec(String.format("os.environ['env:%s']='%s'", aKey, aValue)); } }
org.cohorte.eclipse.runner.basic/src/org/cohorte/eclipse/runner/basic/jython/CPythonFactory.java
package org.cohorte.eclipse.runner.basic.jython; /** * * Object Factory that is used to coerce python module into a * Java class */ import java.io.File; import java.io.IOException; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.python.core.PyBoolean; import org.python.core.PyFloat; import org.python.core.PyInteger; import org.python.core.PyList; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class CPythonFactory implements IPythonFactory { /** * <pre> * define the level of the log for python call by default INFO * -Dorg.cohorte.eclipse.runner.basic.jython.level=INFO * </pre> */ static final String PROP_JYTHON_LEVEL = "org.cohorte.eclipse.runner.basic.jython.level"; static final String PROP_JYTHON_ENV = "org.cohorte.eclipse.runner.basic.jython.env"; public static PyObject getPyObject(final Object aJavaObj) { if (aJavaObj instanceof List<?>) { return new PyList((List<?>) aJavaObj); } else if (aJavaObj instanceof Integer) { return new PyInteger((Integer) aJavaObj); } else if (aJavaObj instanceof String) { return new PyString((String) aJavaObj); } else if (aJavaObj instanceof Float) { return new PyFloat((Float) aJavaObj); } else if (aJavaObj instanceof Boolean) { return new PyBoolean((Boolean) aJavaObj); } else if (aJavaObj instanceof PyObject) { return (PyObject) aJavaObj; } else { // to to get an invocation handler InvocationHandler wHandler = Proxy.getInvocationHandler(aJavaObj); if (wHandler instanceof CPyObjectHandler) { return ((CPyObjectHandler) wHandler).getPyObject(); } return null; } } // base directory where to lookup the python module private final List<String> pBaseDirs; /** * Create a new PythonInterpreter object, then use it to execute some python * code. In this case, we want to import the python module that we will * coerce. * * Once the module is imported than we obtain a reference to it and assign * the reference to a Java variable */ private final PythonInterpreter pInterpreter; private final List<String> pLoadedFile; /** * allow to retrieve from a pyObject the proxy */ private final Map<Integer, Integer> pMapHashCode; private final Map<Integer, WeakReference<Object>> pMapProxy; public CPythonFactory() { this(null, null); } public CPythonFactory(final List<String> aPythonPath, final String aLib) { pBaseDirs = aPythonPath; pLoadedFile = new ArrayList<String>(); Properties wProps = new Properties(); wProps.put("python.home", aLib); wProps.put("python.console.encoding", "UTF-8"); wProps.put("python.security.respectJavaAccessibility", "false"); wProps.put("python.import.site", "false"); PythonInterpreter.initialize(System.getProperties(), wProps, new String[0]); pInterpreter = new PythonInterpreter(); pInterpreter.exec("import sys"); pInterpreter.exec("import logging"); pInterpreter.exec("import os"); String wLevel = System.getProperty(PROP_JYTHON_LEVEL); if( wLevel == null || wLevel.isEmpty() ) { wLevel = "INFO"; } pInterpreter.exec(String.format("logging.basicConfig(level=logging.%s)",wLevel)); initEnvironnementVariable(); if (aPythonPath != null) { addPythonPath(aPythonPath); } pMapHashCode = new HashMap<Integer, Integer>(); pMapProxy = new HashMap<Integer, WeakReference<Object>>(); } private void setEnvironnementVariable(String aKey, String aValue) { // read relevant environment variable pInterpreter.exec(String.format("os.environ['%s']='%s'",aKey,aValue)); pInterpreter.exec(String.format("os.environ['env:%s']='%s'",aKey,aValue)); } private void initEnvironnementVariable() { String wEnvToAdd = System.getProperty(PROP_JYTHON_ENV); // read relevant environment variable setEnvironnementVariable("COHORTE_HOME",System.getProperty("cohorte.home")); setEnvironnementVariable("COHORTE_DEV",System.getProperty("org.cohorte.eclipse.runner.basic.cohorte.dev")); setEnvironnementVariable("COHORTE_BASE",System.getProperty("cohorte.base")); setEnvironnementVariable("data-dir",System.getProperty("cohorte.node.data.dir")); //TODO add cohorte_home.... //set cohorte-dev environment variable if( wEnvToAdd != null && !wEnvToAdd.isEmpty()) { List<String> wSplitEnv = Arrays.asList(wEnvToAdd.split(";")); wSplitEnv.stream().forEach(wEnv->{ if( wEnv != null && wEnv.contains("=") ) { String[] wEnvSpl = wEnv.split("="); setEnvironnementVariable(wEnvSpl[0],wEnvSpl[1]); } }); } } @Override public void addPythonPath(final List<String> aPythonPath) { for (String wPath : aPythonPath) { String wAppend = "sys.path.append('" + wPath + "')"; pInterpreter.exec(wAppend); } } /** * The create method is responsible for performing the actual coercion of * the referenced python module into Java bytecode * * @throws IOException */ public PyObject classForName(final String aModuleName, final String aClassName, final Object... aArguments) throws IOException { // import module String wFoundFullPath = null; // check existance of the file for (int i = 0; i < pBaseDirs.size() && wFoundFullPath == null; i++) { String wBaseDir = pBaseDirs.get(i); String path = wBaseDir + File.separatorChar + aModuleName; if (new File(path).exists()) { wFoundFullPath = path; } } if (wFoundFullPath != null) { if (!new File(wFoundFullPath).exists()) { throw new IOException(String.format("file {0} doesn't exists", wFoundFullPath)); } if (!pLoadedFile.contains(wFoundFullPath)) { pInterpreter.execfile(wFoundFullPath); pLoadedFile.add(wFoundFullPath); } // construct the argument return pInterpreter.get(aClassName); } else { throw new IOException(String.format("can't find module [%s]", aModuleName)); } } @Override public void clear() { pMapProxy.clear(); pMapHashCode.clear(); pLoadedFile.clear(); pInterpreter.cleanup(); pInterpreter.close(); } public PyObject[] convertToPyObject(final Object[] aObjects) { if (aObjects != null && aObjects.length > 0) { List<PyObject> wListArg = new ArrayList<PyObject>(); for (Object wArg : aObjects) { wListArg.add(getPyObject(wArg)); } // get the class PyObject[] wPyObjectArr = new PyObject[wListArg.size()]; wListArg.toArray(wPyObjectArr); return wPyObjectArr; } return null; } public Object getObject(final PyObject aPyObject) { if (aPyObject instanceof PyInteger) { return ((PyInteger) aPyObject).getValue(); } else if (aPyObject instanceof PyString) { return ((PyString) aPyObject).toString(); } else if (aPyObject instanceof PyFloat) { return ((PyFloat) aPyObject).getValue(); } else if (aPyObject instanceof PyBoolean) { return ((PyBoolean) aPyObject).getBooleanValue(); } else { if (pMapHashCode.get(aPyObject.hashCode()) != null) { WeakReference<Object> wRef = pMapProxy.get(pMapHashCode .get(aPyObject.hashCode())); return wRef.get(); } // not supported return aPyObject; } } @Override public Object newInstance(final Class<?> aInterface, final Object... aArgs) throws IOException { PythonClass wAnn = aInterface.getAnnotation(PythonClass.class); if (wAnn != null) { String wmodulePath = wAnn.modulepath().replaceAll("\\.", "/") + ".py"; String className = wAnn.classname(); PyObject wPyClass = classForName(wmodulePath, className); PyObject wPyObject = newInstance(wPyClass, aArgs); Object wInstance = Proxy.newProxyInstance( aInterface.getClassLoader(), new Class[] { aInterface }, new CPyObjectHandler(wPyObject, this)); // assign the hasCode betwwen proxy and pyObject pMapHashCode.put(wPyObject.hashCode(), wInstance.hashCode()); pMapProxy.put(wInstance.hashCode(), new WeakReference<Object>( wInstance)); return wInstance; } return null; } public PyObject newInstance(final PyObject aPythonClass, final Object... aArguments) { PyObject wPythonObject; PyObject[] wPyObjectArr = convertToPyObject(aArguments); if (wPyObjectArr != null && wPyObjectArr.length > 0) { wPythonObject = aPythonClass.__call__(wPyObjectArr); } else { wPythonObject = aPythonClass.__call__(); } return wPythonObject; } }
use file.separatorChar instead of /
org.cohorte.eclipse.runner.basic/src/org/cohorte/eclipse/runner/basic/jython/CPythonFactory.java
use file.separatorChar instead of /
Java
apache-2.0
9eed546979458f07155e0d1d13819abe20277c89
0
fengbaicanhe/cas,j-fuentes/cas,zhangjianTFTC/cas,joansmith/cas,battags/cas,thomasdarimont/cas,dfish3r/cas-x509-crl-ldaptive,rallportctr/cas,battags/cas,fogbeam/fogbeam_cas,nestle1998/cas,openedbox/cas,moghaddam/cas,CruGlobal/cas,luneo7/cas,youjava/cas,yisiqi/cas,yisiqi/cas,icanfly/cas,openedbox/cas,zhangjianTFTC/cas,zhoffice/cas,Kevin2030/cas,jacklotusho/cas,thomasdarimont/cas,fengbaicanhe/cas,fannyfinal/cas,Kuohong/cas,nader93k/cas,zhangwei5095/jasig-cas-server,icereval/cas,keshvari/cas,creamer/cas,nader93k/cas,vbonamy/cas,HuangWeiWei1919/cas,youjava/cas,jacklotusho/cas,NicolasMarcotte/cas,vbonamy/cas,HuangWeiWei1919/cas,zawn/cas,PetrGasparik/cas,daniel-he/cas,CruGlobal/cas,fatherican/cas,zhaorui1/cas,openedbox/cas,zion64/cas-private,mduszyk/cas,fengbaicanhe/cas,rallportctr/cas,zion64/cas-private,j-fuentes/cas,icanfly/cas,lijihuai/cas,fogbeam/fogbeam_cas,j-fuentes/cas,fannyfinal/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,zhaorui1/cas,NicolasMarcotte/cas,NicolasMarcotte/cas,fannyfinal/cas,mabes/cas,Kuohong/cas,NicolasMarcotte/cas,zawn/cas,daniel-he/cas,nestle1998/cas,seanrbaker/cas,zhangwei5095/jasig-cas-server,austgl/cas,jacklotusho/cas,Kuohong/cas,nestle1998/cas,fogbeam/fogbeam_cas,DICE-UNC/cas,jasonchw/cas,ssmyka/cas,mabes/cas,joansmith/cas,DICE-UNC/cas,Kevin2030/cas,vbonamy/cas,yisiqi/cas,icereval/cas,keshvari/cas,openedbox/cas,zawn/cas,fatherican/cas,creamer/cas,austgl/cas,youjava/cas,joansmith/cas,luneo7/cas,seanrbaker/cas,zhaorui1/cas,HuangWeiWei1919/cas,eBaoTech/cas,jasonchw/cas,zion64/cas-private,moghaddam/cas,fannyfinal/cas,icereval/cas,ssmyka/cas,austgl/cas,icanfly/cas,thomasdarimont/cas,Kuohong/cas,luneo7/cas,nader93k/cas,DICE-UNC/cas,rallportctr/cas,DICE-UNC/cas,briandwyer/cas-hudson,zhaorui1/cas,mabes/cas,lijihuai/cas,luneo7/cas,battags/cas,austgl/cas,Kevin2030/cas,eBaoTech/cas,icereval/cas,ssmyka/cas,icanfly/cas,eBaoTech/cas,kalatestimine/cas,lijihuai/cas,Kevin2030/cas,jasonchw/cas,creamer/cas,fatherican/cas,zhoffice/cas,creamer/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,fogbeam/fogbeam_cas,briandwyer/cas-hudson,PetrGasparik/cas,ssmyka/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,zhoffice/cas,PetrGasparik/cas,dfish3r/cas-x509-crl-ldaptive,vbonamy/cas,kalatestimine/cas,PetrGasparik/cas,moghaddam/cas,eBaoTech/cas,yisiqi/cas,mduszyk/cas,daniel-he/cas,rallportctr/cas,lnthai2002/cas,zhangwei5095/jasig-cas-server,keshvari/cas,HuangWeiWei1919/cas,zhangjianTFTC/cas,moghaddam/cas,lnthai2002/cas,zhangjianTFTC/cas,mduszyk/cas,joansmith/cas,zawn/cas,jasonchw/cas,thomasdarimont/cas,daniel-he/cas,kalatestimine/cas,zhoffice/cas,mabes/cas,nestle1998/cas,j-fuentes/cas,zhangwei5095/jasig-cas-server,kalatestimine/cas,nader93k/cas,mduszyk/cas,seanrbaker/cas,youjava/cas,fengbaicanhe/cas,jacklotusho/cas,dfish3r/cas-x509-crl-ldaptive,battags/cas,dfish3r/cas-x509-crl-ldaptive,lijihuai/cas,keshvari/cas,fatherican/cas,seanrbaker/cas
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.adaptors.ldap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import org.apache.commons.lang.StringUtils; import org.jasig.cas.authentication.AbstractPasswordPolicyEnforcer; import org.jasig.cas.authentication.LdapPasswordPolicyEnforcementException; import org.jasig.cas.util.LdapUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.LdapTemplate; import org.springframework.util.Assert; /** * Class that fetches a password expiration date from an AD/LDAP database. * Based on AccountStatusGetter by Bart Ophelders & Johan Peeters * * @author Eric Pierce * @version 1.3 12/14/2009 11:47:37 * */ public class LdapPasswordPolicyEnforcer extends AbstractPasswordPolicyEnforcer { private static final class LdapPasswordPolicyResult { private String dateResult = null; private String noWarnAttributeResult = null; private String userId = null; private String validDaysResult = null; private String warnDaysResult = null; public LdapPasswordPolicyResult(final String userId) { this.userId = userId; } public String getDateResult() { return this.dateResult; } public String getNoWarnAttributeResult() { return this.noWarnAttributeResult; } public String getUserId() { return this.userId; } public String getValidDaysResult() { return this.validDaysResult; } public String getWarnDaysResult() { return this.warnDaysResult; } public void setDateResult(final String date) { this.dateResult = date; } public void setNoWarnAttributeResult(final String noWarnAttributeResult) { this.noWarnAttributeResult = noWarnAttributeResult; } public void setValidDaysResult(final String valid) { this.validDaysResult = valid; } public void setWarnDaysResult(final String warn) { this.warnDaysResult = warn; } } /** Default time zone used in calculations **/ private static final DateTimeZone DEFAULT_TIME_ZONE = DateTimeZone.UTC; /** The default maximum number of results to return. */ private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 10; /** The default timeout. */ private static final int DEFAULT_TIMEOUT = 1000; private static final long YEARS_FROM_1601_1970 = 1970 - 1601; private static final int PASSWORD_STATUS_PASS = -1; /** Value set by AD that indicates an account whose password never expires **/ private static final double PASSWORD_STATUS_NEVER_EXPIRE = Math.pow(2, 63) - 1; /** * Consider leap years, divide by 4. * Consider non-leap centuries, (1700,1800,1900). 2000 is a leap century */ private static final long TOTAL_SECONDS_FROM_1601_1970 = (YEARS_FROM_1601_1970 * 365 + YEARS_FROM_1601_1970 / 4 - 3) * 24 * 60 * 60; /** The list of valid scope values. */ private static final int[] VALID_SCOPE_VALUES = new int[] { SearchControls.OBJECT_SCOPE, SearchControls.ONELEVEL_SCOPE, SearchControls.SUBTREE_SCOPE }; /** The filter path to the lookup value of the user. */ private String filter; /** Whether the LdapTemplate should ignore partial results. */ private boolean ignorePartialResultException = false; /** LdapTemplate to execute ldap queries. */ private LdapTemplate ldapTemplate; /** The maximum number of results to return. */ private int maxNumberResults = LdapPasswordPolicyEnforcer.DEFAULT_MAX_NUMBER_OF_RESULTS; /** The attribute that contains the data that will determine if password warning is skipped */ private String noWarnAttribute; /** The value that will cause password warning to be bypassed */ private List<String> noWarnValues; /** The scope. */ private int scope = SearchControls.SUBTREE_SCOPE; /** The search base to find the user under. */ private String searchBase; /** The amount of time to wait. */ private int timeout = LdapPasswordPolicyEnforcer.DEFAULT_TIMEOUT; /** default number of days a password is valid */ private int validDays = 180; /** default number of days that a warning message will be displayed */ private int warningDays = 30; /** The attribute that contains the date the password will expire or last password change */ protected String dateAttribute; /** The format of the date in DateAttribute */ protected String dateFormat; /** The attribute that contains the number of days the user's password is valid */ protected String validDaysAttribute; /** Disregard WarnPeriod and warn all users of password expiration */ protected Boolean warnAll = Boolean.FALSE; /** The attribute that contains the user's warning days */ protected String warningDaysAttribute; public void afterPropertiesSet() throws Exception { Assert.notNull(this.ldapTemplate, "ldapTemplate cannot be null"); Assert.notNull(this.filter, "filter cannot be null"); Assert.notNull(this.searchBase, "searchBase cannot be null"); Assert.notNull(this.warnAll, "warnAll cannot be null"); Assert.notNull(this.dateAttribute, "dateAttribute cannot be null"); Assert.notNull(this.dateFormat, "dateFormat cannot be null"); Assert.isTrue(this.filter.contains("%u") || this.filter.contains("%U"), "filter must contain %u"); this.ldapTemplate.setIgnorePartialResultException(this.ignorePartialResultException); for (final int element : VALID_SCOPE_VALUES) if (this.scope == element) return; throw new IllegalStateException("You must set a valid scope. Valid scope values are: " + Arrays.toString(VALID_SCOPE_VALUES)); } /** * @return Number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS} */ public long getNumberOfDaysToPasswordExpirationDate(final String userId) throws LdapPasswordPolicyEnforcementException { String msgToLog = null; final LdapPasswordPolicyResult ldapResult = getEnforcedPasswordPolicy(userId); if (ldapResult == null) { logDebug("Skipping all password policy checks..."); return PASSWORD_STATUS_PASS; } if (!StringUtils.isEmpty(this.noWarnAttribute)) logDebug("No warning attribute value for " + this.noWarnAttribute + " is set to: " + ldapResult.getNoWarnAttributeResult()); if (isPasswordSetToNeverExpire(ldapResult.getNoWarnAttributeResult())) { logDebug("Account password will never expire. Skipping password warning check..."); return PASSWORD_STATUS_PASS; } if (StringUtils.isEmpty(ldapResult.getWarnDaysResult())) logDebug("No warning days value is found for " + userId + ". Using system default of " + this.warningDays); else this.warningDays = Integer.parseInt(ldapResult.getWarnDaysResult()); if (StringUtils.isEmpty(ldapResult.getValidDaysResult())) logDebug("No maximum password valid days found for " + ldapResult.getUserId() + ". Using system default of " + this.validDays + " days"); else this.validDays = Integer.parseInt(ldapResult.getValidDaysResult()); final DateTime expireTime = getExpirationDateToUse(ldapResult.getDateResult()); if (expireTime == null) { msgToLog = "Expiration date cannot be determined for date " + ldapResult.getDateResult(); final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog); logError(msgToLog, exc); throw exc; } return getDaysToExpirationDate(userId, expireTime); } /** * Method to set the data source and generate a LDAPTemplate. * * @param dataSource the data source to use. */ public void setContextSource(final ContextSource contextSource) { this.ldapTemplate = new LdapTemplate(contextSource); } /** * @param DateAttribute The DateAttribute to set. */ public void setDateAttribute(final String dateAttribute) { this.dateAttribute = dateAttribute; logDebug("Date attribute: " + dateAttribute); } /** * @param dateFormat String to pass to SimpleDateFormat() that describes the * date in the ExpireDateAttribute. This parameter is required. */ public void setDateFormat(final String dateFormat) { this.dateFormat = dateFormat; logDebug("Date format: " + dateFormat); } /** * @param filter The LDAP filter to set. */ public void setFilter(final String filter) { this.filter = filter; logDebug("Search filter: " + filter); } public void setIgnorePartialResultException(final boolean ignorePartialResultException) { this.ignorePartialResultException = ignorePartialResultException; } /** * @param maxNumberResults The maxNumberResults to set. */ public void setMaxNumberResults(final int maxNumberResults) { this.maxNumberResults = maxNumberResults; } /** * @param noWarnAttribute The noWarnAttribute to set. */ public void setNoWarnAttribute(final String noWarnAttribute) { this.noWarnAttribute = noWarnAttribute; logDebug("Attribute to flag warning bypass: " + noWarnAttribute); } /** * @param noWarnAttribute The noWarnAttribute to set. */ public void setNoWarnValues(final List<String> noWarnValues) { this.noWarnValues = noWarnValues; logDebug("Value to flag warning bypass: " + noWarnValues.toString()); } /** * @param filter The scope to set. */ public void setScope(final int scope) { this.scope = scope; } /** * @param searchBase The searchBase to set. */ public void setSearchBase(final String searchBase) { this.searchBase = searchBase; logDebug("Search base: " + searchBase); } /** * @param timeout The timeout to set. */ public void setTimeout(final int timeout) { this.timeout = timeout; logDebug("Timeout: " + this.timeout); } /** * @param validDays Number of days that a password is valid for. * Used as a default if DateAttribute is not set or is not found in the LDAP results */ public void setValidDays(final int validDays) { this.validDays = validDays; logDebug("Password valid days: " + validDays); } /** * @param ValidDaysAttribute The ValidDaysAttribute to set. */ public void setValidDaysAttribute(final String validDaysAttribute) { this.validDaysAttribute = validDaysAttribute; logDebug("Valid days attribute: " + validDaysAttribute); } /** * @param warnAll Disregard warningPeriod and warn all users of password expiration. */ public void setWarnAll(final Boolean warnAll) { this.warnAll = warnAll; logDebug("warnAll: " + warnAll); } /** * @param warningDays Number of days before expiration that a warning * message is displayed to set. Used as a default if warningDaysAttribute is * not set or is not found in the LDAP results. This parameter is required. */ public void setWarningDays(final int warningDays) { this.warningDays = warningDays; logDebug("Default warningDays: " + warningDays); } /** * @param WarningDaysAttribute The WarningDaysAttribute to set. */ public void setWarningDaysAttribute(final String warnDays) { this.warningDaysAttribute = warnDays; logDebug("Warning days attribute: " + warnDays); } /*** * Converts the numbers in Active Directory date fields for pwdLastSet, accountExpires, * lastLogonTimestamp, lastLogon, and badPasswordTime to a common date format. * @param pswValue */ private DateTime convertDateToActiveDirectoryFormat(final String pswValue) { final long l = Long.parseLong(pswValue.trim()); final long totalSecondsSince1601 = l / 10000000; final long totalSecondsSince1970 = totalSecondsSince1601 - TOTAL_SECONDS_FROM_1601_1970; final DateTime dt = new DateTime(totalSecondsSince1970 * 1000, DEFAULT_TIME_ZONE); logInfo("Recalculated " + this.dateFormat + " " + this.dateAttribute + " attribute to " + dt.toString()); return dt; } /** * Parses and formats the retrieved date value from Ldap * @param ldapResult * @return newly constructed date object whose value was passed */ private DateTime formatDateByPattern(final String ldapResult) { final DateTimeFormatter fmt = DateTimeFormat.forPattern(this.dateFormat); final DateTime date = new DateTime(DateTime.parse(ldapResult, fmt), DEFAULT_TIME_ZONE); return date; } /** * Determines the expiration date to use based on the settings. * @param ldapDateResult * @return Constructed the {@link #org.joda.time.DateTime DateTime} object which indicates the expiration date */ private DateTime getExpirationDateToUse(final String ldapDateResult) { DateTime dateValue = null; if (isUsingActiveDirectory()) dateValue = convertDateToActiveDirectoryFormat(ldapDateResult); else dateValue = formatDateByPattern(ldapDateResult); DateTime expireDate = dateValue.plusDays(this.validDays); logDebug("Retrieved date value " + dateValue.toString() + " for date attribute " + this.dateAttribute + " and added " + this.validDays + " days. The final expiration date is " + expireDate.toString()); return expireDate; } /** * Calculates the number of days lefty to the expiration date based on the {@code expireDate} parameter * @param expireDate * @param userId * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS} */ private long getDaysToExpirationDate(final String userId, final DateTime expireDate) throws LdapPasswordPolicyEnforcementException { logDebug("Calculating number of days left to the expiration date for user " + userId); final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE); logInfo("Current date is " + currentTime.toString()); logInfo("Expiration date is " + expireDate.toString()); final Days d = Days.daysBetween(currentTime, expireDate); int daysToExpirationDate = d.getDays(); if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) { String msgToLog = "Authentication failed because account password has expired with " + daysToExpirationDate + " to expiration date. "; msgToLog += "Verify the value of the " + this.dateAttribute + " attribute and make sure it's not before the current date, which is " + currentTime.toString(); final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog); logError(msgToLog, exc); throw exc; } /* * Warning period begins from X number of ways before the expiration date */ DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE); warnPeriod = warnPeriod.minusDays(this.warningDays); logInfo("Warning period begins on " + warnPeriod.toString()); if (this.warnAll) logInfo("Warning all. The password for " + userId + " will expire in " + daysToExpirationDate + " days."); else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) logInfo("Password will expire in " + daysToExpirationDate + " days."); else { logInfo("Password is not expiring. " + daysToExpirationDate + " days left to the warning"); daysToExpirationDate = PASSWORD_STATUS_PASS; } return daysToExpirationDate; } private LdapPasswordPolicyResult getEnforcedPasswordPolicy(final String userId) { LdapPasswordPolicyResult ldapResult = null; ldapResult = getResultsFromLdap(userId); if (ldapResult == null) { String msgToLog = "No entry was found for user " + userId + ". Verify your LPPE settings. "; msgToLog += "If you are not using LPPE, set the 'enabled' property to false. "; msgToLog += "Password policy enforcement is currently turned on but not configured."; if (this.logger.isWarnEnabled()) this.logger.warn(msgToLog); } return ldapResult; } /** * Retrieves the password policy results from the configured ldap repository based on the attributes defined. * @param userId * @return {@code null} if the user id cannot be found, or the {@code LdapPasswordPolicyResult} instance. */ private LdapPasswordPolicyResult getResultsFromLdap(final String userId) { String[] attributeIds; final List<String> attributeList = new ArrayList<String>(); attributeList.add(this.dateAttribute); if (this.warningDaysAttribute != null) attributeList.add(this.warningDaysAttribute); if (this.validDaysAttribute != null) attributeList.add(this.validDaysAttribute); if (this.noWarnAttribute != null) attributeList.add(this.noWarnAttribute); attributeIds = new String[attributeList.size()]; attributeList.toArray(attributeIds); final String searchFilter = LdapUtils.getFilterWithValues(this.filter, userId); logDebug("Starting search with searchFilter: " + searchFilter); String attributeListLog = attributeIds[0]; for (int i = 1; i < attributeIds.length; i++) attributeListLog = attributeListLog.concat(":" + attributeIds[i]); logDebug("Returning attributes " + attributeListLog); try { final AttributesMapper mapper = new AttributesMapper() { public Object mapFromAttributes(final Attributes attrs) throws NamingException { final LdapPasswordPolicyResult result = new LdapPasswordPolicyResult(userId); if (LdapPasswordPolicyEnforcer.this.dateAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute) != null) { final String date = (String) attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute).get(); result.setDateResult(date); } if (LdapPasswordPolicyEnforcer.this.warningDaysAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute) != null) { final String warn = (String) attrs.get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute).get(); result.setWarnDaysResult(warn); } if (LdapPasswordPolicyEnforcer.this.noWarnAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.noWarnAttribute) != null) { final String attrib = (String) attrs.get(LdapPasswordPolicyEnforcer.this.noWarnAttribute).get(); result.setNoWarnAttributeResult(attrib); } if (attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute) != null) { final String valid = (String) attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute).get(); result.setValidDaysResult(valid); } return result; } }; final List<?> LdapResultList = this.ldapTemplate.search(this.searchBase, searchFilter, getSearchControls(attributeIds), mapper); if (LdapResultList.size() > 0) return (LdapPasswordPolicyResult) LdapResultList.get(0); } catch (final Exception e) { logError(e.getMessage(), e); } return null; } private SearchControls getSearchControls(final String[] attributeIds) { final SearchControls constraints = new SearchControls(); constraints.setSearchScope(this.scope); constraints.setReturningAttributes(attributeIds); constraints.setTimeLimit(this.timeout); constraints.setCountLimit(this.maxNumberResults); return constraints; } /** * Determines if the password value is set to never expire. * It will check the value against the previously defined list of {@link #noWarnValues}. * If that fails, checks the value against {@link #PASSWORD_STATUS_NEVER_EXPIRE} * * @return boolean that indicates whether or not password warning should proceed. */ private boolean isPasswordSetToNeverExpire(final String pswValue) { boolean ignoreChecks = this.noWarnValues.contains(pswValue); if (!ignoreChecks && StringUtils.isNumeric(pswValue)) { final double psw = Double.parseDouble(pswValue); ignoreChecks = psw == PASSWORD_STATUS_NEVER_EXPIRE; } return ignoreChecks; } /** * Determines whether the {@link #dateFormat} field is configured for ActiveDirectory. * Accepted values are {@code ActiveDirectory} or {@code AD} * @return boolean that says whether or not {@link #dateFormat} is defined for ActiveDirectory. */ private boolean isUsingActiveDirectory() { return this.dateFormat.equalsIgnoreCase("ActiveDirectory") || this.dateFormat.equalsIgnoreCase("AD"); } private void logDebug(final String log) { if (this.logger.isDebugEnabled()) this.logger.debug(log); } private void logError(final String log, final Exception e) { if (this.logger.isErrorEnabled()) this.logger.error(e.getMessage(), e); } private void logInfo(final String log) { if (this.logger.isInfoEnabled()) this.logger.info(log); } }
cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/LdapPasswordPolicyEnforcer.java
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a * copy of the License at the following location: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jasig.cas.adaptors.ldap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.naming.NamingException; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import org.apache.commons.lang.StringUtils; import org.jasig.cas.authentication.AbstractPasswordPolicyEnforcer; import org.jasig.cas.authentication.LdapPasswordPolicyEnforcementException; import org.jasig.cas.util.LdapUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.ldap.core.AttributesMapper; import org.springframework.ldap.core.ContextSource; import org.springframework.ldap.core.LdapTemplate; import org.springframework.util.Assert; /** * Class that fetches a password expiration date from an AD/LDAP database. * Based on AccountStatusGetter by Bart Ophelders & Johan Peeters * * @author Eric Pierce * @version 1.3 12/14/2009 11:47:37 * */ public class LdapPasswordPolicyEnforcer extends AbstractPasswordPolicyEnforcer { private static final class LdapPasswordPolicyResult { private String dateResult = null; private String noWarnAttributeResult = null; private String userId = null; private String validDaysResult = null; private String warnDaysResult = null; public LdapPasswordPolicyResult(final String userId) { this.userId = userId; } public String getDateResult() { return this.dateResult; } public String getNoWarnAttributeResult() { return this.noWarnAttributeResult; } public String getUserId() { return this.userId; } public String getValidDaysResult() { return this.validDaysResult; } public String getWarnDaysResult() { return this.warnDaysResult; } public void setDateResult(final String date) { this.dateResult = date; } public void setNoWarnAttributeResult(final String noWarnAttributeResult) { this.noWarnAttributeResult = noWarnAttributeResult; } public void setValidDaysResult(final String valid) { this.validDaysResult = valid; } public void setWarnDaysResult(final String warn) { this.warnDaysResult = warn; } } /** Default time zone used in calculations **/ private static final DateTimeZone DEFAULT_TIME_ZONE = DateTimeZone.UTC; /** The default maximum number of results to return. */ private static final int DEFAULT_MAX_NUMBER_OF_RESULTS = 10; /** The default timeout. */ private static final int DEFAULT_TIMEOUT = 1000; private static final long YEARS_FROM_1601_1970 = 1970 - 1601; private static final int PASSWORD_STATUS_PASS = -1; /** Value set by AD that indicates an account whose password never expires **/ private static final double PASSWORD_STATUS_NEVER_EXPIRE = Math.pow(2, 63) - 1; /** * Consider leap years, divide by 4. * Consider non-leap centuries, (1700,1800,1900). 2000 is a leap century */ private static final long TOTAL_SECONDS_FROM_1601_1970 = (YEARS_FROM_1601_1970 * 365 + YEARS_FROM_1601_1970 / 4 - 3) * 24 * 60 * 60; /** The list of valid scope values. */ private static final int[] VALID_SCOPE_VALUES = new int[] { SearchControls.OBJECT_SCOPE, SearchControls.ONELEVEL_SCOPE, SearchControls.SUBTREE_SCOPE }; /** The filter path to the lookup value of the user. */ private String filter; /** Whether the LdapTemplate should ignore partial results. */ private boolean ignorePartialResultException = false; /** LdapTemplate to execute ldap queries. */ private LdapTemplate ldapTemplate; /** The maximum number of results to return. */ private int maxNumberResults = LdapPasswordPolicyEnforcer.DEFAULT_MAX_NUMBER_OF_RESULTS; /** The attribute that contains the data that will determine if password warning is skipped */ private String noWarnAttribute; /** The value that will cause password warning to be bypassed */ private List<String> noWarnValues; /** The scope. */ private int scope = SearchControls.SUBTREE_SCOPE; /** The search base to find the user under. */ private String searchBase; /** The amount of time to wait. */ private int timeout = LdapPasswordPolicyEnforcer.DEFAULT_TIMEOUT; /** default number of days a password is valid */ private int validDays = 180; /** default number of days that a warning message will be displayed */ private int warningDays = 30; /** The attribute that contains the date the password will expire or last password change */ protected String dateAttribute; /** The format of the date in DateAttribute */ protected String dateFormat; /** The attribute that contains the number of days the user's password is valid */ protected String validDaysAttribute; /** Disregard WarnPeriod and warn all users of password expiration */ protected Boolean warnAll = Boolean.FALSE; /** The attribute that contains the user's warning days */ protected String warningDaysAttribute; public void afterPropertiesSet() throws Exception { Assert.notNull(this.ldapTemplate, "ldapTemplate cannot be null"); Assert.notNull(this.filter, "filter cannot be null"); Assert.notNull(this.searchBase, "searchBase cannot be null"); Assert.notNull(this.warnAll, "warnAll cannot be null"); Assert.notNull(this.dateAttribute, "dateAttribute cannot be null"); Assert.notNull(this.dateFormat, "dateFormat cannot be null"); Assert.isTrue(this.filter.contains("%u") || this.filter.contains("%U"), "filter must contain %u"); this.ldapTemplate.setIgnorePartialResultException(this.ignorePartialResultException); for (final int element : VALID_SCOPE_VALUES) if (this.scope == element) return; throw new IllegalStateException("You must set a valid scope. Valid scope values are: " + Arrays.toString(VALID_SCOPE_VALUES)); } /** * @return Number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS} */ public long getNumberOfDaysToPasswordExpirationDate(final String userId) throws LdapPasswordPolicyEnforcementException { String msgToLog = null; final LdapPasswordPolicyResult ldapResult = getEnforcedPasswordPolicy(userId); if (ldapResult == null) { logDebug("Skipping all password policy checks..."); return PASSWORD_STATUS_PASS; } if (this.noWarnAttribute != null) logDebug("No warning attribute value for " + this.noWarnAttribute + " is set to: " + ldapResult.getNoWarnAttributeResult()); if (isPasswordSetToNeverExpire(ldapResult.getNoWarnAttributeResult())) { logDebug("Account password will never expire. Skipping password warning check..."); return PASSWORD_STATUS_PASS; } if (ldapResult.getWarnDaysResult() == null) logDebug("No warning days value is found for " + userId + ". Using system default of " + this.warningDays); else this.warningDays = Integer.parseInt(ldapResult.getWarnDaysResult()); if (ldapResult.getValidDaysResult() == null) logDebug("No maximum password valid days found for " + ldapResult.getUserId() + ". Using system default of " + this.validDays + " days"); else this.validDays = Integer.parseInt(ldapResult.getValidDaysResult()); final DateTime expireTime = getDateToUse(ldapResult.getDateResult()); if (expireTime == null) { msgToLog = "Expiration date cannot be determined for date " + ldapResult.getDateResult(); final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog); logError(msgToLog, exc); throw exc; } return getDaysToExpirationDate(userId, expireTime); } /** * Method to set the data source and generate a LDAPTemplate. * * @param dataSource the data source to use. */ public void setContextSource(final ContextSource contextSource) { this.ldapTemplate = new LdapTemplate(contextSource); } /** * @param DateAttribute The DateAttribute to set. */ public void setDateAttribute(final String DateAttribute) { this.dateAttribute = DateAttribute; logDebug("Date attribute: " + DateAttribute); } /** * @param dateFormat String to pass to SimpleDateFormat() that describes the * date in the ExpireDateAttribute. This parameter is required. */ public void setDateFormat(final String dateFormat) { this.dateFormat = dateFormat; logDebug("Date format: " + dateFormat); } /** * @param filter The LDAP filter to set. */ public void setFilter(final String filter) { this.filter = filter; logDebug("Search filter: " + filter); } public void setIgnorePartialResultException(final boolean ignorePartialResultException) { this.ignorePartialResultException = ignorePartialResultException; } /** * @param maxNumberResults The maxNumberResults to set. */ public void setMaxNumberResults(final int maxNumberResults) { this.maxNumberResults = maxNumberResults; } /** * @param noWarnAttribute The noWarnAttribute to set. */ public void setNoWarnAttribute(final String noWarnAttribute) { this.noWarnAttribute = noWarnAttribute; logDebug("Attribute to flag warning bypass: " + noWarnAttribute); } /** * @param noWarnAttribute The noWarnAttribute to set. */ public void setNoWarnValues(final List<String> noWarnValues) { this.noWarnValues = noWarnValues; logDebug("Value to flag warning bypass: " + noWarnValues.toString()); } /** * @param filter The scope to set. */ public void setScope(final int scope) { this.scope = scope; } /** * @param searchBase The searchBase to set. */ public void setSearchBase(final String searchBase) { this.searchBase = searchBase; logDebug("Search Base: " + searchBase); } /** * @param timeout The timeout to set. */ public void setTimeout(final int timeout) { this.timeout = timeout; logDebug("Timeout: " + this.timeout); } /** * @param validDays Number of days that a password is valid for. * Used as a default if DateAttribute is not set or is not found in the LDAP results */ public void setValidDays(final int validDays) { this.validDays = validDays; logDebug("Password valid days: " + validDays); } /** * @param ValidDaysAttribute The ValidDaysAttribute to set. */ public void setValidDaysAttribute(final String ValidDaysAttribute) { this.validDaysAttribute = ValidDaysAttribute; logDebug("Valid days attribute: " + ValidDaysAttribute); } /** * @param warnAll Disregard warningPeriod and warn all users of password expiration. */ public void setWarnAll(final Boolean warnAll) { this.warnAll = warnAll; logDebug("warnAll: " + warnAll); } /** * @param warningDays Number of days before expiration that a warning * message is displayed to set. Used as a default if warningDaysAttribute is * not set or is not found in the LDAP results. This parameter is required. */ public void setWarningDays(final int warningDays) { this.warningDays = warningDays; logDebug("Default warningDays: " + warningDays); } /** * @param WarningDaysAttribute The WarningDaysAttribute to set. */ public void setWarningDaysAttribute(final String warnDays) { this.warningDaysAttribute = warnDays; logDebug("Warning days Attribute: " + warnDays); } /*** * Converts the numbers in Active Directory date fields for pwdLastSet, accountExpires, * lastLogonTimestamp, lastLogon, and badPasswordTime to a common date format. * @param pswValue */ private DateTime convertDateToActiveDirectoryFormat(final String pswValue) { final long l = Long.parseLong(pswValue.trim()); final long totalSecondsSince1601 = l / 10000000; final long totalSecondsSince1970 = totalSecondsSince1601 - TOTAL_SECONDS_FROM_1601_1970; final DateTime dt = new DateTime(totalSecondsSince1970 * 1000, DEFAULT_TIME_ZONE); logInfo("Recalculated AD " + this.dateAttribute + " attribute to " + dt.toString()); return dt; } /** * Parses and formats the retrieved date value from Ldap * @param ldapResult * @return newly constructed date object whose value was passed */ private DateTime formatDateByPattern(final String ldapResult) { final DateTimeFormatter fmt = DateTimeFormat.forPattern(this.dateFormat); final DateTime date = new DateTime(DateTime.parse(ldapResult, fmt), DEFAULT_TIME_ZONE); return date; } /** * Determines the expiration date to use based on the settings. * @param ldapDateResult * @return Constructed the {@link #org.joda.time.DateTime DateTime} object which indicates the expiration date */ private DateTime getDateToUse(final String ldapDateResult) { DateTime expireDate = null; if (isUsingActiveDirectory()) expireDate = convertDateToActiveDirectoryFormat(ldapDateResult); else expireDate = formatDateByPattern(ldapDateResult); return expireDate; } /** * Calculates the number of days lefty to the expiration date based on the {@code expireDate} parameter * @param expireDate * @param userId * @return number of days left to the expiration date, or {@value #PASSWORD_STATUS_PASS} */ private long getDaysToExpirationDate(final String userId, final DateTime expireDate) throws LdapPasswordPolicyEnforcementException { logDebug("Calculating number of days left to the expiration date for user " + userId); final DateTime currentTime = new DateTime(DEFAULT_TIME_ZONE); logInfo("Current date is " + currentTime.toString()); logInfo("Expiration date is " + expireDate.toString()); final Days d = Days.daysBetween(currentTime, expireDate); int daysToExpirationDate = d.getDays(); if (expireDate.equals(currentTime) || expireDate.isBefore(currentTime)) { String msgToLog = "Authentication failed because account password has expired with " + daysToExpirationDate + " to expiration date. "; msgToLog += "Verify the value of the " + this.dateAttribute + " attribute and make sure it's not before the current date, which is " + currentTime.toString(); final LdapPasswordPolicyEnforcementException exc = new LdapPasswordPolicyEnforcementException(msgToLog); logError(msgToLog, exc); throw exc; } /* * Warning period begins from X number of ways before the expiration date */ DateTime warnPeriod = new DateTime(DateTime.parse(expireDate.toString()), DEFAULT_TIME_ZONE); warnPeriod = warnPeriod.minusDays(this.warningDays); logInfo("Warning period begins on " + warnPeriod.toString()); if (this.warnAll) logInfo("Warning all. The password for " + userId + " will expire in " + daysToExpirationDate + " days."); else if (currentTime.equals(warnPeriod) || currentTime.isAfter(warnPeriod)) logInfo("Password will expire in " + daysToExpirationDate + " days."); else { logInfo("Password is not expiring. " + daysToExpirationDate + " days left to the warning"); daysToExpirationDate = PASSWORD_STATUS_PASS; } return daysToExpirationDate; } private LdapPasswordPolicyResult getEnforcedPasswordPolicy(final String userId) { LdapPasswordPolicyResult ldapResult = null; ldapResult = getResultsFromLdap(userId); if (ldapResult == null) { String msgToLog = "No entry was found for user " + userId + ". Verify your LPPE settings. "; msgToLog += "If you are not using LPPE, set the 'enabled' property to false. "; msgToLog += "Password policy enforcement is currently turned on but not configured."; if (this.logger.isWarnEnabled()) this.logger.warn(msgToLog); } return ldapResult; } /** * Retrieves the password policy results from the configured ldap repository based on the attributes defined. * @param userId * @return {@code null} if the user id cannot be found, or the {@code LdapPasswordPolicyResult} instance. */ private LdapPasswordPolicyResult getResultsFromLdap(final String userId) { String[] attributeIds; final List<String> attributeList = new ArrayList<String>(); attributeList.add(this.dateAttribute); if (this.warningDaysAttribute != null) attributeList.add(this.warningDaysAttribute); if (this.validDaysAttribute != null) attributeList.add(this.validDaysAttribute); if (this.noWarnAttribute != null) attributeList.add(this.noWarnAttribute); attributeIds = new String[attributeList.size()]; attributeList.toArray(attributeIds); final String searchFilter = LdapUtils.getFilterWithValues(this.filter, userId); logDebug("Starting search with searchFilter: " + searchFilter); String attributeListLog = attributeIds[0]; for (int i = 1; i < attributeIds.length; i++) attributeListLog = attributeListLog.concat(":" + attributeIds[i]); logDebug("Returning attributes " + attributeListLog); try { final AttributesMapper mapper = new AttributesMapper() { public Object mapFromAttributes(final Attributes attrs) throws NamingException { final LdapPasswordPolicyResult result = new LdapPasswordPolicyResult(userId); if (LdapPasswordPolicyEnforcer.this.dateAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute) != null) { final String date = (String) attrs.get(LdapPasswordPolicyEnforcer.this.dateAttribute).get(); result.setDateResult(date); } if (LdapPasswordPolicyEnforcer.this.warningDaysAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute) != null) { final String warn = (String) attrs.get(LdapPasswordPolicyEnforcer.this.warningDaysAttribute).get(); result.setWarnDaysResult(warn); } if (LdapPasswordPolicyEnforcer.this.noWarnAttribute != null) if (attrs.get(LdapPasswordPolicyEnforcer.this.noWarnAttribute) != null) { final String attrib = (String) attrs.get(LdapPasswordPolicyEnforcer.this.noWarnAttribute).get(); result.setNoWarnAttributeResult(attrib); } if (attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute) != null) { final String valid = (String) attrs.get(LdapPasswordPolicyEnforcer.this.validDaysAttribute).get(); result.setValidDaysResult(valid); } return result; } }; final List<?> LdapResultList = this.ldapTemplate.search(this.searchBase, searchFilter, getSearchControls(attributeIds), mapper); if (LdapResultList.size() > 0) return (LdapPasswordPolicyResult) LdapResultList.get(0); } catch (final Exception e) { logError(e.getMessage(), e); } return null; } private SearchControls getSearchControls(final String[] attributeIds) { final SearchControls constraints = new SearchControls(); constraints.setSearchScope(this.scope); constraints.setReturningAttributes(attributeIds); constraints.setTimeLimit(this.timeout); constraints.setCountLimit(this.maxNumberResults); return constraints; } /** * Determines if the password value is set to never expire. * It will check the value against the previously defined list of {@link #noWarnValues}. * If that fails, checks the value against {@link #PASSWORD_STATUS_NEVER_EXPIRE} * * @return boolean that indicates whether or not password warning should proceed. */ private boolean isPasswordSetToNeverExpire(final String pswValue) { boolean ignoreChecks = this.noWarnValues.contains(pswValue); if (!ignoreChecks && StringUtils.isNumeric(pswValue)) { final double psw = Double.parseDouble(pswValue); ignoreChecks = psw == PASSWORD_STATUS_NEVER_EXPIRE; } return ignoreChecks; } /** * Determines whether the {@link #dateFormat} field is configured for ActiveDirectory. * Accepted values are {@code ActiveDirectory} or {@code AD} * @return boolean that says whether or not {@link #dateFormat} is defined for ActiveDirectory. */ private boolean isUsingActiveDirectory() { return this.dateFormat.equalsIgnoreCase("ActiveDirectory") || this.dateFormat.equalsIgnoreCase("AD"); } private void logDebug(final String log) { if (this.logger.isDebugEnabled()) this.logger.debug(log); } private void logError(final String log, final Exception e) { if (this.logger.isErrorEnabled()) this.logger.error(e.getMessage(), e); } private void logInfo(final String log) { if (this.logger.isInfoEnabled()) this.logger.info(log); } }
CAS-1132: Fixed a bug where validDays value was not taken into account when calculating expiration dates.
cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/LdapPasswordPolicyEnforcer.java
CAS-1132: Fixed a bug where validDays value was not taken into account when calculating expiration dates.
Java
apache-2.0
9c0f27d905c0bfc710dd73c1f88c7a67f79f73b9
0
PRIDE-Archive/web-service,PRIDE-Archive/web-service,PRIDE-Archive/web-service
package uk.ac.ebi.pride.archive.web.service.controller.psm; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import uk.ac.ebi.pride.archive.dataprovider.identification.ModificationProvider; import uk.ac.ebi.pride.archive.web.service.util.WsUtils; import uk.ac.ebi.pride.indexutils.modifications.Modification; import uk.ac.ebi.pride.psmindex.mongo.search.model.MongoPsm; import uk.ac.ebi.pride.psmindex.mongo.search.service.MongoPsmIndexService; import uk.ac.ebi.pride.psmindex.mongo.search.service.MongoPsmSearchService; import uk.ac.ebi.pride.psmindex.search.model.Psm; import uk.ac.ebi.pride.psmindex.search.service.PsmSearchService; import javax.annotation.Resource; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "classpath:test-context.xml", "classpath:mvc-config.xml", "classpath:spring-mongo-test-context.xml"}) public class PsmControllerFunctionalTest { //TODO fix unit tests using Fongo @Autowired private WebApplicationContext webApplicationContext; @Autowired private PsmSearchService psmSearchService; @Resource private MongoPsmIndexService mongoPsmIndexService; @Autowired private MongoPsmSearchService mongoPsmSearchService; private MockMvc mockMvc; private static final String ID = "PXTEST1_1234"; private static final String PROJECT_ACCESSION = "PXTEST1"; private static final String ASSAY_ACCESSION = "1234"; private static final String PROTEIN_ACCESSION = "P12345"; @Before public void setUp() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); Psm psm = new Psm(); psm.setId(ID); psm.setProteinAccession(PROTEIN_ACCESSION); psm.setProjectAccession(PROJECT_ACCESSION); psm.setAssayAccession(ASSAY_ACCESSION); List<Psm> list = new ArrayList<>(1); list.add(psm); Page<Psm> page = new PageImpl<>(list); PageRequest pageRequest = new PageRequest(0, 10, Sort.Direction.ASC, "peptide_sequence"); when( psmSearchService.findByProjectAccession(PROJECT_ACCESSION, pageRequest) ).thenReturn(page); when( psmSearchService.findByAssayAccession(ASSAY_ACCESSION, pageRequest) ).thenReturn(page); pageRequest = new PageRequest(0, 2, Sort.Direction.ASC, "peptide_sequence"); when( psmSearchService.findByProjectAccession(PROJECT_ACCESSION, pageRequest) ).thenReturn(page); when( psmSearchService.findByAssayAccession(ASSAY_ACCESSION, pageRequest) ).thenReturn(page); mongoPsmIndexService.deleteAll(); MongoPsm mongoPsm = new MongoPsm(); mongoPsm.setId(ID); mongoPsm.setProteinAccession(PROTEIN_ACCESSION); mongoPsm.setProjectAccession(PROJECT_ACCESSION); mongoPsm.setAssayAccession(ASSAY_ACCESSION); mongoPsmIndexService.save(mongoPsm); } @Test // /peptide/list/project/{projectAccession} public void getPsmByProjectAccession() throws Exception { // test default use case /* mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); // test with custom paging configuration mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION + "?show=2&page=0")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION)));*/ } @Test // /peptide/list/project/{projectAccession} public void getPsmByProjectAccessionMaxPageSizeExpecetion() throws Exception { // test with custom paging configuration mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION + "?show=" + (WsUtils.MAX_PAGE_SIZE + 1) + "&page=0")) .andExpect(status().isForbidden()); } @Test // /peptide/list/assay/{assayAccession} public void getPsmByAssayAccession() throws Exception { // test default use case /* mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); // test with custom paging configuration mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION + "?show=2&page=0")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION)));*/ } @Test // /peptide/list/assay/{assayAccession} public void getPsmByAssaytAccessionMaxPageSizeException() throws Exception { // test with custom paging configuration mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION + "?show="+ (WsUtils.MAX_PAGE_SIZE + 1)+"&page=0")) .andExpect(status().isForbidden()); } }
src/test/java/uk/ac/ebi/pride/archive/web/service/controller/psm/PsmControllerFunctionalTest.java
package uk.ac.ebi.pride.archive.web.service.controller.psm; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import uk.ac.ebi.pride.archive.dataprovider.identification.ModificationProvider; import uk.ac.ebi.pride.archive.web.service.util.WsUtils; import uk.ac.ebi.pride.indexutils.modifications.Modification; import uk.ac.ebi.pride.psmindex.mongo.search.model.MongoPsm; import uk.ac.ebi.pride.psmindex.mongo.search.service.MongoPsmIndexService; import uk.ac.ebi.pride.psmindex.mongo.search.service.MongoPsmSearchService; import uk.ac.ebi.pride.psmindex.search.model.Psm; import uk.ac.ebi.pride.psmindex.search.service.PsmSearchService; import javax.annotation.Resource; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({"classpath:test-context.xml", "classpath:mvc-config.xml", "classpath:spring-mongo-test-context.xml"}) public class PsmControllerFunctionalTest { //TODO fix unit tests using Fongo @Autowired private WebApplicationContext webApplicationContext; @Autowired private PsmSearchService psmSearchService; @Resource private MongoPsmIndexService mongoPsmIndexService; @Autowired private MongoPsmSearchService mongoPsmSearchService; private MockMvc mockMvc; private static final String ID = "PXTEST1_1234"; private static final String PROJECT_ACCESSION = "PXTEST1"; private static final String ASSAY_ACCESSION = "1234"; private static final String PROTEIN_ACCESSION = "P12345"; @Before public void setUp() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); Psm psm = new Psm(); psm.setId(ID); psm.setProteinAccession(PROTEIN_ACCESSION); psm.setProjectAccession(PROJECT_ACCESSION); psm.setAssayAccession(ASSAY_ACCESSION); List<Psm> list = new ArrayList<>(1); list.add(psm); Page<Psm> page = new PageImpl<>(list); PageRequest pageRequest = new PageRequest(0, 10, Sort.Direction.ASC, "peptide_sequence"); when( psmSearchService.findByProjectAccession(PROJECT_ACCESSION, pageRequest) ).thenReturn(page); when( psmSearchService.findByAssayAccession(ASSAY_ACCESSION, pageRequest) ).thenReturn(page); pageRequest = new PageRequest(0, 2, Sort.Direction.ASC, "peptide_sequence"); when( psmSearchService.findByProjectAccession(PROJECT_ACCESSION, pageRequest) ).thenReturn(page); when( psmSearchService.findByAssayAccession(ASSAY_ACCESSION, pageRequest) ).thenReturn(page); mongoPsmIndexService.deleteAll(); MongoPsm mongoPsm = new MongoPsm(); mongoPsm.setId(ID); mongoPsm.setProteinAccession(PROTEIN_ACCESSION); mongoPsm.setProjectAccession(PROJECT_ACCESSION); mongoPsm.setAssayAccession(ASSAY_ACCESSION); mongoPsmIndexService.save(mongoPsm); } @Test // /peptide/list/project/{projectAccession} public void getPsmByProjectAccession() throws Exception { // test default use case mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); // test with custom paging configuration mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION + "?show=2&page=0")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); } @Test // /peptide/list/project/{projectAccession} public void getPsmByProjectAccessionMaxPageSizeExpecetion() throws Exception { // test with custom paging configuration mockMvc.perform(get("/peptide/list/project/" + PROJECT_ACCESSION + "?show=" + (WsUtils.MAX_PAGE_SIZE + 1) + "&page=0")) .andExpect(status().isForbidden()); } @Test // /peptide/list/assay/{assayAccession} public void getPsmByAssayAccession() throws Exception { // test default use case mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); // test with custom paging configuration mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION + "?show=2&page=0")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(content().string(containsString(PROJECT_ACCESSION))) .andExpect(content().string(containsString(ASSAY_ACCESSION))) .andExpect(content().string(containsString(PROTEIN_ACCESSION))); } @Test // /peptide/list/assay/{assayAccession} public void getPsmByAssaytAccessionMaxPageSizeException() throws Exception { // test with custom paging configuration mockMvc.perform(get("/peptide/list/assay/" + ASSAY_ACCESSION + "?show="+ (WsUtils.MAX_PAGE_SIZE + 1)+"&page=0")) .andExpect(status().isForbidden()); } }
PSM mockito unit tests still broken.
src/test/java/uk/ac/ebi/pride/archive/web/service/controller/psm/PsmControllerFunctionalTest.java
PSM mockito unit tests still broken.
Java
apache-2.0
a2e1a5281d19260317682ff357f9bb0e32b387b8
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.structuralsearch.plugin.ui; import com.intellij.codeInsight.highlighting.HighlightHandlerBase; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.codeInsight.template.TemplateBuilder; import com.intellij.codeInsight.template.impl.TemplateEditorUtil; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.find.FindBundle; import com.intellij.find.FindInProjectSettings; import com.intellij.find.FindSettings; import com.intellij.icons.AllIcons; import com.intellij.ide.AppLifecycleListener; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.DynamicPluginListener; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.Language; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationGroupManager; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.CheckboxAction; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.EditorFontType; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.*; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.*; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler; import com.intellij.structuralsearch.impl.matcher.predicates.ScriptSupport; import com.intellij.structuralsearch.inspection.StructuralSearchProfileActionProvider; import com.intellij.structuralsearch.plugin.StructuralSearchPlugin; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.replace.impl.Replacer; import com.intellij.structuralsearch.plugin.replace.ui.ReplaceCommand; import com.intellij.structuralsearch.plugin.replace.ui.ReplaceConfiguration; import com.intellij.structuralsearch.plugin.ui.filters.FilterPanel; import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink; import com.intellij.ui.ComponentUtil; import com.intellij.ui.EditorTextField; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.OnePixelSplitter; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; import com.intellij.util.SmartList; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.textCompletion.TextCompletionUtil; import com.intellij.util.ui.TextTransferable; import org.jdom.JDOMException; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import static com.intellij.openapi.util.text.StringUtil.isEmpty; import static com.intellij.openapi.util.text.StringUtil.trimEnd; /** * This dialog is used in two ways: * 1. a non-modal search dialog, showing a scope panel * 2. a modal edit dialog for Structural Search inspection patterns * * @author Bas Leijdekkers */ public class StructuralSearchDialog extends DialogWrapper implements DocumentListener { @NonNls private static final String SEARCH_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralSearchDialog"; @NonNls private static final String REPLACE_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralReplaceDialog"; @NonNls private static final String RECURSIVE_STATE = "structural.search.recursive"; @NonNls private static final String SHORTEN_FQN_STATE = "structural.search.shorten.fqn"; @NonNls private static final String REFORMAT_STATE = "structural.search.reformat"; @NonNls private static final String USE_STATIC_IMPORT_STATE = "structural.search.use.static.import"; @NonNls private static final String FILTERS_VISIBLE_STATE = "structural.search.filters.visible"; public static final Key<StructuralSearchDialog> STRUCTURAL_SEARCH_DIALOG = Key.create("STRUCTURAL_SEARCH_DIALOG"); public static final Key<String> STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID = Key.create("STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID"); public static final Key<Runnable> STRUCTURAL_SEARCH_ERROR_CALLBACK = Key.create("STRUCTURAL_SEARCH_ERROR_CALLBACK"); private static final Key<Configuration> STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION = Key.create("STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION"); public static final Key<Boolean> TEST_STRUCTURAL_SEARCH_DIALOG = Key.create("TEST_STRUCTURAL_SEARCH_DIALOG"); @NotNull private final SearchContext mySearchContext; private Editor myEditor; private boolean myReplace; @NotNull private Configuration myConfiguration; @NotNull @NonNls private LanguageFileType myFileType = StructuralSearchUtil.getDefaultFileType(); private Language myDialect; private PatternContext myPatternContext; private final List<RangeHighlighter> myRangeHighlighters = new SmartList<>(); private final DocumentListener myRestartHighlightingListener = new DocumentListener() { final Runnable runnable = () -> ReadAction.nonBlocking(() -> addMatchHighlights()) .withDocumentsCommitted(getProject()) .expireWith(getDisposable()) .coalesceBy(this) .submit(AppExecutorUtil.getAppExecutorService()); @Override public void documentChanged(@NotNull DocumentEvent event) { if (myAlarm.isDisposed()) return; myAlarm.cancelRequest(runnable); myAlarm.addRequest(runnable, 100); } }; // ui management private final Alarm myAlarm; private boolean myUseLastConfiguration; private final boolean myEditConfigOnly; private boolean myDoingOkAction; // components private final FileTypeChooser myFileTypeChooser = new FileTypeChooser(); private ActionToolbarImpl myOptionsToolbar; private EditorTextField mySearchCriteriaEdit; private EditorTextField myReplaceCriteriaEdit; private OnePixelSplitter mySearchEditorPanel; private FilterPanel myFilterPanel; private LinkComboBox myTargetComboBox; private ScopePanel myScopePanel; private JCheckBox myOpenInNewTab; private JComponent myReplacePanel; private SwitchAction mySwitchAction; public StructuralSearchDialog(@NotNull SearchContext searchContext, boolean replace) { this(searchContext, replace, false); } public StructuralSearchDialog(@NotNull SearchContext searchContext, boolean replace, boolean editConfigOnly) { super(searchContext.getProject(), true); if (!editConfigOnly) { setModal(false); setOKButtonText(FindBundle.message("find.dialog.find.button")); } myReplace = replace; myEditConfigOnly = editConfigOnly; mySearchContext = searchContext; myEditor = searchContext.getEditor(); addRestartHighlightingListenerToCurrentEditor(); final FileEditorManagerListener listener = new FileEditorManagerListener() { FileEditor myNewEditor; final Runnable runnable = () -> { removeRestartHighlightingListenerFromCurrentEditor(); removeMatchHighlights(); if (myNewEditor instanceof TextEditor) { myEditor = ((TextEditor)myNewEditor).getEditor(); addMatchHighlights(); addRestartHighlightingListenerToCurrentEditor(); } else { myEditor = null; } }; @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (myAlarm.isDisposed()) return; myAlarm.cancelRequest(runnable); myNewEditor = event.getNewEditor(); myAlarm.addRequest(runnable, 100); } }; final MessageBusConnection connection = getProject().getMessageBus().connect(getDisposable()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, listener); connection.subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() { @Override public void beforePluginUnload(@NotNull IdeaPluginDescriptor pluginDescriptor, boolean isUpdate) { close(CANCEL_EXIT_CODE); } }); connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() { @Override public void appClosing() { close(CANCEL_EXIT_CODE); } }); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { if (project == getProject()) { close(CANCEL_EXIT_CODE); } } }); myConfiguration = createConfiguration(null); setTitle(getDefaultTitle()); init(); myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable); } private void addRestartHighlightingListenerToCurrentEditor() { if (myEditor != null) { myEditor.getDocument().addDocumentListener(myRestartHighlightingListener); } } private void removeRestartHighlightingListenerFromCurrentEditor() { if (myEditor != null) { myEditor.getDocument().removeDocumentListener(myRestartHighlightingListener); } } public void setUseLastConfiguration(boolean useLastConfiguration) { myUseLastConfiguration = useLastConfiguration; } private EditorTextField createEditor(boolean replace) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; final Document document = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, "", profile); document.addDocumentListener(this, myDisposable); document.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, (myPatternContext == null) ? "" : myPatternContext.getId()); final EditorTextField textField = new MyEditorTextField(document, replace); final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); textField.setFont(scheme.getFont(EditorFontType.PLAIN)); textField.setPreferredSize(new Dimension(550, 150)); textField.setMinimumSize(new Dimension(200, 50)); return textField; } @Override public void documentChanged(@NotNull final DocumentEvent event) { initiateValidation(); } private void initiateValidation() { if (myAlarm.isDisposed()) return; myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { final boolean success = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> { try { final CompiledPattern compiledPattern = compilePattern(); checkReplacementPattern(); final JRootPane component = getRootPane(); if (component == null) { return; } initializeFilterPanel(); if (compiledPattern != null) { addMatchHighlights(); } ApplicationManager.getApplication().invokeLater(() -> { setSearchTargets(myConfiguration.getMatchOptions()); getOKAction().setEnabled(compiledPattern != null); }, ModalityState.stateForComponent(component)); } catch (ProcessCanceledException e) { throw e; } catch (RuntimeException e) { Logger.getInstance(StructuralSearchDialog.class).error(e); } }); if (!success) { initiateValidation(); } }, 100); } private void initializeFilterPanel() { final MatchOptions matchOptions = getConfiguration().getMatchOptions(); final CompiledPattern compiledPattern = PatternCompiler.compilePattern(getProject(), matchOptions, false, false); if (compiledPattern == null) return; ApplicationManager.getApplication().invokeLater(() -> { SubstitutionShortInfoHandler.updateEditorInlays(mySearchCriteriaEdit.getEditor()); if (myReplace) SubstitutionShortInfoHandler.updateEditorInlays(myReplaceCriteriaEdit.getEditor()); myFilterPanel.setCompiledPattern(compiledPattern); if (myFilterPanel.getVariable() == null) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration)); } }, ModalityState.stateForComponent(myFilterPanel.getComponent())); } @NotNull private Configuration createConfiguration(Configuration template) { if (myReplace) { return (template == null) ? new ReplaceConfiguration(getUserDefined(), getUserDefined()) : new ReplaceConfiguration(template); } return (template == null) ? new SearchConfiguration(getUserDefined(), getUserDefined()) : new SearchConfiguration(template); } private void setTextFromContext() { final Editor editor = myEditor; if (editor != null) { final SelectionModel selectionModel = editor.getSelectionModel(); final String selectedText = selectionModel.getSelectedText(); if (selectedText != null) { if (loadConfiguration(selectedText)) { return; } final String text = selectedText.trim(); setTextForEditor(text.trim(), mySearchCriteriaEdit); if (myReplace) { setTextForEditor(text, myReplaceCriteriaEdit); } myScopePanel.setScopesFromContext(); ApplicationManager.getApplication().invokeLater(() -> startTemplate()); return; } } final Configuration previousConfiguration = getProject().getUserData(STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION); if (previousConfiguration != null) { loadConfiguration(previousConfiguration); } else { final Configuration configuration = ConfigurationManager.getInstance(getProject()).getMostRecentConfiguration(); if (configuration != null) { loadConfiguration(configuration); } } } private void setTextForEditor(String text, EditorTextField editor) { editor.setText(text); editor.selectAll(); final Project project = getProject(); final Document document = editor.getDocument(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); documentManager.commitDocument(document); final PsiFile file = documentManager.getPsiFile(document); if (file == null) return; WriteCommandAction.runWriteCommandAction(project, SSRBundle.message("command.name.adjust.line.indent"), "Structural Search", () -> CodeStyleManager.getInstance(project) .adjustLineIndent(file, new TextRange(0, document.getTextLength())), file); } private void startSearching() { if (myReplace) { new ReplaceCommand(myConfiguration, mySearchContext).startSearching(); } else { new SearchCommand(myConfiguration, mySearchContext).startSearching(); } } @NotNull @Nls @NlsContexts.DialogTitle private String getDefaultTitle() { return myReplace ? SSRBundle.message("structural.replace.title") : SSRBundle.message("structural.search.title"); } @Override protected JComponent createCenterPanel() { mySearchEditorPanel = new OnePixelSplitter(false, 1.0f); mySearchEditorPanel.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_SECOND_MIN_SIZE); mySearchCriteriaEdit = createEditor(false); mySearchEditorPanel.setFirstComponent(mySearchCriteriaEdit); final JPanel wrapper = new JPanel(new BorderLayout()); final Color color = UIManager.getColor("Borders.ContrastBorderColor"); wrapper.setBorder(IdeBorderFactory.createBorder(color)); wrapper.add(mySearchEditorPanel, BorderLayout.CENTER); myReplacePanel = createReplacePanel(); myReplacePanel.setVisible(myReplace); myScopePanel = new ScopePanel(getProject(), myDisposable); if (!myEditConfigOnly) { myScopePanel.setRecentDirectories(FindInProjectSettings.getInstance(getProject()).getRecentDirectories()); myScopePanel.setScopeConsumer(scope -> initiateValidation()); } else { myScopePanel.setVisible(false); } myFilterPanel = new FilterPanel(getProject(), myFileType, getDisposable()); myFilterPanel.setConstraintChangedCallback(() -> initiateValidation()); myFilterPanel.getComponent().setMinimumSize(new Dimension(300, 50)); mySearchEditorPanel.setSecondComponent(myFilterPanel.getComponent()); final JLabel searchTargetLabel = new JLabel(SSRBundle.message("search.target.label")); myTargetComboBox = new LinkComboBox(SSRBundle.message("complete.match.variable.name")); myTargetComboBox.setItemConsumer(item -> { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); for (String name : matchOptions.getVariableConstraintNames()) { matchOptions.getVariableConstraint(name).setPartOfSearchResults(name.equals(item)); } initiateValidation(); }); final JPanel centerPanel = new JPanel(null); final GroupLayout layout = new GroupLayout(centerPanel); centerPanel.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup() .addComponent(wrapper) .addComponent(myReplacePanel) .addComponent(myScopePanel) .addGroup(layout.createSequentialGroup() .addComponent(searchTargetLabel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 5, 5) .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) ); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(wrapper) .addGap(8) .addComponent(myReplacePanel) .addComponent(myScopePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(16) .addGroup(layout.createParallelGroup() .addComponent(searchTargetLabel) .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) ); return centerPanel; } private JComponent createReplacePanel() { final ToolbarLabel replacementTemplateLabel = new ToolbarLabel(SSRBundle.message("replacement.template.label")); final DefaultActionGroup labelGroup = new DefaultActionGroup(new Spacer(), replacementTemplateLabel); final ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar labelToolbar = actionManager.createActionToolbar("StructuralSearchDialog", labelGroup, true); final CheckboxAction shortenFqn = new CheckboxAction(SSRBundle.message("shorten.fully.qualified.names.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); e.getPresentation().setEnabledAndVisible(profile != null && profile.supportsShortenFQNames()); } @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToShortenFQN(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToShortenFQN(state); } }; final CheckboxAction staticImport = new CheckboxAction(SSRBundle.message("use.static.import.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); e.getPresentation().setEnabledAndVisible(profile != null && profile.supportsUseStaticImports()); } @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToUseStaticImport(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToUseStaticImport(state); } }; final CheckboxAction reformat = new CheckboxAction(SSRBundle.message("reformat.checkbox")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToReformatAccordingToStyle(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToReformatAccordingToStyle(state); } }; final DefaultActionGroup replacementActionGroup = new DefaultActionGroup(shortenFqn, staticImport, reformat); final ActionToolbar replacementToolbar = actionManager.createActionToolbar("StructuralSearchDialog", replacementActionGroup, true); final OnePixelSplitter replaceEditorPanel = new OnePixelSplitter(false, 1.0f); replaceEditorPanel.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_SECOND_MIN_SIZE); myReplaceCriteriaEdit = createEditor(true); replaceEditorPanel.setFirstComponent(myReplaceCriteriaEdit); final JPanel wrapper = new JPanel(new BorderLayout()); final Color color = UIManager.getColor("Borders.ContrastBorderColor"); wrapper.setBorder(IdeBorderFactory.createBorder(color)); wrapper.add(replaceEditorPanel, BorderLayout.CENTER); final JPanel replacePanel = new JPanel(null); final GroupLayout layout = new GroupLayout(replacePanel); replacePanel.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent(labelToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE) .addComponent(replacementToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) .addComponent(wrapper) ); layout.setVerticalGroup( layout.createSequentialGroup(). addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(labelToolbar.getComponent()) .addComponent(replacementToolbar.getComponent()) ) .addGap(4) .addComponent(wrapper) ); return replacePanel; } @Nullable @Override protected JComponent createNorthPanel() { final DumbAwareAction historyAction = new DumbAwareAction(SSRBundle.messagePointer("history.button"), SSRBundle.messagePointer("history.button.description"), AllIcons.Actions.SearchWithHistory) { @Override public void actionPerformed(@NotNull AnActionEvent e) { final Object source = e.getInputEvent().getSource(); if (!(source instanceof Component)) return; JBPopupFactory.getInstance() .createPopupChooserBuilder(ConfigurationManager.getInstance(getProject()).getHistoryConfigurations()) .setRenderer(new ConfigurationCellRenderer()) .setItemChosenCallback(c -> { if (c instanceof ReplaceConfiguration && !myReplace) { mySwitchAction.actionPerformed( AnActionEvent.createFromAnAction(mySwitchAction, null, ActionPlaces.UNKNOWN, DataContext.EMPTY_CONTEXT)); } loadConfiguration(c); }) .setSelectionMode(ListSelectionModel.SINGLE_SELECTION) .createPopup() .showUnderneathOf((Component)source); } }; final ToolbarLabel searchTemplateLabel = new ToolbarLabel(SSRBundle.message("search.template")); final DefaultActionGroup historyActionGroup = new DefaultActionGroup(historyAction, searchTemplateLabel); final ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar historyToolbar = actionManager.createActionToolbar("StructuralSearchDialog", historyActionGroup, true); final CheckboxAction injected = new CheckboxAction(SSRBundle.message("search.in.injected.checkbox")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration.getMatchOptions().isSearchInjectedCode(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getMatchOptions().setSearchInjectedCode(state); initiateValidation(); } }; final CheckboxAction recursive = new CheckboxAction(SSRBundle.message("recursive.matching.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); e.getPresentation().setEnabledAndVisible(!myReplace); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration instanceof SearchConfiguration && myConfiguration.getMatchOptions().isRecursiveSearch(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { if (myConfiguration instanceof SearchConfiguration) { myConfiguration.getMatchOptions().setRecursiveSearch(state); initiateValidation(); } } }; final CheckboxAction matchCase = new CheckboxAction(FindBundle.message("find.popup.case.sensitive")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration.getMatchOptions().isCaseSensitiveMatch(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getMatchOptions().setCaseSensitiveMatch(state); initiateValidation(); } }; myFileType = UIUtil.detectFileType(mySearchContext); myDialect = myFileType.getLanguage(); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); if (profile != null) { final List<PatternContext> contexts = profile.getPatternContexts(); if (!contexts.isEmpty()) { myPatternContext = contexts.get(0); } } myFileTypeChooser.setSelectedItem(myFileType, myDialect, myPatternContext); myFileTypeChooser.setFileTypeInfoConsumer(info -> { myOptionsToolbar.updateActionsImmediately(); myFileType = info.getFileType(); myFilterPanel.setFileType(myFileType); myDialect = info.getDialect(); myPatternContext = info.getContext(); final String contextId = (myPatternContext == null) ? "" : myPatternContext.getId(); final StructuralSearchProfile profile1 = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile1 != null; final Document searchDocument = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, mySearchCriteriaEdit.getText(), profile1); searchDocument.addDocumentListener(this, myDisposable); mySearchCriteriaEdit.setNewDocumentAndFileType(myFileType, searchDocument); searchDocument.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, contextId); final Document replaceDocument = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, myReplaceCriteriaEdit.getText(), profile1); replaceDocument.addDocumentListener(this, myDisposable); myReplaceCriteriaEdit.setNewDocumentAndFileType(myFileType, replaceDocument); replaceDocument.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, contextId); initiateValidation(); }); final DefaultActionGroup templateActionGroup = new DefaultActionGroup(); templateActionGroup.add( new DumbAwareAction(SSRBundle.message("save.template.text.button")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { ConfigurationManager.getInstance(getProject()).showSaveTemplateAsDialog(getConfiguration()); } }); templateActionGroup.add( new DumbAwareAction(SSRBundle.message("save.inspection.action.text")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { StructuralSearchProfileActionProvider.createNewInspection(getConfiguration(), getProject()); } }); templateActionGroup.addSeparator(); mySwitchAction = new SwitchAction(); templateActionGroup.addAll( new CopyConfigurationAction(), new PasteConfigurationAction(), new DumbAwareAction(SSRBundle.message("copy.existing.template.button")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { final SelectTemplateDialog dialog = new SelectTemplateDialog(getProject(), false, myReplace); if (!dialog.showAndGet()) { return; } final Configuration[] configurations = dialog.getSelectedConfigurations(); if (configurations.length == 1) { loadConfiguration(configurations[0]); } } }, Separator.getInstance(), mySwitchAction ); templateActionGroup.setPopup(true); final Presentation presentation = templateActionGroup.getTemplatePresentation(); presentation.setIcon(AllIcons.General.Settings); presentation.setText(SSRBundle.message("tools.button")); final Icon filterModifiedIcon = ExecutionUtil.getLiveIndicator(AllIcons.General.Filter); final AnAction filterAction = new DumbAwareToggleAction(SSRBundle.message("filter.button"), SSRBundle.message("filter.button.description"), filterModifiedIcon) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setIcon(myFilterPanel.hasVisibleFilter() ? filterModifiedIcon : AllIcons.General.Filter); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return isFilterPanelVisible(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { setFilterPanelVisible(state); } }; final DefaultActionGroup optionsActionGroup = new DefaultActionGroup(injected, recursive, matchCase, myFileTypeChooser, filterAction, templateActionGroup); myOptionsToolbar = (ActionToolbarImpl)actionManager.createActionToolbar("StructuralSearchDialog", optionsActionGroup, true); myOptionsToolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY); myOptionsToolbar.setForceMinimumSize(true); final JPanel northPanel = new JPanel(null); final GroupLayout layout = new GroupLayout(northPanel); northPanel.setLayout(layout); layout.setHonorsVisibility(true); layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(historyToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE) .addComponent(myOptionsToolbar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(historyToolbar.getComponent()) .addComponent(myOptionsToolbar) ); return northPanel; } @Nullable @Override protected JPanel createSouthAdditionalPanel() { if (myEditConfigOnly) return null; final JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 0)); myOpenInNewTab = new JCheckBox(SSRBundle.message("open.in.new.tab.checkbox")); myOpenInNewTab.setSelected(FindSettings.getInstance().isShowResultsInSeparateView()); panel.add(myOpenInNewTab, BorderLayout.EAST); return panel; } private Project getProject() { return mySearchContext.getProject(); } @Nullable @Override public Point getInitialLocation() { // handle dimension service manually to store dimensions correctly when switching between search/replace in the same dialog final DimensionService dimensionService = DimensionService.getInstance(); final Dimension size = dimensionService.getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY, getProject()); if (size != null) { setSize(size.width, myEditConfigOnly ? size.height - myScopePanel.getPreferredSize().height : size.height); } else { pack(); // set width from replace if search not available and vice versa final Dimension otherSize = dimensionService.getSize(myReplace ? SEARCH_DIMENSION_SERVICE_KEY : REPLACE_DIMENSION_SERVICE_KEY, getProject()); if (otherSize != null) { setSize(otherSize.width, getSize().height); } } if (myEditConfigOnly) return super.getInitialLocation(); final Point location = dimensionService.getLocation(SEARCH_DIMENSION_SERVICE_KEY, getProject()); return (location == null) ? super.getInitialLocation() : location; } @Override public void show() { if (!myUseLastConfiguration) { setTextFromContext(); } final PropertiesComponent properties = PropertiesComponent.getInstance(); setFilterPanelVisible(properties.getBoolean(FILTERS_VISIBLE_STATE, true)); super.show(); StructuralSearchPlugin.getInstance(getProject()).setDialog(this); } private void startTemplate() { if (!Registry.is("ssr.template.from.selection.builder")) { return; } final Document document = mySearchCriteriaEdit.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document); assert psiFile != null; final TemplateBuilder builder = new StructuralSearchTemplateBuilder(psiFile).buildTemplate(); WriteCommandAction .runWriteCommandAction(getProject(), SSRBundle.message("command.name.live.search.template.builder"), "Structural Search", () -> builder.run(Objects.requireNonNull(mySearchCriteriaEdit.getEditor()), true)); } @Override public JComponent getPreferredFocusedComponent() { return mySearchCriteriaEdit; } @Override public void doCancelAction() { super.doCancelAction(); removeMatchHighlights(); } @Override protected void doOKAction() { myDoingOkAction = true; removeMatchHighlights(); final CompiledPattern compiledPattern = compilePattern(); myDoingOkAction = false; if (compiledPattern == null) return; myAlarm.cancelAllRequests(); myConfiguration.removeUnusedVariables(); super.doOKAction(); if (myEditConfigOnly) return; final SearchScope scope = myScopePanel.getScope(); if (scope instanceof GlobalSearchScopesCore.DirectoryScope) { final GlobalSearchScopesCore.DirectoryScope directoryScope = (GlobalSearchScopesCore.DirectoryScope)scope; FindInProjectSettings.getInstance(getProject()).addDirectory(directoryScope.getDirectory().getPresentableUrl()); } final FindSettings findSettings = FindSettings.getInstance(); findSettings.setShowResultsInSeparateView(myOpenInNewTab.isSelected()); try { ConfigurationManager.getInstance(getProject()).addHistoryConfiguration(myConfiguration); startSearching(); } catch (MalformedPatternException ex) { reportMessage(SSRBundle.message("this.pattern.is.malformed.message", ex.getMessage()), true, mySearchCriteriaEdit); } } public Configuration getConfiguration() { saveConfiguration(); return myConfiguration.copy(); } @Nullable private CompiledPattern compilePattern() { final MatchOptions matchOptions = getConfiguration().getMatchOptions(); final Project project = getProject(); try { final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions, true, !myEditConfigOnly); reportMessage(null, false, mySearchCriteriaEdit); return compiledPattern; } catch (MalformedPatternException e) { removeMatchHighlights(); final String message = isEmpty(matchOptions.getSearchPattern()) ? null : SSRBundle.message("this.pattern.is.malformed.message", (e.getMessage() != null) ? e.getMessage() : ""); if (!e.isErrorElement || !Registry.is("ssr.in.editor.problem.highlighting")) { reportMessage(message, true, mySearchCriteriaEdit); } return null; } catch (UnsupportedPatternException e) { removeMatchHighlights(); reportMessage(SSRBundle.message("this.pattern.is.unsupported.message", e.getMessage()), true, mySearchCriteriaEdit); return null; } catch (NoMatchFoundException e) { removeMatchHighlights(); reportMessage(e.getMessage(), false, myScopePanel); return null; } } private void checkReplacementPattern() { if (!myReplace) { return; } try { Replacer.checkReplacementPattern(getProject(), myConfiguration.getReplaceOptions()); reportMessage(null, false, myReplaceCriteriaEdit); } catch (UnsupportedPatternException ex) { reportMessage(SSRBundle.message("unsupported.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit); } catch (MalformedPatternException ex) { if (!ex.isErrorElement || !Registry.is("ssr.in.editor.problem.highlighting")) { reportMessage(SSRBundle.message("malformed.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit); } } } private void removeMatchHighlights() { if (myEditConfigOnly || myRangeHighlighters.isEmpty()) { return; } // retrieval of editor needs to be outside of invokeLater(), otherwise the editor might have already changed. final Editor editor = myEditor; if (editor == null) { return; } ApplicationManager.getApplication().invokeLater(() -> { final Project project = getProject(); if (project.isDisposed()) { return; } final HighlightManager highlightManager = HighlightManager.getInstance(project); for (RangeHighlighter highlighter : myRangeHighlighters) { highlightManager.removeSegmentHighlighter(editor, highlighter); } WindowManager.getInstance().getStatusBar(project).setInfo(""); myRangeHighlighters.clear(); }); } private void addMatchHighlights() { if (myEditConfigOnly || DumbService.isDumb(getProject())) { // Search hits in the current editor are not shown when dumb. return; } final Project project = getProject(); final Editor editor = myEditor; if (editor == null) { return; } final Document document = editor.getDocument(); final PsiFile file = ReadAction.compute(() -> PsiDocumentManager.getInstance(project).getPsiFile(document)); if (file == null) { return; } final MatchOptions matchOptions = getConfiguration().getMatchOptions(); matchOptions.setScope(new LocalSearchScope(file, PredefinedSearchScopeProviderImpl.getCurrentFileScopeName())); final CollectingMatchResultSink sink = new CollectingMatchResultSink(); try { new Matcher(project, matchOptions).findMatches(sink); final List<MatchResult> matches = sink.getMatches(); removeMatchHighlights(); addMatchHighlights(matches, editor, file, SSRBundle.message("status.bar.text.results.found.in.current.file", matches.size())); } catch (StructuralSearchException e) { reportMessage(e.getMessage().replace(ScriptSupport.UUID, ""), true, mySearchCriteriaEdit); removeMatchHighlights(); } } private void addMatchHighlights(@NotNull List<? extends MatchResult> matchResults, @NotNull Editor editor, @NotNull PsiFile file, @NlsContexts.StatusBarText @Nullable String statusBarText) { ApplicationManager.getApplication().invokeLater(() -> { final Project project = getProject(); if (project.isDisposed()) { return; } if (!matchResults.isEmpty()) { for (MatchResult result : matchResults) { final PsiElement match = result.getMatch(); if (match == null || match.getContainingFile() != file) continue; int start = -1; int end = -1; if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) { for (MatchResult child : result.getChildren()) { final TextRange range = child.getMatch().getTextRange(); final int startOffset = range.getStartOffset(); if (start == -1 || start > startOffset) { start = startOffset; } final int endOffset = range.getEndOffset(); if (end < endOffset) { end = endOffset; } } } else { final TextRange range = match.getTextRange(); start = range.getStartOffset(); end = range.getEndOffset(); } final HighlightManager highlightManager = HighlightManager.getInstance(project); highlightManager.addRangeHighlight(editor, start, end, EditorColors.SEARCH_RESULT_ATTRIBUTES, false, myRangeHighlighters); } HighlightHandlerBase.setupFindModel(project); } WindowManager.getInstance().getStatusBar(project).setInfo(statusBarText); }); } private Balloon myBalloon; private void reportMessage(@NlsContexts.PopupContent @Nullable String message, boolean error, @NotNull JComponent component) { ApplicationManager.getApplication().invokeLater(() -> { if (myBalloon != null) myBalloon.hide(); component.putClientProperty("JComponent.outline", (!error || message == null) ? null : "error"); component.repaint(); if (message == null) return; myBalloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, error ? MessageType.ERROR : MessageType.WARNING, null) .setHideOnFrameResize(false) .createBalloon(); if (component != myScopePanel) { myBalloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, component.getHeight())), Balloon.Position.below); } else { myBalloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, 0)), Balloon.Position.above); } myBalloon.showInCenterOf(component); Disposer.register(myDisposable, myBalloon); }, ModalityState.stateForComponent(component)); } private void securityCheck() { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); int scripts = 0; for (String name : matchOptions.getVariableConstraintNames()) { final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name); if (constraint.getScriptCodeConstraint().length() > 2) scripts++; } if (myConfiguration instanceof ReplaceConfiguration) { final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); for (ReplacementVariableDefinition variableDefinition : replaceOptions.getVariableDefinitions()) { if (variableDefinition.getScriptCodeConstraint().length() > 2) scripts++; } } if (scripts > 0) { final NotificationGroup notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup(UIUtil.SSR_NOTIFICATION_GROUP_ID); notificationGroup.createNotification(NotificationType.WARNING) .setTitle(SSRBundle.message("import.template.script.warning.title")) .setContent(SSRBundle.message("import.template.script.warning", ApplicationNamesInfo.getInstance().getFullProductName(), scripts)) .notify(mySearchContext.getProject()); } } public void showFilterPanel(String variableName) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration)); setFilterPanelVisible(true); myConfiguration.setCurrentVariableName(variableName); } private void setFilterPanelVisible(boolean visible) { if (visible) { if (myFilterPanel.getVariable() == null) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration)); } if (!isFilterPanelVisible()) { mySearchEditorPanel.setSecondComponent(myFilterPanel.getComponent()); } } else { if (isFilterPanelVisible()) { mySearchEditorPanel.setSecondComponent(null); myConfiguration.setCurrentVariableName(null); } } } private boolean isFilterPanelVisible() { return mySearchEditorPanel.getSecondComponent() != null; } private void setSearchTargets(MatchOptions matchOptions) { final List<String> names = new ArrayList<>(matchOptions.getUsedVariableNames()); Collections.sort(names); names.remove(Configuration.CONTEXT_VAR_NAME); names.add(SSRBundle.message("complete.match.variable.name")); myTargetComboBox.setItems(names); if (names.size() > 1) { myTargetComboBox.setEnabled(true); for (@NlsSafe String name : names) { final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name); if (constraint != null && constraint.isPartOfSearchResults()) { myTargetComboBox.setSelectedItem(name); return; } } myTargetComboBox.setSelectedItem(SSRBundle.message("complete.match.variable.name")); } else { myTargetComboBox.setEnabled(false); } } /** * @param text the text to try and load a configuration from * @return {@code true}, if some configuration was found, even if it was broken or corrupted {@code false} otherwise. */ private boolean loadConfiguration(String text) { if (text == null) { return false; } try { final Configuration configuration = ConfigurationUtil.fromXml(text); if (configuration == null) { return false; } if (configuration instanceof ReplaceConfiguration && !myReplace) { mySwitchAction.actionPerformed( AnActionEvent.createFromAnAction(mySwitchAction, null, ActionPlaces.UNKNOWN, DataContext.EMPTY_CONTEXT)); } loadConfiguration(configuration); securityCheck(); } catch (JDOMException e) { reportMessage(SSRBundle.message("import.template.script.corrupted") + '\n' + e.getMessage(), false, myOptionsToolbar); } return true; } public void loadConfiguration(Configuration configuration) { final Configuration newConfiguration = createConfiguration(configuration); if (myUseLastConfiguration) { newConfiguration.setUuid(myConfiguration.getUuid()); newConfiguration.setName(myConfiguration.getName()); newConfiguration.setDescription(myConfiguration.getDescription()); newConfiguration.setSuppressId(myConfiguration.getSuppressId()); newConfiguration.setProblemDescriptor(myConfiguration.getProblemDescriptor()); } myConfiguration = newConfiguration; final MatchOptions matchOptions = myConfiguration.getMatchOptions(); setSearchTargets(matchOptions); if (!myEditConfigOnly) { myScopePanel.setScopesFromContext(); final SearchScope scope = matchOptions.getScope(); if (scope != null) myScopePanel.setScope(scope); } myFileTypeChooser.setSelectedItem(matchOptions.getFileType(), matchOptions.getDialect(), matchOptions.getPatternContext()); final Editor searchEditor = mySearchCriteriaEdit.getEditor(); if (searchEditor != null) { searchEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } UIUtil.setContent(mySearchCriteriaEdit, matchOptions.getSearchPattern()); final PropertiesComponent properties = PropertiesComponent.getInstance(); if (myReplace) { final Editor replaceEditor = myReplaceCriteriaEdit.getEditor(); if (replaceEditor != null) { replaceEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } if (configuration instanceof ReplaceConfiguration) { final ReplaceOptions replaceOptions = configuration.getReplaceOptions(); UIUtil.setContent(myReplaceCriteriaEdit, replaceOptions.getReplacement()); } else { UIUtil.setContent(myReplaceCriteriaEdit, matchOptions.getSearchPattern()); } } else { if (configuration instanceof ReplaceConfiguration) { matchOptions.setRecursiveSearch(properties.getBoolean(RECURSIVE_STATE)); } } } private void saveConfiguration() { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); if (!myEditConfigOnly) { final SearchScope scope = myScopePanel.getScope(); final boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(scope.getDisplayName()); // We need to reset search within hierarchy scope during online validation since the scope works with user participation matchOptions.setScope(searchWithinHierarchy && !myDoingOkAction ? GlobalSearchScope.projectScope(getProject()) : scope); } else { matchOptions.setScope(null); } matchOptions.setFileType(myFileType); matchOptions.setDialect(myDialect); matchOptions.setPatternContext(myPatternContext); matchOptions.setSearchPattern(getPattern(mySearchCriteriaEdit)); final PropertiesComponent properties = PropertiesComponent.getInstance(); if (myReplace) { final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); replaceOptions.setReplacement(getPattern(myReplaceCriteriaEdit)); matchOptions.setRecursiveSearch(false); properties.setValue(SHORTEN_FQN_STATE, replaceOptions.isToShortenFQN()); properties.setValue(USE_STATIC_IMPORT_STATE, replaceOptions.isToUseStaticImport()); properties.setValue(REFORMAT_STATE, replaceOptions.isToReformatAccordingToStyle()); } else { properties.setValue(RECURSIVE_STATE, matchOptions.isRecursiveSearch()); } } private String getPattern(EditorTextField textField) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; final Document document = textField.getDocument(); final String pattern = ReadAction.compute(() -> { final PsiFile file = PsiDocumentManager.getInstance(getProject()).getPsiFile(document); assert file != null; return profile.getCodeFragmentText(file); }); return pattern.isEmpty() ? textField.getText() : pattern; } @Nullable @Override protected final String getDimensionServiceKey() { return null; } @Override public void dispose() { getProject().putUserData(STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION, myConfiguration); if (myReplace) storeDimensions(REPLACE_DIMENSION_SERVICE_KEY, SEARCH_DIMENSION_SERVICE_KEY); else storeDimensions(SEARCH_DIMENSION_SERVICE_KEY, REPLACE_DIMENSION_SERVICE_KEY); final PropertiesComponent properties = PropertiesComponent.getInstance(); properties.setValue(FILTERS_VISIBLE_STATE, isFilterPanelVisible(), true); StructuralSearchPlugin.getInstance(getProject()).setDialog(null); myAlarm.cancelAllRequests(); mySearchCriteriaEdit.removeNotify(); myReplaceCriteriaEdit.removeNotify(); removeRestartHighlightingListenerFromCurrentEditor(); super.dispose(); } private void storeDimensions(String key1, String key2) { if (myEditConfigOnly) return; // don't store dimensions when editing structural search inspection patterns // handle own dimension service to store dimensions correctly when switching between search/replace in the same dialog final Dimension size = getSize(); final DimensionService dimensionService = DimensionService.getInstance(); final Point location = getLocation(); if (location.x < 0) location.x = 0; if (location.y < 0) location.y = 0; dimensionService.setLocation(SEARCH_DIMENSION_SERVICE_KEY, location, getProject()); dimensionService.setSize(key1, size, getProject()); final Dimension otherSize = dimensionService.getSize(key2); if (otherSize != null && otherSize.width != size.width) { otherSize.width = size.width; dimensionService.setSize(key2, otherSize, getProject()); } } @Override protected String getHelpId() { return "find.structuredSearch"; } private static class ErrorBorder implements Border { private final Border myErrorBorder; ErrorBorder(Border errorBorder) { myErrorBorder = errorBorder; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { final EditorTextField editorTextField = ComponentUtil.getParentOfType((Class<? extends EditorTextField>)EditorTextField.class, c); if (editorTextField == null) { return; } final Object object = editorTextField.getClientProperty("JComponent.outline"); if ("error".equals(object) || "warning".equals(object)) { myErrorBorder.paintBorder(c, g, x, y, width, height); } } @Override public Insets getBorderInsets(Component c) { return myErrorBorder.getBorderInsets(c); } @Override public boolean isBorderOpaque() { return false; } } private class SwitchAction extends AnAction implements DumbAware { SwitchAction() { init(); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myReplace = !myReplace; setTitle(getDefaultTitle()); myReplacePanel.setVisible(myReplace); loadConfiguration(myConfiguration); final Dimension size = DimensionService.getInstance().getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY); if (size != null) { setSize(getSize().width, size.height); } else { pack(); } init(); } private void init() { getTemplatePresentation().setText(SSRBundle.messagePointer(myReplace ? "switch.to.search.action" : "switch.to.replace.action")); final ActionManager actionManager = ActionManager.getInstance(); final ShortcutSet searchShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralSearchAction").getShortcutSet(); final ShortcutSet replaceShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralReplaceAction").getShortcutSet(); final ShortcutSet shortcutSet = myReplace ? new CompositeShortcutSet(searchShortcutSet, replaceShortcutSet) : new CompositeShortcutSet(replaceShortcutSet, searchShortcutSet); registerCustomShortcutSet(shortcutSet, getRootPane()); } } private class CopyConfigurationAction extends AnAction implements DumbAware { CopyConfigurationAction() { super(SSRBundle.messagePointer("export.template.action")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { CopyPasteManager.getInstance().setContents(new TextTransferable(ConfigurationUtil.toXml(myConfiguration))); } } private class PasteConfigurationAction extends AnAction implements DumbAware { PasteConfigurationAction() { super(SSRBundle.messagePointer("import.template.action")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final String contents = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); if (!loadConfiguration(contents)) { reportMessage(SSRBundle.message("no.template.found.warning"), false, myOptionsToolbar); } } } public static @Nls(capitalization = Nls.Capitalization.Sentence) String getUserDefined() { return SSRBundle.message("new.template.defaultname"); } private class MyEditorTextField extends EditorTextField { private final boolean myReplace; MyEditorTextField(Document document, boolean replace) { super(document, StructuralSearchDialog.this.getProject(), StructuralSearchDialog.this.myFileType, false, false); myReplace = replace; } @Override protected EditorEx createEditor() { final EditorEx editor = super.createEditor(); editor.setHorizontalScrollbarVisible(true); editor.setVerticalScrollbarVisible(true); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; TemplateEditorUtil.setHighlighter(editor, UIUtil.getTemplateContextType(profile)); SubstitutionShortInfoHandler.install(editor, variableName -> { if (variableName.endsWith(ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX)) { //noinspection AssignmentToLambdaParameter variableName = trimEnd(variableName, ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX); assert myConfiguration instanceof ReplaceConfiguration; myFilterPanel.initFilters(UIUtil.getOrAddReplacementVariable(variableName, myConfiguration)); } else{ myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration)); } if (isFilterPanelVisible()) { myConfiguration.setCurrentVariableName(variableName); } }, myDisposable, myReplace); editor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); getDocument().putUserData(STRUCTURAL_SEARCH_ERROR_CALLBACK, () -> { putClientProperty("JComponent.outline", "error"); repaint(); getOKAction().setEnabled(false); if (!myReplace) removeMatchHighlights(); }); TextCompletionUtil.installCompletionHint(editor); editor.putUserData(STRUCTURAL_SEARCH_DIALOG, StructuralSearchDialog.this); editor.setEmbeddedIntoDialogWrapper(true); return editor; } @Override protected void updateBorder(@NotNull EditorEx editor) { setupBorder(editor); final JScrollPane scrollPane = editor.getScrollPane(); scrollPane.setBorder(new ErrorBorder(scrollPane.getBorder())); } } }
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.structuralsearch.plugin.ui; import com.intellij.codeInsight.highlighting.HighlightHandlerBase; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.codeInsight.template.TemplateBuilder; import com.intellij.codeInsight.template.impl.TemplateEditorUtil; import com.intellij.execution.runners.ExecutionUtil; import com.intellij.find.FindBundle; import com.intellij.find.FindInProjectSettings; import com.intellij.find.FindSettings; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.DynamicPluginListener; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.Language; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationGroupManager; import com.intellij.notification.NotificationType; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.CheckboxAction; import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.EditorFontType; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.ide.CopyPasteManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.util.ProgressIndicatorUtils; import com.intellij.openapi.project.*; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.Splitter; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.*; import com.intellij.structuralsearch.*; import com.intellij.structuralsearch.impl.matcher.CompiledPattern; import com.intellij.structuralsearch.impl.matcher.compiler.PatternCompiler; import com.intellij.structuralsearch.impl.matcher.predicates.ScriptSupport; import com.intellij.structuralsearch.inspection.StructuralSearchProfileActionProvider; import com.intellij.structuralsearch.plugin.StructuralSearchPlugin; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import com.intellij.structuralsearch.plugin.replace.impl.Replacer; import com.intellij.structuralsearch.plugin.replace.ui.ReplaceCommand; import com.intellij.structuralsearch.plugin.replace.ui.ReplaceConfiguration; import com.intellij.structuralsearch.plugin.ui.filters.FilterPanel; import com.intellij.structuralsearch.plugin.util.CollectingMatchResultSink; import com.intellij.ui.ComponentUtil; import com.intellij.ui.EditorTextField; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.OnePixelSplitter; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; import com.intellij.util.SmartList; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.textCompletion.TextCompletionUtil; import com.intellij.util.ui.TextTransferable; import org.jdom.JDOMException; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import static com.intellij.openapi.util.text.StringUtil.isEmpty; import static com.intellij.openapi.util.text.StringUtil.trimEnd; /** * This dialog is used in two ways: * 1. a non-modal search dialog, showing a scope panel * 2. a modal edit dialog for Structural Search inspection patterns * * @author Bas Leijdekkers */ public class StructuralSearchDialog extends DialogWrapper implements DocumentListener { @NonNls private static final String SEARCH_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralSearchDialog"; @NonNls private static final String REPLACE_DIMENSION_SERVICE_KEY = "#com.intellij.structuralsearch.plugin.ui.StructuralReplaceDialog"; @NonNls private static final String RECURSIVE_STATE = "structural.search.recursive"; @NonNls private static final String SHORTEN_FQN_STATE = "structural.search.shorten.fqn"; @NonNls private static final String REFORMAT_STATE = "structural.search.reformat"; @NonNls private static final String USE_STATIC_IMPORT_STATE = "structural.search.use.static.import"; @NonNls private static final String FILTERS_VISIBLE_STATE = "structural.search.filters.visible"; public static final Key<StructuralSearchDialog> STRUCTURAL_SEARCH_DIALOG = Key.create("STRUCTURAL_SEARCH_DIALOG"); public static final Key<String> STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID = Key.create("STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID"); public static final Key<Runnable> STRUCTURAL_SEARCH_ERROR_CALLBACK = Key.create("STRUCTURAL_SEARCH_ERROR_CALLBACK"); private static final Key<Configuration> STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION = Key.create("STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION"); public static final Key<Boolean> TEST_STRUCTURAL_SEARCH_DIALOG = Key.create("TEST_STRUCTURAL_SEARCH_DIALOG"); @NotNull private final SearchContext mySearchContext; private Editor myEditor; private boolean myReplace; @NotNull private Configuration myConfiguration; @NotNull @NonNls private LanguageFileType myFileType = StructuralSearchUtil.getDefaultFileType(); private Language myDialect; private PatternContext myPatternContext; private final List<RangeHighlighter> myRangeHighlighters = new SmartList<>(); private final DocumentListener myRestartHighlightingListener = new DocumentListener() { final Runnable runnable = () -> ReadAction.nonBlocking(() -> addMatchHighlights()) .withDocumentsCommitted(getProject()) .expireWith(getDisposable()) .coalesceBy(this) .submit(AppExecutorUtil.getAppExecutorService()); @Override public void documentChanged(@NotNull DocumentEvent event) { if (myAlarm.isDisposed()) return; myAlarm.cancelRequest(runnable); myAlarm.addRequest(runnable, 100); } }; // ui management private final Alarm myAlarm; private boolean myUseLastConfiguration; private final boolean myEditConfigOnly; private boolean myDoingOkAction; // components private final FileTypeChooser myFileTypeChooser = new FileTypeChooser(); private ActionToolbarImpl myOptionsToolbar; private EditorTextField mySearchCriteriaEdit; private EditorTextField myReplaceCriteriaEdit; private OnePixelSplitter mySearchEditorPanel; private FilterPanel myFilterPanel; private LinkComboBox myTargetComboBox; private ScopePanel myScopePanel; private JCheckBox myOpenInNewTab; private JComponent myReplacePanel; private SwitchAction mySwitchAction; public StructuralSearchDialog(@NotNull SearchContext searchContext, boolean replace) { this(searchContext, replace, false); } public StructuralSearchDialog(@NotNull SearchContext searchContext, boolean replace, boolean editConfigOnly) { super(searchContext.getProject(), true); if (!editConfigOnly) { setModal(false); setOKButtonText(FindBundle.message("find.dialog.find.button")); } myReplace = replace; myEditConfigOnly = editConfigOnly; mySearchContext = searchContext; myEditor = searchContext.getEditor(); addRestartHighlightingListenerToCurrentEditor(); final FileEditorManagerListener listener = new FileEditorManagerListener() { FileEditor myNewEditor; final Runnable runnable = () -> { removeRestartHighlightingListenerFromCurrentEditor(); removeMatchHighlights(); if (myNewEditor instanceof TextEditor) { myEditor = ((TextEditor)myNewEditor).getEditor(); addMatchHighlights(); addRestartHighlightingListenerToCurrentEditor(); } else { myEditor = null; } }; @Override public void selectionChanged(@NotNull FileEditorManagerEvent event) { if (myAlarm.isDisposed()) return; myAlarm.cancelRequest(runnable); myNewEditor = event.getNewEditor(); myAlarm.addRequest(runnable, 100); } }; final MessageBusConnection connection = getProject().getMessageBus().connect(getDisposable()); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, listener); connection.subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() { @Override public void beforePluginUnload(@NotNull IdeaPluginDescriptor pluginDescriptor, boolean isUpdate) { close(CANCEL_EXIT_CODE); } }); connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { close(CANCEL_EXIT_CODE); } }); myConfiguration = createConfiguration(null); setTitle(getDefaultTitle()); init(); myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myDisposable); } private void addRestartHighlightingListenerToCurrentEditor() { if (myEditor != null) { myEditor.getDocument().addDocumentListener(myRestartHighlightingListener); } } private void removeRestartHighlightingListenerFromCurrentEditor() { if (myEditor != null) { myEditor.getDocument().removeDocumentListener(myRestartHighlightingListener); } } public void setUseLastConfiguration(boolean useLastConfiguration) { myUseLastConfiguration = useLastConfiguration; } private EditorTextField createEditor(boolean replace) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; final Document document = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, "", profile); document.addDocumentListener(this, myDisposable); document.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, (myPatternContext == null) ? "" : myPatternContext.getId()); final EditorTextField textField = new MyEditorTextField(document, replace); final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); textField.setFont(scheme.getFont(EditorFontType.PLAIN)); textField.setPreferredSize(new Dimension(550, 150)); textField.setMinimumSize(new Dimension(200, 50)); return textField; } @Override public void documentChanged(@NotNull final DocumentEvent event) { initiateValidation(); } private void initiateValidation() { if (myAlarm.isDisposed()) return; myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> { final boolean success = ProgressIndicatorUtils.runInReadActionWithWriteActionPriority(() -> { try { final CompiledPattern compiledPattern = compilePattern(); checkReplacementPattern(); final JRootPane component = getRootPane(); if (component == null) { return; } initializeFilterPanel(); if (compiledPattern != null) { addMatchHighlights(); } ApplicationManager.getApplication().invokeLater(() -> { setSearchTargets(myConfiguration.getMatchOptions()); getOKAction().setEnabled(compiledPattern != null); }, ModalityState.stateForComponent(component)); } catch (ProcessCanceledException e) { throw e; } catch (RuntimeException e) { Logger.getInstance(StructuralSearchDialog.class).error(e); } }); if (!success) { initiateValidation(); } }, 100); } private void initializeFilterPanel() { final MatchOptions matchOptions = getConfiguration().getMatchOptions(); final CompiledPattern compiledPattern = PatternCompiler.compilePattern(getProject(), matchOptions, false, false); if (compiledPattern == null) return; ApplicationManager.getApplication().invokeLater(() -> { SubstitutionShortInfoHandler.updateEditorInlays(mySearchCriteriaEdit.getEditor()); if (myReplace) SubstitutionShortInfoHandler.updateEditorInlays(myReplaceCriteriaEdit.getEditor()); myFilterPanel.setCompiledPattern(compiledPattern); if (myFilterPanel.getVariable() == null) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration)); } }, ModalityState.stateForComponent(myFilterPanel.getComponent())); } @NotNull private Configuration createConfiguration(Configuration template) { if (myReplace) { return (template == null) ? new ReplaceConfiguration(getUserDefined(), getUserDefined()) : new ReplaceConfiguration(template); } return (template == null) ? new SearchConfiguration(getUserDefined(), getUserDefined()) : new SearchConfiguration(template); } private void setTextFromContext() { final Editor editor = myEditor; if (editor != null) { final SelectionModel selectionModel = editor.getSelectionModel(); final String selectedText = selectionModel.getSelectedText(); if (selectedText != null) { if (loadConfiguration(selectedText)) { return; } final String text = selectedText.trim(); setTextForEditor(text.trim(), mySearchCriteriaEdit); if (myReplace) { setTextForEditor(text, myReplaceCriteriaEdit); } myScopePanel.setScopesFromContext(); ApplicationManager.getApplication().invokeLater(() -> startTemplate()); return; } } final Configuration previousConfiguration = getProject().getUserData(STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION); if (previousConfiguration != null) { loadConfiguration(previousConfiguration); } else { final Configuration configuration = ConfigurationManager.getInstance(getProject()).getMostRecentConfiguration(); if (configuration != null) { loadConfiguration(configuration); } } } private void setTextForEditor(String text, EditorTextField editor) { editor.setText(text); editor.selectAll(); final Project project = getProject(); final Document document = editor.getDocument(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); documentManager.commitDocument(document); final PsiFile file = documentManager.getPsiFile(document); if (file == null) return; WriteCommandAction.runWriteCommandAction(project, SSRBundle.message("command.name.adjust.line.indent"), "Structural Search", () -> CodeStyleManager.getInstance(project) .adjustLineIndent(file, new TextRange(0, document.getTextLength())), file); } private void startSearching() { if (myReplace) { new ReplaceCommand(myConfiguration, mySearchContext).startSearching(); } else { new SearchCommand(myConfiguration, mySearchContext).startSearching(); } } @NotNull @Nls @NlsContexts.DialogTitle private String getDefaultTitle() { return myReplace ? SSRBundle.message("structural.replace.title") : SSRBundle.message("structural.search.title"); } @Override protected JComponent createCenterPanel() { mySearchEditorPanel = new OnePixelSplitter(false, 1.0f); mySearchEditorPanel.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_SECOND_MIN_SIZE); mySearchCriteriaEdit = createEditor(false); mySearchEditorPanel.setFirstComponent(mySearchCriteriaEdit); final JPanel wrapper = new JPanel(new BorderLayout()); final Color color = UIManager.getColor("Borders.ContrastBorderColor"); wrapper.setBorder(IdeBorderFactory.createBorder(color)); wrapper.add(mySearchEditorPanel, BorderLayout.CENTER); myReplacePanel = createReplacePanel(); myReplacePanel.setVisible(myReplace); myScopePanel = new ScopePanel(getProject(), myDisposable); if (!myEditConfigOnly) { myScopePanel.setRecentDirectories(FindInProjectSettings.getInstance(getProject()).getRecentDirectories()); myScopePanel.setScopeConsumer(scope -> initiateValidation()); } else { myScopePanel.setVisible(false); } myFilterPanel = new FilterPanel(getProject(), myFileType, getDisposable()); myFilterPanel.setConstraintChangedCallback(() -> initiateValidation()); myFilterPanel.getComponent().setMinimumSize(new Dimension(300, 50)); mySearchEditorPanel.setSecondComponent(myFilterPanel.getComponent()); final JLabel searchTargetLabel = new JLabel(SSRBundle.message("search.target.label")); myTargetComboBox = new LinkComboBox(SSRBundle.message("complete.match.variable.name")); myTargetComboBox.setItemConsumer(item -> { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); for (String name : matchOptions.getVariableConstraintNames()) { matchOptions.getVariableConstraint(name).setPartOfSearchResults(name.equals(item)); } initiateValidation(); }); final JPanel centerPanel = new JPanel(null); final GroupLayout layout = new GroupLayout(centerPanel); centerPanel.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup() .addComponent(wrapper) .addComponent(myReplacePanel) .addComponent(myScopePanel) .addGroup(layout.createSequentialGroup() .addComponent(searchTargetLabel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 5, 5) .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) ); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(wrapper) .addGap(8) .addComponent(myReplacePanel) .addComponent(myScopePanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(16) .addGroup(layout.createParallelGroup() .addComponent(searchTargetLabel) .addComponent(myTargetComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) ); return centerPanel; } private JComponent createReplacePanel() { final ToolbarLabel replacementTemplateLabel = new ToolbarLabel(SSRBundle.message("replacement.template.label")); final DefaultActionGroup labelGroup = new DefaultActionGroup(new Spacer(), replacementTemplateLabel); final ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar labelToolbar = actionManager.createActionToolbar("StructuralSearchDialog", labelGroup, true); final CheckboxAction shortenFqn = new CheckboxAction(SSRBundle.message("shorten.fully.qualified.names.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); e.getPresentation().setEnabledAndVisible(profile != null && profile.supportsShortenFQNames()); } @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToShortenFQN(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToShortenFQN(state); } }; final CheckboxAction staticImport = new CheckboxAction(SSRBundle.message("use.static.import.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); e.getPresentation().setEnabledAndVisible(profile != null && profile.supportsUseStaticImports()); } @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToUseStaticImport(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToUseStaticImport(state); } }; final CheckboxAction reformat = new CheckboxAction(SSRBundle.message("reformat.checkbox")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { if (!myReplace) return false; return myConfiguration.getReplaceOptions().isToReformatAccordingToStyle(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getReplaceOptions().setToReformatAccordingToStyle(state); } }; final DefaultActionGroup replacementActionGroup = new DefaultActionGroup(shortenFqn, staticImport, reformat); final ActionToolbar replacementToolbar = actionManager.createActionToolbar("StructuralSearchDialog", replacementActionGroup, true); final OnePixelSplitter replaceEditorPanel = new OnePixelSplitter(false, 1.0f); replaceEditorPanel.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_SECOND_MIN_SIZE); myReplaceCriteriaEdit = createEditor(true); replaceEditorPanel.setFirstComponent(myReplaceCriteriaEdit); final JPanel wrapper = new JPanel(new BorderLayout()); final Color color = UIManager.getColor("Borders.ContrastBorderColor"); wrapper.setBorder(IdeBorderFactory.createBorder(color)); wrapper.add(replaceEditorPanel, BorderLayout.CENTER); final JPanel replacePanel = new JPanel(null); final GroupLayout layout = new GroupLayout(replacePanel); replacePanel.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup() .addGroup( layout.createSequentialGroup() .addComponent(labelToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE) .addComponent(replacementToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ) .addComponent(wrapper) ); layout.setVerticalGroup( layout.createSequentialGroup(). addGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(labelToolbar.getComponent()) .addComponent(replacementToolbar.getComponent()) ) .addGap(4) .addComponent(wrapper) ); return replacePanel; } @Nullable @Override protected JComponent createNorthPanel() { final DumbAwareAction historyAction = new DumbAwareAction(SSRBundle.messagePointer("history.button"), SSRBundle.messagePointer("history.button.description"), AllIcons.Actions.SearchWithHistory) { @Override public void actionPerformed(@NotNull AnActionEvent e) { final Object source = e.getInputEvent().getSource(); if (!(source instanceof Component)) return; JBPopupFactory.getInstance() .createPopupChooserBuilder(ConfigurationManager.getInstance(getProject()).getHistoryConfigurations()) .setRenderer(new ConfigurationCellRenderer()) .setItemChosenCallback(c -> { if (c instanceof ReplaceConfiguration && !myReplace) { mySwitchAction.actionPerformed( AnActionEvent.createFromAnAction(mySwitchAction, null, ActionPlaces.UNKNOWN, DataContext.EMPTY_CONTEXT)); } loadConfiguration(c); }) .setSelectionMode(ListSelectionModel.SINGLE_SELECTION) .createPopup() .showUnderneathOf((Component)source); } }; final ToolbarLabel searchTemplateLabel = new ToolbarLabel(SSRBundle.message("search.template")); final DefaultActionGroup historyActionGroup = new DefaultActionGroup(historyAction, searchTemplateLabel); final ActionManager actionManager = ActionManager.getInstance(); final ActionToolbar historyToolbar = actionManager.createActionToolbar("StructuralSearchDialog", historyActionGroup, true); final CheckboxAction injected = new CheckboxAction(SSRBundle.message("search.in.injected.checkbox")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration.getMatchOptions().isSearchInjectedCode(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getMatchOptions().setSearchInjectedCode(state); initiateValidation(); } }; final CheckboxAction recursive = new CheckboxAction(SSRBundle.message("recursive.matching.checkbox")) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); e.getPresentation().setEnabledAndVisible(!myReplace); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration instanceof SearchConfiguration && myConfiguration.getMatchOptions().isRecursiveSearch(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { if (myConfiguration instanceof SearchConfiguration) { myConfiguration.getMatchOptions().setRecursiveSearch(state); initiateValidation(); } } }; final CheckboxAction matchCase = new CheckboxAction(FindBundle.message("find.popup.case.sensitive")) { @Override public boolean isSelected(@NotNull AnActionEvent e) { return myConfiguration.getMatchOptions().isCaseSensitiveMatch(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { myConfiguration.getMatchOptions().setCaseSensitiveMatch(state); initiateValidation(); } }; myFileType = UIUtil.detectFileType(mySearchContext); myDialect = myFileType.getLanguage(); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); if (profile != null) { final List<PatternContext> contexts = profile.getPatternContexts(); if (!contexts.isEmpty()) { myPatternContext = contexts.get(0); } } myFileTypeChooser.setSelectedItem(myFileType, myDialect, myPatternContext); myFileTypeChooser.setFileTypeInfoConsumer(info -> { myOptionsToolbar.updateActionsImmediately(); myFileType = info.getFileType(); myFilterPanel.setFileType(myFileType); myDialect = info.getDialect(); myPatternContext = info.getContext(); final String contextId = (myPatternContext == null) ? "" : myPatternContext.getId(); final StructuralSearchProfile profile1 = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile1 != null; final Document searchDocument = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, mySearchCriteriaEdit.getText(), profile1); searchDocument.addDocumentListener(this, myDisposable); mySearchCriteriaEdit.setNewDocumentAndFileType(myFileType, searchDocument); searchDocument.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, contextId); final Document replaceDocument = UIUtil.createDocument(getProject(), myFileType, myDialect, myPatternContext, myReplaceCriteriaEdit.getText(), profile1); replaceDocument.addDocumentListener(this, myDisposable); myReplaceCriteriaEdit.setNewDocumentAndFileType(myFileType, replaceDocument); replaceDocument.putUserData(STRUCTURAL_SEARCH_PATTERN_CONTEXT_ID, contextId); initiateValidation(); }); final DefaultActionGroup templateActionGroup = new DefaultActionGroup(); templateActionGroup.add( new DumbAwareAction(SSRBundle.message("save.template.text.button")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { ConfigurationManager.getInstance(getProject()).showSaveTemplateAsDialog(getConfiguration()); } }); templateActionGroup.add( new DumbAwareAction(SSRBundle.message("save.inspection.action.text")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { StructuralSearchProfileActionProvider.createNewInspection(getConfiguration(), getProject()); } }); templateActionGroup.addSeparator(); mySwitchAction = new SwitchAction(); templateActionGroup.addAll( new CopyConfigurationAction(), new PasteConfigurationAction(), new DumbAwareAction(SSRBundle.message("copy.existing.template.button")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { final SelectTemplateDialog dialog = new SelectTemplateDialog(getProject(), false, myReplace); if (!dialog.showAndGet()) { return; } final Configuration[] configurations = dialog.getSelectedConfigurations(); if (configurations.length == 1) { loadConfiguration(configurations[0]); } } }, Separator.getInstance(), mySwitchAction ); templateActionGroup.setPopup(true); final Presentation presentation = templateActionGroup.getTemplatePresentation(); presentation.setIcon(AllIcons.General.Settings); presentation.setText(SSRBundle.message("tools.button")); final Icon filterModifiedIcon = ExecutionUtil.getLiveIndicator(AllIcons.General.Filter); final AnAction filterAction = new DumbAwareToggleAction(SSRBundle.message("filter.button"), SSRBundle.message("filter.button.description"), filterModifiedIcon) { @Override public void update(@NotNull AnActionEvent e) { super.update(e); final Presentation presentation = e.getPresentation(); presentation.setIcon(myFilterPanel.hasVisibleFilter() ? filterModifiedIcon : AllIcons.General.Filter); } @Override public boolean isSelected(@NotNull AnActionEvent e) { return isFilterPanelVisible(); } @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { setFilterPanelVisible(state); } }; final DefaultActionGroup optionsActionGroup = new DefaultActionGroup(injected, recursive, matchCase, myFileTypeChooser, filterAction, templateActionGroup); myOptionsToolbar = (ActionToolbarImpl)actionManager.createActionToolbar("StructuralSearchDialog", optionsActionGroup, true); myOptionsToolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY); myOptionsToolbar.setForceMinimumSize(true); final JPanel northPanel = new JPanel(null); final GroupLayout layout = new GroupLayout(northPanel); northPanel.setLayout(layout); layout.setHonorsVisibility(true); layout.setHorizontalGroup( layout.createSequentialGroup() .addComponent(historyToolbar.getComponent(), GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, 20, Integer.MAX_VALUE) .addComponent(myOptionsToolbar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(GroupLayout.Alignment.CENTER) .addComponent(historyToolbar.getComponent()) .addComponent(myOptionsToolbar) ); return northPanel; } @Nullable @Override protected JPanel createSouthAdditionalPanel() { if (myEditConfigOnly) return null; final JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 0)); myOpenInNewTab = new JCheckBox(SSRBundle.message("open.in.new.tab.checkbox")); myOpenInNewTab.setSelected(FindSettings.getInstance().isShowResultsInSeparateView()); panel.add(myOpenInNewTab, BorderLayout.EAST); return panel; } private Project getProject() { return mySearchContext.getProject(); } @Nullable @Override public Point getInitialLocation() { // handle dimension service manually to store dimensions correctly when switching between search/replace in the same dialog final DimensionService dimensionService = DimensionService.getInstance(); final Dimension size = dimensionService.getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY, getProject()); if (size != null) { setSize(size.width, myEditConfigOnly ? size.height - myScopePanel.getPreferredSize().height : size.height); } else { pack(); // set width from replace if search not available and vice versa final Dimension otherSize = dimensionService.getSize(myReplace ? SEARCH_DIMENSION_SERVICE_KEY : REPLACE_DIMENSION_SERVICE_KEY, getProject()); if (otherSize != null) { setSize(otherSize.width, getSize().height); } } if (myEditConfigOnly) return super.getInitialLocation(); final Point location = dimensionService.getLocation(SEARCH_DIMENSION_SERVICE_KEY, getProject()); return (location == null) ? super.getInitialLocation() : location; } @Override public void show() { if (!myUseLastConfiguration) { setTextFromContext(); } final PropertiesComponent properties = PropertiesComponent.getInstance(); setFilterPanelVisible(properties.getBoolean(FILTERS_VISIBLE_STATE, true)); super.show(); StructuralSearchPlugin.getInstance(getProject()).setDialog(this); } private void startTemplate() { if (!Registry.is("ssr.template.from.selection.builder")) { return; } final Document document = mySearchCriteriaEdit.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document); assert psiFile != null; final TemplateBuilder builder = new StructuralSearchTemplateBuilder(psiFile).buildTemplate(); WriteCommandAction .runWriteCommandAction(getProject(), SSRBundle.message("command.name.live.search.template.builder"), "Structural Search", () -> builder.run(Objects.requireNonNull(mySearchCriteriaEdit.getEditor()), true)); } @Override public JComponent getPreferredFocusedComponent() { return mySearchCriteriaEdit; } @Override public void doCancelAction() { super.doCancelAction(); removeMatchHighlights(); } @Override protected void doOKAction() { myDoingOkAction = true; removeMatchHighlights(); final CompiledPattern compiledPattern = compilePattern(); myDoingOkAction = false; if (compiledPattern == null) return; myAlarm.cancelAllRequests(); myConfiguration.removeUnusedVariables(); super.doOKAction(); if (myEditConfigOnly) return; final SearchScope scope = myScopePanel.getScope(); if (scope instanceof GlobalSearchScopesCore.DirectoryScope) { final GlobalSearchScopesCore.DirectoryScope directoryScope = (GlobalSearchScopesCore.DirectoryScope)scope; FindInProjectSettings.getInstance(getProject()).addDirectory(directoryScope.getDirectory().getPresentableUrl()); } final FindSettings findSettings = FindSettings.getInstance(); findSettings.setShowResultsInSeparateView(myOpenInNewTab.isSelected()); try { ConfigurationManager.getInstance(getProject()).addHistoryConfiguration(myConfiguration); startSearching(); } catch (MalformedPatternException ex) { reportMessage(SSRBundle.message("this.pattern.is.malformed.message", ex.getMessage()), true, mySearchCriteriaEdit); } } public Configuration getConfiguration() { saveConfiguration(); return myConfiguration.copy(); } @Nullable private CompiledPattern compilePattern() { final MatchOptions matchOptions = getConfiguration().getMatchOptions(); final Project project = getProject(); try { final CompiledPattern compiledPattern = PatternCompiler.compilePattern(project, matchOptions, true, !myEditConfigOnly); reportMessage(null, false, mySearchCriteriaEdit); return compiledPattern; } catch (MalformedPatternException e) { removeMatchHighlights(); final String message = isEmpty(matchOptions.getSearchPattern()) ? null : SSRBundle.message("this.pattern.is.malformed.message", (e.getMessage() != null) ? e.getMessage() : ""); if (!e.isErrorElement || !Registry.is("ssr.in.editor.problem.highlighting")) { reportMessage(message, true, mySearchCriteriaEdit); } return null; } catch (UnsupportedPatternException e) { removeMatchHighlights(); reportMessage(SSRBundle.message("this.pattern.is.unsupported.message", e.getMessage()), true, mySearchCriteriaEdit); return null; } catch (NoMatchFoundException e) { removeMatchHighlights(); reportMessage(e.getMessage(), false, myScopePanel); return null; } } private void checkReplacementPattern() { if (!myReplace) { return; } try { Replacer.checkReplacementPattern(getProject(), myConfiguration.getReplaceOptions()); reportMessage(null, false, myReplaceCriteriaEdit); } catch (UnsupportedPatternException ex) { reportMessage(SSRBundle.message("unsupported.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit); } catch (MalformedPatternException ex) { if (!ex.isErrorElement || !Registry.is("ssr.in.editor.problem.highlighting")) { reportMessage(SSRBundle.message("malformed.replacement.pattern.message", ex.getMessage()), true, myReplaceCriteriaEdit); } } } private void removeMatchHighlights() { if (myEditConfigOnly || myRangeHighlighters.isEmpty()) { return; } // retrieval of editor needs to be outside of invokeLater(), otherwise the editor might have already changed. final Editor editor = myEditor; if (editor == null) { return; } ApplicationManager.getApplication().invokeLater(() -> { final Project project = getProject(); if (project.isDisposed()) { return; } final HighlightManager highlightManager = HighlightManager.getInstance(project); for (RangeHighlighter highlighter : myRangeHighlighters) { highlightManager.removeSegmentHighlighter(editor, highlighter); } WindowManager.getInstance().getStatusBar(project).setInfo(""); myRangeHighlighters.clear(); }); } private void addMatchHighlights() { if (myEditConfigOnly || DumbService.isDumb(getProject())) { // Search hits in the current editor are not shown when dumb. return; } final Project project = getProject(); final Editor editor = myEditor; if (editor == null) { return; } final Document document = editor.getDocument(); final PsiFile file = ReadAction.compute(() -> PsiDocumentManager.getInstance(project).getPsiFile(document)); if (file == null) { return; } final MatchOptions matchOptions = getConfiguration().getMatchOptions(); matchOptions.setScope(new LocalSearchScope(file, PredefinedSearchScopeProviderImpl.getCurrentFileScopeName())); final CollectingMatchResultSink sink = new CollectingMatchResultSink(); try { new Matcher(project, matchOptions).findMatches(sink); final List<MatchResult> matches = sink.getMatches(); removeMatchHighlights(); addMatchHighlights(matches, editor, file, SSRBundle.message("status.bar.text.results.found.in.current.file", matches.size())); } catch (StructuralSearchException e) { reportMessage(e.getMessage().replace(ScriptSupport.UUID, ""), true, mySearchCriteriaEdit); removeMatchHighlights(); } } private void addMatchHighlights(@NotNull List<? extends MatchResult> matchResults, @NotNull Editor editor, @NotNull PsiFile file, @NlsContexts.StatusBarText @Nullable String statusBarText) { ApplicationManager.getApplication().invokeLater(() -> { final Project project = getProject(); if (project.isDisposed()) { return; } if (!matchResults.isEmpty()) { for (MatchResult result : matchResults) { final PsiElement match = result.getMatch(); if (match == null || match.getContainingFile() != file) continue; int start = -1; int end = -1; if (MatchResult.MULTI_LINE_MATCH.equals(result.getName())) { for (MatchResult child : result.getChildren()) { final TextRange range = child.getMatch().getTextRange(); final int startOffset = range.getStartOffset(); if (start == -1 || start > startOffset) { start = startOffset; } final int endOffset = range.getEndOffset(); if (end < endOffset) { end = endOffset; } } } else { final TextRange range = match.getTextRange(); start = range.getStartOffset(); end = range.getEndOffset(); } final HighlightManager highlightManager = HighlightManager.getInstance(project); highlightManager.addRangeHighlight(editor, start, end, EditorColors.SEARCH_RESULT_ATTRIBUTES, false, myRangeHighlighters); } HighlightHandlerBase.setupFindModel(project); } WindowManager.getInstance().getStatusBar(project).setInfo(statusBarText); }); } private Balloon myBalloon; private void reportMessage(@NlsContexts.PopupContent @Nullable String message, boolean error, @NotNull JComponent component) { ApplicationManager.getApplication().invokeLater(() -> { if (myBalloon != null) myBalloon.hide(); component.putClientProperty("JComponent.outline", (!error || message == null) ? null : "error"); component.repaint(); if (message == null) return; myBalloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, error ? MessageType.ERROR : MessageType.WARNING, null) .setHideOnFrameResize(false) .createBalloon(); if (component != myScopePanel) { myBalloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, component.getHeight())), Balloon.Position.below); } else { myBalloon.show(new RelativePoint(component, new Point(component.getWidth() / 2, 0)), Balloon.Position.above); } myBalloon.showInCenterOf(component); Disposer.register(myDisposable, myBalloon); }, ModalityState.stateForComponent(component)); } private void securityCheck() { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); int scripts = 0; for (String name : matchOptions.getVariableConstraintNames()) { final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name); if (constraint.getScriptCodeConstraint().length() > 2) scripts++; } if (myConfiguration instanceof ReplaceConfiguration) { final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); for (ReplacementVariableDefinition variableDefinition : replaceOptions.getVariableDefinitions()) { if (variableDefinition.getScriptCodeConstraint().length() > 2) scripts++; } } if (scripts > 0) { final NotificationGroup notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup(UIUtil.SSR_NOTIFICATION_GROUP_ID); notificationGroup.createNotification(NotificationType.WARNING) .setTitle(SSRBundle.message("import.template.script.warning.title")) .setContent(SSRBundle.message("import.template.script.warning", ApplicationNamesInfo.getInstance().getFullProductName(), scripts)) .notify(mySearchContext.getProject()); } } public void showFilterPanel(String variableName) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration)); setFilterPanelVisible(true); myConfiguration.setCurrentVariableName(variableName); } private void setFilterPanelVisible(boolean visible) { if (visible) { if (myFilterPanel.getVariable() == null) { myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(Configuration.CONTEXT_VAR_NAME, myConfiguration)); } if (!isFilterPanelVisible()) { mySearchEditorPanel.setSecondComponent(myFilterPanel.getComponent()); } } else { if (isFilterPanelVisible()) { mySearchEditorPanel.setSecondComponent(null); myConfiguration.setCurrentVariableName(null); } } } private boolean isFilterPanelVisible() { return mySearchEditorPanel.getSecondComponent() != null; } private void setSearchTargets(MatchOptions matchOptions) { final List<String> names = new ArrayList<>(matchOptions.getUsedVariableNames()); Collections.sort(names); names.remove(Configuration.CONTEXT_VAR_NAME); names.add(SSRBundle.message("complete.match.variable.name")); myTargetComboBox.setItems(names); if (names.size() > 1) { myTargetComboBox.setEnabled(true); for (@NlsSafe String name : names) { final MatchVariableConstraint constraint = matchOptions.getVariableConstraint(name); if (constraint != null && constraint.isPartOfSearchResults()) { myTargetComboBox.setSelectedItem(name); return; } } myTargetComboBox.setSelectedItem(SSRBundle.message("complete.match.variable.name")); } else { myTargetComboBox.setEnabled(false); } } /** * @param text the text to try and load a configuration from * @return {@code true}, if some configuration was found, even if it was broken or corrupted {@code false} otherwise. */ private boolean loadConfiguration(String text) { if (text == null) { return false; } try { final Configuration configuration = ConfigurationUtil.fromXml(text); if (configuration == null) { return false; } if (configuration instanceof ReplaceConfiguration && !myReplace) { mySwitchAction.actionPerformed( AnActionEvent.createFromAnAction(mySwitchAction, null, ActionPlaces.UNKNOWN, DataContext.EMPTY_CONTEXT)); } loadConfiguration(configuration); securityCheck(); } catch (JDOMException e) { reportMessage(SSRBundle.message("import.template.script.corrupted") + '\n' + e.getMessage(), false, myOptionsToolbar); } return true; } public void loadConfiguration(Configuration configuration) { final Configuration newConfiguration = createConfiguration(configuration); if (myUseLastConfiguration) { newConfiguration.setUuid(myConfiguration.getUuid()); newConfiguration.setName(myConfiguration.getName()); newConfiguration.setDescription(myConfiguration.getDescription()); newConfiguration.setSuppressId(myConfiguration.getSuppressId()); newConfiguration.setProblemDescriptor(myConfiguration.getProblemDescriptor()); } myConfiguration = newConfiguration; final MatchOptions matchOptions = myConfiguration.getMatchOptions(); setSearchTargets(matchOptions); if (!myEditConfigOnly) { myScopePanel.setScopesFromContext(); final SearchScope scope = matchOptions.getScope(); if (scope != null) myScopePanel.setScope(scope); } myFileTypeChooser.setSelectedItem(matchOptions.getFileType(), matchOptions.getDialect(), matchOptions.getPatternContext()); final Editor searchEditor = mySearchCriteriaEdit.getEditor(); if (searchEditor != null) { searchEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } UIUtil.setContent(mySearchCriteriaEdit, matchOptions.getSearchPattern()); final PropertiesComponent properties = PropertiesComponent.getInstance(); if (myReplace) { final Editor replaceEditor = myReplaceCriteriaEdit.getEditor(); if (replaceEditor != null) { replaceEditor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); } if (configuration instanceof ReplaceConfiguration) { final ReplaceOptions replaceOptions = configuration.getReplaceOptions(); UIUtil.setContent(myReplaceCriteriaEdit, replaceOptions.getReplacement()); } else { UIUtil.setContent(myReplaceCriteriaEdit, matchOptions.getSearchPattern()); } } else { if (configuration instanceof ReplaceConfiguration) { matchOptions.setRecursiveSearch(properties.getBoolean(RECURSIVE_STATE)); } } } private void saveConfiguration() { final MatchOptions matchOptions = myConfiguration.getMatchOptions(); if (!myEditConfigOnly) { final SearchScope scope = myScopePanel.getScope(); final boolean searchWithinHierarchy = IdeBundle.message("scope.class.hierarchy").equals(scope.getDisplayName()); // We need to reset search within hierarchy scope during online validation since the scope works with user participation matchOptions.setScope(searchWithinHierarchy && !myDoingOkAction ? GlobalSearchScope.projectScope(getProject()) : scope); } else { matchOptions.setScope(null); } matchOptions.setFileType(myFileType); matchOptions.setDialect(myDialect); matchOptions.setPatternContext(myPatternContext); matchOptions.setSearchPattern(getPattern(mySearchCriteriaEdit)); final PropertiesComponent properties = PropertiesComponent.getInstance(); if (myReplace) { final ReplaceOptions replaceOptions = myConfiguration.getReplaceOptions(); replaceOptions.setReplacement(getPattern(myReplaceCriteriaEdit)); matchOptions.setRecursiveSearch(false); properties.setValue(SHORTEN_FQN_STATE, replaceOptions.isToShortenFQN()); properties.setValue(USE_STATIC_IMPORT_STATE, replaceOptions.isToUseStaticImport()); properties.setValue(REFORMAT_STATE, replaceOptions.isToReformatAccordingToStyle()); } else { properties.setValue(RECURSIVE_STATE, matchOptions.isRecursiveSearch()); } } private String getPattern(EditorTextField textField) { final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; final Document document = textField.getDocument(); final String pattern = ReadAction.compute(() -> { final PsiFile file = PsiDocumentManager.getInstance(getProject()).getPsiFile(document); assert file != null; return profile.getCodeFragmentText(file); }); return pattern.isEmpty() ? textField.getText() : pattern; } @Nullable @Override protected final String getDimensionServiceKey() { return null; } @Override public void dispose() { getProject().putUserData(STRUCTURAL_SEARCH_PREVIOUS_CONFIGURATION, myConfiguration); if (myReplace) storeDimensions(REPLACE_DIMENSION_SERVICE_KEY, SEARCH_DIMENSION_SERVICE_KEY); else storeDimensions(SEARCH_DIMENSION_SERVICE_KEY, REPLACE_DIMENSION_SERVICE_KEY); final PropertiesComponent properties = PropertiesComponent.getInstance(); properties.setValue(FILTERS_VISIBLE_STATE, isFilterPanelVisible(), true); StructuralSearchPlugin.getInstance(getProject()).setDialog(null); myAlarm.cancelAllRequests(); mySearchCriteriaEdit.removeNotify(); myReplaceCriteriaEdit.removeNotify(); removeRestartHighlightingListenerFromCurrentEditor(); super.dispose(); } private void storeDimensions(String key1, String key2) { if (myEditConfigOnly) return; // don't store dimensions when editing structural search inspection patterns // handle own dimension service to store dimensions correctly when switching between search/replace in the same dialog final Dimension size = getSize(); final DimensionService dimensionService = DimensionService.getInstance(); final Point location = getLocation(); if (location.x < 0) location.x = 0; if (location.y < 0) location.y = 0; dimensionService.setLocation(SEARCH_DIMENSION_SERVICE_KEY, location, getProject()); dimensionService.setSize(key1, size, getProject()); final Dimension otherSize = dimensionService.getSize(key2); if (otherSize != null && otherSize.width != size.width) { otherSize.width = size.width; dimensionService.setSize(key2, otherSize, getProject()); } } @Override protected String getHelpId() { return "find.structuredSearch"; } private static class ErrorBorder implements Border { private final Border myErrorBorder; ErrorBorder(Border errorBorder) { myErrorBorder = errorBorder; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { final EditorTextField editorTextField = ComponentUtil.getParentOfType((Class<? extends EditorTextField>)EditorTextField.class, c); if (editorTextField == null) { return; } final Object object = editorTextField.getClientProperty("JComponent.outline"); if ("error".equals(object) || "warning".equals(object)) { myErrorBorder.paintBorder(c, g, x, y, width, height); } } @Override public Insets getBorderInsets(Component c) { return myErrorBorder.getBorderInsets(c); } @Override public boolean isBorderOpaque() { return false; } } private class SwitchAction extends AnAction implements DumbAware { SwitchAction() { init(); } @Override public void actionPerformed(@NotNull AnActionEvent e) { myReplace = !myReplace; setTitle(getDefaultTitle()); myReplacePanel.setVisible(myReplace); loadConfiguration(myConfiguration); final Dimension size = DimensionService.getInstance().getSize(myReplace ? REPLACE_DIMENSION_SERVICE_KEY : SEARCH_DIMENSION_SERVICE_KEY); if (size != null) { setSize(getSize().width, size.height); } else { pack(); } init(); } private void init() { getTemplatePresentation().setText(SSRBundle.messagePointer(myReplace ? "switch.to.search.action" : "switch.to.replace.action")); final ActionManager actionManager = ActionManager.getInstance(); final ShortcutSet searchShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralSearchAction").getShortcutSet(); final ShortcutSet replaceShortcutSet = actionManager.getAction("StructuralSearchPlugin.StructuralReplaceAction").getShortcutSet(); final ShortcutSet shortcutSet = myReplace ? new CompositeShortcutSet(searchShortcutSet, replaceShortcutSet) : new CompositeShortcutSet(replaceShortcutSet, searchShortcutSet); registerCustomShortcutSet(shortcutSet, getRootPane()); } } private class CopyConfigurationAction extends AnAction implements DumbAware { CopyConfigurationAction() { super(SSRBundle.messagePointer("export.template.action")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { CopyPasteManager.getInstance().setContents(new TextTransferable(ConfigurationUtil.toXml(myConfiguration))); } } private class PasteConfigurationAction extends AnAction implements DumbAware { PasteConfigurationAction() { super(SSRBundle.messagePointer("import.template.action")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final String contents = CopyPasteManager.getInstance().getContents(DataFlavor.stringFlavor); if (!loadConfiguration(contents)) { reportMessage(SSRBundle.message("no.template.found.warning"), false, myOptionsToolbar); } } } public static @Nls(capitalization = Nls.Capitalization.Sentence) String getUserDefined() { return SSRBundle.message("new.template.defaultname"); } private class MyEditorTextField extends EditorTextField { private final boolean myReplace; MyEditorTextField(Document document, boolean replace) { super(document, StructuralSearchDialog.this.getProject(), StructuralSearchDialog.this.myFileType, false, false); myReplace = replace; } @Override protected EditorEx createEditor() { final EditorEx editor = super.createEditor(); editor.setHorizontalScrollbarVisible(true); editor.setVerticalScrollbarVisible(true); final StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(myFileType); assert profile != null; TemplateEditorUtil.setHighlighter(editor, UIUtil.getTemplateContextType(profile)); SubstitutionShortInfoHandler.install(editor, variableName -> { if (variableName.endsWith(ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX)) { //noinspection AssignmentToLambdaParameter variableName = trimEnd(variableName, ReplaceConfiguration.REPLACEMENT_VARIABLE_SUFFIX); assert myConfiguration instanceof ReplaceConfiguration; myFilterPanel.initFilters(UIUtil.getOrAddReplacementVariable(variableName, myConfiguration)); } else{ myFilterPanel.initFilters(UIUtil.getOrAddVariableConstraint(variableName, myConfiguration)); } if (isFilterPanelVisible()) { myConfiguration.setCurrentVariableName(variableName); } }, myDisposable, myReplace); editor.putUserData(SubstitutionShortInfoHandler.CURRENT_CONFIGURATION_KEY, myConfiguration); getDocument().putUserData(STRUCTURAL_SEARCH_ERROR_CALLBACK, () -> { putClientProperty("JComponent.outline", "error"); repaint(); getOKAction().setEnabled(false); if (!myReplace) removeMatchHighlights(); }); TextCompletionUtil.installCompletionHint(editor); editor.putUserData(STRUCTURAL_SEARCH_DIALOG, StructuralSearchDialog.this); editor.setEmbeddedIntoDialogWrapper(true); return editor; } @Override protected void updateBorder(@NotNull EditorEx editor) { setupBorder(editor); final JScrollPane scrollPane = editor.getScrollPane(); scrollPane.setBorder(new ErrorBorder(scrollPane.getBorder())); } } }
SSR: close dialog when app is closing or when the project it belongs to is closed GitOrigin-RevId: d435b78235ba05ca80072d5baeb943e7d275cd56
platform/structuralsearch/source/com/intellij/structuralsearch/plugin/ui/StructuralSearchDialog.java
SSR: close dialog when app is closing or when the project it belongs to is closed
Java
apache-2.0
dbfaa5ac6abcbd72883cd7397f8b3561af71d86c
0
codeaudit/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jerome79/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.currency; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.DoubleLabelledMatrix1D; import com.opengamma.util.ArgumentChecker; /** * Converts a value from one currency to another, preserving all other properties. */ public class CurrencyConversionFunction extends AbstractFunction.NonCompiledInvoker { private static final String DEFAULT_CURRENCY_INJECTION = ValuePropertyNames.OUTPUT_RESERVED_PREFIX + ValuePropertyNames.CURRENCY; /** * The property this function will put on an output indicating the currency of the original value. */ public static final String ORIGINAL_CURRENCY = "Original" + ValuePropertyNames.CURRENCY; private static final Logger s_logger = LoggerFactory.getLogger(CurrencyConversionFunction.class); private static final ComputationTargetType TYPE = ComputationTargetType.PORTFOLIO_NODE.or(ComputationTargetType.POSITION).or(ComputationTargetType.SECURITY).or(ComputationTargetType.TRADE); private final Set<String> _valueNames; private boolean _allowViewDefaultCurrency; // = false; public CurrencyConversionFunction(final String valueName) { ArgumentChecker.notNull(valueName, "valueName"); _valueNames = Collections.singleton(valueName); } public CurrencyConversionFunction(final String... valueNames) { ArgumentChecker.notEmpty(valueNames, "valueNames"); _valueNames = new HashSet<String>(Arrays.asList(valueNames)); } protected Set<String> getValueNames() { return _valueNames; } public void setAllowViewDefaultCurrency(final boolean allowViewDefaultCurrency) { _allowViewDefaultCurrency = allowViewDefaultCurrency; } public boolean isAllowViewDefaultCurrency() { return _allowViewDefaultCurrency; } private ValueRequirement getInputValueRequirement(final ComputationTargetSpecification targetSpec, final ValueRequirement desiredValue) { return new ValueRequirement(desiredValue.getValueName(), targetSpec, desiredValue.getConstraints().copy().withoutAny(DEFAULT_CURRENCY_INJECTION) .withAny(ValuePropertyNames.CURRENCY).withoutAny(ORIGINAL_CURRENCY).get()); } private ValueRequirement getInputValueRequirement(final ComputationTargetSpecification targetSpec, final ValueRequirement desiredValue, final String forceCurrency) { return new ValueRequirement(desiredValue.getValueName(), targetSpec, desiredValue.getConstraints().copy().withoutAny(ValuePropertyNames.CURRENCY).with( ValuePropertyNames.CURRENCY, forceCurrency).withoutAny(ORIGINAL_CURRENCY).withOptional(DEFAULT_CURRENCY_INJECTION).get()); } /** * Divides the value by the conversion rate. Override this in a subclass for anything more elaborate - e.g. if the value is in "somethings per currency unit foo" so needs multiplying by the rate * instead. * * @param value input value to convert * @param conversionRate conversion rate to use * @return the converted value */ protected double convertDouble(final double value, final double conversionRate) { return value / conversionRate; } protected double[] convertDoubleArray(final double[] values, final double conversionRate) { final double[] newValues = new double[values.length]; for (int i = 0; i < values.length; i++) { newValues[i] = convertDouble(values[i], conversionRate); } return newValues; } protected DoubleLabelledMatrix1D convertDoubleLabelledMatrix1D(final DoubleLabelledMatrix1D value, final double conversionRate) { return new DoubleLabelledMatrix1D(value.getKeys(), value.getLabels(), convertDoubleArray(value.getValues(), conversionRate)); } /** * Delegates off to the other convert methods depending on the type of value. * * @param inputValue input value to convert * @param desiredValue requested value requirement * @param conversionRate conversion rate to use * @return the converted value */ protected Object convertValue(final ComputedValue inputValue, final ValueRequirement desiredValue, final double conversionRate) { final Object value = inputValue.getValue(); if (value instanceof Double) { return convertDouble((Double) value, conversionRate); } else if (value instanceof DoubleLabelledMatrix1D) { return convertDoubleLabelledMatrix1D((DoubleLabelledMatrix1D) value, conversionRate); } else { s_logger.error("Can't convert object with type {} to {}", inputValue.getValue().getClass(), desiredValue); return null; } } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { ComputedValue inputValue = null; double exchangeRate = 0; for (final ComputedValue input : inputs.getAllValues()) { if (ValueRequirementNames.SPOT_RATE.equals(input.getSpecification().getValueName())) { if (input.getValue() instanceof Double) { exchangeRate = (Double) input.getValue(); } else { return null; } } else { inputValue = input; } } if (inputValue == null) { return null; } final ValueRequirement desiredValue = desiredValues.iterator().next(); final String outputCurrency = desiredValue.getConstraint(ValuePropertyNames.CURRENCY); final String inputCurrency = inputValue.getSpecification().getProperty(ValuePropertyNames.CURRENCY); if (outputCurrency.equals(inputCurrency)) { // Don't think this should happen return Collections.singleton(inputValue); } else { s_logger.debug("Converting from {} to {}", inputCurrency, outputCurrency); final Object converted = convertValue(inputValue, desiredValue, exchangeRate); if (converted != null) { return Collections.singleton(new ComputedValue(new ValueSpecification(desiredValue.getValueName(), target.toSpecification(), desiredValue.getConstraints()), converted)); } else { return null; } } } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<String> possibleCurrencies = desiredValue.getConstraints().getValues(ValuePropertyNames.CURRENCY); if (possibleCurrencies == null) { s_logger.debug("Must specify a currency constraint; use DefaultCurrencyFunction instead"); return null; } else if (possibleCurrencies.isEmpty()) { if (isAllowViewDefaultCurrency()) { // The original function may not have delivered a result because it had heterogeneous input currencies, so try forcing the view default final String defaultCurrencyISO = DefaultCurrencyFunction.getViewDefaultCurrencyISO(context); if (defaultCurrencyISO == null) { s_logger.debug("No default currency from the view to inject"); return null; } s_logger.debug("Injecting view default currency {}", defaultCurrencyISO); return Collections.singleton(getInputValueRequirement(target.toSpecification(), desiredValue, defaultCurrencyISO)); } else { s_logger.debug("Cannot satisfy a wildcard currency constraint"); return null; } } else { // Actual input requirement is desired requirement with the currency wild-carded return Collections.singleton(getInputValueRequirement(target.toSpecification(), desiredValue)); } } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { // Maximal set of outputs is the valueNames with the infinite property set final ComputationTargetSpecification targetSpec = target.toSpecification(); if (getValueNames().size() == 1) { return Collections.singleton(new ValueSpecification(getValueNames().iterator().next(), targetSpec, ValueProperties.all())); } final Set<ValueSpecification> result = new HashSet<ValueSpecification>(); for (final String valueName : getValueNames()) { result.add(new ValueSpecification(valueName, targetSpec, ValueProperties.all())); } return result; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { final Map.Entry<ValueSpecification, ValueRequirement> input = inputs.entrySet().iterator().next(); if (input.getValue().getConstraints().getValues(DEFAULT_CURRENCY_INJECTION) == null) { // Resolved output is the input with the currency wild-carded, and the function ID the same final ValueSpecification value = input.getKey(); final Set<String> currencies = value.getProperties().getValues(ValuePropertyNames.CURRENCY); if (currencies.size() != 1) { // This will fail at the getAdditionalRequirements return null; } final ValueProperties.Builder properties = value.getProperties().copy(); properties.withAny(ValuePropertyNames.CURRENCY); properties.withoutAny(ORIGINAL_CURRENCY).with(ORIGINAL_CURRENCY, currencies); return Collections.singleton(new ValueSpecification(value.getValueName(), value.getTargetSpecification(), properties.get())); } // The input was requested with the converted currency, so return the same specification to remove this node from the graph return Collections.singleton(input.getKey()); } private String getCurrency(final Collection<ValueSpecification> specifications) { final ValueSpecification specification = specifications.iterator().next(); final Set<String> currencies = specification.getProperties().getValues(ValuePropertyNames.CURRENCY); if ((currencies == null) || (currencies.size() != 1)) { return null; } return currencies.iterator().next(); } private ValueRequirement getCurrencyConversion(final String fromCurrency, final String toCurrency) { return CurrencyMatrixSpotSourcingFunction.getConversionRequirement(fromCurrency, toCurrency); } @Override public Set<ValueRequirement> getAdditionalRequirements(final FunctionCompilationContext context, final ComputationTarget target, final Set<ValueSpecification> inputs, final Set<ValueSpecification> outputs) { s_logger.debug("FX requirements for {} -> {}", inputs, outputs); final String inputCurrency = getCurrency(inputs); if (inputCurrency == null) { return null; } final String outputCurrency = getCurrency(outputs); if (outputCurrency == null) { return null; } if (inputCurrency.equals(outputCurrency)) { // If the input and output currencies are the same then we shouldn't have this node in the graph return null; } return Collections.singleton(getCurrencyConversion(inputCurrency, outputCurrency)); } @Override public ComputationTargetType getTargetType() { return TYPE; } }
projects/OG-Financial/src/main/java/com/opengamma/financial/currency/CurrencyConversionFunction.java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.currency; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.DoubleLabelledMatrix1D; import com.opengamma.util.ArgumentChecker; /** * Converts a value from one currency to another, preserving all other properties. */ public class CurrencyConversionFunction extends AbstractFunction.NonCompiledInvoker { private static final String DEFAULT_CURRENCY_INJECTION = ValuePropertyNames.OUTPUT_RESERVED_PREFIX + ValuePropertyNames.CURRENCY; /** * The property this function will put on an output indicating the currency of the original value. */ public static final String ORIGINAL_CURRENCY = "Original" + ValuePropertyNames.CURRENCY; private static final Logger s_logger = LoggerFactory.getLogger(CurrencyConversionFunction.class); private static final ComputationTargetType TYPE = ComputationTargetType.PORTFOLIO_NODE.or(ComputationTargetType.POSITION).or(ComputationTargetType.SECURITY).or(ComputationTargetType.TRADE); private final Set<String> _valueNames; private boolean _allowViewDefaultCurrency; // = false; public CurrencyConversionFunction(final String valueName) { ArgumentChecker.notNull(valueName, "valueName"); _valueNames = Collections.singleton(valueName); } public CurrencyConversionFunction(final String... valueNames) { ArgumentChecker.notEmpty(valueNames, "valueNames"); _valueNames = new HashSet<String>(Arrays.asList(valueNames)); } protected Set<String> getValueNames() { return _valueNames; } public void setAllowViewDefaultCurrency(final boolean allowViewDefaultCurrency) { _allowViewDefaultCurrency = allowViewDefaultCurrency; } public boolean isAllowViewDefaultCurrency() { return _allowViewDefaultCurrency; } private ValueRequirement getInputValueRequirement(final ComputationTargetSpecification targetSpec, final ValueRequirement desiredValue) { return new ValueRequirement(desiredValue.getValueName(), targetSpec, desiredValue.getConstraints().copy().withoutAny(DEFAULT_CURRENCY_INJECTION) .withAny(ValuePropertyNames.CURRENCY).get()); } private ValueRequirement getInputValueRequirement(final ComputationTargetSpecification targetSpec, final ValueRequirement desiredValue, final String forceCurrency) { return new ValueRequirement(desiredValue.getValueName(), targetSpec, desiredValue.getConstraints().copy().withoutAny(ValuePropertyNames.CURRENCY).with( ValuePropertyNames.CURRENCY, forceCurrency).withOptional(DEFAULT_CURRENCY_INJECTION).get()); } /** * Divides the value by the conversion rate. Override this in a subclass for anything more elaborate - e.g. if the value is in "somethings per currency unit foo" so needs multiplying by the rate * instead. * * @param value input value to convert * @param conversionRate conversion rate to use * @return the converted value */ protected double convertDouble(final double value, final double conversionRate) { return value / conversionRate; } protected double[] convertDoubleArray(final double[] values, final double conversionRate) { final double[] newValues = new double[values.length]; for (int i = 0; i < values.length; i++) { newValues[i] = convertDouble(values[i], conversionRate); } return newValues; } protected DoubleLabelledMatrix1D convertDoubleLabelledMatrix1D(final DoubleLabelledMatrix1D value, final double conversionRate) { return new DoubleLabelledMatrix1D(value.getKeys(), value.getLabels(), convertDoubleArray(value.getValues(), conversionRate)); } /** * Delegates off to the other convert methods depending on the type of value. * * @param inputValue input value to convert * @param desiredValue requested value requirement * @param conversionRate conversion rate to use * @return the converted value */ protected Object convertValue(final ComputedValue inputValue, final ValueRequirement desiredValue, final double conversionRate) { final Object value = inputValue.getValue(); if (value instanceof Double) { return convertDouble((Double) value, conversionRate); } else if (value instanceof DoubleLabelledMatrix1D) { return convertDoubleLabelledMatrix1D((DoubleLabelledMatrix1D) value, conversionRate); } else { s_logger.error("Can't convert object with type {} to {}", inputValue.getValue().getClass(), desiredValue); return null; } } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { ComputedValue inputValue = null; double exchangeRate = 0; for (final ComputedValue input : inputs.getAllValues()) { if (ValueRequirementNames.SPOT_RATE.equals(input.getSpecification().getValueName())) { if (input.getValue() instanceof Double) { exchangeRate = (Double) input.getValue(); } else { return null; } } else { inputValue = input; } } if (inputValue == null) { return null; } final ValueRequirement desiredValue = desiredValues.iterator().next(); final String outputCurrency = desiredValue.getConstraint(ValuePropertyNames.CURRENCY); final String inputCurrency = inputValue.getSpecification().getProperty(ValuePropertyNames.CURRENCY); if (outputCurrency.equals(inputCurrency)) { // Don't think this should happen return Collections.singleton(inputValue); } else { s_logger.debug("Converting from {} to {}", inputCurrency, outputCurrency); final Object converted = convertValue(inputValue, desiredValue, exchangeRate); if (converted != null) { return Collections.singleton(new ComputedValue(new ValueSpecification(desiredValue.getValueName(), target.toSpecification(), desiredValue.getConstraints()), converted)); } else { return null; } } } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<String> possibleCurrencies = desiredValue.getConstraints().getValues(ValuePropertyNames.CURRENCY); if (possibleCurrencies == null) { s_logger.debug("Must specify a currency constraint; use DefaultCurrencyFunction instead"); return null; } else if (possibleCurrencies.isEmpty()) { if (isAllowViewDefaultCurrency()) { // The original function may not have delivered a result because it had heterogeneous input currencies, so try forcing the view default final String defaultCurrencyISO = DefaultCurrencyFunction.getViewDefaultCurrencyISO(context); if (defaultCurrencyISO == null) { s_logger.debug("No default currency from the view to inject"); return null; } s_logger.debug("Injecting view default currency {}", defaultCurrencyISO); return Collections.singleton(getInputValueRequirement(target.toSpecification(), desiredValue, defaultCurrencyISO)); } else { s_logger.debug("Cannot satisfy a wildcard currency constraint"); return null; } } else { // Actual input requirement is desired requirement with the currency wild-carded return Collections.singleton(getInputValueRequirement(target.toSpecification(), desiredValue)); } } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { // Maximal set of outputs is the valueNames with the infinite property set final ComputationTargetSpecification targetSpec = target.toSpecification(); if (getValueNames().size() == 1) { return Collections.singleton(new ValueSpecification(getValueNames().iterator().next(), targetSpec, ValueProperties.all())); } final Set<ValueSpecification> result = new HashSet<ValueSpecification>(); for (final String valueName : getValueNames()) { result.add(new ValueSpecification(valueName, targetSpec, ValueProperties.all())); } return result; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { final Map.Entry<ValueSpecification, ValueRequirement> input = inputs.entrySet().iterator().next(); if (input.getValue().getConstraints().getValues(DEFAULT_CURRENCY_INJECTION) == null) { // Resolved output is the input with the currency wild-carded, and the function ID the same final ValueSpecification value = input.getKey(); final Set<String> currencies = value.getProperties().getValues(ValuePropertyNames.CURRENCY); if (currencies.size() != 1) { // This will fail at the getAdditionalRequirements return null; } final ValueProperties.Builder properties = value.getProperties().copy(); properties.withAny(ValuePropertyNames.CURRENCY); properties.withoutAny(ORIGINAL_CURRENCY).with(ORIGINAL_CURRENCY, currencies); return Collections.singleton(new ValueSpecification(value.getValueName(), value.getTargetSpecification(), properties.get())); } // The input was requested with the converted currency, so return the same specification to remove this node from the graph return Collections.singleton(input.getKey()); } private String getCurrency(final Collection<ValueSpecification> specifications) { final ValueSpecification specification = specifications.iterator().next(); final Set<String> currencies = specification.getProperties().getValues(ValuePropertyNames.CURRENCY); if ((currencies == null) || (currencies.size() != 1)) { return null; } return currencies.iterator().next(); } private ValueRequirement getCurrencyConversion(final String fromCurrency, final String toCurrency) { return CurrencyMatrixSpotSourcingFunction.getConversionRequirement(fromCurrency, toCurrency); } @Override public Set<ValueRequirement> getAdditionalRequirements(final FunctionCompilationContext context, final ComputationTarget target, final Set<ValueSpecification> inputs, final Set<ValueSpecification> outputs) { s_logger.debug("FX requirements for {} -> {}", inputs, outputs); final String inputCurrency = getCurrency(inputs); if (inputCurrency == null) { return null; } final String outputCurrency = getCurrency(outputs); if (outputCurrency == null) { return null; } if (inputCurrency.equals(outputCurrency)) { // If the input and output currencies are the same then we shouldn't have this node in the graph return null; } return Collections.singleton(getCurrencyConversion(inputCurrency, outputCurrency)); } @Override public ComputationTargetType getTargetType() { return TYPE; } }
Don't pass the OriginalCurrency constraint on to the input values - this should decorate the conversion result only.
projects/OG-Financial/src/main/java/com/opengamma/financial/currency/CurrencyConversionFunction.java
Don't pass the OriginalCurrency constraint on to the input values - this should decorate the conversion result only.
Java
apache-2.0
22437ce764e9de86891704f79be09cb23851db91
0
oehf/ipf,oehf/ipf,oehf/ipf,krasserm/ipf,oehf/ipf,krasserm/ipf
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.platform.camel.ihe.ws; import java.util.List; import java.util.Map; import org.apache.camel.impl.DefaultComponent; import org.apache.cxf.interceptor.AbstractBasicInterceptorProvider; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.interceptor.InterceptorProvider; import org.openehealth.ipf.commons.ihe.ws.ItiServiceInfo; import org.apache.cxf.message.Message; /** * Base component class for Web Service-based IHE components. * @author Dmytro Rud */ abstract public class AbstractWsComponent<C extends ItiServiceInfo> extends DefaultComponent { protected InterceptorProvider getCustomInterceptors(Map<String, Object> parameters) { AbstractBasicInterceptorProvider provider = new AbstractBasicInterceptorProvider() {}; provider.setInInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "inInterceptors", Interceptor.class))); provider.setInFaultInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "inFaultInterceptors", Interceptor.class))); provider.setOutInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "outInterceptors", Interceptor.class))); provider.setOutFaultInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "outFaultInterceptors", Interceptor.class))); return provider; } @SuppressWarnings({ "unchecked", "rawtypes" }) private List<Interceptor<? extends Message>> castList( List<Interceptor> param) { return (List<Interceptor<? extends Message>>) (List<?>) param; } public abstract C getWebServiceConfiguration(); }
platform-camel/ihe/ws/src/main/java/org/openehealth/ipf/platform/camel/ihe/ws/AbstractWsComponent.java
/* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.platform.camel.ihe.ws; import java.util.List; import java.util.Map; import org.apache.camel.impl.DefaultComponent; import org.apache.cxf.interceptor.AbstractBasicInterceptorProvider; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.interceptor.InterceptorProvider; import org.openehealth.ipf.commons.ihe.ws.ItiServiceInfo; import org.apache.cxf.message.Message; /** * Base component class for Web Service-based IHE components. * @author Dmytro Rud */ abstract public class AbstractWsComponent<C extends ItiServiceInfo> extends DefaultComponent { protected InterceptorProvider getCustomInterceptors(Map<String, Object> parameters) { AbstractBasicInterceptorProvider provider = new AbstractBasicInterceptorProvider() {}; provider.setInInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "inInterceptors", Interceptor.class))); provider.setInFaultInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "inFaultInterceptors", Interceptor.class))); provider.setOutInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "outInterceptors", Interceptor.class))); provider.setOutFaultInterceptors(castList(resolveAndRemoveReferenceListParameter( parameters, "outFaultInterceptors", Interceptor.class))); return provider; } @SuppressWarnings({ "unchecked", "rawtypes" }) private List<Interceptor<? extends Message>> castList( List<Interceptor> param) { return (List<Interceptor<? extends Message>>) (List<?>) param; } public abstract C getWebServiceConfiguration(); }
tiny reformatting after merge
platform-camel/ihe/ws/src/main/java/org/openehealth/ipf/platform/camel/ihe/ws/AbstractWsComponent.java
tiny reformatting after merge
Java
apache-2.0
18885fcd2525578c06cb15c682788e34116de17c
0
gzxishan/OftenPorter
package cn.xishan.oftenporter.porter.simple; import cn.xishan.oftenporter.porter.core.JResponse; import cn.xishan.oftenporter.porter.core.ResultCode; import cn.xishan.oftenporter.porter.core.annotation.NeceParam; import cn.xishan.oftenporter.porter.core.annotation.UneceParam; import cn.xishan.oftenporter.porter.core.annotation.deal.AnnoUtil; import cn.xishan.oftenporter.porter.core.annotation.sth.PorterOfFun; import cn.xishan.oftenporter.porter.core.base.*; import cn.xishan.oftenporter.porter.core.exception.WCallException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * @author Created by https://github.com/CLovinr on 2018/5/12. */ public class DefaultArgumentsFactory implements IArgumentsFactory { interface ArgHandle { Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap); } static class WObjectArgHandle implements ArgHandle { @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { return wObject; } } static class NeceArgHandle implements ArgHandle { private InNames.Name name; private TypeParserStore typeParserStore; public NeceArgHandle(InNames.Name name, TypeParserStore typeParserStore) { this.name = name; this.typeParserStore = typeParserStore; } @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { Object v = optionArgMap.get(name); if (v == null) { v = DefaultParamDealt.getParam(name.varName, wObject.getParamSource(), typeParserStore.byId(name.typeParserId), name.getDealt()); if (v == null) { v = DefaultFailedReason.lackNecessaryParams("Lack necessary params!", name.varName); } } if (v != null && (v instanceof ParamDealt.FailedReason)) { ParamDealt.FailedReason failedReason = (ParamDealt.FailedReason) v; JResponse jResponse = new JResponse(ResultCode.PARAM_DEAL_EXCEPTION); jResponse.setExtra(failedReason.toJSON()); jResponse.setDescription(failedReason.desc()); throw new WCallException(jResponse); } return v; } } static class UneceArgHandle implements ArgHandle { private InNames.Name name; private TypeParserStore typeParserStore; public UneceArgHandle(InNames.Name name, TypeParserStore typeParserStore) { this.name = name; this.typeParserStore = typeParserStore; } @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { Object v = optionArgMap.get(name.varName); if (v == null) { v = DefaultParamDealt.getParam(name.varName, wObject.getParamSource(), typeParserStore.byId(name.typeParserId), name.getDealt()); } if (v instanceof ParamDealt.FailedReason) { ParamDealt.FailedReason failedReason = (ParamDealt.FailedReason) v; JResponse jResponse = new JResponse(ResultCode.PARAM_DEAL_EXCEPTION); jResponse.setExtra(failedReason.toJSON()); jResponse.setDescription(failedReason.desc()); throw new WCallException(jResponse); } return v; } } static class IArgsHandleImpl implements IArgsHandle { private ArgHandle[] argHandles; public IArgsHandleImpl(PorterOfFun porterOfFun, TypeParserStore typeParserStore) throws ClassNotFoundException { Method method = porterOfFun.getMethod(); Class<?>[] methodArgTypes = method.getParameterTypes(); Annotation[][] methodAnnotations = method.getParameterAnnotations(); Parameter[] parameters = method.getParameters(); List<ArgHandle> argHandleList = new ArrayList<>(); for (int i = 0; i < methodArgTypes.length; i++) { Class<?> type = methodArgTypes[i]; if (type.equals(WObject.class)) { argHandleList.add(new WObjectArgHandle()); continue; } Annotation[] annotations = methodAnnotations[i]; NeceParam neceParam = AnnoUtil.getAnnotation(annotations, NeceParam.class); UneceParam uneceParam = AnnoUtil.getAnnotation(annotations, UneceParam.class); String name = ""; if (neceParam != null) { name = neceParam.value(); } else if (uneceParam != null) { name = uneceParam.value(); } if (name.equals("")) { Parameter parameter = parameters[i]; name = parameter.getName(); } InNames.Name theName = porterOfFun.getPorter().getName(name, type); ArgHandle argHandle = neceParam != null ? new NeceArgHandle(theName, typeParserStore) : new UneceArgHandle(theName, typeParserStore); argHandleList.add(argHandle); } this.argHandles = argHandleList.toArray(new ArgHandle[0]); } @Override public Object[] getInvokeArgs(WObject wObject, Method method, Object[] args) { Map<String, Object> map; if (args.length == 0) { map = Collections.emptyMap(); } else { map = new HashMap<>(6); for (Object arg : args) { if (arg != null) { map.put(arg.getClass().getName(), arg); } } } Object[] newArgs = new Object[argHandles.length]; for (int i = 0; i < newArgs.length; i++) { newArgs[i] = argHandles[i].getArg(wObject, method, map); } return newArgs; } } private Map<PorterOfFun, IArgsHandle> handleMap = new ConcurrentHashMap<>(); public DefaultArgumentsFactory() { } @Override public void initArgsHandle(PorterOfFun porterOfFun, TypeParserStore typeParserStore) throws Exception { IArgsHandle handle = new IArgsHandleImpl(porterOfFun, typeParserStore); handleMap.put(porterOfFun, handle); } @Override public IArgsHandle getArgsHandle(PorterOfFun porterOfFun) throws Exception { IArgsHandle handle = handleMap.get(porterOfFun); return handle; } }
Porter-Core/src/main/java/cn/xishan/oftenporter/porter/simple/DefaultArgumentsFactory.java
package cn.xishan.oftenporter.porter.simple; import cn.xishan.oftenporter.porter.core.JResponse; import cn.xishan.oftenporter.porter.core.ResultCode; import cn.xishan.oftenporter.porter.core.annotation.NeceParam; import cn.xishan.oftenporter.porter.core.annotation.UneceParam; import cn.xishan.oftenporter.porter.core.annotation.deal.AnnoUtil; import cn.xishan.oftenporter.porter.core.annotation.sth.PorterOfFun; import cn.xishan.oftenporter.porter.core.base.*; import cn.xishan.oftenporter.porter.core.exception.WCallException; import cn.xishan.oftenporter.porter.core.util.ConcurrentKeyLock; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author Created by https://github.com/CLovinr on 2018/5/12. */ public class DefaultArgumentsFactory implements IArgumentsFactory { interface ArgHandle { Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap); } static class WObjectArgHandle implements ArgHandle { @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { return wObject; } } static class NeceArgHandle implements ArgHandle { private InNames.Name name; private TypeParserStore typeParserStore; public NeceArgHandle(InNames.Name name, TypeParserStore typeParserStore) { this.name = name; this.typeParserStore = typeParserStore; } @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { Object v = optionArgMap.get(name); if (v == null) { v = DefaultParamDealt.getParam(name.varName, wObject.getParamSource(), typeParserStore.byId(name.typeParserId), name.getDealt()); if (v == null) { v = DefaultFailedReason.lackNecessaryParams("Lack necessary params!", name.varName); } } if (v != null && (v instanceof ParamDealt.FailedReason)) { ParamDealt.FailedReason failedReason = (ParamDealt.FailedReason) v; JResponse jResponse = new JResponse(ResultCode.PARAM_DEAL_EXCEPTION); jResponse.setExtra(failedReason.toJSON()); jResponse.setDescription(failedReason.desc()); throw new WCallException(jResponse); } return v; } } static class UneceArgHandle implements ArgHandle { private InNames.Name name; private TypeParserStore typeParserStore; public UneceArgHandle(InNames.Name name, TypeParserStore typeParserStore) { this.name = name; this.typeParserStore = typeParserStore; } @Override public final Object getArg(WObject wObject, Method method, Map<String, Object> optionArgMap) { Object v = optionArgMap.get(name.varName); if (v == null) { v = DefaultParamDealt.getParam(name.varName, wObject.getParamSource(), typeParserStore.byId(name.typeParserId), name.getDealt()); } if (v instanceof ParamDealt.FailedReason) { ParamDealt.FailedReason failedReason = (ParamDealt.FailedReason) v; JResponse jResponse = new JResponse(ResultCode.PARAM_DEAL_EXCEPTION); jResponse.setExtra(failedReason.toJSON()); jResponse.setDescription(failedReason.desc()); throw new WCallException(jResponse); } return v; } } static class IArgsHandleImpl implements IArgsHandle { private ArgHandle[] argHandles; public IArgsHandleImpl(PorterOfFun porterOfFun, TypeParserStore typeParserStore) throws ClassNotFoundException { Method method = porterOfFun.getMethod(); Class<?>[] methodArgTypes = method.getParameterTypes(); Annotation[][] methodAnnotations = method.getParameterAnnotations(); Parameter[] parameters = method.getParameters(); List<ArgHandle> argHandleList = new ArrayList<>(); for (int i = 0; i < methodArgTypes.length; i++) { Class<?> type = methodArgTypes[i]; if (type.equals(WObject.class)) { argHandleList.add(new WObjectArgHandle()); continue; } Annotation[] annotations = methodAnnotations[i]; NeceParam neceParam = AnnoUtil.getAnnotation(annotations, NeceParam.class); UneceParam uneceParam = AnnoUtil.getAnnotation(annotations, UneceParam.class); String name = ""; if (neceParam != null) { name = neceParam.value(); } else if (uneceParam != null) { name = uneceParam.value(); } if (name.equals("")) { Parameter parameter = parameters[i]; name = parameter.getName(); } InNames.Name theName = porterOfFun.getPorter().getName(name, type); ArgHandle argHandle = neceParam != null ? new NeceArgHandle(theName, typeParserStore) : new UneceArgHandle(theName, typeParserStore); argHandleList.add(argHandle); } this.argHandles = argHandleList.toArray(new ArgHandle[0]); } @Override public Object[] getInvokeArgs(WObject wObject, Method method, Object[] args) { Map<String, Object> map = new HashMap<>(); for (Object arg : args) { if (arg != null) { map.put(arg.getClass().getName(), arg); } } Object[] newArgs = new Object[argHandles.length]; for (int i = 0; i < newArgs.length; i++) { newArgs[i] = argHandles[i].getArg(wObject, method, map); } return newArgs; } } private Map<PorterOfFun, IArgsHandle> handleMap = new ConcurrentHashMap<>(); private ConcurrentKeyLock<PorterOfFun> keyLock = new ConcurrentKeyLock<>(); public DefaultArgumentsFactory() { } @Override public void initArgsHandle(PorterOfFun porterOfFun, TypeParserStore typeParserStore) throws Exception { // IArgsHandle handle = handleMap.get(porterOfFun); // if (handle == null) // { // keyLock.lock(porterOfFun); // try // { // handle = handleMap.get(porterOfFun); // if (handle == null) // { // handle = new IArgsHandleImpl(porterOfFun, typeParserStore); // handleMap.put(porterOfFun, handle); // } // } finally // { // keyLock.unlock(porterOfFun); // } // } IArgsHandle handle = new IArgsHandleImpl(porterOfFun, typeParserStore); handleMap.put(porterOfFun, handle); } @Override public IArgsHandle getArgsHandle(PorterOfFun porterOfFun) throws Exception { IArgsHandle handle = handleMap.get(porterOfFun); return handle; } }
增加:IArgumentsFactory
Porter-Core/src/main/java/cn/xishan/oftenporter/porter/simple/DefaultArgumentsFactory.java
增加:IArgumentsFactory
Java
bsd-2-clause
51e951e4dc9229e963d00d048e766160fd77ccbb
0
runelite/runelite,runelite/runelite,runelite/runelite,Sethtroll/runelite,l2-/runelite,l2-/runelite,Sethtroll/runelite
/* * Copyright (c) 2018, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.attackstyles; import com.google.inject.Guice; import com.google.inject.testing.fieldbinder.Bind; import com.google.inject.testing.fieldbinder.BoundFieldModule; import java.util.Set; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.Skill; import net.runelite.api.VarPlayer; import net.runelite.api.Varbits; import net.runelite.api.events.WidgetHiddenChanged; import net.runelite.client.events.ConfigChanged; import net.runelite.api.events.VarbitChanged; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.ui.overlay.OverlayManager; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class AttackStylesPluginTest { @Mock @Bind Client client; @Mock @Bind OverlayManager overlayManager; @Mock @Bind AttackStylesConfig attackConfig; @Inject AttackStylesPlugin attackPlugin; @Before public void before() { Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this); } /* * Verify that red text is displayed when attacking with a style that gains experience * in one of the unwanted skills. */ @Test public void testWarning() { ConfigChanged warnForAttackEvent = new ConfigChanged(); warnForAttackEvent.setGroup("attackIndicator"); warnForAttackEvent.setKey("warnForAttack"); warnForAttackEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForAttackEvent); // Verify there is a warned skill Set<Skill> warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); // Set mock client to attack in style that gives attack xp when(client.getVar(VarPlayer.ATTACK_STYLE)).thenReturn(AttackStyle.ACCURATE.ordinal()); // verify that earning xp in a warned skill will display red text on the widget attackPlugin.onVarbitChanged(new VarbitChanged()); assertTrue(attackPlugin.isWarnedSkillSelected()); // Switch to attack style that doesn't give attack xp when(client.getVar(VarPlayer.ATTACK_STYLE)).thenReturn(AttackStyle.AGGRESSIVE.ordinal()); // Verify the widget will now display white text attackPlugin.onVarbitChanged(new VarbitChanged()); warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); assertFalse(attackPlugin.isWarnedSkillSelected()); } /* * Verify that attack style widgets are hidden when filtered with the AttackStylesPlugin. */ @Test public void testHiddenWidget() { ConfigChanged warnForAttackEvent = new ConfigChanged(); warnForAttackEvent.setGroup("attackIndicator"); warnForAttackEvent.setKey("warnForAttack"); warnForAttackEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForAttackEvent); // Set up mock widgets for atk and str attack styles Widget atkWidget = mock(Widget.class); Widget strWidget = mock(Widget.class); when(client.getWidget(WidgetInfo.COMBAT_STYLE_ONE)).thenReturn(atkWidget); when(client.getWidget(WidgetInfo.COMBAT_STYLE_TWO)).thenReturn(strWidget); // Set widgets to return their hidden value in widgetsToHide when isHidden() is called when(atkWidget.isHidden()).thenAnswer(x -> isAtkHidden()); when(strWidget.isHidden()).thenAnswer(x -> isStrHidden()); // equip type_4 weapon type on player when(client.getVar(Varbits.EQUIPPED_WEAPON_TYPE)).thenReturn(WeaponType.TYPE_4.ordinal()); attackPlugin.onVarbitChanged(new VarbitChanged()); // Verify there is a warned skill Set<Skill> warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); // Enable hiding widgets ConfigChanged hideWidgetEvent = new ConfigChanged(); hideWidgetEvent.setGroup("attackIndicator"); hideWidgetEvent.setKey("removeWarnedStyles"); hideWidgetEvent.setNewValue("true"); attackPlugin.onConfigChanged(hideWidgetEvent); when(attackConfig.removeWarnedStyles()).thenReturn(true); // verify that the accurate attack style widget is hidden assertTrue(atkWidget.isHidden()); // add another warned skill ConfigChanged warnForStrengthEvent = new ConfigChanged(); warnForStrengthEvent.setGroup("attackIndicator"); warnForStrengthEvent.setKey("warnForStrength"); warnForStrengthEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForStrengthEvent); // verify that the aggressive attack style widget is now hidden assertTrue(strWidget.isHidden()); // disable hiding attack style widgets hideWidgetEvent.setGroup("attackIndicator"); hideWidgetEvent.setKey("removeWarnedStyles"); hideWidgetEvent.setNewValue("false"); attackPlugin.onConfigChanged(hideWidgetEvent); // verify that the aggressive and accurate attack style widgets are no longer hidden assertFalse(attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_ONE)); assertFalse(attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_THREE)); } /* * Verify that the defensive style is hidden when switching from bludgeon to bow */ @Test public void testHiddenLongrange() { final ArgumentCaptor<Boolean> captor = ArgumentCaptor.forClass(Boolean.class); final ConfigChanged warnForAttackEvent = new ConfigChanged(); warnForAttackEvent.setGroup("attackIndicator"); warnForAttackEvent.setKey("warnForDefensive"); warnForAttackEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForAttackEvent); // verify there is a warned skill Set<Skill> warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.DEFENCE)); // Set up mock widget for strength and longrange final Widget widget = mock(Widget.class); when(client.getWidget(WidgetInfo.COMBAT_STYLE_FOUR)).thenReturn(widget); // Set up hidden changed event final WidgetHiddenChanged widgetHiddenChanged = new WidgetHiddenChanged(); widgetHiddenChanged.setWidget(widget); when(widget.getId()).thenReturn(WidgetInfo.COMBAT_STYLE_FOUR.getPackedId()); // Enable hiding widgets final ConfigChanged hideWidgetEvent = new ConfigChanged(); hideWidgetEvent.setGroup("attackIndicator"); hideWidgetEvent.setKey("removeWarnedStyles"); hideWidgetEvent.setNewValue("true"); attackPlugin.onConfigChanged(hideWidgetEvent); when(attackConfig.removeWarnedStyles()).thenReturn(true); // equip bludgeon on player when(client.getVar(Varbits.EQUIPPED_WEAPON_TYPE)).thenReturn(WeaponType.TYPE_26.ordinal()); attackPlugin.onVarbitChanged(new VarbitChanged()); attackPlugin.onWidgetHiddenChanged(widgetHiddenChanged); // verify that the agressive style style widget is showing verify(widget, atLeastOnce()).setHidden(captor.capture()); assertFalse(captor.getValue()); // equip bow on player // the equipped weaopn varbit will change after the hiddenChanged event has been dispatched attackPlugin.onWidgetHiddenChanged(widgetHiddenChanged); when(client.getVar(Varbits.EQUIPPED_WEAPON_TYPE)).thenReturn(WeaponType.TYPE_3.ordinal()); attackPlugin.onVarbitChanged(new VarbitChanged()); // verify that the longrange attack style widget is now hidden verify(widget, atLeastOnce()).setHidden(captor.capture()); assertTrue(captor.getValue()); } private boolean isAtkHidden() { if (attackPlugin.getHiddenWidgets().size() == 0) { return false; } return attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_ONE); } private boolean isStrHidden() { if (attackPlugin.getHiddenWidgets().size() == 0) { return false; } return attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_TWO); } }
runelite-client/src/test/java/net/runelite/client/plugins/attackstyles/AttackStylesPluginTest.java
/* * Copyright (c) 2018, Adam <Adam@sigterm.info> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.attackstyles; import com.google.inject.Guice; import com.google.inject.testing.fieldbinder.Bind; import com.google.inject.testing.fieldbinder.BoundFieldModule; import java.util.Set; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.Skill; import net.runelite.api.VarPlayer; import net.runelite.api.Varbits; import net.runelite.client.events.ConfigChanged; import net.runelite.api.events.VarbitChanged; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.ui.overlay.OverlayManager; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class AttackStylesPluginTest { @Mock @Bind Client client; @Mock @Bind OverlayManager overlayManager; @Mock @Bind AttackStylesConfig attackConfig; @Inject AttackStylesPlugin attackPlugin; @Before public void before() { Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this); } /* * Verify that red text is displayed when attacking with a style that gains experience * in one of the unwanted skills. */ @Test public void testWarning() { ConfigChanged warnForAttackEvent = new ConfigChanged(); warnForAttackEvent.setGroup("attackIndicator"); warnForAttackEvent.setKey("warnForAttack"); warnForAttackEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForAttackEvent); // Verify there is a warned skill Set<Skill> warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); // Set mock client to attack in style that gives attack xp when(client.getVar(VarPlayer.ATTACK_STYLE)).thenReturn(AttackStyle.ACCURATE.ordinal()); // verify that earning xp in a warned skill will display red text on the widget attackPlugin.onVarbitChanged(new VarbitChanged()); assertTrue(attackPlugin.isWarnedSkillSelected()); // Switch to attack style that doesn't give attack xp when(client.getVar(VarPlayer.ATTACK_STYLE)).thenReturn(AttackStyle.AGGRESSIVE.ordinal()); // Verify the widget will now display white text attackPlugin.onVarbitChanged(new VarbitChanged()); warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); assertFalse(attackPlugin.isWarnedSkillSelected()); } /* * Verify that attack style widgets are hidden when filtered with the AttackStylesPlugin. */ @Test public void testHiddenWidget() { ConfigChanged warnForAttackEvent = new ConfigChanged(); warnForAttackEvent.setGroup("attackIndicator"); warnForAttackEvent.setKey("warnForAttack"); warnForAttackEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForAttackEvent); // Set up mock widgets for atk and str attack styles Widget atkWidget = mock(Widget.class); Widget strWidget = mock(Widget.class); when(client.getWidget(WidgetInfo.COMBAT_STYLE_ONE)).thenReturn(atkWidget); when(client.getWidget(WidgetInfo.COMBAT_STYLE_TWO)).thenReturn(strWidget); // Set widgets to return their hidden value in widgetsToHide when isHidden() is called when(atkWidget.isHidden()).thenAnswer(x -> isAtkHidden()); when(strWidget.isHidden()).thenAnswer(x -> isStrHidden()); // equip type_4 weapon type on player when(client.getVar(Varbits.EQUIPPED_WEAPON_TYPE)).thenReturn(WeaponType.TYPE_4.ordinal()); attackPlugin.onVarbitChanged(new VarbitChanged()); // Verify there is a warned skill Set<Skill> warnedSkills = attackPlugin.getWarnedSkills(); assertTrue(warnedSkills.contains(Skill.ATTACK)); // Enable hiding widgets ConfigChanged hideWidgetEvent = new ConfigChanged(); hideWidgetEvent.setGroup("attackIndicator"); hideWidgetEvent.setKey("removeWarnedStyles"); hideWidgetEvent.setNewValue("true"); attackPlugin.onConfigChanged(hideWidgetEvent); when(attackConfig.removeWarnedStyles()).thenReturn(true); // verify that the accurate attack style widget is hidden assertTrue(atkWidget.isHidden()); // add another warned skill ConfigChanged warnForStrengthEvent = new ConfigChanged(); warnForStrengthEvent.setGroup("attackIndicator"); warnForStrengthEvent.setKey("warnForStrength"); warnForStrengthEvent.setNewValue("true"); attackPlugin.onConfigChanged(warnForStrengthEvent); // verify that the aggressive attack style widget is now hidden assertTrue(strWidget.isHidden()); // disable hiding attack style widgets hideWidgetEvent.setGroup("attackIndicator"); hideWidgetEvent.setKey("removeWarnedStyles"); hideWidgetEvent.setNewValue("false"); attackPlugin.onConfigChanged(hideWidgetEvent); // verify that the aggressive and accurate attack style widgets are no longer hidden assertFalse(attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_ONE)); assertFalse(attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_THREE)); } private boolean isAtkHidden() { if (attackPlugin.getHiddenWidgets().size() == 0) { return false; } return attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_ONE); } private boolean isStrHidden() { if (attackPlugin.getHiddenWidgets().size() == 0) { return false; } return attackPlugin.getHiddenWidgets().get(WeaponType.TYPE_4, WidgetInfo.COMBAT_STYLE_TWO); } }
attack styles: add test for swap between bludgeon and bow When swapping between bludgeon and bow, onWidgetHiddenChanged is called before the weapon varbit is set. Since that varbit determines which widgets should be hidden we would like to make sure the widget is set to hidden even after a varbit change.
runelite-client/src/test/java/net/runelite/client/plugins/attackstyles/AttackStylesPluginTest.java
attack styles: add test for swap between bludgeon and bow
Java
bsd-3-clause
42c00c69fd34f6f7fb87c1a2bb91055788851e57
0
hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Chilledheart/chromium,Chilledheart/chromium,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Chilledheart/chromium,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,hgl888/chromium-crosswalk
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome; /** * Contains all of the command line switches that are specific to the chrome/ * portion of Chromium on Android. */ public abstract class ChromeSwitches { // Switches used from Java. Please continue switch style used Chrome where // options-have-hypens and are_not_split_with_underscores. /** Testing: pretend that the switch value is the name of a child account. */ public static final String CHILD_ACCOUNT = "child-account"; /** Mimic a low end device */ public static final String ENABLE_ACCESSIBILITY_TAB_SWITCHER = "enable-accessibility-tab-switcher"; /** Whether fullscreen support is disabled (auto hiding controls, etc...). */ public static final String DISABLE_FULLSCREEN = "disable-fullscreen"; /** Show the undo bar for high end UI devices. */ public static final String ENABLE_HIGH_END_UI_UNDO = "enable-high-end-ui-undo"; /** Enable toolbar swipe to change tabs in document mode */ public static final String ENABLE_TOOLBAR_SWIPE_IN_DOCUMENT_MODE = "enable-toolbar-swipe-in-document-mode"; /** Whether instant is disabled. */ public static final String DISABLE_INSTANT = "disable-instant"; /** Enables StrictMode violation detection. By default this logs violations to logcat. */ public static final String STRICT_MODE = "strict-mode"; /** Don't restore persistent state from saved files on startup. */ public static final String NO_RESTORE_STATE = "no-restore-state"; /** Disable the First Run Experience. */ public static final String DISABLE_FIRST_RUN_EXPERIENCE = "disable-fre"; /** Force the crash dump to be uploaded regardless of preferences. */ public static final String FORCE_CRASH_DUMP_UPLOAD = "force-dump-upload"; /** Enable debug logs for the video casting feature. */ public static final String ENABLE_CAST_DEBUG_LOGS = "enable-cast-debug"; /** Prevent automatic reconnection to current Cast video when Chrome restarts. */ public static final String DISABLE_CAST_RECONNECTION = "disable-cast-reconnection"; /** Whether or not to enable the experimental tablet tab stack. */ public static final String ENABLE_TABLET_TAB_STACK = "enable-tablet-tab-stack"; /** Disables support for playing videos remotely via Android MediaRouter API. */ public static final String DISABLE_CAST = "disable-cast"; /** Never forward URL requests to external intents. */ public static final String DISABLE_EXTERNAL_INTENT_REQUESTS = "disable-external-intent-requests"; /** Disable document mode. */ public static final String DISABLE_DOCUMENT_MODE = "disable-document-mode"; /** Disable Contextual Search. */ public static final String DISABLE_CONTEXTUAL_SEARCH = "disable-contextual-search"; /** Enable Contextual Search. */ public static final String ENABLE_CONTEXTUAL_SEARCH = "enable-contextual-search"; /** Disable Contextual Search first-run flow, for testing. Not exposed to user. */ public static final String DISABLE_CONTEXTUAL_SEARCH_PROMO_FOR_TESTING = "disable-contextual-search-promo-for-testing"; /** Enable Contextual Search for instrumentation testing. Not exposed to user. */ public static final String ENABLE_CONTEXTUAL_SEARCH_FOR_TESTING = "enable-contextual-search-for-testing"; /** * Enable embedded mode so that embedded activity can be launched. */ public static final String ENABLE_EMBEDDED_MODE = "enable-embedded-mode"; // How many thumbnails should we allow in the cache (per tab stack)? public static final String THUMBNAILS = "thumbnails"; // How many "approximated" thumbnails should we allow in the cache // (per tab stack)? These take very low memory but have poor quality. public static final String APPROXIMATION_THUMBNAILS = "approximation-thumbnails"; /////////////////////////////////////////////////////////////////////////////////////////////// // Native Switches /////////////////////////////////////////////////////////////////////////////////////////////// /** * Sets the max number of render processes to use. * Native switch - content_switches::kRendererProcessLimit. */ public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit"; /** Enable begin frame scheduling. */ public static final String ENABLE_BEGIN_FRAME_SCHEDULING = "enable-begin-frame-scheduling"; /** * Enable enhanced bookmarks feature. * Native switch - switches::kEnhancedBookmarksExperiment */ public static final String ENABLE_ENHANCED_BOOKMARKS = "enhanced-bookmarks-experiment"; /** Enable the DOM Distiller. */ public static final String ENABLE_DOM_DISTILLER = "enable-dom-distiller"; /** Enable experimental web-platform features, such as Push Messaging. */ public static final String EXPERIMENTAL_WEB_PLAFTORM_FEATURES = "enable-experimental-web-platform-features"; /** Enable Reader Mode button animation. */ public static final String ENABLE_READER_MODE_BUTTON_ANIMATION = "enable-dom-distiller-button-animation"; /** Enable the native app banners. */ public static final String ENABLE_APP_INSTALL_ALERTS = "enable-app-install-alerts"; /** * Use sandbox Wallet environment for requestAutocomplete. * Native switch - autofill::switches::kWalletServiceUseSandbox. */ public static final String USE_SANDBOX_WALLET_ENVIRONMENT = "wallet-service-use-sandbox"; /** * Change Google base URL. * Native switch - switches::kGoogleBaseURL. */ public static final String GOOGLE_BASE_URL = "google-base-url"; /** * Use fake device for Media Stream to replace actual camera and microphone. * Native switch - switches::kUseFakeDeviceForMediaStream. */ public static final String USE_FAKE_DEVICE_FOR_MEDIA_STREAM = "use-fake-device-for-media-stream"; // Prevent instantiation. private ChromeSwitches() {} }
chrome/android/java/src/org/chromium/chrome/ChromeSwitches.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome; /** * Contains all of the command line switches that are specific to the chrome/ * portion of Chromium on Android. */ public abstract class ChromeSwitches { // Switches used from Java. Please continue switch style used Chrome where // options-have-hypens and are_not_split_with_underscores. /** Testing: pretend that the switch value is the name of a child account. */ public static final String CHILD_ACCOUNT = "child-account"; /** Mimic a low end device */ public static final String ENABLE_ACCESSIBILITY_TAB_SWITCHER = "enable-accessibility-tab-switcher"; /** Whether fullscreen support is disabled (auto hiding controls, etc...). */ public static final String DISABLE_FULLSCREEN = "disable-fullscreen"; /** Show the undo bar for high end UI devices. */ public static final String ENABLE_HIGH_END_UI_UNDO = "enable-high-end-ui-undo"; /** Enable toolbar swipe to change tabs in document mode */ public static final String ENABLE_TOOLBAR_SWIPE_IN_DOCUMENT_MODE = "enable-toolbar-swipe-in-document-mode"; /** Whether instant is disabled. */ public static final String DISABLE_INSTANT = "disable-instant"; /** Enables StrictMode violation detection. By default this logs violations to logcat. */ public static final String STRICT_MODE = "strict-mode"; /** Don't restore persistent state from saved files on startup. */ public static final String NO_RESTORE_STATE = "no-restore-state"; /** Disable the First Run Experience. */ public static final String DISABLE_FIRST_RUN_EXPERIENCE = "disable-fre"; /** Force the crash dump to be uploaded regardless of preferences. */ public static final String FORCE_CRASH_DUMP_UPLOAD = "force-dump-upload"; /** Enable debug logs for the video casting feature. */ public static final String ENABLE_CAST_DEBUG_LOGS = "enable-cast-debug"; /** Prevent automatic reconnection to current Cast video when Chrome restarts. */ public static final String DISABLE_CAST_RECONNECTION = "disable-cast-reconnection"; /** Whether or not to enable the experimental tablet tab stack. */ public static final String ENABLE_TABLET_TAB_STACK = "enable-tablet-tab-stack"; /** Disables support for playing videos remotely via Android MediaRouter API. */ public static final String DISABLE_CAST = "disable-cast"; /** Never forward URL requests to external intents. */ public static final String DISABLE_EXTERNAL_INTENT_REQUESTS = "disable-external-intent-requests"; /** Disable document mode. */ public static final String DISABLE_DOCUMENT_MODE = "disable-document-mode"; /** Disable Contextual Search. */ public static final String DISABLE_CONTEXTUAL_SEARCH = "disable-contextual-search"; /** Enable Contextual Search. */ public static final String ENABLE_CONTEXTUAL_SEARCH = "enable-contextual-search"; /** Disable Contextual Search first-run flow, for testing. Not exposed to user. */ public static final String DISABLE_CONTEXTUAL_SEARCH_PROMO_FOR_TESTING = "disable-contextual-search-promo-for-testing"; /** Enable Contextual Search for instrumentation testing. Not exposed to user. */ public static final String ENABLE_CONTEXTUAL_SEARCH_FOR_TESTING = "enable-contextual-search-for-testing"; // How many thumbnails should we allow in the cache (per tab stack)? public static final String THUMBNAILS = "thumbnails"; // How many "approximated" thumbnails should we allow in the cache // (per tab stack)? These take very low memory but have poor quality. public static final String APPROXIMATION_THUMBNAILS = "approximation-thumbnails"; /////////////////////////////////////////////////////////////////////////////////////////////// // Native Switches /////////////////////////////////////////////////////////////////////////////////////////////// /** * Sets the max number of render processes to use. * Native switch - content_switches::kRendererProcessLimit. */ public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit"; /** Enable begin frame scheduling. */ public static final String ENABLE_BEGIN_FRAME_SCHEDULING = "enable-begin-frame-scheduling"; /** * Enable enhanced bookmarks feature. * Native switch - switches::kEnhancedBookmarksExperiment */ public static final String ENABLE_ENHANCED_BOOKMARKS = "enhanced-bookmarks-experiment"; /** Enable the DOM Distiller. */ public static final String ENABLE_DOM_DISTILLER = "enable-dom-distiller"; /** Enable experimental web-platform features, such as Push Messaging. */ public static final String EXPERIMENTAL_WEB_PLAFTORM_FEATURES = "enable-experimental-web-platform-features"; /** Enable Reader Mode button animation. */ public static final String ENABLE_READER_MODE_BUTTON_ANIMATION = "enable-dom-distiller-button-animation"; /** Enable the native app banners. */ public static final String ENABLE_APP_INSTALL_ALERTS = "enable-app-install-alerts"; /** * Use sandbox Wallet environment for requestAutocomplete. * Native switch - autofill::switches::kWalletServiceUseSandbox. */ public static final String USE_SANDBOX_WALLET_ENVIRONMENT = "wallet-service-use-sandbox"; /** * Change Google base URL. * Native switch - switches::kGoogleBaseURL. */ public static final String GOOGLE_BASE_URL = "google-base-url"; /** * Use fake device for Media Stream to replace actual camera and microphone. * Native switch - switches::kUseFakeDeviceForMediaStream. */ public static final String USE_FAKE_DEVICE_FOR_MEDIA_STREAM = "use-fake-device-for-media-stream"; // Prevent instantiation. private ChromeSwitches() {} }
Add a commandline switch for embedded mode This CL adds a switch to ChromeSwitchers for feature enabling on android. BUG=482003 Review URL: https://codereview.chromium.org/1118393003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#328023}
chrome/android/java/src/org/chromium/chrome/ChromeSwitches.java
Add a commandline switch for embedded mode
Java
mit
ac2e957afe2028230f20e0b101cf657995249e29
0
CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab
/* * Copyright (c) 2010. M.I.T. All Rights Reserved * Licensed under the MIT license. Please see http://www.opensource.org/licenses/mit-license.php * or the license.txt file included in this distribution for the full text of the license. */ package org.xcolab.hooks.climatecolab; import com.ext.portlet.model.Contest; import com.ext.portlet.service.ContestLocalServiceUtil; import com.ext.portlet.service.ContestTypeLocalServiceUtil; import com.liferay.portal.kernel.events.Action; import com.liferay.portal.kernel.events.ActionException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.Theme; import com.liferay.portal.service.ThemeLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import org.xcolab.client.admin.enums.ConfigurationAttributeKey; import org.xcolab.client.members.MessagingClient; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EXTServicePreAction extends Action { private static final String COLLABORATORIUM_THEME_NAME = "climatecolab-theme"; private static final String THEME_TIMESTAMP_ATTRIBUTE = "THEME_TIMESTAMP"; private static final Log _log = LogFactoryUtil.getLog(EXTServicePreAction.class); @Override public void run(HttpServletRequest req, HttpServletResponse res) throws ActionException { ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY); Map<String, Object> vmVariables = (Map) req.getAttribute(WebKeys.VM_VARIABLES); if (vmVariables == null) { vmVariables = new HashMap<>(); } List<Theme> themes = ThemeLocalServiceUtil.getThemes(themeDisplay.getCompanyId()); String themeTimestamp = ""; for (Theme theme : themes) { if (theme.getName().equals(COLLABORATORIUM_THEME_NAME)) { themeTimestamp = String.valueOf(theme.getTimestamp()); } } vmVariables.put("unreadMessages", MessagingClient.getUnreadMessageCountForUser(themeDisplay.getUserId())); //Decide whether to show contest menu items try { vmVariables.put("_contest_pages", ContestTypeLocalServiceUtil.getActiveContestTypes()); } catch (SystemException e) { _log.error("Could not retrieve contest types to populate menu items", e); } vmVariables.put("_colab_name", ConfigurationAttributeKey.COLAB_NAME.getStringValue()); vmVariables.put("_colab_short_name", ConfigurationAttributeKey.COLAB_SHORT_NAME.getStringValue()); vmVariables.put("betaRibbonShow", ConfigurationAttributeKey.BETA_RIBBON_SHOW.getBooleanValue()); final boolean mitHeaderBarShow = ConfigurationAttributeKey.MIT_HEADER_BAR_SHOW .getBooleanValue(); vmVariables.put("mitHeaderBarShow", ConfigurationAttributeKey.MIT_HEADER_BAR_SHOW); if (mitHeaderBarShow) { vmVariables.put("mitHeaderBarLinkText", ConfigurationAttributeKey.MIT_HEADER_BAR_LINK_TEXT.getStringValue()); vmVariables.put("mitHeaderBarLinkUrl", ConfigurationAttributeKey.MIT_HEADER_BAR_LINK_URL.getStringValue()); } String contestIdStr = req.getParameter("_collab_paramcontestId"); if (contestIdStr != null) { try { Contest contest = ContestLocalServiceUtil.getContest(Long.parseLong(contestIdStr)); vmVariables.put("collab_contest", contest); } catch (NumberFormatException e) { _log.error("An exception has been thrown when trying to parse contest id " + contestIdStr); } catch (PortalException | SystemException e) { _log.error("An exception has been thrown when loading contest with id " + contestIdStr, e); } } vmVariables.put("themeTimestamp", themeTimestamp); req.setAttribute(WebKeys.VM_VARIABLES, vmVariables); req.setAttribute(THEME_TIMESTAMP_ATTRIBUTE, themeTimestamp); } }
hooks/climatecolab-hooks/src/main/java/org/xcolab/hooks/climatecolab/EXTServicePreAction.java
/* * Copyright (c) 2010. M.I.T. All Rights Reserved * Licensed under the MIT license. Please see http://www.opensource.org/licenses/mit-license.php * or the license.txt file included in this distribution for the full text of the license. */ package org.xcolab.hooks.climatecolab; import com.ext.portlet.model.Contest; import com.ext.portlet.service.ContestLocalServiceUtil; import com.ext.portlet.service.ContestTypeLocalServiceUtil; import com.liferay.portal.kernel.events.Action; import com.liferay.portal.kernel.events.ActionException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.Theme; import com.liferay.portal.service.ThemeLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import org.xcolab.client.admin.enums.ConfigurationAttributeKey; import org.xcolab.client.members.MessagingClient; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EXTServicePreAction extends Action { private static final String COLLABORATORIUM_THEME_NAME = "climatecolab-theme"; private static final String THEME_TIMESTAMP_ATTRIBUTE = "THEME_TIMESTAMP"; private static final Log _log = LogFactoryUtil.getLog(EXTServicePreAction.class); @Override public void run(HttpServletRequest req, HttpServletResponse res) throws ActionException { ThemeDisplay themeDisplay = (ThemeDisplay) req.getAttribute(WebKeys.THEME_DISPLAY); Map<String, Object> vmVariables = (Map) req.getAttribute(WebKeys.VM_VARIABLES); if (vmVariables == null) { vmVariables = new HashMap<>(); } List<Theme> themes = ThemeLocalServiceUtil.getThemes(themeDisplay.getCompanyId()); String themeTimestamp = ""; for (Theme theme : themes) { if (theme.getName().equals(COLLABORATORIUM_THEME_NAME)) { themeTimestamp = String.valueOf(theme.getTimestamp()); } } vmVariables.put("unreadMessages", MessagingClient.getUnreadMessageCountForUser(themeDisplay.getUserId())); //Decide whether to show contest menu items try { vmVariables.put("_contest_pages", ContestTypeLocalServiceUtil.getActiveContestTypes()); } catch (SystemException e) { _log.error("Could not retrieve contest types to populate menu items", e); } vmVariables.put("_colab_name", ConfigurationAttributeKey.COLAB_NAME.getStringValue()); vmVariables.put("_colab_short_name", ConfigurationAttributeKey.COLAB_SHORT_NAME.getStringValue()); vmVariables.put("betaRibbonShow", ConfigurationAttributeKey.MIT_HEADER_BAR_SHOW.getBooleanValue()); final boolean mitHeaderBarShow = ConfigurationAttributeKey.MIT_HEADER_BAR_SHOW .getBooleanValue(); vmVariables.put("mitHeaderBarShow", ConfigurationAttributeKey.MIT_HEADER_BAR_SHOW); if (mitHeaderBarShow) { vmVariables.put("mitHeaderBarLinkText", ConfigurationAttributeKey.MIT_HEADER_BAR_LINK_TEXT.getStringValue()); vmVariables.put("mitHeaderBarLinkUrl", ConfigurationAttributeKey.MIT_HEADER_BAR_LINK_URL.getStringValue()); } String contestIdStr = req.getParameter("_collab_paramcontestId"); if (contestIdStr != null) { try { Contest contest = ContestLocalServiceUtil.getContest(Long.parseLong(contestIdStr)); vmVariables.put("collab_contest", contest); } catch (NumberFormatException e) { _log.error("An exception has been thrown when trying to parse contest id " + contestIdStr); } catch (PortalException | SystemException e) { _log.error("An exception has been thrown when loading contest with id " + contestIdStr, e); } } vmVariables.put("themeTimestamp", themeTimestamp); req.setAttribute(WebKeys.VM_VARIABLES, vmVariables); req.setAttribute(THEME_TIMESTAMP_ATTRIBUTE, themeTimestamp); } }
[COLAB-1215] Fixed Beta ribbon
hooks/climatecolab-hooks/src/main/java/org/xcolab/hooks/climatecolab/EXTServicePreAction.java
[COLAB-1215] Fixed Beta ribbon
Java
mit
9d8d253259f045d02c0fe1c2310a965ed7565daf
0
tobiatesan/serleena-android,tobiatesan/serleena-android
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: SerleenaSQLiteDataSource.java * Package: com.kyloth.serleena.persistence.sqlite * Author: Filippo Sestini * Date: 2015-05-06 * * History: * Version Programmer Date Changes * 1.0.0 Filippo Sestini 2015-05-06 Creazione file e scrittura di codice * e documentazione in Javadoc. * 1.0.1 Tobia Tesan 2015-05-07 Aggiunta di getIJ * 1.0.2 Tobia Tesan 2015-05-07 Aggiunta di getPath * 1.0.3 Tobia Tesan 2015-05-10 Riscrittura di getForecast con GregorianCalendar */ package com.kyloth.serleena.persistence.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import com.kyloth.serleena.common.Checkpoint; import com.kyloth.serleena.common.CheckpointReachedTelemetryEvent; import com.kyloth.serleena.common.EmergencyContact; import com.kyloth.serleena.common.GeoPoint; import com.kyloth.serleena.common.HeartRateTelemetryEvent; import com.kyloth.serleena.common.IQuadrant; import com.kyloth.serleena.common.ImmutableList; import com.kyloth.serleena.common.ListAdapter; import com.kyloth.serleena.common.LocationTelemetryEvent; import com.kyloth.serleena.common.Quadrant; import com.kyloth.serleena.common.TelemetryEvent; import com.kyloth.serleena.common.UserPoint; import com.kyloth.serleena.persistence.IExperienceStorage; import com.kyloth.serleena.persistence.ITelemetryStorage; import com.kyloth.serleena.persistence.ITrackStorage; import com.kyloth.serleena.persistence.IWeatherStorage; import com.kyloth.serleena.persistence.WeatherForecastEnum; import java.io.File; import java.text.DateFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import static java.lang.Math.floor; /** * Classe concreta contenente l’implementazione del data source per l’accesso al * database SQLite dell’applicazione. * * @author Filippo Sestini <sestini.filippo@gmail.com> * @version 1.0.0 * @since 2015-05-06 */ public class SerleenaSQLiteDataSource implements ISerleenaSQLiteDataSource { final static int QUADRANT_LATSIZE = 10; final static int QUADRANT_LONGSIZE = 10; final static int TOT_LAT_QUADRANTS = 180 / QUADRANT_LATSIZE; final static int TOT_LONG_QUADRANTS = 360 / QUADRANT_LONGSIZE; final static String RASTER_PATH = "raster/"; SerleenaDatabase dbHelper; Context context; public SerleenaSQLiteDataSource(Context context, SerleenaDatabase dbHelper) { this.dbHelper = dbHelper; this.context = context; } /** * Ritorna il percorso del file per il quadrante i,j-esimo. * * @return Il path */ public static String getRasterPath(int i, int j) { return RASTER_PATH + i + "_" + j; } /** * Ritorna la coppia i,j che identifica il quadrante a cui appartiene un punto. * * @param p Il punto geografico * @return Un array int [2] di due punti i,j che identifica il quadrante. */ public static int[] getIJ(GeoPoint p) { assert(p.latitude() >= -90.0); assert(p.latitude() <= 90.0); assert(p.longitude() >= -180.0); assert(p.longitude() < 180.0); int ij[] = new int[2]; ij[0] = (int)(floor((p.latitude() + 90.0) / QUADRANT_LATSIZE)); assert(ij[0] < TOT_LAT_QUADRANTS); ij[1] = (int)(floor((p.longitude() + 180.0) / QUADRANT_LONGSIZE) % TOT_LONG_QUADRANTS); assert(ij[1] < TOT_LONG_QUADRANTS); return ij; } /** * Implementazione di ISerleenaSQLiteDataSource.getTracks(). * * Viene eseguita una query sul database per ottenere gli ID di tutti i * Percorsi associati all'Esperienza specificata, da cui vengono creati * rispettivi oggetti SQLiteDAOTrack. * * @param experience Esperienza di cui si vogliono ottenere i Percorsi. * @return Insieme enumerabile di Percorsi. */ @Override public Iterable<SQLiteDAOTrack> getTracks(SQLiteDAOExperience experience) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "track_experience = " + experience.id(); Cursor result = db.query(SerleenaDatabase.TABLE_TRACKS, new String[] { "track_id" }, where, null, null, null, null); ArrayList<SQLiteDAOTrack> list = new ArrayList<SQLiteDAOTrack>(); int columnIndex = result.getColumnIndexOrThrow("track_id"); while (result.moveToNext()) { int trackId = result.getInt(columnIndex); list.add(new SQLiteDAOTrack(getCheckpoints(trackId) ,trackId, this)); } result.close(); return list; } /** * Restituisce i checkpoint di un Percorso. * * @param trackId ID del percorso di cui si vogliono ottenere i Checkpoint. * @return Elenco di checkpoint del Percorso specificato. */ private ImmutableList<Checkpoint> getCheckpoints(int trackId) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "checkpoint_track = " + trackId; String orderBy = "checkpoint_num ASC"; Cursor result = db.query(SerleenaDatabase.TABLE_CHECKPOINTS, new String[] { "checkpoint_latitude", "checkpoint_longitude"}, where, null, null, null, orderBy); ArrayList<Checkpoint> list = new ArrayList<Checkpoint>(); int latIndex = result.getColumnIndexOrThrow("checkpoint_latitude"); int lonIndex = result.getColumnIndexOrThrow("checkpoint_longitude"); while (result.moveToNext()) { double lat = result.getDouble(latIndex); double lon = result.getDouble(lonIndex); list.add(new Checkpoint(lat, lon)); } result.close(); return new ListAdapter<Checkpoint>(list); } /** * Implementazione di ISerleenaSQLiteDataSource.getTelemetries(). * * Viene eseguita una query sul database per ottenere gli ID di tutti i * Tracciamenti associati al Percorso specificato, da cui vengono creati * rispettivi oggetti SQLiteDAOTelemetry. * * @param track Percorso di cui si vogliono ottenere i Tracciamenti. * @return Insieme enumerabile di Tracciamenti. */ @Override public Iterable<SQLiteDAOTelemetry> getTelemetries(SQLiteDAOTrack track) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "telem_track = " + track.id(); Cursor result = db.query(SerleenaDatabase.TABLE_TELEMETRIES, new String[] { "telem_id" }, where, null, null, null, null); ArrayList<SQLiteDAOTelemetry> list = new ArrayList<SQLiteDAOTelemetry>(); int columnIndex = result.getColumnIndexOrThrow("telem_id"); while (result.moveToNext()) { int telemId = result.getInt(columnIndex); Iterable<TelemetryEvent> events = getTelemetryEvents(telemId); list.add(new SQLiteDAOTelemetry(telemId, events)); } result.close(); return list; } /** * Implementazione di ISerleenaSQLiteDataSource.getUserPoints(). * * Viene eseguita una query sul database per ottenere i Punti Utente * associati all'Esperienza specificata. * * @param experience Esperienza di cui si vogliono ottenere i Punti Utente. * @return Insieme enumerabile di Punti Utente. */ @Override public Iterable<UserPoint> getUserPoints(SQLiteDAOExperience experience) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "userpoint_experience = " + experience.id(); Cursor result = db.query(SerleenaDatabase.TABLE_USER_POINTS, new String[] { "userpoint_x", "userpoint_y" }, where, null, null, null, null); int latIndex = result.getColumnIndexOrThrow("userpoint_x"); int lonIndex = result.getColumnIndexOrThrow("userpoint_y"); ArrayList<UserPoint> list = new ArrayList<>(); while (result.moveToNext()) { double latitude = result.getDouble(latIndex); double longitude = result.getDouble(lonIndex); list.add(new UserPoint(latitude, longitude)); } result.close(); return list; } /** * Implementazione di ISerleenaSQLiteDataSource.addUserPoint(). * * @param experience Esperienza a cui aggiungere il punto utente. * @param point Punto utente da aggiungere. */ @Override public void addUserPoint(SQLiteDAOExperience experience, UserPoint point) { ContentValues values = new ContentValues(); SQLiteDatabase db = dbHelper.getWritableDatabase(); values.put("userpoint_x", point.latitude()); values.put("userpoint_y", point.longitude()); values.put("userpoint_experience", experience.id()); db.insert(SerleenaDatabase.TABLE_USER_POINTS, null, values); } /** * Implementazione di ISerleenaSQLiteDataSource.createTelemetry(). * * @param events Eventi di tracciamento da cui costruire il Tracciamento. * @param track Percorso a cui associare il Tracciamento. */ @Override public void createTelemetry(Iterable<TelemetryEvent> events, SQLiteDAOTrack track) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("telem_track", track.id()); long newId = db.insert(SerleenaDatabase.TABLE_TELEMETRIES, null, values); for (TelemetryEvent event : events) { values = new ContentValues(); if (event instanceof LocationTelemetryEvent) { LocationTelemetryEvent eventl = (LocationTelemetryEvent) event; values.put("eventl_timestamp", eventl.timestamp()); values.put("eventl_latitude", eventl.location().latitude()); values.put("eventl_longitude", eventl.location().longitude()); values.put("eventl_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_LOCATION, null, values); } else if (event instanceof HeartRateTelemetryEvent) { HeartRateTelemetryEvent eventh = (HeartRateTelemetryEvent) event; values.put("eventhc_timestamp", eventh.timestamp()); values.put("eventhc_value", eventh.heartRate()); values.put("eventhc_type", SerleenaDatabase.EVENT_TYPE_HEARTRATE); values.put("eventhc_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, null, values); } else if (event instanceof CheckpointReachedTelemetryEvent) { CheckpointReachedTelemetryEvent eventc = (CheckpointReachedTelemetryEvent) event; values.put("eventhc_timestamp", eventc.timestamp()); values.put("eventhc_value", eventc.checkpointNumber()); values.put("eventhc_type", SerleenaDatabase.EVENT_TYPE_CHECKPOINT); values.put("eventhc_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, null, values); } } } /** * Implementazione di IPersistenceDataSource.getExperiences(). * * Ritorna un'enumerazione di tutte le Esperienze presenti nel database, * dietro interfaccia IExperienceStorage. * * @return Insieme enumerabile di Esperienze. * @see com.kyloth.serleena.persistence.IPersistenceDataSource */ @Override public Iterable<IExperienceStorage> getExperiences() { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor result = db.query(SerleenaDatabase.TABLE_EXPERIENCES, new String[] { "experience_id", "experience_name" }, null, null, null, null, null); int idIndex = result.getColumnIndexOrThrow("experience_id"); int nameIndex = result.getColumnIndexOrThrow("experience_name"); ArrayList<IExperienceStorage> list = new ArrayList<IExperienceStorage>(); while (result.moveToNext()) { int id = result.getInt(idIndex); String name = result.getString(nameIndex); list.add(new SQLiteDAOExperience(name, id, this)); } result.close(); return list; } /** * Implementazione di IPersistenceDataStorage.getWeatherInfo(). * * @param location Posizione geografica di cui si vogliono ottenere le * previsioni. * @param date Data di cui si vogliono ottenere le previsioni. * @return Previsioni metereologiche. */ @Override public IWeatherStorage getWeatherInfo(GeoPoint location, Date date) { if (date == null) return null; GregorianCalendar morning = new GregorianCalendar(); morning.setTime(date); morning.set(Calendar.HOUR_OF_DAY, 6); morning.set(Calendar.MINUTE, 0); morning.set(Calendar.SECOND, 0); morning.set(Calendar.MILLISECOND, 0); GregorianCalendar morningAfter = new GregorianCalendar(); morningAfter.setTime(date); morningAfter.set(Calendar.HOUR_OF_DAY, 6); morningAfter.set(Calendar.HOUR_OF_DAY, 6); morningAfter.set(Calendar.MINUTE, 0); morningAfter.set(Calendar.SECOND, 0); morningAfter.set(Calendar.MILLISECOND, 0); morningAfter.add(Calendar.HOUR_OF_DAY, 24); GregorianCalendar afternoon = new GregorianCalendar(); afternoon.setTime(date); afternoon.set(Calendar.HOUR_OF_DAY, 14); afternoon.set(Calendar.MINUTE, 0); afternoon.set(Calendar.SECOND, 0); afternoon.set(Calendar.MILLISECOND, 0); GregorianCalendar night = new GregorianCalendar(); night.setTime(date); night.set(Calendar.HOUR_OF_DAY, 21); night.set(Calendar.MINUTE, 0); night.set(Calendar.SECOND, 0); night.set(Calendar.MILLISECOND, 0); int morningStart = Math.round(morning.getTimeInMillis() / 1000); int morningEnd = Math.round(afternoon.getTimeInMillis() / 1000); int afternoonStart = Math.round(afternoon.getTimeInMillis() / 1000); int afternoonEnd = Math.round(night.getTimeInMillis() / 1000); int nightStart = Math.round(night.getTimeInMillis() / 1000); int nightEnd = Math.round(morningAfter.getTimeInMillis() / 1000); SimpleWeather morningWeather = getForecast(location, morningStart, morningEnd); SimpleWeather afternoonWeather = getForecast(location, afternoonStart, afternoonEnd); SimpleWeather nightWeather = getForecast(location, nightStart, nightEnd); if (morning != null && afternoon != null && night != null) { return new SQLiteDAOWeather(morningWeather.forecast(), afternoonWeather.forecast(), nightWeather.forecast(), morningWeather.temperature(), afternoonWeather.temperature(), nightWeather.temperature(), date); } return null; } /** * Restituisce il quadrante i cui limiti comprendono la posizione * geografica specificata. * * @param location Posizione geografica che ricade nei limiti del quadrante. * @return Oggetto IQuadrant. */ @Override public IQuadrant getQuadrant(GeoPoint location) { int[] ij = getIJ(location); assert(ij[0] < TOT_LAT_QUADRANTS); assert(ij[1] < TOT_LONG_QUADRANTS); String fileName = getRasterPath(ij[0], ij[1]); GeoPoint p1 = new GeoPoint(ij[0] * QUADRANT_LATSIZE, ij[1] * QUADRANT_LONGSIZE); GeoPoint p2 = new GeoPoint((ij[0] + 1) * QUADRANT_LATSIZE, (ij[1] + 1) * QUADRANT_LONGSIZE); Bitmap raster = null; File file = new File(context.getFilesDir(), fileName); if (file.exists()) raster = BitmapFactory.decodeFile(file.getAbsolutePath()); return new Quadrant(p1, p2, raster); } /** * Implementazione di IPersistenceDataSource.getContacts(). * * @param location Punto geografico del cui intorno si vogliono ottenere * i contatti di autorità locali. * @return Insieme enumerabile di contatti di emergenza. */ @Override public Iterable<EmergencyContact> getContacts(GeoPoint location) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ArrayList<EmergencyContact> list = new ArrayList<EmergencyContact>(); String where = "(contact_ne_corner_latitude + 90) <= " + (location.latitude() + 90) + " AND " + "(contact_ne_corner_longitude + 180) <= " + (location.longitude() + 180) + " AND " + "(contact_sw_corner_latitude + 90) >= " + (location.latitude() + 90) + " AND " + "(contact_sw_corner_longitude + 180) >= " + (location.longitude() + 180); Cursor result = db.query(SerleenaDatabase.TABLE_CONTACTS, new String[]{"contact_name", "contact_value"}, where, null, null, null, null); int nameIndex = result.getColumnIndexOrThrow("contact_name"); int valueIndex = result.getColumnIndexOrThrow("contact_value"); while (result.moveToNext()) { String name = result.getString(nameIndex); String value = result.getString(valueIndex); list.add(new EmergencyContact(name, value)); } result.close(); return list; } /** * Restituisce gli eventi di Tracciamento associati al Tracciamento con ID * specificato, memorizzati nel database SQLite. * * @param id ID del Tracciamento di cui si vogliono ottenere gli eventi. * @return Insieme enumerabile di eventi di Tracciamento. */ private Iterable<TelemetryEvent> getTelemetryEvents(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ArrayList<TelemetryEvent> list = new ArrayList<TelemetryEvent>(); String where = "eventhc_telem = " + id; Cursor result = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, new String[] { "eventhc_timestamp", "eventhc_value", "eventhc_type" }, where, null, null, null, null); int timestampIndex = result.getColumnIndexOrThrow("eventhc_timestamp"); int valueIndex = result.getColumnIndexOrThrow("eventhc_value"); int typeIndex = result.getColumnIndexOrThrow("eventhc_type"); while (result.moveToNext()) { int time = result.getInt(timestampIndex); int value = Integer.parseInt(result.getString(valueIndex)); String type = result.getString(typeIndex); TelemetryEvent event = null; switch (type) { case SerleenaDatabase.EVENT_TYPE_CHECKPOINT: event = new CheckpointReachedTelemetryEvent(time, value); break; case SerleenaDatabase.EVENT_TYPE_HEARTRATE: event = new HeartRateTelemetryEvent(time, value); break; default: /*throw new Exception();*/ } list.add(event); } where = "eventl_telem = " + id; result = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_LOCATION, new String[] { "eventl_timestamp", "eventl_latitude", "eventl_longitude" }, where, null, null, null, null); timestampIndex = result.getColumnIndexOrThrow("eventl_timestamp"); int latitudeIndex = result.getColumnIndexOrThrow("eventl_latitude"); int longitudeIndex = result.getColumnIndexOrThrow("eventl_longitude"); while (result.moveToNext()) { int time = result.getInt(timestampIndex); double latitude = result.getDouble(latitudeIndex); double longitude = result.getDouble(longitudeIndex); GeoPoint location = new GeoPoint(latitude, longitude); list.add(new LocationTelemetryEvent(time, location)); } result.close(); return list; } /** * Restituisce le previsioni, comprensive di condizione metereologica e * temperatura, per una posizione geografica e un intervallo di tempo * specificati. * * @param location Posizione geografica di cui si vogliono ottenere le * previsioni. * @param startTime Inizio dell'intervallo di tempo di cui si vogliono * ottenere le previsioni, in UNIX time. * @param endTime Fine dell'intervallo di tempo di cui si vogliono * ottenere le previsioni, in UNIX time. * @return Previsioni metereologiche. */ private SimpleWeather getForecast(GeoPoint location, int startTime, int endTime) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "weather_end >= " + startTime + " AND " + "weather_start <= " + endTime + " AND " + "(weather_ne_corner_latitude + 90) <= " + (location.latitude() + 90) + " AND " + "(weather_ne_corner_longitude + 180) <= " + (location.longitude() + 180) + " AND " + "(weather_sw_corner_latitude + 90) >= " + (location.latitude() + 90) + " AND " + "(weather_sw_corner_longitude + 180) >= " + (location.longitude() + 180); Cursor result = db.query(SerleenaDatabase.TABLE_WEATHER_FORECASTS, new String[] { "weather_condition", "weather_temperature" }, where, null, null, null, null); int conditionIndex = result.getColumnIndex("weather_condition"); int temperatureIndex = result.getColumnIndex("weather_temperature"); if (result.moveToNext()) { WeatherForecastEnum forecast = WeatherForecastEnum.values()[result.getInt(conditionIndex)]; int temperature = result.getInt(temperatureIndex); return new SimpleWeather(forecast, temperature); } else return null; } /** * Rappresenta una previsione metereologica in un istante di tempo, * comprensiva di condizione e temperatura previste. */ private class SimpleWeather { private WeatherForecastEnum forecast; private int temperature; public SimpleWeather(WeatherForecastEnum forecast, int temperature) { this.forecast = forecast; this.temperature = temperature; } public WeatherForecastEnum forecast() { return forecast; } public int temperature() { return temperature; } } }
serleena/app/src/main/java/com/kyloth/serleena/persistence/sqlite/SerleenaSQLiteDataSource.java
/////////////////////////////////////////////////////////////////////////////// // // This file is part of Serleena. // // The MIT License (MIT) // // Copyright (C) 2015 Antonio Cavestro, Gabriele Pozzan, Matteo Lisotto, // Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // /////////////////////////////////////////////////////////////////////////////// /** * Name: SerleenaSQLiteDataSource.java * Package: com.kyloth.serleena.persistence.sqlite * Author: Filippo Sestini * Date: 2015-05-06 * * History: * Version Programmer Date Changes * 1.0.0 Filippo Sestini 2015-05-06 Creazione file e scrittura di codice * e documentazione in Javadoc. * 1.0.1 Tobia Tesan 2015-05-07 Aggiunta di getIJ * 1.0.2 Tobia Tesan 2015-05-07 Aggiunta di getPath * 1.0.3 Tobia Tesan 2015-05-10 Riscrittura di getForecast con GregorianCalendar */ package com.kyloth.serleena.persistence.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import com.kyloth.serleena.common.Checkpoint; import com.kyloth.serleena.common.CheckpointReachedTelemetryEvent; import com.kyloth.serleena.common.EmergencyContact; import com.kyloth.serleena.common.GeoPoint; import com.kyloth.serleena.common.HeartRateTelemetryEvent; import com.kyloth.serleena.common.IQuadrant; import com.kyloth.serleena.common.ImmutableList; import com.kyloth.serleena.common.ListAdapter; import com.kyloth.serleena.common.LocationTelemetryEvent; import com.kyloth.serleena.common.Quadrant; import com.kyloth.serleena.common.TelemetryEvent; import com.kyloth.serleena.common.UserPoint; import com.kyloth.serleena.persistence.IExperienceStorage; import com.kyloth.serleena.persistence.ITelemetryStorage; import com.kyloth.serleena.persistence.ITrackStorage; import com.kyloth.serleena.persistence.IWeatherStorage; import com.kyloth.serleena.persistence.WeatherForecastEnum; import java.io.File; import java.text.DateFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import static java.lang.Math.floor; /** * Classe concreta contenente l’implementazione del data source per l’accesso al * database SQLite dell’applicazione. * * @author Filippo Sestini <sestini.filippo@gmail.com> * @version 1.0.0 * @since 2015-05-06 */ public class SerleenaSQLiteDataSource implements ISerleenaSQLiteDataSource { final static int QUADRANT_LATSIZE = 10; final static int QUADRANT_LONGSIZE = 10; final static int TOT_LAT_QUADRANTS = 360 / QUADRANT_LATSIZE; final static int TOT_LONG_QUADRANTS = 180 / QUADRANT_LONGSIZE; final static String RASTER_PATH = "raster/"; SerleenaDatabase dbHelper; Context context; public SerleenaSQLiteDataSource(Context context, SerleenaDatabase dbHelper) { this.dbHelper = dbHelper; this.context = context; } /** * Ritorna il percorso del file per il quadrante i,j-esimo. * * @return Il path */ public static String getRasterPath(int i, int j) { return RASTER_PATH + i + "_" + j; } /** * Ritorna la coppia i,j che identifica il quadrante a cui appartiene un punto. * * @param p Il punto geografico * @return Un array int [2] di due punti i,j che identifica il quadrante. */ public static int[] getIJ(GeoPoint p) { assert(p.latitude() >= -90.0); assert(p.latitude() <= 90.0); assert(p.longitude() >= -180.0); assert(p.longitude() < 180.0); int ij[] = new int[2]; ij[0] = (int)(floor((p.latitude() + 90.0) / QUADRANT_LATSIZE)); assert(ij[0] < TOT_LAT_QUADRANTS); ij[1] = (int)(floor((p.longitude() + 180.0) / QUADRANT_LONGSIZE) % TOT_LONG_QUADRANTS); assert(ij[1] < TOT_LONG_QUADRANTS); return ij; } /** * Implementazione di ISerleenaSQLiteDataSource.getTracks(). * * Viene eseguita una query sul database per ottenere gli ID di tutti i * Percorsi associati all'Esperienza specificata, da cui vengono creati * rispettivi oggetti SQLiteDAOTrack. * * @param experience Esperienza di cui si vogliono ottenere i Percorsi. * @return Insieme enumerabile di Percorsi. */ @Override public Iterable<SQLiteDAOTrack> getTracks(SQLiteDAOExperience experience) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "track_experience = " + experience.id(); Cursor result = db.query(SerleenaDatabase.TABLE_TRACKS, new String[] { "track_id" }, where, null, null, null, null); ArrayList<SQLiteDAOTrack> list = new ArrayList<SQLiteDAOTrack>(); int columnIndex = result.getColumnIndexOrThrow("track_id"); while (result.moveToNext()) { int trackId = result.getInt(columnIndex); list.add(new SQLiteDAOTrack(getCheckpoints(trackId) ,trackId, this)); } result.close(); return list; } /** * Restituisce i checkpoint di un Percorso. * * @param trackId ID del percorso di cui si vogliono ottenere i Checkpoint. * @return Elenco di checkpoint del Percorso specificato. */ private ImmutableList<Checkpoint> getCheckpoints(int trackId) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "checkpoint_track = " + trackId; String orderBy = "checkpoint_num ASC"; Cursor result = db.query(SerleenaDatabase.TABLE_CHECKPOINTS, new String[] { "checkpoint_latitude", "checkpoint_longitude"}, where, null, null, null, orderBy); ArrayList<Checkpoint> list = new ArrayList<Checkpoint>(); int latIndex = result.getColumnIndexOrThrow("checkpoint_latitude"); int lonIndex = result.getColumnIndexOrThrow("checkpoint_longitude"); while (result.moveToNext()) { double lat = result.getDouble(latIndex); double lon = result.getDouble(lonIndex); list.add(new Checkpoint(lat, lon)); } result.close(); return new ListAdapter<Checkpoint>(list); } /** * Implementazione di ISerleenaSQLiteDataSource.getTelemetries(). * * Viene eseguita una query sul database per ottenere gli ID di tutti i * Tracciamenti associati al Percorso specificato, da cui vengono creati * rispettivi oggetti SQLiteDAOTelemetry. * * @param track Percorso di cui si vogliono ottenere i Tracciamenti. * @return Insieme enumerabile di Tracciamenti. */ @Override public Iterable<SQLiteDAOTelemetry> getTelemetries(SQLiteDAOTrack track) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "telem_track = " + track.id(); Cursor result = db.query(SerleenaDatabase.TABLE_TELEMETRIES, new String[] { "telem_id" }, where, null, null, null, null); ArrayList<SQLiteDAOTelemetry> list = new ArrayList<SQLiteDAOTelemetry>(); int columnIndex = result.getColumnIndexOrThrow("telem_id"); while (result.moveToNext()) { int telemId = result.getInt(columnIndex); Iterable<TelemetryEvent> events = getTelemetryEvents(telemId); list.add(new SQLiteDAOTelemetry(telemId, events)); } result.close(); return list; } /** * Implementazione di ISerleenaSQLiteDataSource.getUserPoints(). * * Viene eseguita una query sul database per ottenere i Punti Utente * associati all'Esperienza specificata. * * @param experience Esperienza di cui si vogliono ottenere i Punti Utente. * @return Insieme enumerabile di Punti Utente. */ @Override public Iterable<UserPoint> getUserPoints(SQLiteDAOExperience experience) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "userpoint_experience = " + experience.id(); Cursor result = db.query(SerleenaDatabase.TABLE_USER_POINTS, new String[] { "userpoint_x", "userpoint_y" }, where, null, null, null, null); int latIndex = result.getColumnIndexOrThrow("userpoint_x"); int lonIndex = result.getColumnIndexOrThrow("userpoint_y"); ArrayList<UserPoint> list = new ArrayList<>(); while (result.moveToNext()) { double latitude = result.getDouble(latIndex); double longitude = result.getDouble(lonIndex); list.add(new UserPoint(latitude, longitude)); } result.close(); return list; } /** * Implementazione di ISerleenaSQLiteDataSource.addUserPoint(). * * @param experience Esperienza a cui aggiungere il punto utente. * @param point Punto utente da aggiungere. */ @Override public void addUserPoint(SQLiteDAOExperience experience, UserPoint point) { ContentValues values = new ContentValues(); SQLiteDatabase db = dbHelper.getWritableDatabase(); values.put("userpoint_x", point.latitude()); values.put("userpoint_y", point.longitude()); values.put("userpoint_experience", experience.id()); db.insert(SerleenaDatabase.TABLE_USER_POINTS, null, values); } /** * Implementazione di ISerleenaSQLiteDataSource.createTelemetry(). * * @param events Eventi di tracciamento da cui costruire il Tracciamento. * @param track Percorso a cui associare il Tracciamento. */ @Override public void createTelemetry(Iterable<TelemetryEvent> events, SQLiteDAOTrack track) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("telem_track", track.id()); long newId = db.insert(SerleenaDatabase.TABLE_TELEMETRIES, null, values); for (TelemetryEvent event : events) { values = new ContentValues(); if (event instanceof LocationTelemetryEvent) { LocationTelemetryEvent eventl = (LocationTelemetryEvent) event; values.put("eventl_timestamp", eventl.timestamp()); values.put("eventl_latitude", eventl.location().latitude()); values.put("eventl_longitude", eventl.location().longitude()); values.put("eventl_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_LOCATION, null, values); } else if (event instanceof HeartRateTelemetryEvent) { HeartRateTelemetryEvent eventh = (HeartRateTelemetryEvent) event; values.put("eventhc_timestamp", eventh.timestamp()); values.put("eventhc_value", eventh.heartRate()); values.put("eventhc_type", SerleenaDatabase.EVENT_TYPE_HEARTRATE); values.put("eventhc_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, null, values); } else if (event instanceof CheckpointReachedTelemetryEvent) { CheckpointReachedTelemetryEvent eventc = (CheckpointReachedTelemetryEvent) event; values.put("eventhc_timestamp", eventc.timestamp()); values.put("eventhc_value", eventc.checkpointNumber()); values.put("eventhc_type", SerleenaDatabase.EVENT_TYPE_CHECKPOINT); values.put("eventhc_telem", newId); db.insert(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, null, values); } } } /** * Implementazione di IPersistenceDataSource.getExperiences(). * * Ritorna un'enumerazione di tutte le Esperienze presenti nel database, * dietro interfaccia IExperienceStorage. * * @return Insieme enumerabile di Esperienze. * @see com.kyloth.serleena.persistence.IPersistenceDataSource */ @Override public Iterable<IExperienceStorage> getExperiences() { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor result = db.query(SerleenaDatabase.TABLE_EXPERIENCES, new String[] { "experience_id", "experience_name" }, null, null, null, null, null); int idIndex = result.getColumnIndexOrThrow("experience_id"); int nameIndex = result.getColumnIndexOrThrow("experience_name"); ArrayList<IExperienceStorage> list = new ArrayList<IExperienceStorage>(); while (result.moveToNext()) { int id = result.getInt(idIndex); String name = result.getString(nameIndex); list.add(new SQLiteDAOExperience(name, id, this)); } result.close(); return list; } /** * Implementazione di IPersistenceDataStorage.getWeatherInfo(). * * @param location Posizione geografica di cui si vogliono ottenere le * previsioni. * @param date Data di cui si vogliono ottenere le previsioni. * @return Previsioni metereologiche. */ @Override public IWeatherStorage getWeatherInfo(GeoPoint location, Date date) { if (date == null) return null; GregorianCalendar morning = new GregorianCalendar(); morning.setTime(date); morning.set(Calendar.HOUR_OF_DAY, 6); morning.set(Calendar.MINUTE, 0); morning.set(Calendar.SECOND, 0); morning.set(Calendar.MILLISECOND, 0); GregorianCalendar morningAfter = new GregorianCalendar(); morningAfter.setTime(date); morningAfter.set(Calendar.HOUR_OF_DAY, 6); morningAfter.set(Calendar.HOUR_OF_DAY, 6); morningAfter.set(Calendar.MINUTE, 0); morningAfter.set(Calendar.SECOND, 0); morningAfter.set(Calendar.MILLISECOND, 0); morningAfter.add(Calendar.HOUR_OF_DAY, 24); GregorianCalendar afternoon = new GregorianCalendar(); afternoon.setTime(date); afternoon.set(Calendar.HOUR_OF_DAY, 14); afternoon.set(Calendar.MINUTE, 0); afternoon.set(Calendar.SECOND, 0); afternoon.set(Calendar.MILLISECOND, 0); GregorianCalendar night = new GregorianCalendar(); night.setTime(date); night.set(Calendar.HOUR_OF_DAY, 21); night.set(Calendar.MINUTE, 0); night.set(Calendar.SECOND, 0); night.set(Calendar.MILLISECOND, 0); int morningStart = Math.round(morning.getTimeInMillis() / 1000); int morningEnd = Math.round(afternoon.getTimeInMillis() / 1000); int afternoonStart = Math.round(afternoon.getTimeInMillis() / 1000); int afternoonEnd = Math.round(night.getTimeInMillis() / 1000); int nightStart = Math.round(night.getTimeInMillis() / 1000); int nightEnd = Math.round(morningAfter.getTimeInMillis() / 1000); SimpleWeather morningWeather = getForecast(location, morningStart, morningEnd); SimpleWeather afternoonWeather = getForecast(location, afternoonStart, afternoonEnd); SimpleWeather nightWeather = getForecast(location, nightStart, nightEnd); if (morning != null && afternoon != null && night != null) { return new SQLiteDAOWeather(morningWeather.forecast(), afternoonWeather.forecast(), nightWeather.forecast(), morningWeather.temperature(), afternoonWeather.temperature(), nightWeather.temperature(), date); } return null; } /** * Restituisce il quadrante i cui limiti comprendono la posizione * geografica specificata. * * @param location Posizione geografica che ricade nei limiti del quadrante. * @return Oggetto IQuadrant. */ @Override public IQuadrant getQuadrant(GeoPoint location) { int[] ij = getIJ(location); assert(ij[0] < TOT_LAT_QUADRANTS); assert(ij[1] < TOT_LONG_QUADRANTS); String fileName = getRasterPath(ij[0], ij[1]); GeoPoint p1 = new GeoPoint(ij[0] * QUADRANT_LATSIZE, ij[1] * QUADRANT_LONGSIZE); GeoPoint p2 = new GeoPoint((ij[0] + 1) * QUADRANT_LATSIZE, (ij[1] + 1) * QUADRANT_LONGSIZE); Bitmap raster = null; File file = new File(context.getFilesDir(), fileName); if (file.exists()) raster = BitmapFactory.decodeFile(file.getAbsolutePath()); return new Quadrant(p1, p2, raster); } /** * Implementazione di IPersistenceDataSource.getContacts(). * * @param location Punto geografico del cui intorno si vogliono ottenere * i contatti di autorità locali. * @return Insieme enumerabile di contatti di emergenza. */ @Override public Iterable<EmergencyContact> getContacts(GeoPoint location) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ArrayList<EmergencyContact> list = new ArrayList<EmergencyContact>(); String where = "(contact_ne_corner_latitude + 90) <= " + (location.latitude() + 90) + " AND " + "(contact_ne_corner_longitude + 180) <= " + (location.longitude() + 180) + " AND " + "(contact_sw_corner_latitude + 90) >= " + (location.latitude() + 90) + " AND " + "(contact_sw_corner_longitude + 180) >= " + (location.longitude() + 180); Cursor result = db.query(SerleenaDatabase.TABLE_CONTACTS, new String[]{"contact_name", "contact_value"}, where, null, null, null, null); int nameIndex = result.getColumnIndexOrThrow("contact_name"); int valueIndex = result.getColumnIndexOrThrow("contact_value"); while (result.moveToNext()) { String name = result.getString(nameIndex); String value = result.getString(valueIndex); list.add(new EmergencyContact(name, value)); } result.close(); return list; } /** * Restituisce gli eventi di Tracciamento associati al Tracciamento con ID * specificato, memorizzati nel database SQLite. * * @param id ID del Tracciamento di cui si vogliono ottenere gli eventi. * @return Insieme enumerabile di eventi di Tracciamento. */ private Iterable<TelemetryEvent> getTelemetryEvents(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); ArrayList<TelemetryEvent> list = new ArrayList<TelemetryEvent>(); String where = "eventhc_telem = " + id; Cursor result = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_HEART_CHECKP, new String[] { "eventhc_timestamp", "eventhc_value", "eventhc_type" }, where, null, null, null, null); int timestampIndex = result.getColumnIndexOrThrow("eventhc_timestamp"); int valueIndex = result.getColumnIndexOrThrow("eventhc_value"); int typeIndex = result.getColumnIndexOrThrow("eventhc_type"); while (result.moveToNext()) { int time = result.getInt(timestampIndex); int value = Integer.parseInt(result.getString(valueIndex)); String type = result.getString(typeIndex); TelemetryEvent event = null; switch (type) { case SerleenaDatabase.EVENT_TYPE_CHECKPOINT: event = new CheckpointReachedTelemetryEvent(time, value); break; case SerleenaDatabase.EVENT_TYPE_HEARTRATE: event = new HeartRateTelemetryEvent(time, value); break; default: /*throw new Exception();*/ } list.add(event); } where = "eventl_telem = " + id; result = db.query(SerleenaDatabase.TABLE_TELEM_EVENTS_LOCATION, new String[] { "eventl_timestamp", "eventl_latitude", "eventl_longitude" }, where, null, null, null, null); timestampIndex = result.getColumnIndexOrThrow("eventl_timestamp"); int latitudeIndex = result.getColumnIndexOrThrow("eventl_latitude"); int longitudeIndex = result.getColumnIndexOrThrow("eventl_longitude"); while (result.moveToNext()) { int time = result.getInt(timestampIndex); double latitude = result.getDouble(latitudeIndex); double longitude = result.getDouble(longitudeIndex); GeoPoint location = new GeoPoint(latitude, longitude); list.add(new LocationTelemetryEvent(time, location)); } result.close(); return list; } /** * Restituisce le previsioni, comprensive di condizione metereologica e * temperatura, per una posizione geografica e un intervallo di tempo * specificati. * * @param location Posizione geografica di cui si vogliono ottenere le * previsioni. * @param startTime Inizio dell'intervallo di tempo di cui si vogliono * ottenere le previsioni, in UNIX time. * @param endTime Fine dell'intervallo di tempo di cui si vogliono * ottenere le previsioni, in UNIX time. * @return Previsioni metereologiche. */ private SimpleWeather getForecast(GeoPoint location, int startTime, int endTime) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String where = "weather_end >= " + startTime + " AND " + "weather_start <= " + endTime + " AND " + "(weather_ne_corner_latitude + 90) <= " + (location.latitude() + 90) + " AND " + "(weather_ne_corner_longitude + 180) <= " + (location.longitude() + 180) + " AND " + "(weather_sw_corner_latitude + 90) >= " + (location.latitude() + 90) + " AND " + "(weather_sw_corner_longitude + 180) >= " + (location.longitude() + 180); Cursor result = db.query(SerleenaDatabase.TABLE_WEATHER_FORECASTS, new String[] { "weather_condition", "weather_temperature" }, where, null, null, null, null); int conditionIndex = result.getColumnIndex("weather_condition"); int temperatureIndex = result.getColumnIndex("weather_temperature"); if (result.moveToNext()) { WeatherForecastEnum forecast = WeatherForecastEnum.values()[result.getInt(conditionIndex)]; int temperature = result.getInt(temperatureIndex); return new SimpleWeather(forecast, temperature); } else return null; } /** * Rappresenta una previsione metereologica in un istante di tempo, * comprensiva di condizione e temperatura previste. */ private class SimpleWeather { private WeatherForecastEnum forecast; private int temperature; public SimpleWeather(WeatherForecastEnum forecast, int temperature) { this.forecast = forecast; this.temperature = temperature; } public WeatherForecastEnum forecast() { return forecast; } public int temperature() { return temperature; } } }
SQLITE: Correggi k quadranti
serleena/app/src/main/java/com/kyloth/serleena/persistence/sqlite/SerleenaSQLiteDataSource.java
SQLITE: Correggi k quadranti
Java
epl-1.0
4b05f56ecb5a7be22746a157a989fa7125126bd9
0
sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2007, 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.birt.chart.aggregate.IAggregateFunction; import org.eclipse.birt.chart.api.ChartEngine; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.DataType; import org.eclipse.birt.chart.model.attribute.GroupingUnitType; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.SeriesGrouping; import org.eclipse.birt.chart.model.impl.ChartModelHelper; import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.chart.util.PluginSettings; import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionCodec; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.data.engine.api.ISortDefinition; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.api.aggregation.AggregationManager; import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction; import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn; import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SortDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.emf.common.util.EList; import com.ibm.icu.util.ULocale; /** * The class defines basic functions for creating base query. * * @since BIRT 2.3 */ public abstract class AbstractChartBaseQueryGenerator { /** The handle of report item handle. */ protected ReportItemHandle fReportItemHandle; /** Current chart handle. */ protected Chart fChartModel; /** The set stores created binding names. */ protected Set<String> fNameSet = new HashSet<String>( ); /** * This attribute indicates whether new binding will be created for complex * expression or subquery */ protected final boolean bCreateBindingForExpression; protected final ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); protected final IModelAdapter modelAdapter; /** * Constructor of the class. * * @param chart * @param handle */ public AbstractChartBaseQueryGenerator( ReportItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { this( handle, cm, false, modelAdapter ); } /** * * @param handle * @param cm * @param bCreateBindingForExpression * indicates if query definition should create a new binding for * the complex expression or subquery. If current query * definition is subquery, true then always create a new binding. * If not subquery and the expression is simply a binding name, * always do not add the new binding. */ public AbstractChartBaseQueryGenerator( ReportItemHandle handle, Chart cm, boolean bCreateBindingForExpression, IModelAdapter modelAdapter ) { fChartModel = cm; fReportItemHandle = handle; this.bCreateBindingForExpression = bCreateBindingForExpression; this.modelAdapter = modelAdapter; } /** * Create base query definition. * * @param parent * @throws ChartException */ public abstract IDataQueryDefinition createBaseQuery( IDataQueryDefinition parent ) throws ChartException; /** * Create base query definition. * * @param columns * @throws ChartException */ public abstract IDataQueryDefinition createBaseQuery( List<String> columns ) throws ChartException; /** * Add aggregate bindings of value series for grouping case. * * @param query * @param seriesDefinitions * @param innerMostGroupDef * @param valueExprMap * @param baseSD * @throws ChartException */ protected void addValueSeriesAggregateBindingForGrouping( BaseQueryDefinition query, EList<SeriesDefinition> seriesDefinitions, GroupDefinition innerMostGroupDef, Map<String, String[]> valueExprMap, SeriesDefinition baseSD ) throws ChartException { for ( SeriesDefinition orthSD : seriesDefinitions ) { Series series = orthSD.getDesignTimeSeries( ); // The qlist contains available expressions which have aggregation. List<Query> qlist = ChartEngine.instance( ) .getDataSetProcessor( series.getClass( ) ) .getDataDefinitionsForGrouping( series ); for ( Query qry : series.getDataDefinition( ) ) { String expr = qry.getDefinition( ); if ( expr == null || "".equals( expr ) ) //$NON-NLS-1$ { continue; } String aggName = ChartUtil.getAggregateFuncExpr( orthSD, baseSD, qry ); if ( aggName == null ) { if ( !bCreateBindingForExpression || exprCodec.isRowBinding( expr, false ) ) { // If it's complex expression, still create new binding continue; } } // Get a unique name. String name = ChartUtil.generateBindingNameOfValueSeries( qry, orthSD, baseSD ); if ( fNameSet.contains( name ) ) { continue; } fNameSet.add( name ); Binding colBinding = new Binding( name ); colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); if ( qlist.contains( qry ) ) { try { colBinding.setExportable( false ); if ( aggName != null ) { // Set binding expression by different aggregation, // some aggregations can't set expression, like // Count and so on. setBindingExpressionDueToAggregation( colBinding, expr, aggName ); if ( innerMostGroupDef != null ) { colBinding.addAggregateOn( innerMostGroupDef.getName( ) ); } // Set aggregate parameters. colBinding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggName ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggName ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = ChartUtil.getAggFunParameters( orthSD, baseSD, qry ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; colBinding.addArgument( new ScriptExpression( param ) ); } } } else { // Direct setting expression for simple expression // case. exprCodec.decode( expr ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } catch ( DataException e1 ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e1 ); } } else { // Direct setting expression for non-aggregation case. exprCodec.decode( expr ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } String newExpr = getExpressionForEvaluator( name ); try { query.addBinding( colBinding ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } valueExprMap.put( expr, new String[]{ name, newExpr } ); } } } /** * Generate a unique binding name. * * @param expr * @return */ protected String generateUniqueBindingName( String expr ) { String name = StructureFactory.newComputedColumn( fReportItemHandle, ChartUtil.escapeSpecialCharacters( expr ) ).getName( ); if ( fNameSet.contains( name ) ) { name = name + fNameSet.size( ); return generateUniqueBindingName( name ); } fNameSet.add( name ); return name; } /** * Generates extra bindings for grouping and complex expressions. In * addition, add them into query definition. * * @param query * @throws ChartException */ protected void generateExtraBindings( BaseQueryDefinition query ) throws ChartException { // 1. Get first category and orthogonal series definition to get // grouping definition. SeriesDefinition categorySD = null; SeriesDefinition orthSD = null; Axis[] orthAxisArray = null; if ( fChartModel instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) fChartModel; categorySD = cwa.getBaseAxes( )[0].getSeriesDefinitions( ).get( 0 ); orthAxisArray = cwa.getOrthogonalAxes( cwa.getBaseAxes( )[0], true ); orthSD = orthAxisArray[0].getSeriesDefinitions( ).get( 0 ); } else if ( fChartModel instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) fChartModel; categorySD = cwoa.getSeriesDefinitions( ).get( 0 ); orthSD = categorySD.getSeriesDefinitions( ).get( 0 ); } // 2. Add grouping. // 2.1 Add Y optional grouping. initYGroupingNSortKey( query, categorySD, orthSD, orthAxisArray ); // 2.2 Add base grouping. GroupDefinition categoryGroupDefinition = initCategoryGrouping( query, categorySD ); // 3. Add binding for value series aggregate. // The returned map is used to map old expression and new expression, // the key is old expression, the value is new expression. // <p>For aggregate case, the expression of value series will be replace // with new expression for evaluator. And if the expression of value // series is a sort key, it also need using new expression instead of // old expression as sort expression, the related code show in section // 4. Map<String, String[]> valueExprMap = addAggregateBindings( query, categorySD, orthAxisArray ); // If category expression is complex or for subquery, to create a new // binding to evaluate when required if ( bCreateBindingForExpression ) { String exprCategory = ( categorySD.getDesignTimeSeries( ) .getDataDefinition( ).get( 0 ) ).getDefinition( ); String exprYGroup = orthSD.getQuery( ).getDefinition( ); try { exprCodec.decode( exprCategory ); if ( !exprCodec.isRowBinding( false ) ) { addExtraBinding( query, exprCodec ); } exprCodec.decode( exprYGroup ); if ( !exprCodec.isRowBinding( false ) ) { addExtraBinding( query, exprCodec ); } if ( query instanceof ISubqueryDefinition ) { // If the binding expression is not in subquery, copy the // binding from parent and insert into subquery ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, exprCategory ); ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, exprYGroup ); if ( !categorySD.getGrouping( ).isEnabled( ) ) { for ( SeriesDefinition sd : ChartUtil.getAllOrthogonalSeriesDefinitions( fChartModel ) ) { List<Query> queries = sd.getDesignTimeSeries( ) .getDataDefinition( ); for ( Query queryExpr : queries ) { // If the binding expression is not in subquery, // copy the binding from parent and insert into // subquery ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, queryExpr.getDefinition( ) ); } } } } } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } } // 4. Binding sort on category series. if ( categorySD != null ) { bindSortOnCategorySeries( query, categorySD, categoryGroupDefinition, valueExprMap, orthAxisArray ); } } protected void addExtraBinding( BaseQueryDefinition query, ExpressionCodec exprCodec ) throws ChartException { String bindingName = exprCodec.getExpression( ); if ( bindingName == null || bindingName.trim( ).length( ) == 0 ) { return; } try { if ( !query.getBindings( ).containsKey( bindingName ) ) { IBinding colBinding = new Binding( bindingName ); colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); colBinding.setExportable( false ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); query.addBinding( colBinding ); } } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } } /** * @param query * @param categorySD * @param categoryGroupDefinition * @param valueExprMap */ private void bindSortOnCategorySeries( BaseQueryDefinition query, SeriesDefinition categorySD, GroupDefinition categoryGroupDefinition, Map<String, String[]> valueExprMap, Axis[] orthAxisArray ) throws ChartException { String baseSortExpr = getValidSortExpr( categorySD ); if ( !categorySD.isSetSorting( ) || baseSortExpr == null ) { return; } SortDefinition sd = new SortDefinition( ); if ( categorySD.getSortLocale( ) != null ) { sd.setSortLocale( new ULocale( categorySD.getSortLocale( )) ); } // Chart need to set SortStrength to support sorting locale // characters, it is compatibility with old logic of // chart(version<2.3). if ( !categorySD.isSetSortStrength( ) ) { sd.setSortStrength( ISortDefinition.DEFAULT_SORT_STRENGTH ); } else { sd.setSortStrength( categorySD.getSortStrength( ) ); } sd.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( categorySD.getSorting( ) ) ); String sortExpr = baseSortExpr; if ( ChartReportItemUtil.isBaseGroupingDefined( categorySD ) ) { categoryGroupDefinition.addSort( sd ); // If base series set group, add sort on group definition. String baseExpr = categorySD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); if ( baseExpr.equals( getValidSortExpr( categorySD ) ) ) { // sortExpr = baseExpr; sd.setExpression( categoryGroupDefinition.getKeyExpression( ) ); return; } else { String[] nameNewExprArray = valueExprMap.get( baseSortExpr ); if ( nameNewExprArray != null && nameNewExprArray.length == 2 ) { sortExpr = nameNewExprArray[1]; exprCodec.decode( sortExpr ); sd.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); return; } else { sortExpr = baseSortExpr; exprCodec.decode( sortExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); Binding binding = new Binding( name ); try { query.addBinding( binding ); binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); binding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); binding.setExportable( false ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } if ( isYSeriesExpression( sortExpr ) ) { // If the related Y series expression is set aggregate, // then using the aggregate result as sort key. String aggFunc = getAggFunExpr( sortExpr, categorySD, orthAxisArray ); if ( aggFunc != null ) { // Set aggregation on. try { binding.addAggregateOn( categoryGroupDefinition.getName( ) ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Set aggregation function and parameters. binding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggFunc ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggFunc ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = categorySD.getGrouping( ) .getAggregateParameters( ) .toArray( new String[1] ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; binding.addArgument( new ScriptExpression( param ) ); } } } } sd.setExpression( ExpressionUtil.createRowExpression( binding.getBindingName( ) ) ); } } } else { sortExpr = baseSortExpr; query.addSort( sd ); exprCodec.decode( sortExpr ); sd.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } /** * @param query * @param categorySD * @param orthAxisArray * @return * @throws ChartException */ private Map<String, String[]> addAggregateBindings( BaseQueryDefinition query, SeriesDefinition categorySD, Object[] orthAxisArray ) throws ChartException { GroupDefinition innerMostGroupDef = null; if ( query.getGroups( ) != null && query.getGroups( ).size( ) > 0 ) { innerMostGroupDef = (GroupDefinition) query.getGroups( ) .get( query.getGroups( ).size( ) - 1 ); } Map<String, String[]> valueExprMap = new HashMap<String, String[]>( ); // Add aggregates. if ( fChartModel instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { addValueSeriesAggregateBindingForGrouping( query, ( (Axis) orthAxisArray[i] ).getSeriesDefinitions( ), innerMostGroupDef, valueExprMap, categorySD ); } } else if ( fChartModel instanceof ChartWithoutAxes ) { addValueSeriesAggregateBindingForGrouping( query, categorySD.getSeriesDefinitions( ), innerMostGroupDef, valueExprMap, categorySD ); } return valueExprMap; } private GroupDefinition initCategoryGrouping( BaseQueryDefinition query, SeriesDefinition categorySD ) throws ChartException { GroupDefinition baseGroupDefinition = createBaseGroupingDefinition( categorySD ); if ( baseGroupDefinition != null ) { query.addGroup( baseGroupDefinition ); // // #238715 Do not use DTE functions in old report, since chart // // groups data by itself // // #242100 If running aggregate is set, it should not ignore detail // // rows. // if ( !ChartReportItemUtil.isOldChartUsingInternalGroup( fReportItemHandle, // fChartModel ) // && !ChartReportItemUtil.isSetRunningAggregation( fChartModel ) ) // { // query.setUsesDetails( false ); // } } return baseGroupDefinition; } /** * @param query * @param categorySD * @param orthSD * @param orthAxisArray * @return * @throws ChartException */ private GroupDefinition initYGroupingNSortKey( BaseQueryDefinition query, SeriesDefinition categorySD, SeriesDefinition orthSD, Axis[] orthAxisArray ) throws ChartException { GroupDefinition yGroupingDefinition = createOrthogonalGroupingDefinition( orthSD ); if ( yGroupingDefinition != null ) { // Add y optional group to query. query.addGroup( yGroupingDefinition ); if ( !orthSD.isSetSorting( ) ) { return yGroupingDefinition; } // Create a new sort SortDefinition sortDefinition = new SortDefinition( ); if ( categorySD.getSortLocale( ) != null ) { sortDefinition.setSortLocale( new ULocale( categorySD.getSortLocale( )) ); } // Chart need to set SortStrength to support sorting locale // characters, it is compatibility with old logic of // chart(version<2.3). if ( !categorySD.isSetSortStrength( ) ) { sortDefinition.setSortStrength( ISortDefinition.DEFAULT_SORT_STRENGTH ); } else { sortDefinition.setSortStrength( categorySD.getSortStrength( ) ); } sortDefinition.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( orthSD.getSorting( ) ) ); String sortKey = null; if ( orthSD.getSortKey( ) != null && orthSD.getSortKey( ).getDefinition( ) != null ) { sortKey = orthSD.getSortKey( ).getDefinition( ); } if ( sortKey == null || yGroupingDefinition.getKeyExpression( ).equals( sortKey ) ) { // Sort key is group expression. sortDefinition.setExpression( yGroupingDefinition.getKeyExpression( ) ); } else { // Add additional sort on the grouping. exprCodec.decode( sortKey ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); Binding binding = new Binding( name ); try { query.addBinding( binding ); binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); binding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); binding.setExportable( false ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Check if sort key is Y series expression. if ( isYSeriesExpression( sortKey ) ) { // If the related Y series expression is set aggregate, // then using the aggregate result as sort key. // Get aggregate function. String aggFunc = getAggFunExpr( sortKey, categorySD, orthAxisArray ); if ( aggFunc != null ) { // Set aggregation on. try { binding.addAggregateOn( yGroupingDefinition.getName( ) ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Set aggregation function and parameters. binding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggFunc ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggFunc ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = ChartUtil.getAggFunParameters( orthSD, categorySD, null ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; binding.addArgument( new ScriptExpression( param ) ); } } } } sortDefinition.setExpression( ExpressionUtil.createRowExpression( binding.getBindingName( ) ) ); } yGroupingDefinition.addSort( sortDefinition ); } return yGroupingDefinition; } /** * @param expression * @param isYSeriesExpression * @return */ private boolean isYSeriesExpression( String expression ) { String[] vsExprs = ChartUtil.getValueSeriesExpressions( fChartModel ); for ( int i = 0; i < vsExprs.length; i++ ) { if ( vsExprs[i].equals( expression ) ) { return true; } } return false; } /** * Create Y grouping definition. * * @param orthSD * @return */ private GroupDefinition createOrthogonalGroupingDefinition( SeriesDefinition orthSD ) { if ( ChartReportItemUtil.isYGroupingDefined( orthSD ) ) { DataType dataType = null; GroupingUnitType groupUnit = null; double groupIntervalRange = 0; // Default value is 0. String yGroupExpr = orthSD.getQuery( ).getDefinition( ); SeriesGrouping yGroupingInterval = orthSD.getQuery( ).getGrouping( ); if ( yGroupingInterval != null ) { dataType = yGroupingInterval.getGroupType( ); groupUnit = yGroupingInterval.getGroupingUnit( ); groupIntervalRange = yGroupingInterval.getGroupingInterval( ); } exprCodec.decode( yGroupExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); GroupDefinition yGroupDefinition = new GroupDefinition( name ); yGroupDefinition.setKeyExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); yGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); yGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupUnit, groupIntervalRange ) ); return yGroupDefinition; } return null; } /** * Create base grouping definition. * * @param baseSD * @return */ private GroupDefinition createBaseGroupingDefinition( SeriesDefinition baseSD ) { DataType dataType; GroupingUnitType groupUnit; double groupIntervalRange; if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) ) { dataType = baseSD.getGrouping( ).getGroupType( ); groupUnit = baseSD.getGrouping( ).getGroupingUnit( ); groupIntervalRange = baseSD.getGrouping( ).getGroupingInterval( ); if ( groupIntervalRange < 0 ) { groupIntervalRange = 0; } String baseExpr = baseSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); exprCodec.decode( baseExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); GroupDefinition baseGroupDefinition = new GroupDefinition( name ); baseGroupDefinition.setKeyExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); baseGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); baseGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupUnit, groupIntervalRange ) ); return baseGroupDefinition; } return null; } /** * Get aggregation function string of sort key related with value series. * * @param sortKey * @param baseSD * @param orthAxisArray * @return * @throws ChartException */ protected String getAggFunExpr( String sortKey, SeriesDefinition baseSD, Axis[] orthAxisArray ) throws ChartException { String baseAggFunExpr = null; if ( baseSD.getGrouping( ) != null && baseSD.getGrouping( ).isEnabled( ) ) { baseAggFunExpr = baseSD.getGrouping( ).getAggregateExpression( ); } String aggFunction = null; if ( fChartModel instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { EList<SeriesDefinition> sds = orthAxisArray[i].getSeriesDefinitions( ); for ( SeriesDefinition sd : sds ) { if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) { aggFunction = ChartUtil.getAggregateFunctionExpr( sd, baseAggFunExpr, q ); break; } } } } } else if ( fChartModel instanceof ChartWithoutAxes ) { for ( SeriesDefinition sd : baseSD.getSeriesDefinitions( ) ) { if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) { aggFunction = ChartUtil.getAggregateFunctionExpr( sd, baseAggFunExpr, q ); break; } } } } if ( aggFunction == null || "".equals( aggFunction ) ) { //$NON-NLS-1$ return baseAggFunExpr; } return aggFunction; } /** * Get valid sort expression from series definition. * * @param sd * @return */ protected String getValidSortExpr( SeriesDefinition sd ) { if ( !sd.isSetSorting( ) ) { return null; } String sortExpr = null; if ( sd.getSortKey( ) != null && sd.getSortKey( ).getDefinition( ) != null ) { sortExpr = sd.getSortKey( ).getDefinition( ); } else { sortExpr = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); } if ( "".equals( sortExpr ) ) //$NON-NLS-1$ { sortExpr = null; } return sortExpr; } /** * @param expression * @return */ protected String getExpressionForEvaluator( String expression ) { return ExpressionUtil.createJSRowExpression( expression ); } /** * Set binding expression due to aggregation, some aggregation can't set * expression, like Count. * * @param binding * binding object. * @param expression * specified expression. * @param chartAggFunName * aggregation function name of chart. * @throws DataException * if the aggregation restrict info is got failure. */ protected void setBindingExpressionDueToAggregation( Binding binding, String expression, String chartAggFunName ) throws DataException { IAggrFunction dteAggFunc = AggregationManager.getInstance( ) .getAggregation( ChartReportItemUtil.convertToDtEAggFunction( chartAggFunName ) ); IParameterDefn[] parameters = dteAggFunc.getParameterDefn( ); exprCodec.decode( expression ); if ( parameters != null && parameters.length > 0 ) { binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } }
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/AbstractChartBaseQueryGenerator.java
/******************************************************************************* * Copyright (c) 2007, 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.birt.chart.aggregate.IAggregateFunction; import org.eclipse.birt.chart.api.ChartEngine; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.attribute.DataType; import org.eclipse.birt.chart.model.attribute.GroupingUnitType; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.SeriesGrouping; import org.eclipse.birt.chart.model.impl.ChartModelHelper; import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.chart.util.PluginSettings; import org.eclipse.birt.chart.util.ChartExpressionUtil.ExpressionCodec; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.data.engine.api.ISortDefinition; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.api.aggregation.AggregationManager; import org.eclipse.birt.data.engine.api.aggregation.IAggrFunction; import org.eclipse.birt.data.engine.api.aggregation.IParameterDefn; import org.eclipse.birt.data.engine.api.querydefn.BaseQueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SortDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.emf.common.util.EList; import com.ibm.icu.util.ULocale; /** * The class defines basic functions for creating base query. * * @since BIRT 2.3 */ public abstract class AbstractChartBaseQueryGenerator { /** The handle of report item handle. */ protected ReportItemHandle fReportItemHandle; /** Current chart handle. */ protected Chart fChartModel; /** The set stores created binding names. */ protected Set<String> fNameSet = new HashSet<String>( ); /** * This attribute indicates whether new binding will be created for complex * expression or subquery */ protected final boolean bCreateBindingForExpression; protected final ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); protected final IModelAdapter modelAdapter; /** * Constructor of the class. * * @param chart * @param handle */ public AbstractChartBaseQueryGenerator( ReportItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { this( handle, cm, false, modelAdapter ); } /** * * @param handle * @param cm * @param bCreateBindingForExpression * indicates if query definition should create a new binding for * the complex expression or subquery. If current query * definition is subquery, true then always create a new binding. * If not subquery and the expression is simply a binding name, * always do not add the new binding. */ public AbstractChartBaseQueryGenerator( ReportItemHandle handle, Chart cm, boolean bCreateBindingForExpression, IModelAdapter modelAdapter ) { fChartModel = cm; fReportItemHandle = handle; this.bCreateBindingForExpression = bCreateBindingForExpression; this.modelAdapter = modelAdapter; } /** * Create base query definition. * * @param parent * @throws ChartException */ public abstract IDataQueryDefinition createBaseQuery( IDataQueryDefinition parent ) throws ChartException; /** * Create base query definition. * * @param columns * @throws ChartException */ public abstract IDataQueryDefinition createBaseQuery( List<String> columns ) throws ChartException; /** * Add aggregate bindings of value series for grouping case. * * @param query * @param seriesDefinitions * @param innerMostGroupDef * @param valueExprMap * @param baseSD * @throws ChartException */ protected void addValueSeriesAggregateBindingForGrouping( BaseQueryDefinition query, EList<SeriesDefinition> seriesDefinitions, GroupDefinition innerMostGroupDef, Map<String, String[]> valueExprMap, SeriesDefinition baseSD ) throws ChartException { for ( SeriesDefinition orthSD : seriesDefinitions ) { Series series = orthSD.getDesignTimeSeries( ); // The qlist contains available expressions which have aggregation. List<Query> qlist = ChartEngine.instance( ) .getDataSetProcessor( series.getClass( ) ) .getDataDefinitionsForGrouping( series ); for ( Query qry : series.getDataDefinition( ) ) { String expr = qry.getDefinition( ); if ( expr == null || "".equals( expr ) ) //$NON-NLS-1$ { continue; } String aggName = ChartUtil.getAggregateFuncExpr( orthSD, baseSD, qry ); if ( aggName == null ) { if ( !bCreateBindingForExpression || exprCodec.isRowBinding( expr, false ) ) { // If it's complex expression, still create new binding continue; } } // Get a unique name. String name = ChartUtil.generateBindingNameOfValueSeries( qry, orthSD, baseSD ); if ( fNameSet.contains( name ) ) { continue; } fNameSet.add( name ); Binding colBinding = new Binding( name ); colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); if ( qlist.contains( qry ) ) { try { colBinding.setExportable( false ); if ( aggName != null ) { // Set binding expression by different aggregation, // some aggregations can't set expression, like // Count and so on. setBindingExpressionDueToAggregation( colBinding, expr, aggName ); if ( innerMostGroupDef != null ) { colBinding.addAggregateOn( innerMostGroupDef.getName( ) ); } // Set aggregate parameters. colBinding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggName ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggName ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = ChartUtil.getAggFunParameters( orthSD, baseSD, qry ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; colBinding.addArgument( new ScriptExpression( param ) ); } } } else { // Direct setting expression for simple expression // case. exprCodec.decode( expr ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } catch ( DataException e1 ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e1 ); } } else { // Direct setting expression for non-aggregation case. exprCodec.decode( expr ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } String newExpr = getExpressionForEvaluator( name ); try { query.addBinding( colBinding ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } valueExprMap.put( expr, new String[]{ name, newExpr } ); } } } /** * Generate a unique binding name. * * @param expr * @return */ protected String generateUniqueBindingName( String expr ) { String name = StructureFactory.newComputedColumn( fReportItemHandle, ChartUtil.escapeSpecialCharacters( expr ) ).getName( ); if ( fNameSet.contains( name ) ) { name = name + fNameSet.size( ); return generateUniqueBindingName( name ); } fNameSet.add( name ); return name; } /** * Generates extra bindings for grouping and complex expressions. In * addition, add them into query definition. * * @param query * @throws ChartException */ protected void generateExtraBindings( BaseQueryDefinition query ) throws ChartException { // 1. Get first category and orthogonal series definition to get // grouping definition. SeriesDefinition categorySD = null; SeriesDefinition orthSD = null; Axis[] orthAxisArray = null; if ( fChartModel instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) fChartModel; categorySD = cwa.getBaseAxes( )[0].getSeriesDefinitions( ).get( 0 ); orthAxisArray = cwa.getOrthogonalAxes( cwa.getBaseAxes( )[0], true ); orthSD = orthAxisArray[0].getSeriesDefinitions( ).get( 0 ); } else if ( fChartModel instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) fChartModel; categorySD = cwoa.getSeriesDefinitions( ).get( 0 ); orthSD = categorySD.getSeriesDefinitions( ).get( 0 ); } // 2. Add grouping. // 2.1 Add Y optional grouping. initYGroupingNSortKey( query, categorySD, orthSD, orthAxisArray ); // 2.2 Add base grouping. GroupDefinition categoryGroupDefinition = initCategoryGrouping( query, categorySD ); // 3. Add binding for value series aggregate. // The returned map is used to map old expression and new expression, // the key is old expression, the value is new expression. // <p>For aggregate case, the expression of value series will be replace // with new expression for evaluator. And if the expression of value // series is a sort key, it also need using new expression instead of // old expression as sort expression, the related code show in section // 4. Map<String, String[]> valueExprMap = addAggregateBindings( query, categorySD, orthAxisArray ); // If category expression is complex or for subquery, to create a new // binding to evaluate when required if ( bCreateBindingForExpression ) { String exprCategory = ( categorySD.getDesignTimeSeries( ) .getDataDefinition( ).get( 0 ) ).getDefinition( ); String exprYGroup = orthSD.getQuery( ).getDefinition( ); try { exprCodec.decode( exprCategory ); if ( !exprCodec.isRowBinding( false ) ) { addExtraBinding( query, exprCodec ); } exprCodec.decode( exprYGroup ); if ( !exprCodec.isRowBinding( false ) ) { addExtraBinding( query, exprCodec ); } if ( query instanceof ISubqueryDefinition ) { // If the binding expression is not in subquery, copy the // binding from parent and insert into subquery ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, exprCategory ); ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, exprYGroup ); if ( !categorySD.getGrouping( ).isEnabled( ) ) { for ( SeriesDefinition sd : ChartUtil.getAllOrthogonalSeriesDefinitions( fChartModel ) ) { List<Query> queries = sd.getDesignTimeSeries( ) .getDataDefinition( ); for ( Query queryExpr : queries ) { // If the binding expression is not in subquery, // copy the binding from parent and insert into // subquery ChartReportItemUtil.copyAndInsertBindingFromContainer( (ISubqueryDefinition) query, queryExpr.getDefinition( ) ); } } } } } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } } // 4. Binding sort on category series. if ( categorySD != null ) { bindSortOnCategorySeries( query, categorySD, categoryGroupDefinition, valueExprMap, orthAxisArray ); } } protected void addExtraBinding( BaseQueryDefinition query, ExpressionCodec exprCodec ) throws ChartException { String bindingName = exprCodec.getExpression( ); if ( bindingName == null || bindingName.trim( ).length( ) == 0 ) { return; } try { if ( !query.getBindings( ).containsKey( bindingName ) ) { IBinding colBinding = new Binding( bindingName ); colBinding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); colBinding.setExportable( false ); colBinding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); query.addBinding( colBinding ); } } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } } /** * @param query * @param categorySD * @param categoryGroupDefinition * @param valueExprMap */ private void bindSortOnCategorySeries( BaseQueryDefinition query, SeriesDefinition categorySD, GroupDefinition categoryGroupDefinition, Map<String, String[]> valueExprMap, Axis[] orthAxisArray ) throws ChartException { String baseSortExpr = getValidSortExpr( categorySD ); if ( !categorySD.isSetSorting( ) || baseSortExpr == null ) { return; } SortDefinition sd = new SortDefinition( ); if ( categorySD.getSortLocale( ) != null ) { sd.setSortLocale( new ULocale( categorySD.getSortLocale( )) ); } // Chart need to set SortStrength to support sorting locale // characters, it is compatibility with old logic of // chart(version<2.3). if ( !categorySD.isSetSortStrength( ) ) { sd.setSortStrength( ISortDefinition.DEFAULT_SORT_STRENGTH ); } else { sd.setSortStrength( categorySD.getSortStrength( ) ); } sd.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( categorySD.getSorting( ) ) ); String sortExpr = baseSortExpr; if ( ChartReportItemUtil.isBaseGroupingDefined( categorySD ) ) { categoryGroupDefinition.addSort( sd ); // If base series set group, add sort on group definition. String baseExpr = categorySD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); if ( baseExpr.equals( getValidSortExpr( categorySD ) ) ) { // sortExpr = baseExpr; sd.setExpression( categoryGroupDefinition.getKeyExpression( ) ); return; } else { String[] nameNewExprArray = valueExprMap.get( baseSortExpr ); if ( nameNewExprArray != null && nameNewExprArray.length == 2 ) { sortExpr = nameNewExprArray[1]; exprCodec.decode( sortExpr ); sd.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); return; } else { sortExpr = baseSortExpr; exprCodec.decode( sortExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); Binding binding = new Binding( name ); try { query.addBinding( binding ); binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); binding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); binding.setExportable( false ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } if ( isYSeriesExpression( sortExpr ) ) { // If the related Y series expression is set aggregate, // then using the aggregate result as sort key. String aggFunc = getAggFunExpr( sortExpr, categorySD, orthAxisArray ); if ( aggFunc != null ) { // Set aggregation on. try { binding.addAggregateOn( categoryGroupDefinition.getName( ) ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Set aggregation function and parameters. binding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggFunc ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggFunc ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = categorySD.getGrouping( ) .getAggregateParameters( ) .toArray( new String[1] ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; binding.addArgument( new ScriptExpression( param ) ); } } } } sd.setExpression( ExpressionUtil.createRowExpression( binding.getBindingName( ) ) ); } } } else { sortExpr = baseSortExpr; query.addSort( sd ); exprCodec.decode( sortExpr ); sd.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } /** * @param query * @param categorySD * @param orthAxisArray * @return * @throws ChartException */ private Map<String, String[]> addAggregateBindings( BaseQueryDefinition query, SeriesDefinition categorySD, Object[] orthAxisArray ) throws ChartException { GroupDefinition innerMostGroupDef = null; if ( query.getGroups( ) != null && query.getGroups( ).size( ) > 0 ) { innerMostGroupDef = (GroupDefinition) query.getGroups( ) .get( query.getGroups( ).size( ) - 1 ); } Map<String, String[]> valueExprMap = new HashMap<String, String[]>( ); // Add aggregates. if ( fChartModel instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { addValueSeriesAggregateBindingForGrouping( query, ( (Axis) orthAxisArray[i] ).getSeriesDefinitions( ), innerMostGroupDef, valueExprMap, categorySD ); } } else if ( fChartModel instanceof ChartWithoutAxes ) { addValueSeriesAggregateBindingForGrouping( query, categorySD.getSeriesDefinitions( ), innerMostGroupDef, valueExprMap, categorySD ); } return valueExprMap; } private GroupDefinition initCategoryGrouping( BaseQueryDefinition query, SeriesDefinition categorySD ) throws ChartException { GroupDefinition baseGroupDefinition = createBaseGroupingDefinition( categorySD ); if ( baseGroupDefinition != null ) { query.addGroup( baseGroupDefinition ); // #238715 Do not use DTE functions in old report, since chart // groups data by itself // #242100 If running aggregate is set, it should not ignore detail // rows. if ( !ChartReportItemUtil.isOldChartUsingInternalGroup( fReportItemHandle, fChartModel ) && !ChartReportItemUtil.isSetRunningAggregation( fChartModel ) ) { query.setUsesDetails( false ); } } return baseGroupDefinition; } /** * @param query * @param categorySD * @param orthSD * @param orthAxisArray * @return * @throws ChartException */ private GroupDefinition initYGroupingNSortKey( BaseQueryDefinition query, SeriesDefinition categorySD, SeriesDefinition orthSD, Axis[] orthAxisArray ) throws ChartException { GroupDefinition yGroupingDefinition = createOrthogonalGroupingDefinition( orthSD ); if ( yGroupingDefinition != null ) { // Add y optional group to query. query.addGroup( yGroupingDefinition ); if ( !orthSD.isSetSorting( ) ) { return yGroupingDefinition; } // Create a new sort SortDefinition sortDefinition = new SortDefinition( ); if ( categorySD.getSortLocale( ) != null ) { sortDefinition.setSortLocale( new ULocale( categorySD.getSortLocale( )) ); } // Chart need to set SortStrength to support sorting locale // characters, it is compatibility with old logic of // chart(version<2.3). if ( !categorySD.isSetSortStrength( ) ) { sortDefinition.setSortStrength( ISortDefinition.DEFAULT_SORT_STRENGTH ); } else { sortDefinition.setSortStrength( categorySD.getSortStrength( ) ); } sortDefinition.setSortDirection( ChartReportItemUtil.convertToDtESortDirection( orthSD.getSorting( ) ) ); String sortKey = null; if ( orthSD.getSortKey( ) != null && orthSD.getSortKey( ).getDefinition( ) != null ) { sortKey = orthSD.getSortKey( ).getDefinition( ); } if ( sortKey == null || yGroupingDefinition.getKeyExpression( ).equals( sortKey ) ) { // Sort key is group expression. sortDefinition.setExpression( yGroupingDefinition.getKeyExpression( ) ); } else { // Add additional sort on the grouping. exprCodec.decode( sortKey ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); Binding binding = new Binding( name ); try { query.addBinding( binding ); binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); binding.setDataType( org.eclipse.birt.core.data.DataType.ANY_TYPE ); binding.setExportable( false ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Check if sort key is Y series expression. if ( isYSeriesExpression( sortKey ) ) { // If the related Y series expression is set aggregate, // then using the aggregate result as sort key. // Get aggregate function. String aggFunc = getAggFunExpr( sortKey, categorySD, orthAxisArray ); if ( aggFunc != null ) { // Set aggregation on. try { binding.addAggregateOn( yGroupingDefinition.getName( ) ); } catch ( DataException e ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, e ); } // Set aggregation function and parameters. binding.setAggrFunction( ChartReportItemUtil.convertToDtEAggFunction( aggFunc ) ); IAggregateFunction aFunc = PluginSettings.instance( ) .getAggregateFunction( aggFunc ); if ( aFunc.getParametersCount( ) > 0 ) { String[] parameters = ChartUtil.getAggFunParameters( orthSD, categorySD, null ); for ( int i = 0; i < parameters.length && i < aFunc.getParametersCount( ); i++ ) { String param = parameters[i]; binding.addArgument( new ScriptExpression( param ) ); } } } } sortDefinition.setExpression( ExpressionUtil.createRowExpression( binding.getBindingName( ) ) ); } yGroupingDefinition.addSort( sortDefinition ); } return yGroupingDefinition; } /** * @param expression * @param isYSeriesExpression * @return */ private boolean isYSeriesExpression( String expression ) { String[] vsExprs = ChartUtil.getValueSeriesExpressions( fChartModel ); for ( int i = 0; i < vsExprs.length; i++ ) { if ( vsExprs[i].equals( expression ) ) { return true; } } return false; } /** * Create Y grouping definition. * * @param orthSD * @return */ private GroupDefinition createOrthogonalGroupingDefinition( SeriesDefinition orthSD ) { if ( ChartReportItemUtil.isYGroupingDefined( orthSD ) ) { DataType dataType = null; GroupingUnitType groupUnit = null; double groupIntervalRange = 0; // Default value is 0. String yGroupExpr = orthSD.getQuery( ).getDefinition( ); SeriesGrouping yGroupingInterval = orthSD.getQuery( ).getGrouping( ); if ( yGroupingInterval != null ) { dataType = yGroupingInterval.getGroupType( ); groupUnit = yGroupingInterval.getGroupingUnit( ); groupIntervalRange = yGroupingInterval.getGroupingInterval( ); } exprCodec.decode( yGroupExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); GroupDefinition yGroupDefinition = new GroupDefinition( name ); yGroupDefinition.setKeyExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); yGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); yGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupUnit, groupIntervalRange ) ); return yGroupDefinition; } return null; } /** * Create base grouping definition. * * @param baseSD * @return */ private GroupDefinition createBaseGroupingDefinition( SeriesDefinition baseSD ) { DataType dataType; GroupingUnitType groupUnit; double groupIntervalRange; if ( ChartReportItemUtil.isBaseGroupingDefined( baseSD ) ) { dataType = baseSD.getGrouping( ).getGroupType( ); groupUnit = baseSD.getGrouping( ).getGroupingUnit( ); groupIntervalRange = baseSD.getGrouping( ).getGroupingInterval( ); if ( groupIntervalRange < 0 ) { groupIntervalRange = 0; } String baseExpr = baseSD.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); exprCodec.decode( baseExpr ); String name = generateUniqueBindingName( exprCodec.getExpression( ) ); GroupDefinition baseGroupDefinition = new GroupDefinition( name ); baseGroupDefinition.setKeyExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); baseGroupDefinition.setInterval( ChartReportItemUtil.convertToDtEGroupUnit( dataType, groupUnit, groupIntervalRange ) ); baseGroupDefinition.setIntervalRange( ChartReportItemUtil.convertToDtEIntervalRange( dataType, groupUnit, groupIntervalRange ) ); return baseGroupDefinition; } return null; } /** * Get aggregation function string of sort key related with value series. * * @param sortKey * @param baseSD * @param orthAxisArray * @return * @throws ChartException */ protected String getAggFunExpr( String sortKey, SeriesDefinition baseSD, Axis[] orthAxisArray ) throws ChartException { String baseAggFunExpr = null; if ( baseSD.getGrouping( ) != null && baseSD.getGrouping( ).isEnabled( ) ) { baseAggFunExpr = baseSD.getGrouping( ).getAggregateExpression( ); } String aggFunction = null; if ( fChartModel instanceof ChartWithAxes ) { for ( int i = 0; i < orthAxisArray.length; i++ ) { EList<SeriesDefinition> sds = orthAxisArray[i].getSeriesDefinitions( ); for ( SeriesDefinition sd : sds ) { if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) { aggFunction = ChartUtil.getAggregateFunctionExpr( sd, baseAggFunExpr, q ); break; } } } } } else if ( fChartModel instanceof ChartWithoutAxes ) { for ( SeriesDefinition sd : baseSD.getSeriesDefinitions( ) ) { if ( sd.getDesignTimeSeries( ).getDataDefinition( ) != null && sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) != null ) { Query q = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ); if ( sortKey.equals( q.getDefinition( ) ) ) { aggFunction = ChartUtil.getAggregateFunctionExpr( sd, baseAggFunExpr, q ); break; } } } } if ( aggFunction == null || "".equals( aggFunction ) ) { //$NON-NLS-1$ return baseAggFunExpr; } return aggFunction; } /** * Get valid sort expression from series definition. * * @param sd * @return */ protected String getValidSortExpr( SeriesDefinition sd ) { if ( !sd.isSetSorting( ) ) { return null; } String sortExpr = null; if ( sd.getSortKey( ) != null && sd.getSortKey( ).getDefinition( ) != null ) { sortExpr = sd.getSortKey( ).getDefinition( ); } else { sortExpr = sd.getDesignTimeSeries( ) .getDataDefinition( ) .get( 0 ) .getDefinition( ); } if ( "".equals( sortExpr ) ) //$NON-NLS-1$ { sortExpr = null; } return sortExpr; } /** * @param expression * @return */ protected String getExpressionForEvaluator( String expression ) { return ExpressionUtil.createJSRowExpression( expression ); } /** * Set binding expression due to aggregation, some aggregation can't set * expression, like Count. * * @param binding * binding object. * @param expression * specified expression. * @param chartAggFunName * aggregation function name of chart. * @throws DataException * if the aggregation restrict info is got failure. */ protected void setBindingExpressionDueToAggregation( Binding binding, String expression, String chartAggFunName ) throws DataException { IAggrFunction dteAggFunc = AggregationManager.getInstance( ) .getAggregation( ChartReportItemUtil.convertToDtEAggFunction( chartAggFunName ) ); IParameterDefn[] parameters = dteAggFunc.getParameterDefn( ); exprCodec.decode( expression ); if ( parameters != null && parameters.length > 0 ) { binding.setExpression( ChartReportItemUtil.adaptExpression( exprCodec, modelAdapter, false ) ); } } }
TED#25102 Do not set useDetails as false in query definition so that details data will be always outputted. According to DtE's comments, it has little overhead to output detail rows.
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/AbstractChartBaseQueryGenerator.java
TED#25102 Do not set useDetails as false in query definition so that details data will be always outputted. According to DtE's comments, it has little overhead to output detail rows.
Java
epl-1.0
488bc4770147889f446badb495d2186df3ee0ecd
0
fqqb/yamcs-studio,fqqb/yamcs-studio,fqqb/yamcs-studio,fqqb/yamcs-studio,fqqb/yamcs-studio
package org.yamcs.studio.core.model; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import org.yamcs.api.ws.WebSocketRequest; import org.yamcs.protobuf.Rest.EditLinkRequest; import org.yamcs.protobuf.YamcsManagement.LinkEvent; import org.yamcs.protobuf.YamcsManagement.LinkInfo; import org.yamcs.studio.core.ConnectionManager; import org.yamcs.studio.core.YamcsPlugin; import org.yamcs.studio.core.web.ResponseHandler; import org.yamcs.studio.core.web.RestClient; import org.yamcs.studio.core.web.WebSocketRegistrar; /** * Provides access to aggregated state on yamcs data link information. * <p> * There should be only one long-lived instance of this class, which goes down together with the * application (same lifecycle as {@link YamcsPlugin}). This catalogue deals with maintaining * correct state accross connection-reconnects, so listeners only need to register once. */ public class LinkCatalogue implements Catalogue { private static final Logger log = Logger.getLogger(LinkCatalogue.class.getName()); private Set<LinkListener> linkListeners = new CopyOnWriteArraySet<>(); private Map<LinkId, LinkInfo> linksById = new ConcurrentHashMap<>(); public static LinkCatalogue getInstance() { return YamcsPlugin.getDefault().getCatalogue(LinkCatalogue.class); } @Override public void onStudioConnect() { WebSocketRegistrar webSocketClient = ConnectionManager.getInstance().getWebSocketClient(); webSocketClient.sendMessage(new WebSocketRequest("links", "subscribe")); } @Override public void onStudioDisconnect() { // Clear everything, we'll get a fresh set upon connect linksById.clear(); } public void addLinkListener(LinkListener listener) { linkListeners.add(listener); // Inform listeners of the current model linksById.forEach((k, v) -> listener.linkRegistered(v)); } public void processLinkEvent(LinkEvent linkEvent) { LinkInfo incoming = linkEvent.getLinkInfo(); LinkId id = new LinkId(incoming); switch (linkEvent.getType()) { case REGISTERED: linksById.put(id, incoming); linkListeners.forEach(l -> l.linkRegistered(incoming)); break; case UNREGISTERED: LinkInfo linkInfo = linksById.get(id); if (linkInfo == null) { log.warning("Request to unregister unknown link " + incoming.getInstance() + "/" + incoming.getName()); } else { linksById.remove(id); linkListeners.forEach(l -> l.linkUnregistered(incoming)); } break; case UPDATED: LinkInfo oldLinkInfo = linksById.put(id, incoming); if (oldLinkInfo == null) { log.warning("Request to update unknown link " + incoming.getInstance() + "/" + incoming.getName()); } linkListeners.forEach(l -> l.linkUpdated(linkEvent.getLinkInfo())); break; default: log.warning("Unexpected link event " + linkEvent.getType()); } } public void enableLink(String instance, String name, ResponseHandler responseHandler) { RestClient restClient = ConnectionManager.getInstance().getRestClient(); EditLinkRequest req = EditLinkRequest.newBuilder().setState("enabled").build(); restClient.patch("/links/" + instance + "/link/" + name, req, null, responseHandler); } public void disableLink(String instance, String name, ResponseHandler responseHandler) { RestClient restClient = ConnectionManager.getInstance().getRestClient(); EditLinkRequest req = EditLinkRequest.newBuilder().setState("disabled").build(); restClient.patch("/links/" + instance + "/link/" + name, req, null, responseHandler); } public List<LinkInfo> getLinks() { return new ArrayList<>(linksById.values()); } private static class LinkId { final String instance; final String name; public LinkId(LinkInfo linkInfo) { this.instance = linkInfo.getInstance(); this.name = linkInfo.getName(); } @Override public boolean equals(Object obj) { LinkId other = (LinkId) obj; return instance.equals(other.instance) && name.equals(other.name); } @Override public int hashCode() { return Objects.hash(instance, name); } } }
yamcs-studio-tycho/org.yamcs.studio.core/src/main/java/org/yamcs/studio/core/model/LinkCatalogue.java
package org.yamcs.studio.core.model; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Logger; import org.yamcs.api.ws.WebSocketRequest; import org.yamcs.protobuf.Rest.EditLinkRequest; import org.yamcs.protobuf.YamcsManagement.LinkEvent; import org.yamcs.protobuf.YamcsManagement.LinkInfo; import org.yamcs.studio.core.ConnectionManager; import org.yamcs.studio.core.YamcsPlugin; import org.yamcs.studio.core.web.ResponseHandler; import org.yamcs.studio.core.web.RestClient; import org.yamcs.studio.core.web.WebSocketRegistrar; /** * Provides access to aggregated state on yamcs data link information. * <p> * There should be only one long-lived instance of this class, which goes down together with the * application (same lifecycle as {@link YamcsPlugin}). This catalogue deals with maintaining * correct state accross connection-reconnects, so listeners only need to register once. */ public class LinkCatalogue implements Catalogue { private static final Logger log = Logger.getLogger(LinkCatalogue.class.getName()); private Set<LinkListener> linkListeners = new CopyOnWriteArraySet<>(); private Map<LinkId, LinkInfo> linksById = new ConcurrentHashMap<>(); public static LinkCatalogue getInstance() { return YamcsPlugin.getDefault().getCatalogue(LinkCatalogue.class); } @Override public void onStudioConnect() { WebSocketRegistrar webSocketClient = ConnectionManager.getInstance().getWebSocketClient(); webSocketClient.sendMessage(new WebSocketRequest("links", "subscribe")); } @Override public void onStudioDisconnect() { // Clear everything, we'll get a fresh set upon connect linksById.clear(); } public void addLinkListener(LinkListener listener) { linkListeners.add(listener); // Inform listeners of the current model linksById.forEach((k, v) -> listener.linkRegistered(v)); } public void processLinkEvent(LinkEvent linkEvent) { LinkInfo incoming = linkEvent.getLinkInfo(); LinkId id = new LinkId(incoming); switch (linkEvent.getType()) { case REGISTERED: linksById.put(id, incoming); linkListeners.forEach(l -> l.linkRegistered(incoming)); break; case UNREGISTERED: LinkInfo linkInfo = linksById.get(id); if (linkInfo == null) { log.warning("Request to unregister unknown link " + incoming.getInstance() + "/" + incoming.getName()); } else { linksById.remove(id); linkListeners.forEach(l -> l.linkUnregistered(incoming)); } break; case UPDATED: LinkInfo oldLinkInfo = linksById.put(id, incoming); if (oldLinkInfo == null) { log.warning("Request to update unknown link " + incoming.getInstance() + "/" + incoming.getName()); } linkListeners.forEach(l -> l.linkUpdated(linkEvent.getLinkInfo())); break; default: log.warning("Unexpected link event " + linkEvent.getType()); } } public void enableLink(String instance, String name, ResponseHandler responseHandler) { RestClient restClient = ConnectionManager.getInstance().getRestClient(); EditLinkRequest req = EditLinkRequest.newBuilder().setState("enabled").build(); restClient.patch("/links/" + instance + "/" + name, req, null, responseHandler); } public void disableLink(String instance, String name, ResponseHandler responseHandler) { RestClient restClient = ConnectionManager.getInstance().getRestClient(); EditLinkRequest req = EditLinkRequest.newBuilder().setState("disabled").build(); restClient.patch("/links/" + instance + "/" + name, req, null, responseHandler); } public List<LinkInfo> getLinks() { return new ArrayList<>(linksById.values()); } private static class LinkId { final String instance; final String name; public LinkId(LinkInfo linkInfo) { this.instance = linkInfo.getInstance(); this.name = linkInfo.getName(); } @Override public boolean equals(Object obj) { LinkId other = (LinkId) obj; return instance.equals(other.instance) && name.equals(other.name); } @Override public int hashCode() { return Objects.hash(instance, name); } } }
Fix links requests against latest Yamcs API
yamcs-studio-tycho/org.yamcs.studio.core/src/main/java/org/yamcs/studio/core/model/LinkCatalogue.java
Fix links requests against latest Yamcs API
Java
epl-1.0
6893ad5ad1642d73a9640b7008edc22e17838e1c
0
ModelWriter/Tarski,ModelWriter/Tarski,ModelWriter/Tarski,ModelWriter/WP3,ModelWriter/WP3,ModelWriter/WP3
package eu.modelwriter.marker.ui.internal.views.visualizationview; import java.awt.Cursor; import java.awt.Frame; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import org.eclipse.core.resources.IMarker; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.services.ISourceProviderService; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4.Util; import edu.mit.csail.sdg.alloy4graph.GraphEdge; import edu.mit.csail.sdg.alloy4graph.GraphViewer; import edu.mit.csail.sdg.alloy4viz.AlloyAtom; import edu.mit.csail.sdg.alloy4viz.AlloyInstance; import edu.mit.csail.sdg.alloy4viz.AlloyTuple; import edu.mit.csail.sdg.alloy4viz.StaticInstanceReader; import edu.mit.csail.sdg.alloy4viz.VizGraphPanel; import edu.mit.csail.sdg.alloy4viz.VizState; import eu.modelwriter.configuration.alloy.analysis.provider.AnalysisSourceProvider; import eu.modelwriter.configuration.alloy.discovery.AlloyNextSolutionDiscovering; import eu.modelwriter.configuration.alloy.reasoning.AlloyNextSolutionReasoning; import eu.modelwriter.configuration.alloy.trace.TraceManager; import eu.modelwriter.configuration.internal.AlloyUtilities; import eu.modelwriter.marker.internal.MarkUtilities; import eu.modelwriter.marker.ui.Activator; import eu.modelwriter.marker.ui.internal.views.visualizationview.commands.VisualizationActionListenerFactory; public class Visualization extends ViewPart { public static final String ID = "eu.modelwriter.marker.ui.views.visualizationview"; private static VizState myState = null; private static VizGraphPanel graph; private static JPanel graphPanel; private static GraphViewer viewer; private static Frame frame; private static JMenu modelWriterMenu; private static JMenu analysisMenu; private static File f = null; public static Object rightClickedAnnotation; final static String xmlFileName = Util.canon(AlloyUtilities.getLocation()); public static Composite container; public static AnalysisSourceProvider sourceProvider; public static String relation; public static IMarker getMarker(final AlloyAtom highLightedAtom) { if (highLightedAtom.isDashed) return null; final String atomType = highLightedAtom.getType().getName(); final String stringIndex = highLightedAtom.toString().substring(atomType.length()); int index = 0; if (!stringIndex.isEmpty()) { index = Integer.parseInt(stringIndex); } final IMarker marker = AlloyUtilities.findMarker(atomType, index); return marker; } private static MouseAdapter getMouseAdapter() { return new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { super.mouseClicked(e); if (e.getClickCount() > 1) { final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (annotation instanceof AlloyAtom) { final IMarker marker = Visualization.getMarker((AlloyAtom) annotation); if (marker == null) { return; } MarkUtilities.focusMarker(marker); } } } /** * when mouse exited from graph<br> * (not from AlloyAtom or not from AlloyTuple) */ @Override public void mouseExited(final MouseEvent e) { Visualization.frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (annotation == null) { final JMenu modelWriterMenu = (JMenu) Visualization.viewer.pop.getComponent(0); if (!Visualization.viewer.pop.isShowing()) { modelWriterMenu.setVisible(false); } } } @Override public void mousePressed(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON3: // right click Visualization.rightClickedAnnotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (Visualization.rightClickedAnnotation != null) { Visualization.modelWriterMenu.setVisible(true); Visualization.analysisMenu.setVisible(true); if (Visualization.rightClickedAnnotation instanceof AlloyAtom) { final AlloyAtom atom = (AlloyAtom) Visualization.rightClickedAnnotation; Visualization.modelWriterMenu.getItem(0).setVisible(true); Visualization.modelWriterMenu.getItem(1).setVisible(false); Visualization.modelWriterMenu.getItem(2).setVisible(true); Visualization.modelWriterMenu.getItem(3).setVisible(true); Visualization.modelWriterMenu.getItem(4).setVisible(false); Visualization.modelWriterMenu.getItem(6).setVisible(false); if (atom.changed) { Visualization.modelWriterMenu.getItem(5).setVisible(true); } else { Visualization.modelWriterMenu.getItem(5).setVisible(false); } Visualization.analysisMenu.getItem(0).setVisible(false); Visualization.analysisMenu.getItem(1).setVisible(false); Visualization.analysisMenu.getItem(2).setVisible(false); Visualization.analysisMenu.getItem(3).setVisible(false); Visualization.analysisMenu.getItem(4).setVisible(false); Visualization.analysisMenu.getItem(5).setVisible(false); Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); if (atom.isDashed) { Visualization.analysisMenu.getItem(7) .setVisible(!TraceManager.get().hasSigTrace(atom.getType().getName())); Visualization.analysisMenu.getItem(8) .setVisible(TraceManager.get().hasSigTrace(atom.getType().getName())); Visualization.analysisMenu.getItem(9).setVisible(false); Visualization.modelWriterMenu.setVisible(false); } else { Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.modelWriterMenu.setVisible(true); } Visualization.analysisMenu.getItem(11).setVisible(true); } else if (Visualization.rightClickedAnnotation instanceof AlloyTuple) { final AlloyTuple tuple = (AlloyTuple) Visualization.rightClickedAnnotation; final AlloyAtom leftAtom = tuple.getStart(); final AlloyAtom rightAtom = tuple.getEnd(); Visualization.modelWriterMenu.getItem(0).setVisible(false); Visualization.modelWriterMenu.getItem(1).setVisible(false); Visualization.modelWriterMenu.getItem(2).setVisible(false); Visualization.modelWriterMenu.getItem(3).setVisible(false); Visualization.modelWriterMenu.getItem(4).setVisible(true); Visualization.modelWriterMenu.getItem(6).setVisible(false); if (leftAtom.changed && rightAtom.impacted.size() != 0) { Visualization.modelWriterMenu.getItem(5).setVisible(true); } else { Visualization.modelWriterMenu.getItem(5).setVisible(false); } Visualization.analysisMenu.getItem(0).setVisible(false); Visualization.analysisMenu.getItem(1).setVisible(false); if (tuple.isDashed) { Visualization.analysisMenu.setVisible(true); Visualization.analysisMenu.getItem(2) .setVisible(!TraceManager.get().hasInstance()); Visualization.analysisMenu.getItem(9) .setVisible(TraceManager.get().hasInstance()); } else { Visualization.analysisMenu.setVisible(false); Visualization.analysisMenu.getItem(2).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); } Visualization.analysisMenu.getItem(3).setVisible(false); Visualization.analysisMenu.getItem(4).setVisible(false); Visualization.analysisMenu.getItem(5).setVisible(false); Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); Visualization.analysisMenu.getItem(11).setVisible(false); Field field; try { field = GraphViewer.class.getDeclaredField("selected"); field.setAccessible(true); if (field.get(Visualization.viewer) instanceof GraphEdge) { final GraphEdge edge = (GraphEdge) field.get(Visualization.viewer); Visualization.relation = edge.group.toString().substring(0, edge.group.toString().indexOf(":") - 1); } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); } } else { Visualization.modelWriterMenu.setVisible(false); Visualization.analysisMenu.setVisible(false); } } else { Visualization.modelWriterMenu.setVisible(true); Visualization.modelWriterMenu.getItem(0).setVisible(false); Visualization.modelWriterMenu.getItem(1) .setVisible(!TraceManager.get().hasInstance()); Visualization.modelWriterMenu.getItem(2).setVisible(false); Visualization.modelWriterMenu.getItem(3).setVisible(false); Visualization.modelWriterMenu.getItem(4).setVisible(false); Visualization.modelWriterMenu.getItem(5).setVisible(false); Visualization.modelWriterMenu.getItem(6).setVisible(TraceManager.get().hasInstance()); Visualization.analysisMenu.setVisible(true); Visualization.analysisMenu.getItem(0).setVisible(true); Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); final Object curState = Visualization.sourceProvider.getCurrentState() .get(AnalysisSourceProvider.ANALYSIS_STATE); // STATE MACHINE if (curState.equals(AnalysisSourceProvider.ACTIVE)) { Visualization.analysisMenu.getItem(1).setVisible(false); // reason Visualization.analysisMenu.getItem(5).setVisible(false); // discover if (AlloyNextSolutionReasoning.getInstance().getAns() != null || AlloyNextSolutionDiscovering.getInstance().getAns() != null) { Visualization.analysisMenu.getItem(3).setVisible(true); // next Visualization.analysisMenu.getItem(4).setVisible(true); // stop } else { Visualization.analysisMenu.getItem(3).setVisible(false); // next Visualization.analysisMenu.getItem(4).setVisible(false); // stop } } else if (curState.equals(AnalysisSourceProvider.PASSIVE)) { Visualization.analysisMenu.getItem(1).setVisible(true); // reason Visualization.analysisMenu.getItem(5).setVisible(true); // discover Visualization.analysisMenu.getItem(3).setVisible(false); // next Visualization.analysisMenu.getItem(4).setVisible(false); // stop } Visualization.analysisMenu.getItem(2).setVisible(false); if (AlloyUtilities.isAnyReasoned()) { Visualization.analysisMenu.getItem(6).setVisible(true); Visualization.analysisMenu.getItem(10).setVisible(TraceManager.get().hasInstance()); } else { Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); } Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.analysisMenu.getItem(11).setVisible(false); } if (e.getSource() instanceof GraphViewer) { Visualization.viewer.alloyPopup(Visualization.viewer, e.getX(), e.getY()); } else { Visualization.viewer.alloyPopup(Visualization.graphPanel, e.getX(), e.getY()); } default: break; } } }; } private static MouseMotionAdapter getMouseMotionAdapter() { return new MouseMotionAdapter() { @Override public void mouseMoved(final MouseEvent e) { JComponent cmpnt = null; String tooltip = null; try { final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); cmpnt = (JComponent) e.getComponent(); if (annotation instanceof AlloyAtom) { final IMarker marker = Visualization.getMarker((AlloyAtom) annotation); if (marker == null) { return; } Visualization.frame.setCursor(new Cursor(Cursor.HAND_CURSOR)); tooltip = MarkUtilities.getText(marker); } else if (annotation instanceof AlloyTuple) { final AlloyTuple tuple = (AlloyTuple) annotation; final AlloyAtom highLightedAtomStart = tuple.getStart(); final AlloyAtom highLightedAtomEnd = tuple.getEnd(); final IMarker markerStart = Visualization.getMarker(highLightedAtomStart); final IMarker markerEnd = Visualization.getMarker(highLightedAtomEnd); if (markerStart == null || markerEnd == null) { return; } tooltip = MarkUtilities.getText(markerStart) + " --> " + MarkUtilities.getText(markerEnd); Visualization.frame.setCursor(new Cursor(Cursor.HAND_CURSOR)); } else { /** * when mouse exited from AlloyAtom or from AlloyTuple */ Visualization.frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } catch (Exception ex) { System.err.println("onMouseMoved failed"); // ex.printStackTrace(); } finally { cmpnt.setToolTipText(tooltip); } } }; } public static void showViz() { Point lastLocation = new Point(0, 0); if (Visualization.container == null) { return; } if (!AlloyUtilities.isExists()) { if (Visualization.frame != null) { if (Visualization.frame.getComponentCount() > 0) { Visualization.frame.removeAll(); } Visualization.frame.add(new JPanel()); } else if (Visualization.frame == null) { Visualization.frame = SWT_AWT.new_Frame(Visualization.container); Visualization.frame.add(new JPanel()); } return; } Visualization.f = new File(Visualization.xmlFileName); try { if (!Visualization.f.exists()) { throw new IOException("File " + Visualization.xmlFileName + " does not exist."); } final AlloyInstance instance = StaticInstanceReader.parseInstance(Visualization.f); AlloyUtilities.setAllImpactsAndChanges(instance); AlloyUtilities.setAllReasonedTuples(instance); AlloyUtilities.setAllReasonedAtoms(instance); Visualization.myState = new VizState(instance); // FE Visualization.myState.mergeArrows.put(null, false); if (Visualization.graphPanel != null) { lastLocation = Visualization.graphPanel.getLocation(); } if (Visualization.frame == null) { Visualization.frame = SWT_AWT.new_Frame(Visualization.container); } if (Visualization.graph != null && Visualization.frame.getComponent(0) != null) { Visualization.frame.remove(Visualization.graph); } try { /* * TODO BUG * * A Fatal Error occurs while setting GTK look and feel on Ubuntu 16.04 * (com.sun.java.swing.plaf.gtk.GTKLookAndFeel). * */ final String LaF = UIManager.getSystemLookAndFeelClassName(); if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(LaF)) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } else { UIManager.setLookAndFeel(LaF); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } Visualization.graph = new VizGraphPanel(Visualization.myState, false); Visualization.graphPanel = Visualization.graph.getGraphPanel(); Visualization.graphPanel.setLocation(lastLocation); Visualization.viewer = Visualization.graph.alloyGetViewer(); Visualization.frame.removeAll(); Visualization.frame.add(Visualization.graph); Visualization.frame.setVisible(true); Visualization.frame.setAlwaysOnTop(true); Visualization.graph.alloyGetViewer().alloyRepaint(); final ISourceProviderService service = Activator.getDefault().getWorkbench().getService(ISourceProviderService.class); Visualization.sourceProvider = (AnalysisSourceProvider) service.getSourceProvider(AnalysisSourceProvider.ANALYSIS_STATE); } catch (final Err e1) { e1.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } Visualization.createPopupMenu(); Visualization.graph.alloyGetViewer() .addMouseMotionListener(Visualization.getMouseMotionAdapter()); Visualization.graphPanel.addMouseMotionListener(Visualization.getMouseMotionAdapter()); Visualization.graph.alloyGetViewer().addMouseListener(Visualization.getMouseAdapter()); Visualization.graphPanel.addMouseListener(Visualization.getMouseAdapter()); } private static void createPopupMenu() { final JMenu modelWriterMenu = Visualization.modelWriterMenu = new JMenu("Management"); Visualization.graph.alloyGetViewer().pop.add(modelWriterMenu, 0); final JMenuItem deleteAtomMenuItem = new JMenuItem("Delete Atom"); final JMenuItem addRemoveTypeMenuItem = new JMenuItem("Change Type"); final JMenuItem removeRelationMenuItem = new JMenuItem("Remove Relation"); final JMenuItem mappingMenuItem = new JMenuItem("Map Atom"); final JMenuItem createNewAtomMenuItem = new JMenuItem("Create New Atom"); final JMenuItem createInstanceElementMenuItem = new JMenuItem("Create New Atom"); final JMenuItem resolveMenuItem = new JMenuItem("Resolve"); modelWriterMenu.add(addRemoveTypeMenuItem, 0); modelWriterMenu.add(createNewAtomMenuItem, 1); modelWriterMenu.add(deleteAtomMenuItem, 2); modelWriterMenu.add(mappingMenuItem, 3); modelWriterMenu.add(removeRelationMenuItem, 4); modelWriterMenu.add(resolveMenuItem, 5); modelWriterMenu.add(createInstanceElementMenuItem, 6); final JMenu analysisMenu = Visualization.analysisMenu = new JMenu("Analysis"); Visualization.graph.alloyGetViewer().pop.add(analysisMenu, 1); final JMenuItem validateMenuItem = new JMenuItem("Check Consistency"); final JMenuItem discoverRelationMenuItem = new JMenuItem("Reason on Relations"); final JMenuItem acceptReasonedRelationMenuItem = new JMenuItem("Accept Reasoning"); final JMenuItem discoverAtomMenuItem = new JMenuItem("Discover Atoms"); final JMenuItem interpretAtomMenuItem = new JMenuItem("Interpret Atom"); final JMenuItem acceptRelationAsEMFMenuItem = new JMenuItem("Accept Reasoning"); final JMenuItem acceptAtomAsEMFMenuItem = new JMenuItem("Interpret Atom"); final JMenuItem discoverRelationForAtomMenuItem = new JMenuItem("Reasoning for Atom"); final JMenuItem nextSolution = new JMenuItem("Next Solution"); final JMenuItem stopAnalysis = new JMenuItem("Stop Analysis"); final JMenuItem clearAllReasoned = new JMenuItem("Clear All Reasoned Tuples"); final JMenuItem acceptAllReasoned = new JMenuItem("Accept All Reasoned Tuples"); analysisMenu.add(validateMenuItem, 0); analysisMenu.add(discoverRelationMenuItem, 1); analysisMenu.add(acceptReasonedRelationMenuItem, 2); analysisMenu.add(nextSolution, 3); analysisMenu.add(stopAnalysis, 4); analysisMenu.add(discoverAtomMenuItem, 5); analysisMenu.add(clearAllReasoned, 6); analysisMenu.add(interpretAtomMenuItem, 7); analysisMenu.add(acceptAtomAsEMFMenuItem, 8); analysisMenu.add(acceptRelationAsEMFMenuItem, 9); analysisMenu.add(acceptAllReasoned, 10); analysisMenu.add(discoverRelationForAtomMenuItem, 11); final JMenuItem refreshMenuItem = new JMenuItem("Refresh"); Visualization.graph.alloyGetViewer().pop.add(refreshMenuItem, 2); refreshMenuItem.addActionListener(VisualizationActionListenerFactory.refreshActionListener()); addRemoveTypeMenuItem .addActionListener(VisualizationActionListenerFactory.addRemoveTypeActionListener()); createNewAtomMenuItem .addActionListener(VisualizationActionListenerFactory.createNewAtomActionListener()); deleteAtomMenuItem .addActionListener(VisualizationActionListenerFactory.deleteAtomActionListener()); mappingMenuItem.addActionListener(VisualizationActionListenerFactory.mappingActionListener()); removeRelationMenuItem .addActionListener(VisualizationActionListenerFactory.removeRelationActionListener()); resolveMenuItem.addActionListener(VisualizationActionListenerFactory.resolveActionListener()); validateMenuItem.addActionListener(VisualizationActionListenerFactory.validateActionListener()); discoverRelationMenuItem .addActionListener(VisualizationActionListenerFactory.discoverRelationActionListener()); acceptReasonedRelationMenuItem.addActionListener( VisualizationActionListenerFactory.acceptReasonedRelationActionListener()); discoverAtomMenuItem .addActionListener(VisualizationActionListenerFactory.discoverAtomActionListener()); nextSolution.addActionListener(VisualizationActionListenerFactory.nextSolutionActionListener()); stopAnalysis.addActionListener(VisualizationActionListenerFactory.stopAnalysisActionListener()); clearAllReasoned .addActionListener(VisualizationActionListenerFactory.clearAllReasonedActionListener()); interpretAtomMenuItem.addActionListener( VisualizationActionListenerFactory.interpretAtomMenuItemActionListener()); acceptRelationAsEMFMenuItem.addActionListener( VisualizationActionListenerFactory.acceptRelationAsEMFMenuItemActionListener()); acceptAtomAsEMFMenuItem.addActionListener( VisualizationActionListenerFactory.acceptAtomAsEMFMenuItemActionListener()); acceptAllReasoned .addActionListener(VisualizationActionListenerFactory.acceptAllReasonedListener()); discoverRelationForAtomMenuItem.addActionListener( VisualizationActionListenerFactory.discoverRelationForAtomActionListener()); createInstanceElementMenuItem.addActionListener( VisualizationActionListenerFactory.createInstanceElementActionListener()); } @Override public void createPartControl(final Composite parent) { Visualization.container = new Composite(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND); Visualization.frame = null; Visualization.f = null; Visualization.graph = null; Visualization.myState = null; Visualization.showViz(); } @Override public void setFocus() {} }
Source/eu.modelwriter.marker.ui/src/eu/modelwriter/marker/ui/internal/views/visualizationview/Visualization.java
package eu.modelwriter.marker.ui.internal.views.visualizationview; import java.awt.Cursor; import java.awt.Frame; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import org.eclipse.core.resources.IMarker; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.services.ISourceProviderService; import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4.Util; import edu.mit.csail.sdg.alloy4graph.GraphEdge; import edu.mit.csail.sdg.alloy4graph.GraphViewer; import edu.mit.csail.sdg.alloy4viz.AlloyAtom; import edu.mit.csail.sdg.alloy4viz.AlloyInstance; import edu.mit.csail.sdg.alloy4viz.AlloyTuple; import edu.mit.csail.sdg.alloy4viz.StaticInstanceReader; import edu.mit.csail.sdg.alloy4viz.VizGraphPanel; import edu.mit.csail.sdg.alloy4viz.VizState; import eu.modelwriter.configuration.alloy.analysis.provider.AnalysisSourceProvider; import eu.modelwriter.configuration.alloy.discovery.AlloyNextSolutionDiscovering; import eu.modelwriter.configuration.alloy.reasoning.AlloyNextSolutionReasoning; import eu.modelwriter.configuration.alloy.trace.TraceManager; import eu.modelwriter.configuration.internal.AlloyUtilities; import eu.modelwriter.marker.internal.MarkUtilities; import eu.modelwriter.marker.ui.Activator; import eu.modelwriter.marker.ui.internal.views.visualizationview.commands.VisualizationActionListenerFactory; public class Visualization extends ViewPart { public static final String ID = "eu.modelwriter.marker.ui.views.visualizationview"; private static VizState myState = null; private static VizGraphPanel graph; private static JPanel graphPanel; private static GraphViewer viewer; private static Frame frame; private static JMenu modelWriterMenu; private static JMenu analysisMenu; private static File f = null; public static Object rightClickedAnnotation; final static String xmlFileName = Util.canon(AlloyUtilities.getLocation()); public static Composite container; public static AnalysisSourceProvider sourceProvider; public static String relation; public static IMarker getMarker(final AlloyAtom highLightedAtom) { if (highLightedAtom.isDashed) return null; final String atomType = highLightedAtom.getType().getName(); final String stringIndex = highLightedAtom.toString().substring(atomType.length()); int index = 0; if (!stringIndex.isEmpty()) { index = Integer.parseInt(stringIndex); } final IMarker marker = AlloyUtilities.findMarker(atomType, index); return marker; } private static MouseAdapter getMouseAdapter() { return new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { super.mouseClicked(e); if (e.getClickCount() > 1) { final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (annotation instanceof AlloyAtom) { final IMarker marker = Visualization.getMarker((AlloyAtom) annotation); if (marker == null) { return; } MarkUtilities.focusMarker(marker); } } } /** * when mouse exited from graph<br> * (not from AlloyAtom or not from AlloyTuple) */ @Override public void mouseExited(final MouseEvent e) { Visualization.frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (annotation == null) { final JMenu modelWriterMenu = (JMenu) Visualization.viewer.pop.getComponent(0); if (!Visualization.viewer.pop.isShowing()) { modelWriterMenu.setVisible(false); } } } @Override public void mousePressed(final MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON3: // right click Visualization.rightClickedAnnotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); if (Visualization.rightClickedAnnotation != null) { Visualization.modelWriterMenu.setVisible(true); Visualization.analysisMenu.setVisible(true); if (Visualization.rightClickedAnnotation instanceof AlloyAtom) { final AlloyAtom atom = (AlloyAtom) Visualization.rightClickedAnnotation; Visualization.modelWriterMenu.getItem(0).setVisible(true); Visualization.modelWriterMenu.getItem(1).setVisible(false); Visualization.modelWriterMenu.getItem(2).setVisible(true); Visualization.modelWriterMenu.getItem(3).setVisible(true); Visualization.modelWriterMenu.getItem(4).setVisible(false); Visualization.modelWriterMenu.getItem(6).setVisible(false); if (atom.changed) { Visualization.modelWriterMenu.getItem(5).setVisible(true); } else { Visualization.modelWriterMenu.getItem(5).setVisible(false); } Visualization.analysisMenu.getItem(0).setVisible(false); Visualization.analysisMenu.getItem(1).setVisible(false); Visualization.analysisMenu.getItem(2).setVisible(false); Visualization.analysisMenu.getItem(3).setVisible(false); Visualization.analysisMenu.getItem(4).setVisible(false); Visualization.analysisMenu.getItem(5).setVisible(false); Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); if (atom.isDashed) { Visualization.analysisMenu.getItem(7) .setVisible(!TraceManager.get().hasSigTrace(atom.getType().getName())); Visualization.analysisMenu.getItem(8) .setVisible(TraceManager.get().hasSigTrace(atom.getType().getName())); Visualization.analysisMenu.getItem(9).setVisible(false); Visualization.modelWriterMenu.setVisible(false); } else { Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.modelWriterMenu.setVisible(true); } Visualization.analysisMenu.getItem(11).setVisible(true); } else if (Visualization.rightClickedAnnotation instanceof AlloyTuple) { final AlloyTuple tuple = (AlloyTuple) Visualization.rightClickedAnnotation; final AlloyAtom leftAtom = tuple.getStart(); final AlloyAtom rightAtom = tuple.getEnd(); Visualization.modelWriterMenu.getItem(0).setVisible(false); Visualization.modelWriterMenu.getItem(1).setVisible(false); Visualization.modelWriterMenu.getItem(2).setVisible(false); Visualization.modelWriterMenu.getItem(3).setVisible(false); Visualization.modelWriterMenu.getItem(4).setVisible(true); Visualization.modelWriterMenu.getItem(6).setVisible(false); if (leftAtom.changed && rightAtom.impacted.size() != 0) { Visualization.modelWriterMenu.getItem(5).setVisible(true); } else { Visualization.modelWriterMenu.getItem(5).setVisible(false); } Visualization.analysisMenu.getItem(0).setVisible(false); Visualization.analysisMenu.getItem(1).setVisible(false); if (tuple.isDashed) { Visualization.analysisMenu.setVisible(true); Visualization.analysisMenu.getItem(2) .setVisible(!TraceManager.get().hasInstance()); Visualization.analysisMenu.getItem(9) .setVisible(TraceManager.get().hasInstance()); } else { Visualization.analysisMenu.setVisible(false); Visualization.analysisMenu.getItem(2).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); } Visualization.analysisMenu.getItem(3).setVisible(false); Visualization.analysisMenu.getItem(4).setVisible(false); Visualization.analysisMenu.getItem(5).setVisible(false); Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); Visualization.analysisMenu.getItem(11).setVisible(false); Field field; try { field = GraphViewer.class.getDeclaredField("selected"); field.setAccessible(true); if (field.get(Visualization.viewer) instanceof GraphEdge) { final GraphEdge edge = (GraphEdge) field.get(Visualization.viewer); Visualization.relation = edge.group.toString().substring(0, edge.group.toString().indexOf(":") - 1); } } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); } } else { Visualization.modelWriterMenu.setVisible(false); Visualization.analysisMenu.setVisible(false); } } else { Visualization.modelWriterMenu.setVisible(true); Visualization.modelWriterMenu.getItem(0).setVisible(false); Visualization.modelWriterMenu.getItem(1) .setVisible(!TraceManager.get().hasInstance()); Visualization.modelWriterMenu.getItem(2).setVisible(false); Visualization.modelWriterMenu.getItem(3).setVisible(false); Visualization.modelWriterMenu.getItem(4).setVisible(false); Visualization.modelWriterMenu.getItem(5).setVisible(false); Visualization.modelWriterMenu.getItem(6).setVisible(TraceManager.get().hasInstance()); Visualization.analysisMenu.setVisible(true); Visualization.analysisMenu.getItem(0).setVisible(true); Visualization.analysisMenu.getItem(8).setVisible(false); Visualization.analysisMenu.getItem(9).setVisible(false); final Object curState = Visualization.sourceProvider.getCurrentState() .get(AnalysisSourceProvider.ANALYSIS_STATE); // STATE MACHINE if (curState.equals(AnalysisSourceProvider.ACTIVE)) { Visualization.analysisMenu.getItem(1).setVisible(false); // reason Visualization.analysisMenu.getItem(5).setVisible(false); // discover if (AlloyNextSolutionReasoning.getInstance().getAns() != null || AlloyNextSolutionDiscovering.getInstance().getAns() != null) { Visualization.analysisMenu.getItem(3).setVisible(true); // next Visualization.analysisMenu.getItem(4).setVisible(true); // stop } else { Visualization.analysisMenu.getItem(3).setVisible(false); // next Visualization.analysisMenu.getItem(4).setVisible(false); // stop } } else if (curState.equals(AnalysisSourceProvider.PASSIVE)) { Visualization.analysisMenu.getItem(1).setVisible(true); // reason Visualization.analysisMenu.getItem(5).setVisible(true); // discover Visualization.analysisMenu.getItem(3).setVisible(false); // next Visualization.analysisMenu.getItem(4).setVisible(false); // stop } Visualization.analysisMenu.getItem(2).setVisible(false); if (AlloyUtilities.isAnyReasoned()) { Visualization.analysisMenu.getItem(6).setVisible(true); Visualization.analysisMenu.getItem(10).setVisible(TraceManager.get().hasInstance()); } else { Visualization.analysisMenu.getItem(6).setVisible(false); Visualization.analysisMenu.getItem(10).setVisible(false); } Visualization.analysisMenu.getItem(7).setVisible(false); Visualization.analysisMenu.getItem(11).setVisible(false); } if (e.getSource() instanceof GraphViewer) { Visualization.viewer.alloyPopup(Visualization.viewer, e.getX(), e.getY()); } else { Visualization.viewer.alloyPopup(Visualization.graphPanel, e.getX(), e.getY()); } default: break; } } }; } private static MouseMotionAdapter getMouseMotionAdapter() { return new MouseMotionAdapter() { @Override public void mouseMoved(final MouseEvent e) { JComponent cmpnt = null; String tooltip = null; try { final Object annotation = Visualization.viewer.alloyGetAnnotationAtXY(e.getX(), e.getY()); cmpnt = (JComponent) e.getComponent(); if (annotation instanceof AlloyAtom) { final IMarker marker = Visualization.getMarker((AlloyAtom) annotation); if (marker == null) { return; } Visualization.frame.setCursor(new Cursor(Cursor.HAND_CURSOR)); tooltip = MarkUtilities.getText(marker); } else if (annotation instanceof AlloyTuple) { final AlloyTuple tuple = (AlloyTuple) annotation; final AlloyAtom highLightedAtomStart = tuple.getStart(); final AlloyAtom highLightedAtomEnd = tuple.getEnd(); final IMarker markerStart = Visualization.getMarker(highLightedAtomStart); final IMarker markerEnd = Visualization.getMarker(highLightedAtomEnd); if (markerStart == null || markerEnd == null) { return; } tooltip = MarkUtilities.getText(markerStart) + " --> " + MarkUtilities.getText(markerEnd); Visualization.frame.setCursor(new Cursor(Cursor.HAND_CURSOR)); } else { /** * when mouse exited from AlloyAtom or from AlloyTuple */ Visualization.frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } catch (Exception ex) { System.err.println("onMouseMoved failed"); // ex.printStackTrace(); } finally { cmpnt.setToolTipText(tooltip); } } }; } public static void showViz() { if (Visualization.container == null) { return; } if (!AlloyUtilities.isExists()) { if (Visualization.frame != null) { if (Visualization.frame.getComponentCount() > 0) { Visualization.frame.removeAll(); } Visualization.frame.add(new JPanel()); } else if (Visualization.frame == null) { Visualization.frame = SWT_AWT.new_Frame(Visualization.container); Visualization.frame.add(new JPanel()); } return; } Visualization.f = new File(Visualization.xmlFileName); try { if (!Visualization.f.exists()) { throw new IOException("File " + Visualization.xmlFileName + " does not exist."); } final AlloyInstance instance = StaticInstanceReader.parseInstance(Visualization.f); AlloyUtilities.setAllImpactsAndChanges(instance); AlloyUtilities.setAllReasonedTuples(instance); AlloyUtilities.setAllReasonedAtoms(instance); Visualization.myState = new VizState(instance); // FE Visualization.myState.mergeArrows.put(null, false); if (Visualization.frame == null) { Visualization.frame = SWT_AWT.new_Frame(Visualization.container); } if (Visualization.graph != null && Visualization.frame.getComponent(0) != null) { Visualization.frame.remove(Visualization.graph); } try { /* * TODO BUG * * A Fatal Error occurs while setting GTK look and feel on Ubuntu 16.04 * (com.sun.java.swing.plaf.gtk.GTKLookAndFeel). * */ final String LaF = UIManager.getSystemLookAndFeelClassName(); if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(LaF)) { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } else { UIManager.setLookAndFeel(LaF); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } Visualization.graph = new VizGraphPanel(Visualization.myState, false); Visualization.graphPanel = Visualization.graph.getGraphPanel(); Visualization.viewer = Visualization.graph.alloyGetViewer(); Visualization.frame.removeAll(); Visualization.frame.add(Visualization.graph); Visualization.frame.setVisible(true); Visualization.frame.setAlwaysOnTop(true); Visualization.graph.alloyGetViewer().alloyRepaint(); final ISourceProviderService service = Activator.getDefault().getWorkbench().getService(ISourceProviderService.class); Visualization.sourceProvider = (AnalysisSourceProvider) service.getSourceProvider(AnalysisSourceProvider.ANALYSIS_STATE); } catch (final Err e1) { e1.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } Visualization.createPopupMenu(); Visualization.graph.alloyGetViewer() .addMouseMotionListener(Visualization.getMouseMotionAdapter()); Visualization.graphPanel.addMouseMotionListener(Visualization.getMouseMotionAdapter()); Visualization.graph.alloyGetViewer().addMouseListener(Visualization.getMouseAdapter()); Visualization.graphPanel.addMouseListener(Visualization.getMouseAdapter()); } private static void createPopupMenu() { final JMenu modelWriterMenu = Visualization.modelWriterMenu = new JMenu("Management"); Visualization.graph.alloyGetViewer().pop.add(modelWriterMenu, 0); final JMenuItem deleteAtomMenuItem = new JMenuItem("Delete Atom"); final JMenuItem addRemoveTypeMenuItem = new JMenuItem("Change Type"); final JMenuItem removeRelationMenuItem = new JMenuItem("Remove Relation"); final JMenuItem mappingMenuItem = new JMenuItem("Map Atom"); final JMenuItem createNewAtomMenuItem = new JMenuItem("Create New Atom"); final JMenuItem createInstanceElementMenuItem = new JMenuItem("Create New Atom"); final JMenuItem resolveMenuItem = new JMenuItem("Resolve"); modelWriterMenu.add(addRemoveTypeMenuItem, 0); modelWriterMenu.add(createNewAtomMenuItem, 1); modelWriterMenu.add(deleteAtomMenuItem, 2); modelWriterMenu.add(mappingMenuItem, 3); modelWriterMenu.add(removeRelationMenuItem, 4); modelWriterMenu.add(resolveMenuItem, 5); modelWriterMenu.add(createInstanceElementMenuItem, 6); final JMenu analysisMenu = Visualization.analysisMenu = new JMenu("Analysis"); Visualization.graph.alloyGetViewer().pop.add(analysisMenu, 1); final JMenuItem validateMenuItem = new JMenuItem("Check Consistency"); final JMenuItem discoverRelationMenuItem = new JMenuItem("Reason on Relations"); final JMenuItem acceptReasonedRelationMenuItem = new JMenuItem("Accept Reasoning"); final JMenuItem discoverAtomMenuItem = new JMenuItem("Discover Atoms"); final JMenuItem interpretAtomMenuItem = new JMenuItem("Interpret Atom"); final JMenuItem acceptRelationAsEMFMenuItem = new JMenuItem("Accept Reasoning"); final JMenuItem acceptAtomAsEMFMenuItem = new JMenuItem("Interpret Atom"); final JMenuItem discoverRelationForAtomMenuItem = new JMenuItem("Reasoning for Atom"); final JMenuItem nextSolution = new JMenuItem("Next Solution"); final JMenuItem stopAnalysis = new JMenuItem("Stop Analysis"); final JMenuItem clearAllReasoned = new JMenuItem("Clear All Reasoned Tuples"); final JMenuItem acceptAllReasoned = new JMenuItem("Accept All Reasoned Tuples"); analysisMenu.add(validateMenuItem, 0); analysisMenu.add(discoverRelationMenuItem, 1); analysisMenu.add(acceptReasonedRelationMenuItem, 2); analysisMenu.add(nextSolution, 3); analysisMenu.add(stopAnalysis, 4); analysisMenu.add(discoverAtomMenuItem, 5); analysisMenu.add(clearAllReasoned, 6); analysisMenu.add(interpretAtomMenuItem, 7); analysisMenu.add(acceptAtomAsEMFMenuItem, 8); analysisMenu.add(acceptRelationAsEMFMenuItem, 9); analysisMenu.add(acceptAllReasoned, 10); analysisMenu.add(discoverRelationForAtomMenuItem, 11); final JMenuItem refreshMenuItem = new JMenuItem("Refresh"); Visualization.graph.alloyGetViewer().pop.add(refreshMenuItem, 2); refreshMenuItem.addActionListener(VisualizationActionListenerFactory.refreshActionListener()); addRemoveTypeMenuItem .addActionListener(VisualizationActionListenerFactory.addRemoveTypeActionListener()); createNewAtomMenuItem .addActionListener(VisualizationActionListenerFactory.createNewAtomActionListener()); deleteAtomMenuItem .addActionListener(VisualizationActionListenerFactory.deleteAtomActionListener()); mappingMenuItem.addActionListener(VisualizationActionListenerFactory.mappingActionListener()); removeRelationMenuItem .addActionListener(VisualizationActionListenerFactory.removeRelationActionListener()); resolveMenuItem.addActionListener(VisualizationActionListenerFactory.resolveActionListener()); validateMenuItem.addActionListener(VisualizationActionListenerFactory.validateActionListener()); discoverRelationMenuItem .addActionListener(VisualizationActionListenerFactory.discoverRelationActionListener()); acceptReasonedRelationMenuItem.addActionListener( VisualizationActionListenerFactory.acceptReasonedRelationActionListener()); discoverAtomMenuItem .addActionListener(VisualizationActionListenerFactory.discoverAtomActionListener()); nextSolution.addActionListener(VisualizationActionListenerFactory.nextSolutionActionListener()); stopAnalysis.addActionListener(VisualizationActionListenerFactory.stopAnalysisActionListener()); clearAllReasoned .addActionListener(VisualizationActionListenerFactory.clearAllReasonedActionListener()); interpretAtomMenuItem.addActionListener( VisualizationActionListenerFactory.interpretAtomMenuItemActionListener()); acceptRelationAsEMFMenuItem.addActionListener( VisualizationActionListenerFactory.acceptRelationAsEMFMenuItemActionListener()); acceptAtomAsEMFMenuItem.addActionListener( VisualizationActionListenerFactory.acceptAtomAsEMFMenuItemActionListener()); acceptAllReasoned .addActionListener(VisualizationActionListenerFactory.acceptAllReasonedListener()); discoverRelationForAtomMenuItem.addActionListener( VisualizationActionListenerFactory.discoverRelationForAtomActionListener()); createInstanceElementMenuItem.addActionListener( VisualizationActionListenerFactory.createInstanceElementActionListener()); } @Override public void createPartControl(final Composite parent) { Visualization.container = new Composite(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND); Visualization.frame = null; Visualization.f = null; Visualization.graph = null; Visualization.myState = null; Visualization.showViz(); } @Override public void setFocus() {} }
Visualization restores last location after refresh
Source/eu.modelwriter.marker.ui/src/eu/modelwriter/marker/ui/internal/views/visualizationview/Visualization.java
Visualization restores last location after refresh
Java
epl-1.0
eec1b677fb4d28ee64529b62aa0d2e0f04bf4b9f
0
eclipse/dawnsci,DawnScience/dawnsci,belkassaby/dawnsci,xen-0/dawnsci
package org.eclipse.dawnsci.nexus.builder.data.impl; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertAxes; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertIndices; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertShape; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertSignal; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertTarget; import java.util.Arrays; import org.eclipse.dawnsci.nexus.NXdata; import org.eclipse.dawnsci.nexus.NXdetector; import org.eclipse.dawnsci.nexus.NXpositioner; import org.eclipse.dawnsci.nexus.NXroot; import org.eclipse.dawnsci.nexus.NexusBaseClass; import org.eclipse.dawnsci.nexus.NexusException; import org.eclipse.dawnsci.nexus.NexusNodeFactory; import org.eclipse.dawnsci.nexus.builder.AbstractNexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.NexusEntryBuilder; import org.eclipse.dawnsci.nexus.builder.NexusFileBuilder; import org.eclipse.dawnsci.nexus.builder.NexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.data.DataDeviceBuilder; import org.eclipse.dawnsci.nexus.builder.data.NexusDataBuilder; import org.eclipse.dawnsci.nexus.builder.impl.DefaultNexusFileBuilder; import org.eclipse.january.dataset.DatasetFactory; import org.eclipse.january.dataset.FloatDataset; import org.junit.Before; import org.junit.Test; /** * This test class tests that DefaultNexusDataBuilder * can construct the example {@link NXdata} structures from the * document http://wiki.nexusformat.org/2014_axes_and_uncertainties. */ public class DefaultNexusDataExamplesTest { public static class TestDetector extends AbstractNexusObjectProvider<NXdetector> { private final int[] shape; private boolean hasTimeOfFlight; public TestDetector(int... shape) { this("testDetector", shape); } public TestDetector(String name, int... shape) { this(name, true, shape); } public TestDetector(String name, boolean useDeviceName, int... shape) { super(name, NexusBaseClass.NX_DETECTOR, NXdetector.NX_DATA); setUseDeviceNameInNXdata(useDeviceName); this.shape = shape; } @Override protected NXdetector createNexusObject() { NXdetector detector = NexusNodeFactory.createNXdetector(); detector.setData(DatasetFactory.zeros(FloatDataset.class, shape)); if (hasTimeOfFlight) { detector.setTime_of_flight(DatasetFactory.zeros(FloatDataset.class, shape[shape.length - 1])); } return detector; } } public static class TestPositioner extends AbstractNexusObjectProvider<NXpositioner> { private final int[] shape; public TestPositioner(String name, int... shape) { super(name, NexusBaseClass.NX_POSITIONER, NXpositioner.NX_VALUE); this.shape = shape; } @Override protected NXpositioner createNexusObject() { NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setValue(DatasetFactory.zeros(FloatDataset.class, shape)); return positioner; } } public static class PolarAnglePositioner extends AbstractNexusObjectProvider<NXpositioner> { private final int dimensionIndex; private final int[] scanShape; public PolarAnglePositioner(String name, int dimensionIndex, int[] scanShape) { super(name, NexusBaseClass.NX_POSITIONER); this.dimensionIndex = dimensionIndex; this.scanShape = scanShape; setAxisDataFieldNames("rbv", "set"); setDefaultAxisDataFieldName("set"); } @Override protected NXpositioner createNexusObject() { NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setField("rbv", DatasetFactory.zeros(FloatDataset.class, scanShape)); positioner.setField("set", DatasetFactory.zeros(FloatDataset.class, scanShape[dimensionIndex])); return positioner; } } private NexusDataBuilder dataBuilder; private NXroot nxRoot; private NXdata nxData; private NexusEntryBuilder entryBuilder; @Before public void setUp() throws Exception { NexusFileBuilder fileBuilder = new DefaultNexusFileBuilder("test"); nxRoot = fileBuilder.getNXroot(); entryBuilder = fileBuilder.newEntry(); entryBuilder.addDefaultGroups(); dataBuilder = entryBuilder.createDefaultData(); nxData = dataBuilder.getNxData(); } private void addToEntry(NexusObjectProvider<?>... nexusObjects) throws NexusException { entryBuilder.addAll(Arrays.asList(nexusObjects)); } @Test public void testExample1() throws NexusException { TestDetector detector = new TestDetector("data", 100); TestPositioner positioner = new TestPositioner("x", 100); addToEntry(detector, positioner); dataBuilder.setPrimaryDevice(detector); dataBuilder.addAxisDevice(positioner, 0); assertSignal(nxData, "data"); assertAxes(nxData, "x"); assertShape(nxData, "data", 100); assertTarget(nxData, "data", nxRoot, "/entry/instrument/data/data"); assertShape(nxData, "x", 100); assertIndices(nxData, "x", 0); assertTarget(nxData, "x", nxRoot, "/entry/instrument/x/value"); } @Test public void testExample2() throws NexusException { TestDetector mainDetector = new TestDetector("data", 1000, 20); TestDetector pressureDet = new TestDetector("pressure", 20); TestDetector temperatureDet = new TestDetector("temperature", 20); TestDetector timeDet = new TestDetector("time", 1000); addToEntry(mainDetector, pressureDet, temperatureDet, timeDet); dataBuilder.setPrimaryDevice(mainDetector); dataBuilder.addAxisDevice(pressureDet, 1); dataBuilder.addAxisDevice(temperatureDet, null, 1); dataBuilder.addAxisDevice(timeDet, 0); assertSignal(nxData, "data"); assertAxes(nxData, "time", "pressure"); assertShape(nxData, "data", 1000, 20); assertTarget(nxData, "data", nxRoot, "/entry/instrument/data/data"); assertShape(nxData, "pressure", 20); assertIndices(nxData, "pressure", 1); assertTarget(nxData, "pressure", nxRoot, "/entry/instrument/pressure/data"); assertShape(nxData, "temperature", 20); assertIndices(nxData, "temperature", 1); assertTarget(nxData, "temperature", nxRoot, "/entry/instrument/temperature/data"); assertShape(nxData, "time", 1000); assertIndices(nxData, "time", 0); assertTarget(nxData, "time", nxRoot, "/entry/instrument/time/data"); } /** * @throws NexusException */ @Test public void testExample3() throws NexusException { TestDetector mainDetector = new TestDetector("det", true, 100, 100000); TestDetector pressureDetector = new TestDetector("pressure", 100); TestDetector tofDetector = new TestDetector("tof", 100000); addToEntry(mainDetector, pressureDetector, tofDetector); dataBuilder.setPrimaryDevice(mainDetector); dataBuilder.addAxisDevice(pressureDetector, 0); dataBuilder.addAxisDevice(tofDetector, 1); assertSignal(nxData, "det"); assertAxes(nxData, "pressure", "tof"); assertShape(nxData, "det", 100, 100000); assertTarget(nxData, "det", nxRoot, "/entry/instrument/det/data"); assertShape(nxData, "pressure", 100); assertIndices(nxData, "pressure", 0); assertTarget(nxData, "pressure", nxRoot, "/entry/instrument/pressure/data"); assertShape(nxData, "tof", 100000); assertIndices(nxData, "tof", 1); assertTarget(nxData, "tof", nxRoot, "/entry/instrument/tof/data"); } @Test public void testExample4() throws NexusException { // note, wiki page example has 100x512x100000 but this is too large to allocate TestDetector mainDetector = new TestDetector("det", 100, 512, 1000); TestDetector tofDetector = new TestDetector("tof", 1000); TestPositioner xPositioner = new TestPositioner("x", 100, 512); TestPositioner yPositioner = new TestPositioner("y", 100, 512); addToEntry(mainDetector, tofDetector, xPositioner, yPositioner); dataBuilder.setPrimaryDevice(DataDeviceBuilder.newPrimaryDataDevice(mainDetector)); dataBuilder.addAxisDevice(tofDetector, 2); dataBuilder.addAxisDevice(xPositioner, 0, 0, 1); dataBuilder.addAxisDevice(yPositioner, 1, 0, 1); assertSignal(nxData, "det"); assertAxes(nxData, "x", "y", "tof"); assertShape(nxData, "det", 100, 512, 1000); assertTarget(nxData, "det", nxRoot, "/entry/instrument/det/data"); assertIndices(nxData, "x", 0, 1); assertShape(nxData, "x", 100, 512); assertTarget(nxData, "x", nxRoot, "/entry/instrument/x/value"); assertIndices(nxData, "y", 0, 1); assertShape(nxData, "y", 100, 512); assertTarget(nxData, "y", nxRoot, "/entry/instrument/y/value"); } @Test public void testExample5() throws NexusException { TestDetector mainDetector = new TestDetector("det1", 50, 5, 1024); PolarAnglePositioner polarAnglePositioner = new PolarAnglePositioner( "polar_angle", 0, new int[] { 50, 5 }); TestPositioner frameNumberPositioner = new TestPositioner("frame_number", 5); TestPositioner timePositioner = new TestPositioner("time", 50, 5); addToEntry(mainDetector, polarAnglePositioner, frameNumberPositioner, timePositioner); dataBuilder.setPrimaryDevice(DataDeviceBuilder.newPrimaryDataDevice(mainDetector)); dataBuilder.addAxisDevice(polarAnglePositioner, 0, 0, 1); dataBuilder.addAxisDevice(frameNumberPositioner, 1); dataBuilder.addAxisDevice(timePositioner, null, 0, 1); assertSignal(nxData, "det1"); assertAxes(nxData, "polar_angle_set", "frame_number", "."); assertShape(nxData, "det1", 50, 5, 1024); assertTarget(nxData, "det1", nxRoot, "/entry/instrument/det1/data"); assertIndices(nxData, "polar_angle_set", 0); assertShape(nxData, "polar_angle_set", 50); assertTarget(nxData, "polar_angle_set", nxRoot, "/entry/instrument/polar_angle/set"); assertIndices(nxData, "polar_angle_rbv", 0, 1); assertShape(nxData, "polar_angle_rbv", 50, 5); assertTarget(nxData, "polar_angle_rbv", nxRoot, "/entry/instrument/polar_angle/rbv"); assertIndices(nxData, "frame_number", 1); assertShape(nxData, "frame_number", 5); assertTarget(nxData, "frame_number", nxRoot, "/entry/instrument/frame_number/value"); assertIndices(nxData, "time", 0, 1); assertShape(nxData, "time", 50, 5); assertTarget(nxData, "time", nxRoot, "/entry/instrument/time/value"); } }
org.eclipse.dawnsci.nexus.test/src/org/eclipse/dawnsci/nexus/builder/data/impl/DefaultNexusDataExamplesTest.java
package org.eclipse.dawnsci.nexus.builder.data.impl; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertAxes; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertIndices; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertShape; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertSignal; import static org.eclipse.dawnsci.nexus.test.util.NexusAssert.assertTarget; import java.util.Arrays; import org.eclipse.dawnsci.nexus.NXdata; import org.eclipse.dawnsci.nexus.NXdetector; import org.eclipse.dawnsci.nexus.NXpositioner; import org.eclipse.dawnsci.nexus.NXroot; import org.eclipse.dawnsci.nexus.NexusBaseClass; import org.eclipse.dawnsci.nexus.NexusException; import org.eclipse.dawnsci.nexus.NexusNodeFactory; import org.eclipse.dawnsci.nexus.builder.AbstractNexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.NexusEntryBuilder; import org.eclipse.dawnsci.nexus.builder.NexusFileBuilder; import org.eclipse.dawnsci.nexus.builder.NexusObjectProvider; import org.eclipse.dawnsci.nexus.builder.data.DataDeviceBuilder; import org.eclipse.dawnsci.nexus.builder.data.NexusDataBuilder; import org.eclipse.dawnsci.nexus.builder.impl.DefaultNexusFileBuilder; import org.eclipse.january.dataset.DatasetFactory; import org.eclipse.january.dataset.FloatDataset; import org.junit.Before; import org.junit.Test; /** * This test class tests that DefaultNexusDataBuilder * can construct the example {@link NXdata} structures from the * document http://wiki.nexusformat.org/2014_axes_and_uncertainties. */ public class DefaultNexusDataExamplesTest { public static class TestDetector extends AbstractNexusObjectProvider<NXdetector> { private final int[] shape; private boolean hasTimeOfFlight; public TestDetector(int... shape) { this("testDetector", shape); } public TestDetector(String name, int... shape) { this(name, true, shape); } public TestDetector(String name, boolean useDeviceName, int... shape) { super(name, NexusBaseClass.NX_DETECTOR, NXdetector.NX_DATA); setUseDeviceNameInNXdata(useDeviceName); this.shape = shape; } @Override protected NXdetector createNexusObject() { NXdetector detector = NexusNodeFactory.createNXdetector(); detector.setData(DatasetFactory.zeros(FloatDataset.class, shape)); if (hasTimeOfFlight) { detector.setTime_of_flight(DatasetFactory.zeros(FloatDataset.class, shape[shape.length - 1])); } return detector; } } public static class TestPositioner extends AbstractNexusObjectProvider<NXpositioner> { private final int[] shape; public TestPositioner(String name, int... shape) { super(name, NexusBaseClass.NX_POSITIONER, NXpositioner.NX_VALUE); this.shape = shape; } @Override protected NXpositioner createNexusObject() { NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setValue(DatasetFactory.zeros(FloatDataset.class, shape)); return positioner; } } public static class PolarAnglePositioner extends AbstractNexusObjectProvider<NXpositioner> { private final int dimensionIndex; private final int[] scanShape; public PolarAnglePositioner(String name, int dimensionIndex, int[] scanShape) { super(name, NexusBaseClass.NX_POSITIONER); this.dimensionIndex = dimensionIndex; this.scanShape = scanShape; setAxisDataFieldNames("rbv", "demand"); setDefaultAxisDataFieldName("demand"); } @Override protected NXpositioner createNexusObject() { NXpositioner positioner = NexusNodeFactory.createNXpositioner(); positioner.setField("rbv", DatasetFactory.zeros(FloatDataset.class, scanShape)); positioner.setField("demand", DatasetFactory.zeros(FloatDataset.class, scanShape[dimensionIndex])); return positioner; } } private NexusDataBuilder dataBuilder; private NXroot nxRoot; private NXdata nxData; private NexusEntryBuilder entryBuilder; @Before public void setUp() throws Exception { NexusFileBuilder fileBuilder = new DefaultNexusFileBuilder("test"); nxRoot = fileBuilder.getNXroot(); entryBuilder = fileBuilder.newEntry(); entryBuilder.addDefaultGroups(); dataBuilder = entryBuilder.createDefaultData(); nxData = dataBuilder.getNxData(); } private void addToEntry(NexusObjectProvider<?>... nexusObjects) throws NexusException { entryBuilder.addAll(Arrays.asList(nexusObjects)); } @Test public void testExample1() throws NexusException { TestDetector detector = new TestDetector("data", 100); TestPositioner positioner = new TestPositioner("x", 100); addToEntry(detector, positioner); dataBuilder.setPrimaryDevice(detector); dataBuilder.addAxisDevice(positioner, 0); assertSignal(nxData, "data"); assertAxes(nxData, "x"); assertShape(nxData, "data", 100); assertTarget(nxData, "data", nxRoot, "/entry/instrument/data/data"); assertShape(nxData, "x", 100); assertIndices(nxData, "x", 0); assertTarget(nxData, "x", nxRoot, "/entry/instrument/x/value"); } @Test public void testExample2() throws NexusException { TestDetector mainDetector = new TestDetector("data", 1000, 20); TestDetector pressureDet = new TestDetector("pressure", 20); TestDetector temperatureDet = new TestDetector("temperature", 20); TestDetector timeDet = new TestDetector("time", 1000); addToEntry(mainDetector, pressureDet, temperatureDet, timeDet); dataBuilder.setPrimaryDevice(mainDetector); dataBuilder.addAxisDevice(pressureDet, 1); dataBuilder.addAxisDevice(temperatureDet, null, 1); dataBuilder.addAxisDevice(timeDet, 0); assertSignal(nxData, "data"); assertAxes(nxData, "time", "pressure"); assertShape(nxData, "data", 1000, 20); assertTarget(nxData, "data", nxRoot, "/entry/instrument/data/data"); assertShape(nxData, "pressure", 20); assertIndices(nxData, "pressure", 1); assertTarget(nxData, "pressure", nxRoot, "/entry/instrument/pressure/data"); assertShape(nxData, "temperature", 20); assertIndices(nxData, "temperature", 1); assertTarget(nxData, "temperature", nxRoot, "/entry/instrument/temperature/data"); assertShape(nxData, "time", 1000); assertIndices(nxData, "time", 0); assertTarget(nxData, "time", nxRoot, "/entry/instrument/time/data"); } /** * @throws NexusException */ @Test public void testExample3() throws NexusException { TestDetector mainDetector = new TestDetector("det", true, 100, 100000); TestDetector pressureDetector = new TestDetector("pressure", 100); TestDetector tofDetector = new TestDetector("tof", 100000); addToEntry(mainDetector, pressureDetector, tofDetector); dataBuilder.setPrimaryDevice(mainDetector); dataBuilder.addAxisDevice(pressureDetector, 0); dataBuilder.addAxisDevice(tofDetector, 1); assertSignal(nxData, "det"); assertAxes(nxData, "pressure", "tof"); assertShape(nxData, "det", 100, 100000); assertTarget(nxData, "det", nxRoot, "/entry/instrument/det/data"); assertShape(nxData, "pressure", 100); assertIndices(nxData, "pressure", 0); assertTarget(nxData, "pressure", nxRoot, "/entry/instrument/pressure/data"); assertShape(nxData, "tof", 100000); assertIndices(nxData, "tof", 1); assertTarget(nxData, "tof", nxRoot, "/entry/instrument/tof/data"); } @Test public void testExample4() throws NexusException { // note, wiki page example has 100x512x100000 but this is too large to allocate TestDetector mainDetector = new TestDetector("det", 100, 512, 1000); TestDetector tofDetector = new TestDetector("tof", 1000); TestPositioner xPositioner = new TestPositioner("x", 100, 512); TestPositioner yPositioner = new TestPositioner("y", 100, 512); addToEntry(mainDetector, tofDetector, xPositioner, yPositioner); dataBuilder.setPrimaryDevice(DataDeviceBuilder.newPrimaryDataDevice(mainDetector)); dataBuilder.addAxisDevice(tofDetector, 2); dataBuilder.addAxisDevice(xPositioner, 0, 0, 1); dataBuilder.addAxisDevice(yPositioner, 1, 0, 1); assertSignal(nxData, "det"); assertAxes(nxData, "x", "y", "tof"); assertShape(nxData, "det", 100, 512, 1000); assertTarget(nxData, "det", nxRoot, "/entry/instrument/det/data"); assertIndices(nxData, "x", 0, 1); assertShape(nxData, "x", 100, 512); assertTarget(nxData, "x", nxRoot, "/entry/instrument/x/value"); assertIndices(nxData, "y", 0, 1); assertShape(nxData, "y", 100, 512); assertTarget(nxData, "y", nxRoot, "/entry/instrument/y/value"); } @Test public void testExample5() throws NexusException { TestDetector mainDetector = new TestDetector("det1", 50, 5, 1024); PolarAnglePositioner polarAnglePositioner = new PolarAnglePositioner( "polar_angle", 0, new int[] { 50, 5 }); TestPositioner frameNumberPositioner = new TestPositioner("frame_number", 5); TestPositioner timePositioner = new TestPositioner("time", 50, 5); addToEntry(mainDetector, polarAnglePositioner, frameNumberPositioner, timePositioner); dataBuilder.setPrimaryDevice(DataDeviceBuilder.newPrimaryDataDevice(mainDetector)); dataBuilder.addAxisDevice(polarAnglePositioner, 0, 0, 1); dataBuilder.addAxisDevice(frameNumberPositioner, 1); dataBuilder.addAxisDevice(timePositioner, null, 0, 1); assertSignal(nxData, "det1"); assertAxes(nxData, "polar_angle_demand", "frame_number", "."); assertShape(nxData, "det1", 50, 5, 1024); assertTarget(nxData, "det1", nxRoot, "/entry/instrument/det1/data"); assertIndices(nxData, "polar_angle_demand", 0); assertShape(nxData, "polar_angle_demand", 50); assertTarget(nxData, "polar_angle_demand", nxRoot, "/entry/instrument/polar_angle/demand"); assertIndices(nxData, "polar_angle_rbv", 0, 1); assertShape(nxData, "polar_angle_rbv", 50, 5); assertTarget(nxData, "polar_angle_rbv", nxRoot, "/entry/instrument/polar_angle/rbv"); assertIndices(nxData, "frame_number", 1); assertShape(nxData, "frame_number", 5); assertTarget(nxData, "frame_number", nxRoot, "/entry/instrument/frame_number/value"); assertIndices(nxData, "time", 0, 1); assertShape(nxData, "time", 50, 5); assertTarget(nxData, "time", nxRoot, "/entry/instrument/time/value"); } }
[DAQ-352] target value of position changed from _demand to _set Signed-off-by: Matthew Dickie <82dca48737570b4f49d59ca286b5034c15e72ebc@diamond.ac.uk>
org.eclipse.dawnsci.nexus.test/src/org/eclipse/dawnsci/nexus/builder/data/impl/DefaultNexusDataExamplesTest.java
[DAQ-352] target value of position changed from _demand to _set
Java
agpl-3.0
aba1a70c921f0c31897eac385da18f1138f356f1
0
CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine
package com.splicemachine.triggers; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import com.splicemachine.derby.test.framework.SpliceSchemaWatcher; import com.splicemachine.derby.test.framework.SpliceWatcher; import com.splicemachine.derby.utils.TimestampAdmin; import com.splicemachine.homeless.TestUtils; import com.splicemachine.test_dao.TriggerBuilder; import com.splicemachine.test_dao.TriggerDAO; /** * Tests trigger execution of stored procedures. * <p/> * Note the dependency on user-defined stored procedures in this test class.<br/> * See {@link TriggerProcs} for instructions on adding/modifying store procedures. */ public class Trigger_Exec_Stored_Proc_IT { private static final String SCHEMA = Trigger_Exec_Stored_Proc_IT.class.getSimpleName(); @ClassRule public static SpliceSchemaWatcher schemaWatcher = new SpliceSchemaWatcher(SCHEMA); @ClassRule public static SpliceWatcher classWatcher = new SpliceWatcher(SCHEMA); private static final String DERBY_JAR_NAME = SCHEMA + ".TRIGGER_PROCS_JAR"; private static final String CALL_SET_CLASSPATH_STRING = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath', %s)"; private static final String CREATE_PROC = "CREATE PROCEDURE "+ SCHEMA+".proc_call_audit(" + "in schema_name varchar(30), in table_name varchar(20)) " + "PARAMETER STYLE JAVA LANGUAGE JAVA READS SQL DATA " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit'"; private static final String CREATE_PROC_WITH_TRANSITION_VAR = "CREATE PROCEDURE "+ SCHEMA+".proc_call_audit_with_transition(" + "in schema_name varchar(30), in table_name varchar(20), in new_val integer, in old_val integer) " + "PARAMETER STYLE JAVA LANGUAGE JAVA READS SQL DATA " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit_with_transition'"; private static final String CREATE_PROC_WITH_RESULT = "CREATE PROCEDURE "+SCHEMA+".proc_call_audit_with_result(" + "in schema_name varchar(30), in table_name varchar(20)) " + "PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit_with_result'"; private static final String CREATE_EXEC_PROC = "CREATE PROCEDURE "+SCHEMA+".proc_exec_sql(" + "in sqlText varchar(200)) " + "PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_exec_sql'"; @Rule public SpliceWatcher methodWatcher = new SpliceWatcher(SCHEMA); private TriggerBuilder tb = new TriggerBuilder(); private TriggerDAO triggerDAO = new TriggerDAO(methodWatcher.getOrCreateConnection()); @BeforeClass public static void setUpClass() throws Exception { String storedProcsJarFilePath = TriggerProcs.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); // Install the jar file of stored procedures. File jar = new File(storedProcsJarFilePath); Assert.assertTrue("Can't run test without " + storedProcsJarFilePath, jar.exists()); classWatcher.executeUpdate(String.format("CALL SQLJ.INSTALL_JAR('%s', '%s', 0)", storedProcsJarFilePath, DERBY_JAR_NAME)); classWatcher.executeUpdate(String.format(CALL_SET_CLASSPATH_STRING, "'"+ DERBY_JAR_NAME +"'")); classWatcher.executeUpdate(CREATE_PROC); classWatcher.executeUpdate(CREATE_PROC_WITH_TRANSITION_VAR); classWatcher.executeUpdate(CREATE_PROC_WITH_RESULT); classWatcher.executeUpdate(CREATE_EXEC_PROC); } @AfterClass public static void tearDownClass() throws Exception { try { classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit")); classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit_with_transition")); classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit_with_result")); classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_exec_sql")); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } try { classWatcher.executeUpdate(String.format(CALL_SET_CLASSPATH_STRING, "NULL")); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } try { classWatcher.executeUpdate(String.format("CALL SQLJ.REMOVE_JAR('%s', 0)", DERBY_JAR_NAME)); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } } @Before public void setUp() throws Exception { classWatcher.executeUpdate("drop table if exists S"); classWatcher.executeUpdate("create table S (id integer, name varchar(30))"); classWatcher.executeUpdate("drop table if exists audit"); classWatcher.executeUpdate("create table audit (username varchar(20),insert_time timestamp, new_id integer, old_id integer)"); classWatcher.executeUpdate("drop table if exists t_out"); classWatcher.executeUpdate("create table t_out(id int, col2 char(10), col3 varchar(50), tm_time timestamp)"); classWatcher.executeUpdate("drop table if exists t_master"); classWatcher.executeUpdate("create table t_master(id int, col2 char(10), col3 varchar(50), tm_time timestamp)"); classWatcher.executeUpdate("drop table if exists t_slave"); classWatcher.executeUpdate("create table t_slave(id int, description varchar(10),tm_time timestamp)"); classWatcher.executeUpdate("drop table if exists t_slave2"); classWatcher.executeUpdate("create table t_slave2(id int, description varchar(10),tm_time timestamp)"); } /** * Create/fire a statement trigger that records username and timestamp of an insert in another table. */ @Test public void testStatementTriggerUserStoredProc() throws Exception { tb.named("auditme").before().insert().on("S").statement(). then(String.format("CALL proc_call_audit('%s','%s')", SCHEMA,"audit")); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13, 'Joe')"); s.execute("insert into S values (14, 'Henry')"); ResultSet rs = s.executeQuery("select * from audit"); int count =0; while (rs.next()) { ++count; Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); } Assert.assertEquals(2, count); rs.close(); c1.close(); triggerDAO.drop("auditme"); } /** * Create/fire a row trigger that records username, timestamp and new transition value * for an row inserted into another table. */ @Test public void testRowInsertTriggerUserStoredProc() throws Exception { createTrigger(tb.named("row_insert").after().insert().on("S").referencing("NEW AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); // when - insert a row methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); Assert.assertNotNull(rs.getObject(3)); ++count; } Assert.assertEquals(2, count); rs.close(); triggerDAO.drop("row_insert"); } /** * Create/fire a row trigger that records username, timestamp, new transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcNewTransitionValue() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); int id = rs.getInt(3); Assert.assertNotNull(id); Assert.assertEquals(39,id); Assert.assertNull(rs.getObject(4)); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_new"); } /** * Create/fire a row trigger that records username, timestamp, old transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcOldTransitionValue() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_old").after().update().on("S").referencing("OLD AS o") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", null, "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); // Assert.assertNotNull(rs.getObject(3)); int id = rs.getInt(4); Assert.assertNotNull(id); Assert.assertEquals(39, id); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_old"); } /** * Create/fire a row trigger that records username, timestamp, new transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcNewAndOldTransitionValues() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N OLD AS O") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); Assert.assertNotNull(rs.getObject(3)); int id = rs.getInt(4); Assert.assertNotNull(id); Assert.assertEquals(39, id); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_new"); } /** * Create/fire a row trigger that records username, timestamp, new and old transition values * for an row updated in another table. */ @Test public void testRowUpdateTriggerUserStoredProcTwoTriggers() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); createTrigger(tb.named("row_update_old").after().update().on("S").referencing("OLD AS o") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", null, "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); triggerDAO.drop("row_update_new"); triggerDAO.drop("row_update_old"); } /** * Create/fire a statement trigger that records username and timestamp of an insert in another table. */ @Test public void testStatementTriggerUserStoredProcWithResult() throws Exception { tb.named("auditme2").before().insert().on("S").statement(). then(String.format("CALL proc_call_audit_with_result('%s','%s')", SCHEMA,"audit")); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13,'Joe')"); s.execute("insert into S values (-1,'Henry')"); ResultSet rs = s.executeQuery("select * from audit"); int count =0; while (rs.next()) { ++count; Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); } Assert.assertEquals(2, count); rs.close(); c1.close(); triggerDAO.drop("auditme2"); } /** * Create/fire a statement trigger that calls a splice system procedure. */ @Test public void testStatementTriggerSysStoredProc() throws Exception { ResultSet rs = methodWatcher.executeQuery("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder')"); String originalLevel = null; while (rs.next()) { originalLevel = rs.getString(1); } Assert.assertNotNull(originalLevel); String newlevel = "INFO"; if (originalLevel.equals("INFO")) { newlevel = "WARN"; } tb.named("log_level_change").before().insert().on("S").statement(). then("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder', '"+newlevel+"')"); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13,'Joe')"); rs = methodWatcher.executeQuery("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder')"); String changedLevel = null; while (rs.next()) { changedLevel = rs.getString(1); } Assert.assertNotNull(changedLevel); Assert.assertEquals(newlevel, changedLevel); c1.createStatement().execute("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL('com.splicemachine.tools.version" + ".ManifestFinder', '" + originalLevel+"')"); rs.close(); c1.close(); triggerDAO.drop("log_level_change"); } /** * Create/fire a statement trigger that calls a splice system procedure with a SQL string to execute. */ @Test @Ignore("DB-3424: Executing trigger action insert thru a stored proc (disallowed directly) causes infinite recursion.") public void testExecSQLRecursion() throws Exception { methodWatcher.executeUpdate("insert into t_master values (13, 'grrr', 'I''m a pirate!', CURRENT_TIMESTAMP)"); methodWatcher.executeUpdate("insert into t_slave values (99, 'trigger01', CURRENT_TIMESTAMP)"); methodWatcher.executeUpdate("insert into t_slave2 values (22, 'trigger02', CURRENT_TIMESTAMP)"); createTrigger(tb.named("TriggerMaster01").before().insert().on("t_master") .statement().then(String.format("CALL proc_exec_sql('%s')", "insert into "+SCHEMA+".t_master select id, description, ''Is the REAL deal'', CURRENT_TIMESTAMP from "+SCHEMA+".t_slave"))); createTrigger(tb.named("TriggerMaster02").before().insert().on("t_master") .statement().then(String.format("CALL proc_exec_sql('%s')", "insert into "+SCHEMA+".t_master select id, description, ''Is the REAL deal'', CURRENT_TIMESTAMP from "+SCHEMA+".t_slave2"))); // never returns... methodWatcher.executeUpdate("insert into "+SCHEMA+".t_master values (01, 'roar', 'I''m a tiger!', CURRENT_TIMESTAMP)"); triggerDAO.drop("TriggerMaster01"); triggerDAO.drop("TriggerMaster02"); } /** * Create/fire a statement trigger that calls a splice system procedure with a SQL string to execute. */ @Test public void testExecSQL() throws Exception { methodWatcher.executeUpdate("insert into t_master values (13, 'grrr', 'I''m a pirate!', CURRENT_TIMESTAMP)"); methodWatcher.executeUpdate("insert into t_slave values (22, 'trigger01', CURRENT_TIMESTAMP)"); methodWatcher.executeUpdate("insert into t_slave2 values (99, 'trigger02', CURRENT_TIMESTAMP)"); createTrigger(tb.named("TriggerMaster01").before().insert().on("t_master") .statement().then(String.format("CALL proc_exec_sql('%s')", "insert into "+SCHEMA+".t_out select id, description, ''Is the REAL deal'', CURRENT_TIMESTAMP from "+SCHEMA+".t_slave"))); createTrigger(tb.named("TriggerMaster02").before().insert().on("t_master") .statement().then(String.format("CALL proc_exec_sql('%s')", "insert into "+SCHEMA+".t_out select id, description, ''Is the REAL deal'', CURRENT_TIMESTAMP from "+SCHEMA+".t_slave2"))); methodWatcher.executeUpdate("insert into " + SCHEMA + ".t_master values (01, 'roar', 'I''m a tiger!', CURRENT_TIMESTAMP)"); // String query = "select * from t_master"; // ResultSet rs = methodWatcher.executeQuery(query); // TestUtils.printResult(query, rs, System.out); // query = "select * from t_out"; // rs = methodWatcher.executeQuery(query); // TestUtils.printResult(query, rs, System.out); ResultSet rs = methodWatcher.executeQuery("select * from t_master"); int count = 0; while (rs.next()) { ++count; } Assert.assertEquals("Expected 2 rows in t_master", 2, count); rs = methodWatcher.executeQuery("select * from t_out order by id"); Timestamp t1 = null; Timestamp t2 = null; count = 0; while (rs.next()) { ++count; if (count == 1) { Assert.assertEquals("trigger01", rs.getString(2).trim()); t1 = rs.getTimestamp(4); } else { Assert.assertEquals("trigger02", rs.getString(2).trim()); t2 = rs.getTimestamp(4); } } Assert.assertEquals("Expected 2 rows in t_out", 2, count); Assert.assertNotNull(t1); Assert.assertNotNull(t2); Assert.assertTrue(t1.before(t2)); rs.close(); triggerDAO.drop("TriggerMaster01"); triggerDAO.drop("TriggerMaster02"); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Utility // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private void createTrigger(TriggerBuilder tb) throws Exception { // System.out.println(tb.build()); methodWatcher.executeUpdate(tb.build()); } }
splice_machine_test/src/test/java/com/splicemachine/triggers/Trigger_Exec_Stored_Proc_IT.java
package com.splicemachine.triggers; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import com.splicemachine.derby.test.framework.SpliceSchemaWatcher; import com.splicemachine.derby.test.framework.SpliceWatcher; import com.splicemachine.homeless.TestUtils; import com.splicemachine.test_dao.TriggerBuilder; import com.splicemachine.test_dao.TriggerDAO; /** * Tests trigger execution of stored procedures. * <p/> * Note the dependency on user-defined stored procedures in this test class.<br/> * See {@link TriggerProcs} for instructions on adding/modifying store procedures. */ public class Trigger_Exec_Stored_Proc_IT { private static final String SCHEMA = Trigger_Exec_Stored_Proc_IT.class.getSimpleName(); @ClassRule public static SpliceSchemaWatcher schemaWatcher = new SpliceSchemaWatcher(SCHEMA); @ClassRule public static SpliceWatcher classWatcher = new SpliceWatcher(SCHEMA); private static final String DERBY_JAR_NAME = SCHEMA + ".TRIGGER_PROCS_JAR"; private static final String CALL_SET_CLASSPATH_STRING = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath', %s)"; private static final String CREATE_PROC = "CREATE PROCEDURE "+ SCHEMA+".proc_call_audit(" + "in schema_name varchar(30), in table_name varchar(20)) " + "PARAMETER STYLE JAVA LANGUAGE JAVA READS SQL DATA " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit'"; private static final String CREATE_PROC_WITH_TRANSITION_VAR = "CREATE PROCEDURE "+ SCHEMA+".proc_call_audit_with_transition(" + "in schema_name varchar(30), in table_name varchar(20), in new_val integer, in old_val integer) " + "PARAMETER STYLE JAVA LANGUAGE JAVA READS SQL DATA " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit_with_transition'"; private static final String CREATE_PROC_WITH_RESULT = "CREATE PROCEDURE "+SCHEMA+".proc_call_audit_with_result(" + "in schema_name varchar(30), in table_name varchar(20)) " + "PARAMETER STYLE JAVA READS SQL DATA LANGUAGE JAVA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME 'com.splicemachine.triggers.TriggerProcs.proc_call_audit_with_result'"; @Rule public SpliceWatcher methodWatcher = new SpliceWatcher(SCHEMA); private TriggerBuilder tb = new TriggerBuilder(); private TriggerDAO triggerDAO = new TriggerDAO(methodWatcher.getOrCreateConnection()); @BeforeClass public static void setUpClass() throws Exception { String storedProcsJarFilePath = TriggerProcs.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); // Install the jar file of stored procedures. File jar = new File(storedProcsJarFilePath); Assert.assertTrue("Can't run test without " + storedProcsJarFilePath, jar.exists()); classWatcher.executeUpdate(String.format("CALL SQLJ.INSTALL_JAR('%s', '%s', 0)", storedProcsJarFilePath, DERBY_JAR_NAME)); classWatcher.executeUpdate(String.format(CALL_SET_CLASSPATH_STRING, "'"+ DERBY_JAR_NAME +"'")); classWatcher.executeUpdate(CREATE_PROC); classWatcher.executeUpdate(CREATE_PROC_WITH_TRANSITION_VAR); classWatcher.executeUpdate(CREATE_PROC_WITH_RESULT); } @AfterClass public static void tearDownClass() throws Exception { try { classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit")); classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit_with_transition")); classWatcher.executeUpdate(String.format("DROP PROCEDURE %s.%s", SCHEMA, "proc_call_audit_with_result")); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } try { classWatcher.executeUpdate(String.format(CALL_SET_CLASSPATH_STRING, "NULL")); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } try { classWatcher.executeUpdate(String.format("CALL SQLJ.REMOVE_JAR('%s', 0)", DERBY_JAR_NAME)); } catch (Exception e) { System.err.println("Ignoring in test teardown: " + e.getLocalizedMessage()); } } @Before public void setUp() throws Exception { classWatcher.executeUpdate("drop table if exists S"); classWatcher.executeUpdate("drop table if exists audit"); classWatcher.executeUpdate("create table S (id integer, name varchar(30))"); classWatcher.executeUpdate("create table audit (username varchar(20),insert_time timestamp, new_id integer, old_id integer)"); } /** * Create/fire a statement trigger that records username and timestamp of an insert in another table. */ @Test public void testStatementTriggerUserStoredProc() throws Exception { tb.named("auditme").before().insert().on("S").statement(). then(String.format("CALL proc_call_audit('%s','%s')", SCHEMA,"audit")); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13, 'Joe')"); s.execute("insert into S values (14, 'Henry')"); ResultSet rs = s.executeQuery("select * from audit"); int count =0; while (rs.next()) { ++count; Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); } Assert.assertEquals(2, count); rs.close(); c1.close(); triggerDAO.drop("auditme"); } /** * Create/fire a row trigger that records username, timestamp and new transition value * for an row inserted into another table. */ @Test public void testRowInsertTriggerUserStoredProc() throws Exception { createTrigger(tb.named("row_insert").after().insert().on("S").referencing("NEW AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); // when - insert a row methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); Assert.assertNotNull(rs.getObject(3)); ++count; } Assert.assertEquals(2, count); rs.close(); triggerDAO.drop("row_insert"); } /** * Create/fire a row trigger that records username, timestamp, new transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcNewTransitionValue() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); int id = rs.getInt(3); Assert.assertNotNull(id); Assert.assertEquals(39,id); Assert.assertNull(rs.getObject(4)); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_new"); } /** * Create/fire a row trigger that records username, timestamp, old transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcOldTransitionValue() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_old").after().update().on("S").referencing("OLD AS o") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", null, "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); // Assert.assertNotNull(rs.getObject(3)); int id = rs.getInt(4); Assert.assertNotNull(id); Assert.assertEquals(39, id); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_old"); } /** * Create/fire a row trigger that records username, timestamp, new transition values * for an row updated in another table. */ @Test @Ignore("DB-2375: Not seeing update row trigger transition values in procedure call.") public void testRowUpdateTriggerUserStoredProcNewAndOldTransitionValues() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N OLD AS O") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); ResultSet rs = methodWatcher.executeQuery("select * from audit"); // TestUtils.printResult("select * from audit", rs, System.out); int count =0; while (rs.next()) { Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); Assert.assertNotNull(rs.getObject(3)); int id = rs.getInt(4); Assert.assertNotNull(id); Assert.assertEquals(39, id); ++count; } Assert.assertEquals(1, count); rs.close(); triggerDAO.drop("row_update_new"); } /** * Create/fire a row trigger that records username, timestamp, new and old transition values * for an row updated in another table. */ @Test public void testRowUpdateTriggerUserStoredProcTwoTriggers() throws Exception { methodWatcher.executeUpdate("insert into S values (13, 'Joe')"); methodWatcher.executeUpdate("insert into S values (14, 'Henry')"); createTrigger(tb.named("row_update_new").after().update().on("S").referencing("New AS N") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", "N.id", null))); createTrigger(tb.named("row_update_old").after().update().on("S").referencing("OLD AS o") .row().then(String.format("CALL proc_call_audit_with_transition('%s','%s',%s, %s)", SCHEMA, "audit", null, "O.id"))); // when - update a row methodWatcher.executeUpdate("update S set id = 39 where id = 13"); triggerDAO.drop("row_update_new"); triggerDAO.drop("row_update_old"); } /** * Create/fire a statement trigger that records username and timestamp of an insert in another table. */ @Test public void testStatementTriggerUserStoredProcWithResult() throws Exception { tb.named("auditme2").before().insert().on("S").statement(). then(String.format("CALL proc_call_audit_with_result('%s','%s')", SCHEMA,"audit")); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13,'Joe')"); s.execute("insert into S values (-1,'Henry')"); ResultSet rs = s.executeQuery("select * from audit"); int count =0; while (rs.next()) { ++count; Assert.assertEquals("splice",rs.getString(1)); Assert.assertNotNull(rs.getObject(2)); } Assert.assertEquals(2, count); rs.close(); c1.close(); triggerDAO.drop("auditme2"); } /** * Create/fire a statement trigger that calls a splice system procedure. */ @Test public void testStatementTriggerSysStoredProc() throws Exception { ResultSet rs = methodWatcher.executeQuery("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder')"); String originalLevel = null; while (rs.next()) { originalLevel = rs.getString(1); } Assert.assertNotNull(originalLevel); String newlevel = "INFO"; if (originalLevel.equals("INFO")) { newlevel = "WARN"; } tb.named("log_level_change").before().insert().on("S").statement(). then("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder', '"+newlevel+"')"); createTrigger(tb); Connection c1 = classWatcher.createConnection(); Statement s = c1.createStatement(); s.execute("insert into S values (13,'Joe')"); rs = methodWatcher.executeQuery("call SYSCS_UTIL.SYSCS_GET_LOGGER_LEVEL('com.splicemachine.tools.version.ManifestFinder')"); String changedLevel = null; while (rs.next()) { changedLevel = rs.getString(1); } Assert.assertNotNull(changedLevel); Assert.assertEquals(newlevel, changedLevel); c1.createStatement().execute("call SYSCS_UTIL.SYSCS_SET_LOGGER_LEVEL('com.splicemachine.tools.version" + ".ManifestFinder', '" + originalLevel+"')"); rs.close(); c1.close(); triggerDAO.drop("log_level_change"); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private void createTrigger(TriggerBuilder tb) throws Exception { // System.out.println(tb.build()); methodWatcher.executeUpdate(tb.build()); } }
DB-3365: child SQL session context null. The SQLSessionContext is not serialized with an activation but is available in the parent activation. All logic changes in Derby. Added test.
splice_machine_test/src/test/java/com/splicemachine/triggers/Trigger_Exec_Stored_Proc_IT.java
DB-3365: child SQL session context null. The SQLSessionContext is not serialized with an activation but is available in the parent activation. All logic changes in Derby. Added test.
Java
agpl-3.0
17e86be517e98a1e032ddc01ba5462bc2b1a943f
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
48a575da-2e61-11e5-9284-b827eb9e62be
hello.java
489fe002-2e61-11e5-9284-b827eb9e62be
48a575da-2e61-11e5-9284-b827eb9e62be
hello.java
48a575da-2e61-11e5-9284-b827eb9e62be
Java
agpl-3.0
c6f4c75ae5bce37055c19275c2b0958162bd8c1c
0
dgray16/libreplan,Marine-22/libre,PaulLuchyn/libreplan,LibrePlan/libreplan,dgray16/libreplan,LibrePlan/libreplan,poum/libreplan,Marine-22/libre,dgray16/libreplan,poum/libreplan,poum/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,poum/libreplan,LibrePlan/libreplan,skylow95/libreplan,poum/libreplan,dgray16/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,Marine-22/libre,LibrePlan/libreplan,Marine-22/libre,PaulLuchyn/libreplan,LibrePlan/libreplan,skylow95/libreplan,dgray16/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,skylow95/libreplan,LibrePlan/libreplan,poum/libreplan,skylow95/libreplan,Marine-22/libre,skylow95/libreplan,PaulLuchyn/libreplan,Marine-22/libre,dgray16/libreplan,LibrePlan/libreplan
/* * This file is part of NavalPlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.navalplanner.web.limitingresources; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueElement; import org.navalplanner.business.resources.daos.IResourceDAO; import org.navalplanner.business.resources.entities.LimitingResourceQueue; import org.springframework.beans.factory.annotation.Autowired; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTrackerComponent; import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter; import org.zkoss.ganttz.timetracker.zoom.DetailItem; import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.ganttz.util.Interval; import org.zkoss.ganttz.util.MutableTreeModel; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Button; import org.zkoss.zul.ListModel; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listitem; import org.zkoss.zul.Separator; import org.zkoss.zul.SimpleListModel; public class LimitingResourcesPanel extends HtmlMacroComponent { public interface IToolbarCommand { public void doAction(); public String getLabel(); public String getImage(); } private LimitingResourcesController limitingResourcesController; private TimeTrackerComponent timeTrackerComponent; private LimitingResourcesLeftPane leftPane; private QueueListComponent queueListComponent; private MutableTreeModel<LimitingResourceQueue> treeModel; private TimeTracker timeTracker; private Listbox listZoomLevels; private Button paginationDownButton; private Button paginationUpButton; private Listbox horizontalPagination; private Component insertionPointLeftPanel; private Component insertionPointRightPanel; private Component insertionPointTimetracker; public void paginationDown() { horizontalPagination.setSelectedIndex(horizontalPagination .getSelectedIndex() - 1); goToSelectedHorizontalPage(); } public void paginationUp() { horizontalPagination.setSelectedIndex(Math.max(1, horizontalPagination .getSelectedIndex() + 1)); goToSelectedHorizontalPage(); } @Autowired IResourceDAO resourcesDAO; private LimitingDependencyList dependencyList = new LimitingDependencyList( this); private PaginatorFilter paginatorFilter; private TimeTrackerComponent timeTrackerHeader; private IZoomLevelChangedListener zoomChangedListener; /** * Returns the closest upper {@link LimitingResourcesPanel} instance going * all the way up from comp * * @param comp * @return */ public static LimitingResourcesPanel getLimitingResourcesPanel( Component comp) { if (comp == null) { return null; } if (comp instanceof LimitingResourcesPanel) { return (LimitingResourcesPanel) comp; } return getLimitingResourcesPanel(comp.getParent()); } public LimitingResourcesPanel( LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { init(limitingResourcesController, timeTracker); } public void init(LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { this.limitingResourcesController = limitingResourcesController; this.timeTracker = timeTracker; this.setVariable("limitingResourcesController", limitingResourcesController, true); treeModel = createModelForTree(); timeTrackerComponent = timeTrackerForLimitingResourcesPanel(timeTracker); queueListComponent = new QueueListComponent(this, timeTracker, treeModel); leftPane = new LimitingResourcesLeftPane(treeModel, queueListComponent); } public void appendQueueElementToQueue(LimitingResourceQueueElement element) { queueListComponent.appendQueueElement(element); dependencyList.addDependenciesFor(element); } public void removeQueueElementFrom(LimitingResourceQueue queue, LimitingResourceQueueElement element) { queueListComponent.removeQueueElementFrom(queue, element); dependencyList.removeDependenciesFor(element); } private MutableTreeModel<LimitingResourceQueue> createModelForTree() { MutableTreeModel<LimitingResourceQueue> result = MutableTreeModel .create(LimitingResourceQueue.class); for (LimitingResourceQueue LimitingResourceQueue : getLimitingResourceQueues()) { result.addToRoot(LimitingResourceQueue); } return result; } private List<LimitingResourceQueue> getLimitingResourceQueues() { return limitingResourcesController.getLimitingResourceQueues(); } public ListModel getZoomLevels() { ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE, ZoomLevel.DETAIL_SIX }; return new SimpleListModel(selectableZoomlevels); } public void setZoomLevel(final ZoomLevel zoomLevel) { timeTracker.setZoomLevel(zoomLevel); } public void zoomIncrease() { timeTracker.zoomIncrease(); } public void zoomDecrease() { timeTracker.zoomDecrease(); } public void add(final IToolbarCommand... commands) { Component toolbar = getToolbar(); Separator separator = getSeparator(); for (IToolbarCommand c : commands) { toolbar.insertBefore(asButton(c), separator); } } private Button asButton(final IToolbarCommand c) { Button result = new Button(); result.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { c.doAction(); } }); if (!StringUtils.isEmpty(c.getImage())) { result.setImage(c.getImage()); result.setTooltiptext(c.getLabel()); } else { result.setLabel(c.getLabel()); } return result; } @SuppressWarnings("unchecked") private Separator getSeparator() { List<Component> children = getToolbar().getChildren(); Separator separator = ComponentsFinder.findComponentsOfType( Separator.class, children).get(0); return separator; } private Component getToolbar() { Component toolbar = getFellow("toolbar"); return toolbar; } private TimeTrackerComponent timeTrackerForLimitingResourcesPanel( TimeTracker timeTracker) { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { response("", new AuInvoke(queueListComponent, "adjustScrollHorizontalPosition", pixelsDisplacement + "")); } }; } @Override public void afterCompose() { super.afterCompose(); paginatorFilter = new PaginatorFilter(); initializeBindings(); listZoomLevels .setSelectedIndex(timeTracker.getDetailLevel().ordinal() - 2); // Pagination stuff paginationUpButton.setDisabled(paginatorFilter.isLastPage()); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); // Insert leftPane component with limitingresources list insertionPointLeftPanel.appendChild(leftPane); leftPane.afterCompose(); insertionPointRightPanel.appendChild(timeTrackerComponent); insertionPointRightPanel.appendChild(queueListComponent); queueListComponent.afterCompose(); dependencyList = generateDependencyComponentsList(); if (dependencyList != null) { dependencyList.afterCompose(); insertionPointRightPanel.appendChild(dependencyList); } zoomChangedListener = new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel newDetailLevel) { rebuildDependencies(); timeTracker.resetMapper(); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); reloadPanelComponents(); paginatorFilter.populateHorizontalListbox(); paginatorFilter.goToHorizontalPage(0); reloadComponent(); // Reset mapper for first detail if (newDetailLevel == ZoomLevel.DETAIL_THREE) { timeTracker.resetMapper(); queueListComponent.invalidate(); queueListComponent.afterCompose(); rebuildDependencies(); } } }; this.timeTracker.addZoomListener(zoomChangedListener); // Insert timetracker headers timeTrackerHeader = createTimeTrackerHeader(); insertionPointTimetracker.appendChild(timeTrackerHeader); timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); paginatorFilter.populateHorizontalListbox(); } private void rebuildDependencies() { dependencyList.getChildren().clear(); insertionPointRightPanel.appendChild(dependencyList); dependencyList = generateDependencyComponentsList(); dependencyList.afterCompose(); } private void initializeBindings() { // Zoom and pagination listZoomLevels = (Listbox) getFellow("listZoomLevels"); horizontalPagination = (Listbox) getFellow("horizontalPagination"); paginationUpButton = (Button) getFellow("paginationUpButton"); paginationDownButton = (Button) getFellow("paginationDownButton"); insertionPointLeftPanel = getFellow("insertionPointLeftPanel"); insertionPointRightPanel = getFellow("insertionPointRightPanel"); insertionPointTimetracker = getFellow("insertionPointTimetracker"); } private void reloadPanelComponents() { timeTrackerComponent.getChildren().clear(); if (timeTrackerHeader != null) { timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); } dependencyList.invalidate(); } private LimitingDependencyList generateDependencyComponentsList() { Set<LimitingResourceQueueElement> queueElements = queueListComponent .getLimitingResourceElementToQueueTaskMap().keySet(); for (LimitingResourceQueueElement each : queueElements) { dependencyList.addDependenciesFor(each); } return dependencyList; } public Map<LimitingResourceQueueElement, QueueTask> getQueueTaskMap() { return queueListComponent.getLimitingResourceElementToQueueTaskMap(); } public void clearComponents() { getFellow("insertionPointLeftPanel").getChildren().clear(); getFellow("insertionPointRightPanel").getChildren().clear(); getFellow("insertionPointTimetracker").getChildren().clear(); } public TimeTrackerComponent getTimeTrackerComponent() { return timeTrackerComponent; } private TimeTrackerComponent createTimeTrackerHeader() { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { } }; } public void unschedule(QueueTask task) { LimitingResourceQueueElement queueElement = task.getLimitingResourceQueueElement(); LimitingResourceQueue queue = queueElement.getLimitingResourceQueue(); limitingResourcesController.unschedule(task); removeQueueTask(task); dependencyList.removeDependenciesFor(queueElement); queueListComponent.removeQueueElementFrom(queue, queueElement); } private void removeQueueTask(QueueTask task) { task.detach(); } public void moveQueueTask(QueueTask queueTask) { if (limitingResourcesController.moveTask(queueTask.getLimitingResourceQueueElement())) { removeQueueTask(queueTask); } } public void editResourceAllocation(QueueTask queueTask) { limitingResourcesController.editResourceAllocation(queueTask .getLimitingResourceQueueElement()); } public void removeDependenciesFor(LimitingResourceQueueElement element) { dependencyList.removeDependenciesFor(element); } public void addDependenciesFor(LimitingResourceQueueElement element) { dependencyList.addDependenciesFor(element); } public void refreshQueues(Set<LimitingResourceQueue> queues) { for (LimitingResourceQueue each: queues) { refreshQueue(each); } } public void refreshQueue(LimitingResourceQueue queue) { dependencyList.removeDependenciesFor(queue); queueListComponent.refreshQueue(queue); } public void goToSelectedHorizontalPage() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex()); reloadComponent(); } public void reloadComponent() { timeTrackerHeader.recreate(); timeTrackerComponent.recreate(); dependencyList.clear(); queueListComponent.invalidate(); queueListComponent.afterCompose(); rebuildDependencies(); } private class PaginatorFilter implements IDetailItemFilter { private DateTime intervalStart; private DateTime intervalEnd; private DateTime paginatorStart; private DateTime paginatorEnd; @Override public Interval getCurrentPaginationInterval() { return new Interval(paginatorStart.toDate(), paginatorEnd.toDate()); } private Period intervalIncrease() { switch (timeTracker.getDetailLevel()) { case DETAIL_ONE: return Period.years(5); case DETAIL_TWO: return Period.years(5); case DETAIL_THREE: return Period.years(2); case DETAIL_FOUR: return Period.months(12); case DETAIL_FIVE: return Period.weeks(12); case DETAIL_SIX: return Period.weeks(12); } // Default month return Period.years(2); } public void setInterval(Interval realInterval) { intervalStart = realInterval.getStart().toDateTimeAtStartOfDay(); intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay(); paginatorStart = intervalStart; paginatorEnd = intervalStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } @Override public void resetInterval() { setInterval(timeTracker.getRealInterval()); } public void paginationDown() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex() - 1); reloadComponent(); } public void paginationUp() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex() + 1); reloadComponent(); } @Override public Collection<DetailItem> selectsFirstLevel( Collection<DetailItem> firstLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : firstLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } @Override public Collection<DetailItem> selectsSecondLevel( Collection<DetailItem> secondLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : secondLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } public void populateHorizontalListbox() { horizontalPagination.getItems().clear(); DateTimeFormatter df = DateTimeFormat.forPattern("dd/MMM/yyyy"); DateTime intervalStart = timeTracker.getRealInterval().getStart() .toDateTimeAtStartOfDay(); if (intervalStart != null) { DateTime itemStart = intervalStart; DateTime itemEnd = intervalStart.plus(intervalIncrease()); while (intervalEnd.isAfter(itemStart)) { if (intervalEnd.isBefore(itemEnd) || !intervalEnd.isAfter(itemEnd .plus(intervalIncrease()))) { itemEnd = intervalEnd; } Listitem item = new Listitem(df.print(itemStart) + " - " + df.print(itemEnd.minusDays(1))); horizontalPagination.appendChild(item); itemStart = itemEnd; itemEnd = itemEnd.plus(intervalIncrease()); } } horizontalPagination.setSelectedIndex(0); if (horizontalPagination.getItems().size() < 2) { horizontalPagination.setDisabled(true); } } public void goToHorizontalPage(int interval) { paginatorStart = intervalStart; // paginatorStart = new // DateTime(timeTracker.getRealInterval().getStart()); paginatorStart = timeTracker.getDetailsFirstLevel().iterator() .next().getStartDate(); for (int i = 0; i < interval; i++) { paginatorStart = paginatorStart.plus(intervalIncrease()); } paginatorEnd = paginatorStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = paginatorEnd.plus(intervalIncrease()); } timeTracker.resetMapper(); updatePaginationButtons(); } private void updatePaginationButtons() { paginationDownButton.setDisabled(isFirstPage()); paginationUpButton.setDisabled(isLastPage()); } public void previous() { paginatorStart = paginatorStart.minus(intervalIncrease()); paginatorEnd = paginatorEnd.minus(intervalIncrease()); updatePaginationButtons(); } public boolean isFirstPage() { return (horizontalPagination.getSelectedIndex() <= 0) || horizontalPagination.isDisabled(); } private boolean isLastPage() { return (horizontalPagination.getItemCount() == (horizontalPagination .getSelectedIndex() + 1)) || horizontalPagination.isDisabled(); } } }
navalplanner-webapp/src/main/java/org/navalplanner/web/limitingresources/LimitingResourcesPanel.java
/* * This file is part of NavalPlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.navalplanner.web.limitingresources; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueElement; import org.navalplanner.business.resources.daos.IResourceDAO; import org.navalplanner.business.resources.entities.LimitingResourceQueue; import org.springframework.beans.factory.annotation.Autowired; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTrackerComponent; import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter; import org.zkoss.ganttz.timetracker.zoom.DetailItem; import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.ganttz.util.Interval; import org.zkoss.ganttz.util.MutableTreeModel; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Button; import org.zkoss.zul.ListModel; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listitem; import org.zkoss.zul.Separator; import org.zkoss.zul.SimpleListModel; public class LimitingResourcesPanel extends HtmlMacroComponent { public interface IToolbarCommand { public void doAction(); public String getLabel(); public String getImage(); } private LimitingResourcesController limitingResourcesController; private TimeTrackerComponent timeTrackerComponent; private LimitingResourcesLeftPane leftPane; private QueueListComponent queueListComponent; private MutableTreeModel<LimitingResourceQueue> treeModel; private TimeTracker timeTracker; private Listbox listZoomLevels; private Button paginationDownButton; private Button paginationUpButton; private Listbox horizontalPagination; private Component insertionPointLeftPanel; private Component insertionPointRightPanel; private Component insertionPointTimetracker; public void paginationDown() { horizontalPagination.setSelectedIndex(horizontalPagination .getSelectedIndex() - 1); goToSelectedHorizontalPage(); } public void paginationUp() { horizontalPagination.setSelectedIndex(Math.max(1, horizontalPagination .getSelectedIndex() + 1)); goToSelectedHorizontalPage(); } @Autowired IResourceDAO resourcesDAO; private LimitingDependencyList dependencyList = new LimitingDependencyList( this); private PaginatorFilter paginatorFilter; private TimeTrackerComponent timeTrackerHeader; private IZoomLevelChangedListener zoomChangedListener; /** * Returns the closest upper {@link LimitingResourcesPanel} instance going * all the way up from comp * * @param comp * @return */ public static LimitingResourcesPanel getLimitingResourcesPanel( Component comp) { if (comp == null) { return null; } if (comp instanceof LimitingResourcesPanel) { return (LimitingResourcesPanel) comp; } return getLimitingResourcesPanel(comp.getParent()); } public LimitingResourcesPanel( LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { init(limitingResourcesController, timeTracker); } public void init(LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { this.limitingResourcesController = limitingResourcesController; this.timeTracker = timeTracker; this.setVariable("limitingResourcesController", limitingResourcesController, true); treeModel = createModelForTree(); timeTrackerComponent = timeTrackerForLimitingResourcesPanel(timeTracker); queueListComponent = new QueueListComponent(this, timeTracker, treeModel); leftPane = new LimitingResourcesLeftPane(treeModel, queueListComponent); } public void appendQueueElementToQueue(LimitingResourceQueueElement element) { queueListComponent.appendQueueElement(element); dependencyList.addDependenciesFor(element); } public void removeQueueElementFrom(LimitingResourceQueue queue, LimitingResourceQueueElement element) { queueListComponent.removeQueueElementFrom(queue, element); dependencyList.removeDependenciesFor(element); } private MutableTreeModel<LimitingResourceQueue> createModelForTree() { MutableTreeModel<LimitingResourceQueue> result = MutableTreeModel .create(LimitingResourceQueue.class); for (LimitingResourceQueue LimitingResourceQueue : getLimitingResourceQueues()) { result.addToRoot(LimitingResourceQueue); } return result; } private List<LimitingResourceQueue> getLimitingResourceQueues() { return limitingResourcesController.getLimitingResourceQueues(); } public ListModel getZoomLevels() { ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE, ZoomLevel.DETAIL_SIX }; return new SimpleListModel(selectableZoomlevels); } public void setZoomLevel(final ZoomLevel zoomLevel) { timeTracker.setZoomLevel(zoomLevel); } public void zoomIncrease() { timeTracker.zoomIncrease(); } public void zoomDecrease() { timeTracker.zoomDecrease(); } public void add(final IToolbarCommand... commands) { Component toolbar = getToolbar(); Separator separator = getSeparator(); for (IToolbarCommand c : commands) { toolbar.insertBefore(asButton(c), separator); } } private Button asButton(final IToolbarCommand c) { Button result = new Button(); result.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { c.doAction(); } }); if (!StringUtils.isEmpty(c.getImage())) { result.setImage(c.getImage()); result.setTooltiptext(c.getLabel()); } else { result.setLabel(c.getLabel()); } return result; } @SuppressWarnings("unchecked") private Separator getSeparator() { List<Component> children = getToolbar().getChildren(); Separator separator = ComponentsFinder.findComponentsOfType( Separator.class, children).get(0); return separator; } private Component getToolbar() { Component toolbar = getFellow("toolbar"); return toolbar; } private TimeTrackerComponent timeTrackerForLimitingResourcesPanel( TimeTracker timeTracker) { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { response("", new AuInvoke(queueListComponent, "adjustScrollHorizontalPosition", pixelsDisplacement + "")); } }; } @Override public void afterCompose() { super.afterCompose(); paginatorFilter = new PaginatorFilter(); initializeBindings(); listZoomLevels .setSelectedIndex(timeTracker.getDetailLevel().ordinal() - 2); // Pagination stuff paginationUpButton.setDisabled(paginatorFilter.isLastPage()); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); // Insert leftPane component with limitingresources list insertionPointLeftPanel.appendChild(leftPane); leftPane.afterCompose(); insertionPointRightPanel.appendChild(timeTrackerComponent); insertionPointRightPanel.appendChild(queueListComponent); queueListComponent.afterCompose(); dependencyList = generateDependencyComponentsList(); if (dependencyList != null) { dependencyList.afterCompose(); insertionPointRightPanel.appendChild(dependencyList); } zoomChangedListener = new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel newDetailLevel) { rebuildDependencies(); timeTracker.resetMapper(); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); reloadPanelComponents(); paginatorFilter.populateHorizontalListbox(); paginatorFilter.goToHorizontalPage(0); reloadComponent(); // Reset mapper for first detail if (newDetailLevel == ZoomLevel.DETAIL_THREE) { timeTracker.resetMapper(); queueListComponent.invalidate(); queueListComponent.afterCompose(); rebuildDependencies(); } } }; this.timeTracker.addZoomListener(zoomChangedListener); // Insert timetracker headers timeTrackerHeader = createTimeTrackerHeader(); insertionPointTimetracker.appendChild(timeTrackerHeader); timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); paginatorFilter.populateHorizontalListbox(); } private void rebuildDependencies() { dependencyList.getChildren().clear(); insertionPointRightPanel.appendChild(dependencyList); dependencyList = generateDependencyComponentsList(); dependencyList.afterCompose(); } private void initializeBindings() { // Zoom and pagination listZoomLevels = (Listbox) getFellow("listZoomLevels"); horizontalPagination = (Listbox) getFellow("horizontalPagination"); paginationUpButton = (Button) getFellow("paginationUpButton"); paginationDownButton = (Button) getFellow("paginationDownButton"); insertionPointLeftPanel = getFellow("insertionPointLeftPanel"); insertionPointRightPanel = getFellow("insertionPointRightPanel"); insertionPointTimetracker = getFellow("insertionPointTimetracker"); } private void reloadPanelComponents() { timeTrackerComponent.getChildren().clear(); if (timeTrackerHeader != null) { timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); } dependencyList.invalidate(); } private LimitingDependencyList generateDependencyComponentsList() { Set<LimitingResourceQueueElement> queueElements = queueListComponent .getLimitingResourceElementToQueueTaskMap().keySet(); for (LimitingResourceQueueElement each : queueElements) { dependencyList.addDependenciesFor(each); } return dependencyList; } public Map<LimitingResourceQueueElement, QueueTask> getQueueTaskMap() { return queueListComponent.getLimitingResourceElementToQueueTaskMap(); } public void clearComponents() { getFellow("insertionPointLeftPanel").getChildren().clear(); getFellow("insertionPointRightPanel").getChildren().clear(); getFellow("insertionPointTimetracker").getChildren().clear(); } public TimeTrackerComponent getTimeTrackerComponent() { return timeTrackerComponent; } private TimeTrackerComponent createTimeTrackerHeader() { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { } }; } public void unschedule(QueueTask task) { LimitingResourceQueueElement queueElement = task.getLimitingResourceQueueElement(); LimitingResourceQueue queue = queueElement.getLimitingResourceQueue(); limitingResourcesController.unschedule(task); removeQueueTask(task); dependencyList.removeDependenciesFor(queueElement); queueListComponent.removeQueueElementFrom(queue, queueElement); } private void removeQueueTask(QueueTask task) { task.detach(); } public void moveQueueTask(QueueTask queueTask) { if (limitingResourcesController.moveTask(queueTask.getLimitingResourceQueueElement())) { removeQueueTask(queueTask); } } public void editResourceAllocation(QueueTask queueTask) { limitingResourcesController.editResourceAllocation(queueTask .getLimitingResourceQueueElement()); } public void removeDependenciesFor(LimitingResourceQueueElement element) { dependencyList.removeDependenciesFor(element); } public void addDependenciesFor(LimitingResourceQueueElement element) { dependencyList.addDependenciesFor(element); } public void refreshQueues(Set<LimitingResourceQueue> queues) { for (LimitingResourceQueue each: queues) { refreshQueue(each); } } public void refreshQueue(LimitingResourceQueue queue) { dependencyList.removeDependenciesFor(queue); queueListComponent.refreshQueue(queue); } public void goToSelectedHorizontalPage() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex()); reloadComponent(); } public void reloadComponent() { timeTrackerHeader.recreate(); timeTrackerComponent.recreate(); dependencyList.clear(); queueListComponent.invalidate(); queueListComponent.afterCompose(); rebuildDependencies(); } private class PaginatorFilter implements IDetailItemFilter { private DateTime intervalStart; private DateTime intervalEnd; private DateTime paginatorStart; private DateTime paginatorEnd; @Override public Interval getCurrentPaginationInterval() { return new Interval(paginatorStart.toDate(), paginatorEnd.toDate()); } private Period intervalIncrease() { switch (timeTracker.getDetailLevel()) { case DETAIL_ONE: return Period.years(5); case DETAIL_TWO: return Period.years(5); case DETAIL_THREE: return Period.years(2); case DETAIL_FOUR: return Period.months(12); case DETAIL_FIVE: return Period.weeks(12); case DETAIL_SIX: return Period.weeks(12); } // Default month return Period.years(2); } public void setInterval(Interval realInterval) { intervalStart = realInterval.getStart().toDateTimeAtStartOfDay(); intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay(); paginatorStart = intervalStart; paginatorEnd = intervalStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } @Override public void resetInterval() { setInterval(timeTracker.getRealInterval()); } public void paginationDown() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex() - 1); reloadComponent(); } public void paginationUp() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex() + 1); reloadComponent(); } @Override public Collection<DetailItem> selectsFirstLevel( Collection<DetailItem> firstLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : firstLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } @Override public Collection<DetailItem> selectsSecondLevel( Collection<DetailItem> secondLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : secondLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } public void populateHorizontalListbox() { horizontalPagination.getItems().clear(); DateTimeFormatter df = DateTimeFormat.forPattern("dd/MMM/yyyy"); DateTime intervalStart = timeTracker.getRealInterval().getStart() .toDateTimeAtStartOfDay(); if (intervalStart != null) { DateTime itemStart = intervalStart; DateTime itemEnd = intervalStart.plus(intervalIncrease()); while (intervalEnd.isAfter(itemStart)) { if (intervalEnd.isBefore(itemEnd) || !intervalEnd.isAfter(itemEnd .plus(intervalIncrease()))) { itemEnd = intervalEnd; } Listitem item = new Listitem(df.print(itemStart) + " - " + df.print(itemEnd.minusDays(1))); horizontalPagination.appendChild(item); itemStart = itemEnd; itemEnd = itemEnd.plus(intervalIncrease()); } } if (horizontalPagination.getItems().size() < 2) { horizontalPagination.setDisabled(true); horizontalPagination.setSelectedIndex(0); } } public void goToHorizontalPage(int interval) { paginatorStart = intervalStart; // paginatorStart = new // DateTime(timeTracker.getRealInterval().getStart()); paginatorStart = timeTracker.getDetailsFirstLevel().iterator() .next().getStartDate(); for (int i = 0; i < interval; i++) { paginatorStart = paginatorStart.plus(intervalIncrease()); } paginatorEnd = paginatorStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = paginatorEnd.plus(intervalIncrease()); } timeTracker.resetMapper(); updatePaginationButtons(); } private void updatePaginationButtons() { paginationDownButton.setDisabled(isFirstPage()); paginationUpButton.setDisabled(isLastPage()); } public void previous() { paginatorStart = paginatorStart.minus(intervalIncrease()); paginatorEnd = paginatorEnd.minus(intervalIncrease()); updatePaginationButtons(); } public boolean isFirstPage() { return (horizontalPagination.getSelectedIndex() <= 0) || horizontalPagination.isDisabled(); } private boolean isLastPage() { return (horizontalPagination.getItemCount() == (horizontalPagination .getSelectedIndex() + 1)) || horizontalPagination.isDisabled(); } } }
[Bug #781] Fix bug FEA: ItEr67S04BugFixing
navalplanner-webapp/src/main/java/org/navalplanner/web/limitingresources/LimitingResourcesPanel.java
[Bug #781] Fix bug
Java
lgpl-2.1
d51afeb664f26f90e4bfef84fa0b82e1458afc59
0
soul2zimate/wildfly-core,yersan/wildfly-core,soul2zimate/wildfly-core,bstansberry/wildfly-core,ivassile/wildfly-core,darranl/wildfly-core,jfdenise/wildfly-core,jfdenise/wildfly-core,ivassile/wildfly-core,yersan/wildfly-core,soul2zimate/wildfly-core,bstansberry/wildfly-core,jamezp/wildfly-core,jfdenise/wildfly-core,darranl/wildfly-core,yersan/wildfly-core,ivassile/wildfly-core,jamezp/wildfly-core,darranl/wildfly-core,jamezp/wildfly-core,bstansberry/wildfly-core
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.controller.access.constraint; import java.util.regex.Pattern; import org.jboss.as.controller.access.Action; import org.jboss.as.controller.access.JmxAction; import org.jboss.as.controller.access.JmxTarget; import org.jboss.as.controller.access.TargetAttribute; import org.jboss.as.controller.access.TargetResource; import org.jboss.as.controller.access.rbac.StandardRole; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; /** * {@link Constraint} related to whether an attribute is considered security sensitive * because it contains a vault expression. * * @author Brian Stansberry (c) 2013 Red Hat Inc. */ public class SensitiveVaultExpressionConstraint extends AllowAllowNotConstraint { public static final ConstraintFactory FACTORY = new Factory(); private static final Pattern VAULT_EXPRESSION_PATTERN = Pattern.compile(".*\\$\\{VAULT::.*::.*::.*}.*"); private static final SensitiveVaultExpressionConstraint SENSITIVE = new SensitiveVaultExpressionConstraint(true); private static final SensitiveVaultExpressionConstraint NOT_SENSITIVE = new SensitiveVaultExpressionConstraint(false); private static final SensitiveVaultExpressionConstraint ALLOWS = new SensitiveVaultExpressionConstraint(true, true); private static final SensitiveVaultExpressionConstraint DISALLOWS = new SensitiveVaultExpressionConstraint(false, true); private SensitiveVaultExpressionConstraint(boolean sensitive) { super(sensitive); } private SensitiveVaultExpressionConstraint(boolean allowsSensitive, boolean allowsNonSensitive) { super(allowsSensitive, allowsNonSensitive); } private static class Factory extends AbstractConstraintFactory { @Override public Constraint getStandardUserConstraint(StandardRole role, Action.ActionEffect actionEffect) { if (role == StandardRole.ADMINISTRATOR || role == StandardRole.SUPERUSER || role == StandardRole.AUDITOR) { return ALLOWS; } return DISALLOWS; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, Action action, TargetAttribute target) { return isSensitiveAction(action, actionEffect, target) ? SENSITIVE : NOT_SENSITIVE; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, Action action, TargetResource target) { return isSensitiveAction(action, actionEffect) ? SENSITIVE : NOT_SENSITIVE; } private boolean isSensitiveAction(Action action, Action.ActionEffect actionEffect) { if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { ModelNode operation = action.getOperation(); for (Property property : operation.asPropertyList()) { if (isSensitiveValue(property.getValue())) { return true; } } } } return false; } private boolean isSensitiveAction(Action action, Action.ActionEffect actionEffect, TargetAttribute targetAttribute) { if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { ModelNode operation = action.getOperation(); if (operation.hasDefined(targetAttribute.getAttributeName())) { if (isSensitiveValue(operation.get(targetAttribute.getAttributeName()))) { return true; } } if (ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION.equals(operation.get(ModelDescriptionConstants.OP).asString()) && operation.hasDefined(ModelDescriptionConstants.VALUE)) { if (isSensitiveValue(operation.get(ModelDescriptionConstants.VALUE))) { return true; } } } if (actionEffect != Action.ActionEffect.ADDRESS) { if (isSensitiveValue(targetAttribute.getCurrentValue())) { return true; } } } return false; } private boolean isSensitiveValue(ModelNode value) { if (value.getType() == ModelType.EXPRESSION || value.getType() == ModelType.STRING) { String valueString = value.asString(); return VAULT_EXPRESSION_PATTERN.matcher(valueString).matches(); } return false; } @Override protected int internalCompare(AbstractConstraintFactory other) { // We have no preference return 0; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, JmxAction action, JmxTarget target) { //TODO We could do something like this if the action provided the new value and the target // provided the current value. But right now that data isn't provided. // if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { // if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { // if (action.getNewValue() instanceof String && isSensitiveValue(new ModelNode(action.getNewValue().toString()))) { // return SENSITIVE; // } // } // if (actionEffect != Action.ActionEffect.ADDRESS) { // if (target.getCurrentValue() instanceof String && isSensitiveValue(new ModelNode(target.getCurrentValue().toString()))) { // return SENSITIVE; // } // } // } return NOT_SENSITIVE; } } }
controller/src/main/java/org/jboss/as/controller/access/constraint/SensitiveVaultExpressionConstraint.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.controller.access.constraint; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.VaultReader; import org.jboss.as.controller.access.Action; import org.jboss.as.controller.access.JmxAction; import org.jboss.as.controller.access.JmxTarget; import org.jboss.as.controller.access.TargetAttribute; import org.jboss.as.controller.access.TargetResource; import org.jboss.as.controller.access.rbac.StandardRole; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; /** * {@link Constraint} related to whether an attribute is considered security sensitive * because it contains a vault expression. * * @author Brian Stansberry (c) 2013 Red Hat Inc. */ public class SensitiveVaultExpressionConstraint extends AllowAllowNotConstraint { public static final ConstraintFactory FACTORY = new Factory(); private static final SensitiveVaultExpressionConstraint SENSITIVE = new SensitiveVaultExpressionConstraint(true); private static final SensitiveVaultExpressionConstraint NOT_SENSITIVE = new SensitiveVaultExpressionConstraint(false); private static final SensitiveVaultExpressionConstraint ALLOWS = new SensitiveVaultExpressionConstraint(true, true); private static final SensitiveVaultExpressionConstraint DISALLOWS = new SensitiveVaultExpressionConstraint(false, true); private SensitiveVaultExpressionConstraint(boolean sensitive) { super(sensitive); } private SensitiveVaultExpressionConstraint(boolean allowsSensitive, boolean allowsNonSensitive) { super(allowsSensitive, allowsNonSensitive); } private static class Factory extends AbstractConstraintFactory { @Override public Constraint getStandardUserConstraint(StandardRole role, Action.ActionEffect actionEffect) { if (role == StandardRole.ADMINISTRATOR || role == StandardRole.SUPERUSER || role == StandardRole.AUDITOR) { return ALLOWS; } return DISALLOWS; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, Action action, TargetAttribute target) { return isSensitiveAction(action, actionEffect, target) ? SENSITIVE : NOT_SENSITIVE; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, Action action, TargetResource target) { return isSensitiveAction(action, actionEffect) ? SENSITIVE : NOT_SENSITIVE; } private boolean isSensitiveAction(Action action, Action.ActionEffect actionEffect) { if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { ModelNode operation = action.getOperation(); for (Property property : operation.asPropertyList()) { if (isSensitiveValue(property.getValue())) { return true; } } } } return false; } private boolean isSensitiveAction(Action action, Action.ActionEffect actionEffect, TargetAttribute targetAttribute) { if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { ModelNode operation = action.getOperation(); if (operation.hasDefined(targetAttribute.getAttributeName())) { if (isSensitiveValue(operation.get(targetAttribute.getAttributeName()))) { return true; } } if (ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION.equals(operation.get(ModelDescriptionConstants.OP).asString()) && operation.hasDefined(ModelDescriptionConstants.VALUE)) { if (isSensitiveValue(operation.get(ModelDescriptionConstants.VALUE))) { return true; } } } if (actionEffect != Action.ActionEffect.ADDRESS) { if (isSensitiveValue(targetAttribute.getCurrentValue())) { return true; } } } return false; } private boolean isSensitiveValue(ModelNode value) { if (value.getType() == ModelType.EXPRESSION || value.getType() == ModelType.STRING) { String valueString = value.asString(); if (ExpressionResolver.EXPRESSION_PATTERN.matcher(valueString).matches()) { int start = valueString.indexOf("${") + 2; int end = valueString.indexOf("}", start); valueString = valueString.substring(start, end); return VaultReader.STANDARD_VAULT_PATTERN.matcher(valueString).matches(); } } return false; } @Override protected int internalCompare(AbstractConstraintFactory other) { // We have no preference return 0; } @Override public Constraint getRequiredConstraint(Action.ActionEffect actionEffect, JmxAction action, JmxTarget target) { //TODO We could do something like this if the action provided the new value and the target // provided the current value. But right now that data isn't provided. // if (VaultExpressionSensitivityConfig.INSTANCE.isSensitive(actionEffect)) { // if (actionEffect == Action.ActionEffect.WRITE_RUNTIME || actionEffect == Action.ActionEffect.WRITE_CONFIG) { // if (action.getNewValue() instanceof String && isSensitiveValue(new ModelNode(action.getNewValue().toString()))) { // return SENSITIVE; // } // } // if (actionEffect != Action.ActionEffect.ADDRESS) { // if (target.getCurrentValue() instanceof String && isSensitiveValue(new ModelNode(target.getCurrentValue().toString()))) { // return SENSITIVE; // } // } // } return NOT_SENSITIVE; } } }
[WFCORE-5511] Just use a single regular expression to detect a vault expression anywhere within the attribute value.
controller/src/main/java/org/jboss/as/controller/access/constraint/SensitiveVaultExpressionConstraint.java
[WFCORE-5511] Just use a single regular expression to detect a vault expression anywhere within the attribute value.
Java
lgpl-2.1
446fca096ef801b2a27a30c000996c7e8b1ad1c7
0
ironjacamar/ironjacamar,maeste/ironjacamar,ironjacamar/ironjacamar,johnaoahra80/ironjacamar,jpkrohling/ironjacamar,jandsu/ironjacamar,rarguello/ironjacamar,darranl/ironjacamar,ironjacamar/ironjacamar,jesperpedersen/ironjacamar
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.as.rarinfo; import org.jboss.jca.common.api.metadata.ra.AdminObject; import org.jboss.jca.common.api.metadata.ra.ConnectionDefinition; import org.jboss.jca.common.api.metadata.ra.Connector; import org.jboss.jca.common.api.metadata.ra.Connector.Version; import org.jboss.jca.common.api.metadata.ra.MessageListener; import org.jboss.jca.common.api.metadata.ra.ResourceAdapter; import org.jboss.jca.common.api.metadata.ra.ResourceAdapter1516; import org.jboss.jca.common.api.metadata.ra.ra10.ResourceAdapter10; import org.jboss.jca.common.metadata.ra.RaParser; import org.jboss.jca.validator.Validation; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * rar info main class * * @author Jeff Zhang */ public class Main { /** Exit codes */ private static final int SUCCESS = 0; private static final int ERROR = 1; private static final int OTHER = 2; private static final String REPORT_FILE = "file-report.txt"; private static final String RAXML_FILE = "META-INF/ra.xml"; /** * Main * @param args args */ public static void main(String[] args) { PrintStream out = null; try { if (args.length < 1 && args[0].endsWith("rar")) { usage(); System.exit(OTHER); } String rarFile = args[0]; ZipFile zipFile = new ZipFile(rarFile); boolean hasRaXml = false; boolean exsitNativeFile = false; Connector connector = null; Node raNode = null; Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry ze = (ZipEntry) zipEntries.nextElement(); String name = ze.getName(); if (name.endsWith(".so") || name.endsWith(".a") || name.endsWith(".dll")) exsitNativeFile = true; if (name.equals(RAXML_FILE)) { hasRaXml = true; InputStream raIn = zipFile.getInputStream(ze); RaParser parser = new RaParser(); connector = parser.parse(raIn); raIn.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(zipFile.getInputStream(ze))); NodeList raList = doc.getElementsByTagName("resourceadapter"); if (raList != null && raList.getLength() > 0) raNode = raList.item(0); } } if (!hasRaXml) { System.out.println("JCA annotations aren't supported"); System.exit(OTHER); } if (connector == null) { System.out.println("can't parse ra.xml"); System.exit(OTHER); } out = new PrintStream(REPORT_FILE); out.println("Archive:\t" + rarFile); String version; String type = ""; ResourceAdapter ra; if (connector.getVersion() == Version.V_10) { version = "1.0"; ra = connector.getResourceadapter(); type = "OutBound"; } else { if (connector.getVersion() == Version.V_15) version = "1.5"; else version = "1.6"; ResourceAdapter1516 ra1516 = (ResourceAdapter1516)connector.getResourceadapter(); ra = ra1516; if (ra1516.getInboundResourceadapter() != null) { if (ra1516.getOutboundResourceadapter() != null) type = "Bidirect"; else type = "InBound"; } else { if (ra1516.getOutboundResourceadapter() != null) type = "OutBound"; else { out.println("Rar file has problem"); System.exit(ERROR); } } } out.println("JCA version:\t" + version); out.println("Type:\t\t" + type); int systemExitCode = Validation.validate(new File(rarFile).toURI().toURL(), "."); String compliant; if (systemExitCode == SUCCESS) compliant = "Yes"; else compliant = "No"; out.println("Compliant:\t" + compliant); out.print("Native:\t\t"); if (exsitNativeFile) out.println("Yes"); else out.println("No"); if (connector.getVersion() != Version.V_10) { ResourceAdapter1516 ra1516 = (ResourceAdapter1516)ra; out.println(); out.println("Resource-adapter:"); out.println(" Class: " + ra1516.getResourceadapterClass()); out.println(); out.println("Managed-connection-factory:"); if (ra1516.getOutboundResourceadapter() != null) { for (ConnectionDefinition mcf : ra1516.getOutboundResourceadapter().getConnectionDefinitions()) { out.println(" Class: " + mcf.getManagedConnectionFactoryClass()); } } out.println(); out.println("Admin-object:"); for (AdminObject ao : ra1516.getAdminObjects()) { out.println(" Class: " + ao.getAdminobjectClass()); } out.println(); out.println("Activation-spec:"); if (ra1516.getInboundResourceadapter() != null && ra1516.getInboundResourceadapter().getMessageadapter() != null) { for (MessageListener ml : ra1516.getInboundResourceadapter().getMessageadapter().getMessagelisteners()) { out.println(" Class: " + ml.getActivationspec().getActivationspecClass()); } } } else { out.println("Managed-connection-factory:"); ResourceAdapter10 ra10 = (ResourceAdapter10)ra; out.println(" Class: " + ra10.getManagedConnectionFactoryClass()); } if (raNode != null) { out.println(); out.println("Deployment descriptor:"); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer; serializer = tfactory.newTransformer(); //Setup indenting to "pretty print" serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); serializer.transform(new DOMSource(raNode), new StreamResult(out)); } System.out.println("Done."); System.exit(SUCCESS); } catch (Throwable t) { System.err.println("Error: " + t.getMessage()); t.printStackTrace(System.err); System.exit(ERROR); } finally { if (out != null) { try { out.close(); } catch (Exception ioe) { // Ignore } } } } /** * Tool usage */ private static void usage() { System.out.println("Usage: ./rar-info.sh file.rar"); } }
as/src/main/java/org/jboss/jca/as/rarinfo/Main.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.as.rarinfo; import org.jboss.jca.common.api.metadata.ra.AdminObject; import org.jboss.jca.common.api.metadata.ra.ConnectionDefinition; import org.jboss.jca.common.api.metadata.ra.Connector; import org.jboss.jca.common.api.metadata.ra.Connector.Version; import org.jboss.jca.common.api.metadata.ra.MessageListener; import org.jboss.jca.common.api.metadata.ra.ResourceAdapter; import org.jboss.jca.common.api.metadata.ra.ResourceAdapter1516; import org.jboss.jca.common.api.metadata.ra.ra10.ResourceAdapter10; import org.jboss.jca.common.metadata.ra.RaParser; import org.jboss.jca.validator.Validation; import java.io.File; import java.io.InputStream; import java.io.PrintStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * rar info main class * * @author Jeff Zhang */ public class Main { /** Exit codes */ private static final int SUCCESS = 0; private static final int ERROR = 1; private static final int OTHER = 2; private static final String REPORT_FILE = "file-report.txt"; private static final String RAXML_FILE = "META-INF/ra.xml"; /** * Main * @param args args */ public static void main(String[] args) { PrintStream out = null; try { if (args.length < 1 && args[0].endsWith("rar")) { usage(); System.exit(OTHER); } String rarFile = args[0]; ZipFile zipFile = new ZipFile(rarFile); boolean hasRaXml = false; boolean exsitNativeFile = false; Connector connector = null; Node raNode = null; Enumeration zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry ze = (ZipEntry) zipEntries.nextElement(); String name = ze.getName(); if (name.endsWith(".so") || name.endsWith(".a") || name.endsWith(".dll")) exsitNativeFile = true; if (name.equals(RAXML_FILE)) { hasRaXml = true; InputStream raIn = zipFile.getInputStream(ze); RaParser parser = new RaParser(); connector = parser.parse(raIn); raIn.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(zipFile.getInputStream(ze))); NodeList raList = doc.getElementsByTagName("resourceadapter"); if (raList != null && raList.getLength() > 0) raNode = raList.item(0); } } if (!hasRaXml) { System.out.println("JCA annotations aren't supported"); System.exit(OTHER); } if (connector == null) { System.out.println("can't parse ra.xml"); System.exit(OTHER); } out = new PrintStream(REPORT_FILE); out.println("Archive:\t" + rarFile); String version; String type = ""; ResourceAdapter ra; if (connector.getVersion() == Version.V_10) { version = "1.0"; ra = connector.getResourceadapter(); type = "OutBound"; } else { if (connector.getVersion() == Version.V_15) version = "1.5"; else version = "1.6"; ResourceAdapter1516 ra1516 = (ResourceAdapter1516)connector.getResourceadapter(); ra = ra1516; if (ra1516.getInboundResourceadapter() != null) { if (ra1516.getOutboundResourceadapter() != null) type = "Bidirect"; else type = "InBound"; } else { if (ra1516.getOutboundResourceadapter() != null) type = "OutBound"; else { out.println("Rar file has problem"); System.exit(ERROR); } } } out.println("JCA version:\t" + version); out.println("Type:\t\t" + type); int systemExitCode = Validation.validate(new File(rarFile).toURI().toURL(), "."); String compliant; if (systemExitCode == SUCCESS) compliant = "Yes"; else compliant = "No"; out.println("Compliant:\t" + compliant); out.print("Native:\t\t"); if (exsitNativeFile) out.println("Yes"); else out.println("No"); if (connector.getVersion() != Version.V_10) { ResourceAdapter1516 ra1516 = (ResourceAdapter1516)ra; out.println(); out.println("Resource-adapter:"); out.println(" Class: " + ra1516.getResourceadapterClass()); out.println(); out.println("Managed-connection-factory:"); if (ra1516.getOutboundResourceadapter() != null) { for (ConnectionDefinition mcf : ra1516.getOutboundResourceadapter().getConnectionDefinitions()) { out.println(" Class: " + mcf.getManagedConnectionFactoryClass()); } } out.println(); out.println("Admin-object:"); for (AdminObject ao : ra1516.getAdminObjects()) { out.println(" Class: " + ao.getAdminobjectClass()); } out.println(); out.println("Activation-spec:"); if (ra1516.getInboundResourceadapter() != null && ra1516.getInboundResourceadapter().getMessageadapter() != null) { for (MessageListener ml : ra1516.getInboundResourceadapter().getMessageadapter().getMessagelisteners()) { out.println(" Class: " + ml.getActivationspec().getActivationspecClass()); } } } else { out.println("Managed-connection-factory:"); ResourceAdapter10 ra10 = (ResourceAdapter10)ra; out.println(" Class: " + ra10.getManagedConnectionFactoryClass()); } if (raNode != null) { out.println(); TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer; serializer = tfactory.newTransformer(); //Setup indenting to "pretty print" serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); serializer.transform(new DOMSource(raNode), new StreamResult(out)); } System.out.println("Done."); System.exit(SUCCESS); } catch (Throwable t) { System.err.println("Error: " + t.getMessage()); t.printStackTrace(System.err); System.exit(ERROR); } finally { if (out != null) { try { out.close(); } catch (Exception ioe) { // Ignore } } } } /** * Tool usage */ private static void usage() { System.out.println("Usage: ./rar-info.sh file.rar"); } }
[JBJCA-696] miss a hint message
as/src/main/java/org/jboss/jca/as/rarinfo/Main.java
[JBJCA-696] miss a hint message
Java
lgpl-2.1
7e0e2d43c298629a01d26849b55f64235ad4de59
0
cawka/ndnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,ebollens/ccnmp,svartika/ccnx,svartika/ccnx
/** * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.spec.InvalidKeySpecException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.impl.security.keys.BasicKeyManager; import org.ccnx.ccn.impl.security.keys.KeyRepository; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; /** * Top-level interface for managing our own keys, as well as maintaining an address book containing * the keys of others (which will be used by the TrustManager). Also handles loading of the BouncyCastle * provider, which we need for many things. Very minimal interface now, expect to evolve extensively. */ public abstract class KeyManager { /** * Currently default to SHA-256. Only thing that associates a specific digest algorithm * with a version of the CCN protocol is the calculation of the vestigal content digest component * of ContentName used in Interest matching, and publisher digests. Changing the latter * is handled by backwards-compatible changes to the protocol encoding. All other digests are * stored prefaced with an algorithm identifier, to allow them to be modified. * We expect the protocol default digest algorithm to move to SHA3 when defined. */ public static final String DEFAULT_DIGEST_ALGORITHM = "SHA-256"; protected static Provider BC_PROVIDER = null; /** * The default KeyManager for this user/VM pair. The KeyManager will eventually have access * to significant cached state, and so a single one should be shared by as many processes * within the same trust domain as possible. We might make multiple KeyManagers representing * different "users" for testing purposes. */ protected static KeyManager _defaultKeyManager = null; /** * Accessor to retrieve default key manager instance, or create it if necessary. * @return the KeyManager * @throws ConfigurationException if there is a problem with the user or system configuration that * requires intervention to resolve, or we have a significant problem starting up the key manager. */ public static KeyManager getDefaultKeyManager() throws ConfigurationException { if (null != _defaultKeyManager) return _defaultKeyManager; try { return createKeyManager(); } catch (IOException io) { throw new ConfigurationException(io); } } /** * Load the BouncyCastle and other necessary providers, should be called once for initialization. * Currently this is done by CCNHandle. */ public static void initializeProvider() { synchronized(KeyManager.class) { if (null == BC_PROVIDER) { BC_PROVIDER = new BouncyCastleProvider(); Security.addProvider(BC_PROVIDER); } } } /** * Retrieve our default BouncyCastle provider. * @return the BouncyCastle provider instance */ public static Provider getDefaultProvider() { if (null == BC_PROVIDER) { initializeProvider(); } return BC_PROVIDER; } /** * Get our current KeyManager. * @return the key manager */ public static KeyManager getKeyManager() { try { return getDefaultKeyManager(); } catch (ConfigurationException e) { Log.warning("Configuration exception attempting to get KeyManager: " + e.getMessage()); Log.warningStackTrace(e); throw new RuntimeException("Error in system configuration. Cannot get KeyManager.",e); } } /** * Create the default key manager. * @return the key manager * @throws ConfigurationException if there is a problem with the user or system configuration * that requires intervention to fix * @throws IOException if there is an operational problem loading data or intializing the key store */ protected static synchronized KeyManager createKeyManager() throws ConfigurationException, IOException { if (null == _defaultKeyManager) { _defaultKeyManager = new BasicKeyManager(); _defaultKeyManager.initialize(); } return _defaultKeyManager; } /** * Allows subclasses to specialize key manager initialization. * @throws ConfigurationException */ public abstract void initialize() throws ConfigurationException; public static KeyRepository getKeyRepository() { return getKeyManager().keyRepository(); } /** * Get our default key ID. * @return the digest of our default key */ public abstract PublisherPublicKeyDigest getDefaultKeyID(); /** * Get our default private key. * @return our default private key */ public abstract PrivateKey getDefaultSigningKey(); /** * Get our default public key. * @return our default public key */ public abstract PublicKey getDefaultPublicKey(); /** * Get our default key locator. * @return our default key locator */ public abstract KeyLocator getDefaultKeyLocator(); /** * Get the default key locator for a particular public key * @param publisherKeyID the key whose locator we want to retrieve * @return the default key locator for that key */ public abstract KeyLocator getKeyLocator(PublisherPublicKeyDigest publisherKeyID); /** * Generate the default name under which to write this key. * @param keyID the binary digest of the name component of the key * @return the name of the key to publish under */ public abstract ContentName getDefaultKeyName(byte [] keyID); /** * Get the public key associated with a given Java keystore alias * @param alias the alias for the key * @return the key, or null if no such alias */ public abstract PublicKey getPublicKey(String alias); /** * Get the public key associated with a given publisher * @param publisher the digest of the desired key * @return the key, or null if no such key known to our cache */ public abstract PublicKey getPublicKey(PublisherPublicKeyDigest publisher) throws IOException; /** * Get the publisher key digest associated with one of our signing keys * @param signingKey key whose publisher data we want * @return the digest of the corresponding public key */ public abstract PublisherPublicKeyDigest getPublisherKeyID(PrivateKey signingKey); /** * Get the default key locator associated with one of our signing keys * @param signingKey key whose locator data we want * @return the default key locatr for that key */ public abstract KeyLocator getKeyLocator(PrivateKey signingKey); /** * Get the private key associated with a given Java keystore alias * @param alias the alias for the key * @return the key, or null if no such alias */ public abstract PrivateKey getSigningKey(String alias); /** * Get the private key associated with a given publisher * @param publisherKeyID the public key digest of the desired key * @return the key, or null if no such key known to our cache */ public abstract PrivateKey getSigningKey(PublisherPublicKeyDigest publisherKeyID); /** * Get all of our private keys, used for cache loading. * @return an array of our currently available private keys */ public abstract PrivateKey[] getSigningKeys(); /** * Get the public key for a given publisher, going to the network to retrieve it if necessary. * TODO should ensure it is stored in cache * @param publisherKeyID the digest of the keys we want * @param keyLocator the key locator to tell us where to retrieve the key from * @param timeout how long to try to retrieve the key * @return the key * @throws IOException if we run into an error attempting to read the key */ public abstract PublicKey getPublicKey(PublisherPublicKeyDigest publisherKeyID, KeyLocator keyLocator, long timeout) throws IOException; /** * Get the public key for a given publisher, going to the network to retrieve it if necessary. * Uses the default timeout. * TODO should ensure it is stored in cache * @param publisherKeyID the digest of the keys we want * @param keyLocator the key locator to tell us where to retrieve the key from * @return the key * @throws IOException if we run into an error attempting to read the key */ public PublicKey getPublicKey(PublisherPublicKeyDigest publisherKeyID, KeyLocator keyLocator) throws IOException { return getPublicKey(publisherKeyID, keyLocator,KeyRepository.DEFAULT_KEY_TIMEOUT); } /** * Publish a key at a certain name, signed by our default identity. Usually used to * publish our own keys, but can specify other keys we have in our cache. * * This publishes our key to our own internal key server, from whence it can be retrieved * as long as this KeyManager is running. It does not put it on the wire until someone * requests it. * Implementation Note: This code is used in CCNHandle intialization, and as such it * cannot use a CCNHandle or any of the standard network operations without introducing * a circular dependency. The code is very low-level and should only be modified with * great caution. * * @param keyName the name under which the key should be published. For the moment, keys are * unversioned. * @param keyToPublish can be null, in which case we publish our own default public key * @throws InvalidKeyException * @throws ConfigurationException * @throws ConfigurationException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws CertificateEncodingException */ public abstract void publishKey(ContentName keyName, PublisherPublicKeyDigest keyToPublish) throws InvalidKeyException, IOException, ConfigurationException; /** * Publish a key at a certain name, ensuring that it is stored in a repository. Will throw an * exception if no repository available. Usually used to publish our own keys, but can specify * any key known to our key cache. * @param keyName Name under which to publish the key. Currently not versioned (no version added). * @param keyToPublish can be null, in which case we publish our own default public key. * @param handle the handle to use for network requests * @throws InvalidKeyException * @throws IOException * @throws ConfigurationException */ public abstract void publishKeyToRepository(ContentName keyName, PublisherPublicKeyDigest keyToPublish, CCNHandle handle) throws InvalidKeyException, IOException, ConfigurationException; /** * Publish our default key to a repository at its default location. * @param handle the handle used for network requests * @throws InvalidKeyException * @throws IOException * @throws ConfigurationException */ public abstract void publishKeyToRepository(CCNHandle handle) throws InvalidKeyException, IOException, ConfigurationException; /** * Access our internal key store/key server. * @return our KeyRepository */ public abstract KeyRepository keyRepository(); }
javasrc/src/org/ccnx/ccn/KeyManager.java
/** * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertificateEncodingException; import java.security.spec.InvalidKeySpecException; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.impl.security.keys.BasicKeyManager; import org.ccnx.ccn.impl.security.keys.KeyRepository; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.KeyLocator; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; /** * Top-level interface for managing our own keys, as well as maintaining an address book containing * the keys of others (which will be used by the TrustManager). Also handles loading of the BouncyCastle * provider, which we need for many things. Very minimal interface now, expect to evolve extensively. */ public abstract class KeyManager { /** * Currently default to SHA-256. Only thing that associates a specific digest algorithm * with a version of the CCN protocol is the calculation of the vestigal content digest component * of ContentName used in Interest matching, and publisher digests. Changing the latter * is handled by backwards-compatible changes to the protocol encoding. All other digests are * stored prefaced with an algorithm identifier, to allow them to be modified. * We expect the protocol default digest algorithm to move to SHA3 when defined. */ public static final String DEFAULT_DIGEST_ALGORITHM = "SHA-256"; protected static Provider BC_PROVIDER = null; /** * The default KeyManager for this user/VM pair. The KeyManager will eventually have access * to significant cached state, and so a single one should be shared by as many processes * within the same trust domain as possible. We might make multiple KeyManagers representing * different "users" for testing purposes. */ protected static KeyManager _defaultKeyManager = null; /** * Accessor to retrieve default key manager instance, or create it if necessary. * @return the KeyManager * @throws ConfigurationException if there is a problem with the user or system configuration that * requires intervention to resolve, or we have a significant problem starting up the key manager. */ public static KeyManager getDefaultKeyManager() throws ConfigurationException { if (null != _defaultKeyManager) return _defaultKeyManager; try { return createKeyManager(); } catch (IOException io) { throw new ConfigurationException(io); } } /** * Load the BouncyCastle and other necessary providers, should be called once for initialization. * Currently this is done by CCNHandle. */ public static void initializeProvider() { synchronized(KeyManager.class) { if (null == BC_PROVIDER) { BC_PROVIDER = new BouncyCastleProvider(); Security.addProvider(BC_PROVIDER); } } } /** * Retrieve our default BouncyCastle provider. * @return the BouncyCastle provider instance */ public static Provider getDefaultProvider() { if (null == BC_PROVIDER) { initializeProvider(); } return BC_PROVIDER; } /** * Get our current KeyManager. * @return the key manager */ public static KeyManager getKeyManager() { try { return getDefaultKeyManager(); } catch (ConfigurationException e) { Log.warning("Configuration exception attempting to get KeyManager: " + e.getMessage()); Log.warningStackTrace(e); throw new RuntimeException("Error in system configuration. Cannot get KeyManager.",e); } } /** * Create the default key manager. * @return the key manager * @throws ConfigurationException if there is a problem with the user or system configuration * that requires intervention to fix * @throws IOException if there is an operational problem loading data or intializing the key store */ protected static synchronized KeyManager createKeyManager() throws ConfigurationException, IOException { if (null == _defaultKeyManager) { _defaultKeyManager = new BasicKeyManager(); _defaultKeyManager.initialize(); } return _defaultKeyManager; } /** * Allows subclasses to specialize key manager initialization. * @throws ConfigurationException */ public abstract void initialize() throws ConfigurationException; public static KeyRepository getKeyRepository() { return getKeyManager().keyRepository(); } /** * Get our default key ID. * @return the digest of our default key */ public abstract PublisherPublicKeyDigest getDefaultKeyID(); /** * Get our default private key. * @return our default private key */ public abstract PrivateKey getDefaultSigningKey(); /** * Get our default public key. * @return our default public key */ public abstract PublicKey getDefaultPublicKey(); /** * Get our default key locator. * @return our default key locator */ public abstract KeyLocator getDefaultKeyLocator(); /** * Get the default key locator for a particular public key * @param publisherKeyID the key whose locator we want to retrieve * @return the default key locator for that key */ public abstract KeyLocator getKeyLocator(PublisherPublicKeyDigest publisherKeyID); /** * Generate the default name under which to write this key. * @param keyID the binary digest of the name component of the key * @return the name of the key to publish under */ public abstract ContentName getDefaultKeyName(byte [] keyID); /** * Get the public key associated with a given Java keystore alias * @param the alias for the key * @return the key, or null if no such alias */ public abstract PublicKey getPublicKey(String alias); /** * Get the public key associated with a given publisher * @param the digest of the desired key * @return the key, or null if no such key known to our cache */ public abstract PublicKey getPublicKey(PublisherPublicKeyDigest publisher) throws IOException; /** * Get the publisher key digest associated with one of our signing keys * @param signingKey key whose publisher data we want * @return the digest of the corresponding public key */ public abstract PublisherPublicKeyDigest getPublisherKeyID(PrivateKey signingKey); /** * Get the default key locator associated with one of our signing keys * @param signingKey key whose locator data we want * @return the default key locatr for that key */ public abstract KeyLocator getKeyLocator(PrivateKey signingKey); /** * Get the private key associated with a given Java keystore alias * @param the alias for the key * @return the key, or null if no such alias */ public abstract PrivateKey getSigningKey(String alias); /** * Get the private key associated with a given publisher * @param the public key digest of the desired key * @return the key, or null if no such key known to our cache */ public abstract PrivateKey getSigningKey(PublisherPublicKeyDigest publisherKeyID); /** * Get all of our private keys, used for cache loading. * @return an array of our currently available private keys */ public abstract PrivateKey[] getSigningKeys(); /** * Get the public key for a given publisher, going to the network to retrieve it if necessary. * TODO should ensure it is stored in cache * @param publisherKeyID the digest of the keys we want * @param keyLocator the key locator to tell us where to retrieve the key from * @param timeout how long to try to retrieve the key * @return the key * @throws IOException if we run into an error attempting to read the key */ public abstract PublicKey getPublicKey(PublisherPublicKeyDigest publisherKeyID, KeyLocator keyLocator, long timeout) throws IOException; /** * Get the public key for a given publisher, going to the network to retrieve it if necessary. * Uses the default timeout. * TODO should ensure it is stored in cache * @param publisherKeyID the digest of the keys we want * @param keyLocator the key locator to tell us where to retrieve the key from * @return the key * @throws IOException if we run into an error attempting to read the key */ public PublicKey getPublicKey(PublisherPublicKeyDigest publisherKeyID, KeyLocator keyLocator) throws IOException { return getPublicKey(publisherKeyID, keyLocator,KeyRepository.DEFAULT_KEY_TIMEOUT); } /** * Publish a key at a certain name, signed by our default identity. Usually used to * publish our own keys, but can specify other keys we have in our cache. * * This publishes our key to our own internal key server, from whence it can be retrieved * as long as this KeyManager is running. It does not put it on the wire until someone * requests it. * Implementation Note: This code is used in CCNHandle intialization, and as such it * cannot use a CCNHandle or any of the standard network operations without introducing * a circular dependency. The code is very low-level and should only be modified with * great caution. * * @param keyName the name under which the key should be published. For the moment, keys are * unversioned. * @param keyToPublish can be null, in which case we publish our own default public key * @throws InvalidKeyException * @throws ConfigurationException * @throws ConfigurationException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws CertificateEncodingException */ public abstract void publishKey(ContentName keyName, PublisherPublicKeyDigest keyToPublish) throws InvalidKeyException, IOException, ConfigurationException; /** * Publish a key at a certain name, ensuring that it is stored in a repository. Will throw an * exception if no repository available. Usually used to publish our own keys, but can specify * any key known to our key cache. * @param keyName Name under which to publish the key. Currently not versioned (no version added). * @param keyToPublish can be null, in which case we publish our own default public key. * @param handle the handle to use for network requests * @throws InvalidKeyException * @throws IOException * @throws ConfigurationException */ public abstract void publishKeyToRepository(ContentName keyName, PublisherPublicKeyDigest keyToPublish, CCNHandle handle) throws InvalidKeyException, IOException, ConfigurationException; /** * Publish our default key to a repository at its default location. * @param handle the handle used for network requests * @throws InvalidKeyException * @throws IOException * @throws ConfigurationException */ public abstract void publishKeyToRepository(CCNHandle handle) throws InvalidKeyException, IOException, ConfigurationException; /** * Access our internal key store/key server. * @return our KeyRepository */ public abstract KeyRepository keyRepository(); }
Fixed documentation warnings.
javasrc/src/org/ccnx/ccn/KeyManager.java
Fixed documentation warnings.
Java
lgpl-2.1
9955b8b4795aa7b3badd3ad24ad5ba1339542139
0
OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs
package opendap.viewers; import opendap.namespaces.DAP; import org.jdom.Document; import org.jdom.Element; import org.jdom.filter.ElementFilter; import javax.servlet.http.HttpServlet; import java.util.Iterator; /** * Created with IntelliJ IDEA. * User: ndp * Date: 6/4/14 * Time: 7:11 AM * To change this template use File | Settings | File Templates. */ public class NcWmsService implements WebServiceHandler { private String _serviceId; private String _base; private String _applicationName; private String _ncWmsDynamicServiceId; private Element _config; private String _ncWmsServiceUrl; public NcWmsService() { _serviceId = "ncWms"; _applicationName = "ncWMS Service"; _ncWmsServiceUrl = "http://localhost:8080/ncWMS/wms"; _base = "/ncWMS/wms"; _ncWmsDynamicServiceId = "lds"; } @Override public void init(HttpServlet servlet, Element config) { _config = config; Element e; String s; s = _config.getAttributeValue("serviceId"); if (s != null && s.length() != 0) _serviceId = s; e = _config.getChild("applicationName"); if (e != null) { s = e.getTextTrim(); if (s != null && s.length() != 0) _applicationName = s; } e = _config.getChild("NcWmsService"); if (e != null) { s = e.getAttributeValue("href"); if (s != null && s.length() != 0) _ncWmsServiceUrl = s; s = e.getAttributeValue("base"); if (s != null && s.length() != 0) _base = s; s = e.getAttributeValue("ncWmsDynamicServiceId"); if (s != null && s.length() != 0) _ncWmsDynamicServiceId = s; } } @Override public String getName() { return _applicationName; } @Override public String getServiceId() { return _serviceId; } @Override public boolean datasetCanBeViewed(Document ddx) { //Element dataset = ddx.getRootElement(); //Iterator i = dataset.getDescendants(new ElementFilter("Grid", DAP.DAPv32_NS)); return true; // i.hasNext(); } @Override public String getServiceLink(String datasetUrl) { return _ncWmsServiceUrl + "/" + _ncWmsDynamicServiceId + datasetUrl + "?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0"; } public String getBase() { return _base; } public String getDynamicServiceId(){ return _ncWmsDynamicServiceId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("\n"); sb.append(" serviceId: ").append(_serviceId).append("\n"); sb.append(" base: ").append(_base).append("\n"); sb.append(" dynamicServiceId: ").append(_ncWmsDynamicServiceId).append("\n"); sb.append(" applicationName: ").append(_applicationName).append("\n"); sb.append(" WmsService: ").append(_ncWmsServiceUrl).append("\n"); return sb.toString(); } }
src/opendap/viewers/NcWmsService.java
package opendap.viewers; import opendap.namespaces.DAP; import org.jdom.Document; import org.jdom.Element; import org.jdom.filter.ElementFilter; import javax.servlet.http.HttpServlet; import java.util.Iterator; /** * Created with IntelliJ IDEA. * User: ndp * Date: 6/4/14 * Time: 7:11 AM * To change this template use File | Settings | File Templates. */ public class NcWmsService implements WebServiceHandler { private String _serviceId; private String _base; private String _applicationName; private String _ncWmsDynamicServiceId; private Element _config; private String _ncWmsServiceUrl; public NcWmsService() { _serviceId = "ncWms"; _applicationName = "ncWMS Service"; _ncWmsServiceUrl = "http://localhost:8080/ncWMS/wms"; _base = "/ncWMS/wms"; _ncWmsDynamicServiceId = "lds"; } @Override public void init(HttpServlet servlet, Element config) { _config = config; Element e; String s; s = _config.getAttributeValue("serviceId"); if (s != null && s.length() != 0) _serviceId = s; e = _config.getChild("applicationName"); if (e != null) { s = e.getTextTrim(); if (s != null && s.length() != 0) _applicationName = s; } e = _config.getChild("NcWmsService"); if (e != null) { s = e.getAttributeValue("href"); if (s != null && s.length() != 0) _ncWmsServiceUrl = s; s = e.getAttributeValue("base"); if (s != null && s.length() != 0) _base = s; s = e.getAttributeValue("ncWmsDynamicServiceId"); if (s != null && s.length() != 0) _ncWmsDynamicServiceId = s; } } @Override public String getName() { return _applicationName; } @Override public String getServiceId() { return _serviceId; } @Override public boolean datasetCanBeViewed(Document ddx) { //Element dataset = ddx.getRootElement(); //Iterator i = dataset.getDescendants(new ElementFilter("Grid", DAP.DAPv32_NS)); return true; // i.hasNext(); } @Override public String getServiceLink(String datasetUrl) { return _ncWmsServiceUrl + "?DATASET=" + _ncWmsDynamicServiceId + datasetUrl + "&SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0"; } public String getBase() { return _base; } public String getDynamicServiceId(){ return _ncWmsDynamicServiceId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("\n"); sb.append(" serviceId: ").append(_serviceId).append("\n"); sb.append(" base: ").append(_base).append("\n"); sb.append(" dynamicServiceId: ").append(_ncWmsDynamicServiceId).append("\n"); sb.append(" applicationName: ").append(_applicationName).append("\n"); sb.append(" WmsService: ").append(_ncWmsServiceUrl).append("\n"); return sb.toString(); } }
olfs: Failed to patch the NcWMS service, fixed now.
src/opendap/viewers/NcWmsService.java
olfs: Failed to patch the NcWMS service, fixed now.
Java
apache-2.0
492becbb8c44f44e4f91390709e1a42030792067
0
infraling/atomic,infraling/atomic
/******************************************************************************* * Copyright 2016 Stephan Druskat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Stephan Druskat - initial API and implementation *******************************************************************************/ package org.corpus_tools.atomic.extensions; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument; /** * A processing component is a component (usually an NLP component) * that - abstractly put - manipulates a corpus. In terms of types, * implementations of {@link ProcessingComponent}s take an instance * of {@link SDocument} and manipulate it. The manipulation will * usually be made on the {@link SDocument}'s {@link SDocumentGraph}, * but can also be made on the {@link SDocument} itself. * <p> * The formal type parameters define the input type and output type used * to restrict parameter and return values for methods customized for * specific processing component types. Cf., for example, the * abstract classes in sub-package <i>processingcomponent</i> of * this package. * <p> * Note that <b>clients should not implement this interface directly</b>, * but instead extend one of the abstract classes in package * org.corpus_tools.atomic.extensions.processingcomponents. * <p> * <i>Acknowledgements:</i> I'd like to thank Thomas Krause for pointing * me in the right direction concerning the type structure for this * functionality. * * @author Stephan Druskat <mail@sdruskat.net> * */ public interface ProcessingComponent<InputType, OutputType> { /** * Manipulates a given {@link SDocument}. The term "manipulation" * in this context is unrestricted, i.e., it can mean diverse * types of manipulation from partition detection to parsing. * * @param document The document to process */ public void processDocument(SDocument document); /** * Returns the configuration of type {@link ProcessingComponentConfiguration} * for the {@link ProcessingComponent}. * <p> * <b>Note:</b> This method is also used * for checking the "type" of the {@link ProcessingComponent}, i.e., * whether it has a configuration or not. If it is an unconfigurable * component, {@link #getConfiguration()} must return null. * * @return the configuration */ public ProcessingComponentConfiguration<?> getConfiguration(); /** * Processing components create model elements (nodes, * edges and annotations) in the underlying Salt model. * It makes sense to "file" the output of each component * in a separate layer, or add it to an existing layer. * FIXME: Implement AbstractProcessingComponent * which implements this with the default of the * PC name (+ simpleclassname) * <p> * In the former case, clients can provide a designated * name for the layer which will contain the output * of the processing component (i.e., the model elements). * * @return */ public String getDesignatedLayerName(); /** * Processing components create model elements (nodes, * edges and annotations) in the underlying Salt model. * It makes sense to "file" the output of each component * in a separate layer, or add it to an existing layer. * FIXME: Implement AbstractProcessingComponent * which implements this with the default of the * PC name (+ simpleclassname) * <p> * In the latter case, clients can provide the ID of the * target layer which will contain the output * of the processing component (i.e., the model elements). * * @return */ public String getTargetLayerId(); }
plugins/org.corpus-tools.atomic/src/main/java/org/corpus_tools/atomic/extensions/ProcessingComponent.java
/******************************************************************************* * Copyright 2016 Stephan Druskat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Stephan Druskat - initial API and implementation *******************************************************************************/ package org.corpus_tools.atomic.extensions; import de.hu_berlin.german.korpling.saltnpepper.salt.saltCommon.sCorpusStructure.SDocument; /** * A processing component is a component (usually an NLP component) * that - abstractly put - manipulates a corpus. In terms of types, * implementations of {@link ProcessingComponent}s take an instance * of {@link SDocument} and manipulate it. The manipulation will * usually be made on the {@link SDocument}'s {@link SDocumentGraph}, * but can also be made on the {@link SDocument} itself. * <p> * The formal type parameters define the input type and output type used * to restrict parameter and return values for methods customized for * specific processing component types. Cf., for example, the * abstract classes in sub-package <i>processingcomponent</i> of * this package. * <p> * Note that <b>clients should not implement this interface directly</b>, * but instead extend one of the abstract classes in package * org.corpus_tools.atomic.extensions.processingcomponents. * <p> * <i>Acknowledgements:</i> I'd like to thank Thomas Krause for pointing * me in the right direction concerning the type structure for this * functionality. * * @author Stephan Druskat <mail@sdruskat.net> * */ public interface ProcessingComponent<InputType, OutputType> { /** * Manipulates a given {@link SDocument}. The term "manipulation" * in this context is unrestricted, i.e., it can mean diverse * types of manipulation from partition detection to parsing. * * @param document The document to process */ public void processDocument(SDocument document); /** * Returns the configuration of type {@link ProcessingComponentConfiguration} * for the {@link ProcessingComponent}. * <p> * <b>Note:</b> This method is also used * for checking the "type" of the {@link ProcessingComponent}, i.e., * whether it has a configuration or not. If it is an unconfigurable * component, {@link #getConfiguration()} must return null. * * @return the configuration */ public ProcessingComponentConfiguration<?> getConfiguration(); }
Add layer name / id getters to ProcessingComponent
plugins/org.corpus-tools.atomic/src/main/java/org/corpus_tools/atomic/extensions/ProcessingComponent.java
Add layer name / id getters to ProcessingComponent
Java
apache-2.0
2103df4873ea45199ef8749a61a020488440934e
0
jmiserez/onos,chinghanyu/onos,opennetworkinglab/onos,kuujo/onos,y-higuchi/onos,sdnwiselab/onos,lsinfo3/onos,y-higuchi/onos,oeeagle/onos,mengmoya/onos,jinlongliu/onos,donNewtonAlpha/onos,castroflavio/onos,kuangrewawa/onos,oplinkoms/onos,zsh2938/onos,packet-tracker/onos,kuangrewawa/onos,Shashikanth-Huawei/bmp,oplinkoms/onos,oeeagle/onos,kuujo/onos,donNewtonAlpha/onos,LorenzReinhart/ONOSnew,osinstom/onos,osinstom/onos,jmiserez/onos,VinodKumarS-Huawei/ietf96yang,SmartInfrastructures/dreamer,jinlongliu/onos,castroflavio/onos,rvhub/onos,gkatsikas/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,lsinfo3/onos,gkatsikas/onos,gkatsikas/onos,ravikumaran2015/ravikumaran201504,chenxiuyang/onos,mengmoya/onos,gkatsikas/onos,maheshraju-Huawei/actn,chinghanyu/onos,y-higuchi/onos,opennetworkinglab/onos,CNlukai/onos-gerrit-test,gkatsikas/onos,planoAccess/clonedONOS,sdnwiselab/onos,oeeagle/onos,LorenzReinhart/ONOSnew,zsh2938/onos,zsh2938/onos,rvhub/onos,oplinkoms/onos,kkkane/ONOS,ravikumaran2015/ravikumaran201504,lsinfo3/onos,planoAccess/clonedONOS,kuujo/onos,kkkane/ONOS,kkkane/ONOS,sdnwiselab/onos,rvhub/onos,rvhub/onos,chinghanyu/onos,sdnwiselab/onos,opennetworkinglab/onos,oplinkoms/onos,opennetworkinglab/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,sonu283304/onos,maheshraju-Huawei/actn,kuangrewawa/onos,osinstom/onos,donNewtonAlpha/onos,CNlukai/onos-gerrit-test,sdnwiselab/onos,donNewtonAlpha/onos,CNlukai/onos-gerrit-test,jmiserez/onos,mengmoya/onos,ravikumaran2015/ravikumaran201504,LorenzReinhart/ONOSnew,sonu283304/onos,sonu283304/onos,VinodKumarS-Huawei/ietf96yang,SmartInfrastructures/dreamer,Shashikanth-Huawei/bmp,oplinkoms/onos,mengmoya/onos,planoAccess/clonedONOS,VinodKumarS-Huawei/ietf96yang,sdnwiselab/onos,chenxiuyang/onos,VinodKumarS-Huawei/ietf96yang,packet-tracker/onos,Shashikanth-Huawei/bmp,kuujo/onos,LorenzReinhart/ONOSnew,jmiserez/onos,kuujo/onos,CNlukai/onos-gerrit-test,chenxiuyang/onos,planoAccess/clonedONOS,osinstom/onos,chenxiuyang/onos,kuujo/onos,kuujo/onos,jinlongliu/onos,maheshraju-Huawei/actn,Shashikanth-Huawei/bmp,y-higuchi/onos,lsinfo3/onos,castroflavio/onos,osinstom/onos,packet-tracker/onos,oeeagle/onos,kkkane/ONOS,sonu283304/onos,mengmoya/onos,y-higuchi/onos,castroflavio/onos,opennetworkinglab/onos,packet-tracker/onos,jinlongliu/onos,zsh2938/onos,VinodKumarS-Huawei/ietf96yang,oplinkoms/onos,SmartInfrastructures/dreamer,LorenzReinhart/ONOSnew,oplinkoms/onos,chinghanyu/onos,donNewtonAlpha/onos,maheshraju-Huawei/actn
package org.onlab.onos.store.service.impl; import static org.slf4j.LoggerFactory.getLogger; import java.util.Vector; import net.kuujo.copycat.cluster.TcpClusterConfig; import net.kuujo.copycat.cluster.TcpMember; import net.kuujo.copycat.event.LeaderElectEvent; import net.kuujo.copycat.internal.log.ConfigurationEntry; import net.kuujo.copycat.internal.log.CopycatEntry; import net.kuujo.copycat.internal.log.OperationEntry; import net.kuujo.copycat.internal.log.SnapshotEntry; import net.kuujo.copycat.protocol.PingRequest; import net.kuujo.copycat.protocol.PingResponse; import net.kuujo.copycat.protocol.PollRequest; import net.kuujo.copycat.protocol.PollResponse; import net.kuujo.copycat.protocol.Response.Status; import net.kuujo.copycat.protocol.SubmitRequest; import net.kuujo.copycat.protocol.SubmitResponse; import net.kuujo.copycat.protocol.SyncRequest; import net.kuujo.copycat.protocol.SyncResponse; import net.kuujo.copycat.spi.protocol.Protocol; import net.kuujo.copycat.spi.protocol.ProtocolClient; import net.kuujo.copycat.spi.protocol.ProtocolServer; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.onos.cluster.ClusterService; import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService; import org.onlab.onos.store.cluster.messaging.MessageSubject; import org.onlab.onos.store.serializers.KryoNamespaces; import org.onlab.onos.store.serializers.KryoSerializer; import org.onlab.onos.store.serializers.StoreSerializer; import org.onlab.onos.store.service.impl.DatabaseStateMachine.State; import org.onlab.onos.store.service.impl.DatabaseStateMachine.TableMetadata; import org.onlab.util.KryoNamespace; import org.slf4j.Logger; /** * ONOS Cluster messaging based Copycat protocol. */ @Component(immediate = false) @Service public class ClusterMessagingProtocol implements DatabaseProtocolService, Protocol<TcpMember> { private final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterService clusterService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterCommunicationService clusterCommunicator; public static final MessageSubject COPYCAT_PING = new MessageSubject("copycat-raft-consensus-ping"); public static final MessageSubject COPYCAT_SYNC = new MessageSubject("copycat-raft-consensus-sync"); public static final MessageSubject COPYCAT_POLL = new MessageSubject("copycat-raft-consensus-poll"); public static final MessageSubject COPYCAT_SUBMIT = new MessageSubject("copycat-raft-consensus-submit"); static final int AFTER_COPYCAT = KryoNamespaces.BEGIN_USER_CUSTOM_ID + 50; static final KryoNamespace COPYCAT = KryoNamespace.newBuilder() .register(KryoNamespaces.API) .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID) .register(PingRequest.class) .register(PingResponse.class) .register(PollRequest.class) .register(PollResponse.class) .register(SyncRequest.class) .register(SyncResponse.class) .register(SubmitRequest.class) .register(SubmitResponse.class) .register(Status.class) .register(ConfigurationEntry.class) .register(SnapshotEntry.class) .register(CopycatEntry.class) .register(OperationEntry.class) .register(TcpClusterConfig.class) .register(TcpMember.class) .register(LeaderElectEvent.class) .register(Vector.class) .build(); // serializer used for CopyCat Protocol public static final StoreSerializer DB_SERIALIZER = new KryoSerializer() { @Override protected void setupKryoPool() { serializerPool = KryoNamespace.newBuilder() .register(COPYCAT) .nextId(AFTER_COPYCAT) // for snapshot .register(State.class) .register(TableMetadata.class) // TODO: Move this out ? .register(TableModificationEvent.class) .register(TableModificationEvent.Type.class) .build(); } }; @Activate public void activate() { log.info("Started"); } @Deactivate public void deactivate() { log.info("Stopped"); } @Override public ProtocolServer createServer(TcpMember member) { return new ClusterMessagingProtocolServer(clusterCommunicator); } @Override public ProtocolClient createClient(TcpMember member) { return new ClusterMessagingProtocolClient(clusterService, clusterCommunicator, clusterService.getLocalNode(), member); } }
core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java
package org.onlab.onos.store.service.impl; import static org.slf4j.LoggerFactory.getLogger; import java.util.Vector; import net.kuujo.copycat.cluster.TcpClusterConfig; import net.kuujo.copycat.cluster.TcpMember; import net.kuujo.copycat.event.LeaderElectEvent; import net.kuujo.copycat.internal.log.ConfigurationEntry; import net.kuujo.copycat.internal.log.CopycatEntry; import net.kuujo.copycat.internal.log.OperationEntry; import net.kuujo.copycat.internal.log.SnapshotEntry; import net.kuujo.copycat.protocol.PingRequest; import net.kuujo.copycat.protocol.PingResponse; import net.kuujo.copycat.protocol.PollRequest; import net.kuujo.copycat.protocol.PollResponse; import net.kuujo.copycat.protocol.Response.Status; import net.kuujo.copycat.protocol.SubmitRequest; import net.kuujo.copycat.protocol.SubmitResponse; import net.kuujo.copycat.protocol.SyncRequest; import net.kuujo.copycat.protocol.SyncResponse; import net.kuujo.copycat.spi.protocol.Protocol; import net.kuujo.copycat.spi.protocol.ProtocolClient; import net.kuujo.copycat.spi.protocol.ProtocolServer; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.ReferenceCardinality; import org.apache.felix.scr.annotations.Service; import org.onlab.onos.cluster.ClusterService; import org.onlab.onos.store.cluster.messaging.ClusterCommunicationService; import org.onlab.onos.store.cluster.messaging.MessageSubject; import org.onlab.onos.store.serializers.KryoNamespaces; import org.onlab.onos.store.serializers.KryoSerializer; import org.onlab.onos.store.serializers.StoreSerializer; import org.onlab.onos.store.service.impl.DatabaseStateMachine.State; import org.onlab.onos.store.service.impl.DatabaseStateMachine.TableMetadata; import org.onlab.util.KryoNamespace; import org.slf4j.Logger; /** * ONOS Cluster messaging based Copycat protocol. */ @Component(immediate = true) @Service public class ClusterMessagingProtocol implements DatabaseProtocolService, Protocol<TcpMember> { private final Logger log = getLogger(getClass()); @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterService clusterService; @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY) protected ClusterCommunicationService clusterCommunicator; public static final MessageSubject COPYCAT_PING = new MessageSubject("copycat-raft-consensus-ping"); public static final MessageSubject COPYCAT_SYNC = new MessageSubject("copycat-raft-consensus-sync"); public static final MessageSubject COPYCAT_POLL = new MessageSubject("copycat-raft-consensus-poll"); public static final MessageSubject COPYCAT_SUBMIT = new MessageSubject("copycat-raft-consensus-submit"); static final int AFTER_COPYCAT = KryoNamespaces.BEGIN_USER_CUSTOM_ID + 50; static final KryoNamespace COPYCAT = KryoNamespace.newBuilder() .register(KryoNamespaces.API) .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID) .register(PingRequest.class) .register(PingResponse.class) .register(PollRequest.class) .register(PollResponse.class) .register(SyncRequest.class) .register(SyncResponse.class) .register(SubmitRequest.class) .register(SubmitResponse.class) .register(Status.class) .register(ConfigurationEntry.class) .register(SnapshotEntry.class) .register(CopycatEntry.class) .register(OperationEntry.class) .register(TcpClusterConfig.class) .register(TcpMember.class) .register(LeaderElectEvent.class) .register(Vector.class) .build(); // serializer used for CopyCat Protocol public static final StoreSerializer DB_SERIALIZER = new KryoSerializer() { @Override protected void setupKryoPool() { serializerPool = KryoNamespace.newBuilder() .register(COPYCAT) .nextId(AFTER_COPYCAT) // for snapshot .register(State.class) .register(TableMetadata.class) // TODO: Move this out ? .register(TableModificationEvent.class) .register(TableModificationEvent.Type.class) .build(); } }; @Activate public void activate() { log.info("Started"); } @Deactivate public void deactivate() { log.info("Stopped"); } @Override public ProtocolServer createServer(TcpMember member) { return new ClusterMessagingProtocolServer(clusterCommunicator); } @Override public ProtocolClient createClient(TcpMember member) { return new ClusterMessagingProtocolClient(clusterService, clusterCommunicator, clusterService.getLocalNode(), member); } }
ClusterMessagingProtocol: initialize on demand Change-Id: I58b6dfb4c1756a2ee097847b1b3363d829d25676
core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java
ClusterMessagingProtocol: initialize on demand
Java
apache-2.0
f2bf7ac697df61c23e5e2b51391a2e07b9dd9c8f
0
xquery/marklogic-sesame,marklogic/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame,xquery/marklogic-sesame,marklogic/marklogic-sesame
/* * Copyright 2015-2016 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A library that enables access to a MarkLogic-backed triple-store via the * Sesame API. */ package com.marklogic.semantics.sesame.client; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.Binding; import org.openrdf.repository.sparql.query.SPARQLQueryBindingSet; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.FailedRequestException; import com.marklogic.client.Transaction; import com.marklogic.client.impl.SPARQLBindingsImpl; import com.marklogic.client.io.FileHandle; import com.marklogic.client.io.InputStreamHandle; import com.marklogic.client.query.QueryDefinition; import com.marklogic.client.semantics.GraphManager; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.semantics.RDFTypes; import com.marklogic.client.semantics.SPARQLBindings; import com.marklogic.client.semantics.SPARQLQueryDefinition; import com.marklogic.client.semantics.SPARQLQueryManager; import com.marklogic.client.semantics.SPARQLRuleset; import com.marklogic.semantics.sesame.MarkLogicSesameException; /** * internal class for interacting with java api client * * @author James Fuller */ class MarkLogicClientImpl { private static final Logger logger = LoggerFactory.getLogger(MarkLogicClientImpl.class); private static final String DEFAULT_GRAPH_URI = "http://marklogic.com/semantics#default-graph"; private SPARQLRuleset[] ruleset; private QueryDefinition constrainingQueryDef; private GraphPermissions graphPerms; private SPARQLQueryManager sparqlManager; private GraphManager graphManager; private DatabaseClient databaseClient; /** * constructor * * @param host * @param port * @param user * @param password * @param auth */ public MarkLogicClientImpl(String host, int port, String user, String password, String auth) { setDatabaseClient(DatabaseClientFactory.newClient(host, port, user, password, DatabaseClientFactory.Authentication.valueOf(auth))); } /** * set databaseclient * * @param databaseClient */ public MarkLogicClientImpl(DatabaseClient databaseClient) { setDatabaseClient(databaseClient); } /** * set databaseclient and instantate related managers * * @param databaseClient */ private void setDatabaseClient(DatabaseClient databaseClient) { this.databaseClient = databaseClient; this.sparqlManager = getDatabaseClient().newSPARQLQueryManager(); this.graphManager = getDatabaseClient().newGraphManager(); } /** * gets database client * * @return DatabaseClient */ public DatabaseClient getDatabaseClient() { return this.databaseClient; } /** * executes SPARQLQuery * * @param queryString * @param bindings * @param start * @param pageLength * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI); } /** * executes SPARQLQuery * * @param queryString * @param bindings * @param handle * @param start * @param pageLength * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset)){qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())) { qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } qdef.setIncludeDefaultRulesets(includeInferred); if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} if(pageLength > 0){ sparqlManager.setPageLength(pageLength); }else{ sparqlManager.clearPageLength(); } sparqlManager.executeSelect(qdef, handle, start, tx); return new BufferedInputStream(handle.get()); } /** * executes GraphQuery * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performGraphQuery(queryString, bindings, new InputStreamHandle(), tx, includeInferred, baseURI); } /** * executes GraphQuery * * @param queryString * @param bindings * @param handle * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){ qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} qdef.setIncludeDefaultRulesets(includeInferred); sparqlManager.executeDescribe(qdef, handle, tx); return new BufferedInputStream(handle.get()); } /** * executes BooleanQuery * * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI * @return */ public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} qdef.setIncludeDefaultRulesets(includeInferred); if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){ qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} return sparqlManager.executeAsk(qdef,tx); } /** * executes UpdateQuery * * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI */ public void performUpdateQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset) ) {qdef.setRulesets(ruleset);} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} qdef.setIncludeDefaultRulesets(includeInferred); sparqlManager.clearPageLength(); sparqlManager.executeUpdate(qdef, tx); } /** * executes merge of triples from File * * @param file * @param baseURI * @param dataFormat * @param tx * @param contexts * @throws RDFParseException */ // performAdd // as we use mergeGraphs, baseURI is always file.toURI public void performAdd(File file, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException { try { graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType()); if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) { graphManager.mergeGraphs(new FileHandle(file),tx); } else { if (notNull(contexts) && contexts.length>0) { for (int i = 0; i < contexts.length; i++) { if(notNull(contexts[i])){ graphManager.mergeAs(contexts[i].toString(), new FileHandle(file), getGraphPerms(),tx); }else{ graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file),getGraphPerms(), tx); } } } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file), getGraphPerms(),tx); } } } catch (FailedRequestException e) { throw new RDFParseException("Request to MarkLogic server failed, check file and format."); } } /** * executes merge of triples from InputStream * * @param in * @param baseURI * @param dataFormat * @param tx * @param contexts * @throws RDFParseException */ public void performAdd(InputStream in, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException, MarkLogicSesameException { try { graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType()); if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) { graphManager.mergeGraphs(new InputStreamHandle(in),tx); } else { if (notNull(contexts) && contexts.length > 0) { for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { graphManager.mergeAs(contexts[i].toString(), new InputStreamHandle(in), getGraphPerms(), tx); } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx); } } } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx); } } in.close(); } catch (FailedRequestException e) { throw new RDFParseException("Request to MarkLogic server failed, check input is valid."); } catch (IOException e) { logger.error(e.getLocalizedMessage()); throw new MarkLogicSesameException("IO error"); } } /** * executes INSERT of single triple * * @param baseURI * @param subject * @param predicate * @param object * @param tx * @param contexts * @throws MarkLogicSesameException */ public void performAdd(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException { StringBuilder sb = new StringBuilder(); if(notNull(contexts) && contexts.length>0) { if (notNull(baseURI)) sb.append("BASE <" + baseURI + ">\n"); sb.append("INSERT DATA { "); for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} "); } else { sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} "); } } sb.append("}"); } else { sb.append("INSERT DATA { GRAPH <" + DEFAULT_GRAPH_URI + "> {?s ?p ?o .}}"); } SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString()); if (notNull(ruleset) ) {qdef.setRulesets(ruleset);} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if(notNull(subject)) qdef.withBinding("s", subject.stringValue()); if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue()); if(notNull(object)) bindObject(qdef, "o", object); sparqlManager.executeUpdate(qdef, tx); } /** * executes DELETE of single triple * * @param baseURI * @param subject * @param predicate * @param object * @param tx * @param contexts * @throws MarkLogicSesameException */ public void performRemove(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException { StringBuilder sb = new StringBuilder(); if(notNull(contexts) && contexts.length>0) { if (notNull(baseURI))sb.append("BASE <" + baseURI + ">\n"); sb.append("DELETE WHERE { "); for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} "); } else { sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} "); } } sb.append("}"); }else{ sb.append("DELETE WHERE { GRAPH ?ctx { ?s ?p ?o .}}"); } SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString()); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if(notNull(subject)) qdef.withBinding("s", subject.stringValue()); if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue()); if(notNull(object)) bindObject(qdef, "o", object); sparqlManager.executeUpdate(qdef, tx); } /** * clears triples from named graph * * @param tx * @param contexts */ public void performClear(Transaction tx, Resource... contexts) { if(notNull(contexts)) { for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { graphManager.delete(contexts[i].stringValue(), tx); } else { graphManager.delete(DEFAULT_GRAPH_URI, tx); } } }else{ graphManager.delete(DEFAULT_GRAPH_URI, tx); } } /** * clears all triples * * @param tx */ public void performClearAll(Transaction tx) { graphManager.deleteGraphs(tx); } /** * getter rulesets * * @return */ public SPARQLRuleset[] getRulesets() { return this.ruleset; } /** * setter for rulesets, filters out nulls * * @param rulesets */ public void setRulesets(SPARQLRuleset ... rulesets) { if(notNull(rulesets)) { List<SPARQLRuleset> list = new ArrayList<>(); for(Object r : rulesets) { if(r != null && rulesets.length > 0) { list.add((SPARQLRuleset)r); } } this.ruleset = list.toArray(new SPARQLRuleset[list.size()]); }else{ this.ruleset = null; } } /** * setter for graph permissions * * @param graphPerms */ public void setGraphPerms(GraphPermissions graphPerms) { this.graphPerms = graphPerms; } /** * getter for graph permissions * * @return */ public GraphPermissions getGraphPerms() { return this.graphPerms; } /** * setter for ConstrainingQueryDefinition * * @param constrainingQueryDefinition */ public void setConstrainingQueryDefinition(QueryDefinition constrainingQueryDefinition) { this.constrainingQueryDef = constrainingQueryDefinition; } /** * getter for ConstrainingQueryDefinition * * @return */ public QueryDefinition getConstrainingQueryDefinition() { return this.constrainingQueryDef; } /** * close client * * @return */ public void close() { if (this.databaseClient != null) { try { this.databaseClient.release(); } catch (Exception e) { logger.info("Failed releasing DB client", e); } } } /////////////////////////////////////////////////////////////////////////////////////////////// /** * converts Sesame BindingSet to java api client SPARQLBindings * * @param bindings * @return */ protected SPARQLBindings getSPARQLBindings(SPARQLQueryBindingSet bindings) { SPARQLBindings sps = new SPARQLBindingsImpl(); for (Binding binding : bindings) { sps.bind(binding.getName(), binding.getValue().stringValue()); } return sps; } /////////////////////////////////////////////////////////////////////////////////////////////// /** * bind object * * @param qdef * @param variableName * @param object * @return * @throws MarkLogicSesameException */ private static SPARQLQueryDefinition bindObject(SPARQLQueryDefinition qdef, String variableName, Value object) throws MarkLogicSesameException{ SPARQLBindings bindings = qdef.getBindings(); if(object != null){ if (object instanceof URI) { bindings.bind(variableName, object.stringValue()); } else if (object instanceof Literal) { Literal lit = (Literal) object; if (lit.getLanguage() != null) { String languageTag = lit.getLanguage(); bindings.bind(variableName, lit.getLabel(), Locale.forLanguageTag(languageTag)); }else if (((Literal) object).getDatatype() != null) { try { String xsdType = lit.getDatatype().toString(); String fragment = new java.net.URI(xsdType).getFragment(); bindings.bind(variableName,lit.getLabel(),RDFTypes.valueOf(fragment.toUpperCase())); } catch (URISyntaxException e) { throw new MarkLogicSesameException("Problem with object datatype."); } }else { // assume we have a string value bindings.bind(variableName, lit.getLabel(), RDFTypes.STRING); } } qdef.setBindings(bindings); } return qdef; } /** * tedious utility for checking if object is null or not * * @param item * @return */ private static Boolean notNull(Object item) { return item != null; } }
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java
/* * Copyright 2015-2016 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A library that enables access to a MarkLogic-backed triple-store via the * Sesame API. */ package com.marklogic.semantics.sesame.client; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.query.Binding; import org.openrdf.repository.sparql.query.SPARQLQueryBindingSet; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFParseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.FailedRequestException; import com.marklogic.client.Transaction; import com.marklogic.client.impl.SPARQLBindingsImpl; import com.marklogic.client.io.FileHandle; import com.marklogic.client.io.InputStreamHandle; import com.marklogic.client.query.QueryDefinition; import com.marklogic.client.semantics.GraphManager; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.semantics.RDFTypes; import com.marklogic.client.semantics.SPARQLBindings; import com.marklogic.client.semantics.SPARQLQueryDefinition; import com.marklogic.client.semantics.SPARQLQueryManager; import com.marklogic.client.semantics.SPARQLRuleset; import com.marklogic.semantics.sesame.MarkLogicSesameException; /** * internal class for interacting with java api client * * @author James Fuller */ class MarkLogicClientImpl { private static final Logger logger = LoggerFactory.getLogger(MarkLogicClientImpl.class); private static final String DEFAULT_GRAPH_URI = "http://marklogic.com/semantics#default-graph"; private SPARQLRuleset[] ruleset; private QueryDefinition constrainingQueryDef; private GraphPermissions graphPerms; private SPARQLQueryManager sparqlManager; private GraphManager graphManager; private DatabaseClient databaseClient; /** * constructor * * @param host * @param port * @param user * @param password * @param auth */ public MarkLogicClientImpl(String host, int port, String user, String password, String auth) { setDatabaseClient(DatabaseClientFactory.newClient(host, port, user, password, DatabaseClientFactory.Authentication.valueOf(auth))); } /** * set databaseclient * * @param databaseClient */ public MarkLogicClientImpl(DatabaseClient databaseClient) { setDatabaseClient(databaseClient); } /** * set databaseclient and instantate related managers * * @param databaseClient */ private void setDatabaseClient(DatabaseClient databaseClient) { this.databaseClient = databaseClient; this.sparqlManager = getDatabaseClient().newSPARQLQueryManager(); this.graphManager = getDatabaseClient().newGraphManager(); } /** * gets database client * * @return DatabaseClient */ public DatabaseClient getDatabaseClient() { return this.databaseClient; } /** * executes SPARQLQuery * * @param queryString * @param bindings * @param start * @param pageLength * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performSPARQLQuery(queryString, bindings, new InputStreamHandle(), start, pageLength, tx, includeInferred, baseURI); } /** * executes SPARQLQuery * * @param queryString * @param bindings * @param handle * @param start * @param pageLength * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performSPARQLQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, long start, long pageLength, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset)){qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())) { qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition()); qdef.setOptionsName(getConstrainingQueryDefinition().getOptionsName()); } qdef.setIncludeDefaultRulesets(includeInferred); if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} if(pageLength > 0){ sparqlManager.setPageLength(pageLength); }else{ sparqlManager.clearPageLength(); } sparqlManager.executeSelect(qdef, handle, start, tx); return new BufferedInputStream(handle.get()); } /** * executes GraphQuery * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { return performGraphQuery(queryString, bindings, new InputStreamHandle(), tx, includeInferred, baseURI); } /** * executes GraphQuery * * @param queryString * @param bindings * @param handle * @param tx * @param includeInferred * @param baseURI * @return * @throws JsonProcessingException */ public InputStream performGraphQuery(String queryString, SPARQLQueryBindingSet bindings, InputStreamHandle handle, Transaction tx, boolean includeInferred, String baseURI) throws JsonProcessingException { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} qdef.setIncludeDefaultRulesets(includeInferred); sparqlManager.executeDescribe(qdef, handle, tx); return new BufferedInputStream(handle.get()); } /** * executes BooleanQuery * * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI * @return */ public boolean performBooleanQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} qdef.setIncludeDefaultRulesets(includeInferred); if (notNull(ruleset)) {qdef.setRulesets(ruleset);} if (notNull(getConstrainingQueryDefinition())){qdef.setConstrainingQueryDefinition(getConstrainingQueryDefinition());} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} return sparqlManager.executeAsk(qdef,tx); } /** * executes UpdateQuery * * @param queryString * @param bindings * @param tx * @param includeInferred * @param baseURI */ public void performUpdateQuery(String queryString, SPARQLQueryBindingSet bindings, Transaction tx, boolean includeInferred, String baseURI) { SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(queryString); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if (notNull(ruleset) ) {qdef.setRulesets(ruleset);} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} qdef.setIncludeDefaultRulesets(includeInferred); sparqlManager.clearPageLength(); sparqlManager.executeUpdate(qdef, tx); } /** * executes merge of triples from File * * @param file * @param baseURI * @param dataFormat * @param tx * @param contexts * @throws RDFParseException */ // performAdd // as we use mergeGraphs, baseURI is always file.toURI public void performAdd(File file, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException { try { graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType()); if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) { graphManager.mergeGraphs(new FileHandle(file),tx); } else { if (notNull(contexts) && contexts.length>0) { for (int i = 0; i < contexts.length; i++) { if(notNull(contexts[i])){ graphManager.mergeAs(contexts[i].toString(), new FileHandle(file), getGraphPerms(),tx); }else{ graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file),getGraphPerms(), tx); } } } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new FileHandle(file), getGraphPerms(),tx); } } } catch (FailedRequestException e) { throw new RDFParseException("Request to MarkLogic server failed, check file and format."); } } /** * executes merge of triples from InputStream * * @param in * @param baseURI * @param dataFormat * @param tx * @param contexts * @throws RDFParseException */ public void performAdd(InputStream in, String baseURI, RDFFormat dataFormat, Transaction tx, Resource... contexts) throws RDFParseException, MarkLogicSesameException { try { graphManager.setDefaultMimetype(dataFormat.getDefaultMIMEType()); if (dataFormat.equals(RDFFormat.NQUADS) || dataFormat.equals(RDFFormat.TRIG)) { graphManager.mergeGraphs(new InputStreamHandle(in),tx); } else { if (notNull(contexts) && contexts.length > 0) { for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { graphManager.mergeAs(contexts[i].toString(), new InputStreamHandle(in), getGraphPerms(), tx); } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx); } } } else { graphManager.mergeAs(DEFAULT_GRAPH_URI, new InputStreamHandle(in),getGraphPerms(), tx); } } in.close(); } catch (FailedRequestException e) { throw new RDFParseException("Request to MarkLogic server failed, check input is valid."); } catch (IOException e) { logger.error(e.getLocalizedMessage()); throw new MarkLogicSesameException("IO error"); } } /** * executes INSERT of single triple * * @param baseURI * @param subject * @param predicate * @param object * @param tx * @param contexts * @throws MarkLogicSesameException */ public void performAdd(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException { StringBuilder sb = new StringBuilder(); if(notNull(contexts) && contexts.length>0) { if (notNull(baseURI)) sb.append("BASE <" + baseURI + ">\n"); sb.append("INSERT DATA { "); for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} "); } else { sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} "); } } sb.append("}"); } else { sb.append("INSERT DATA { GRAPH <" + DEFAULT_GRAPH_URI + "> {?s ?p ?o .}}"); } SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString()); if (notNull(ruleset) ) {qdef.setRulesets(ruleset);} if(notNull(graphPerms)){ qdef.setUpdatePermissions(graphPerms);} if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if(notNull(subject)) qdef.withBinding("s", subject.stringValue()); if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue()); if(notNull(object)) bindObject(qdef, "o", object); sparqlManager.executeUpdate(qdef, tx); } /** * executes DELETE of single triple * * @param baseURI * @param subject * @param predicate * @param object * @param tx * @param contexts * @throws MarkLogicSesameException */ public void performRemove(String baseURI, Resource subject, URI predicate, Value object, Transaction tx, Resource... contexts) throws MarkLogicSesameException { StringBuilder sb = new StringBuilder(); if(notNull(contexts) && contexts.length>0) { if (notNull(baseURI))sb.append("BASE <" + baseURI + ">\n"); sb.append("DELETE WHERE { "); for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { sb.append("GRAPH <" + contexts[i].stringValue() + "> { ?s ?p ?o .} "); } else { sb.append("GRAPH <" + DEFAULT_GRAPH_URI + "> { ?s ?p ?o .} "); } } sb.append("}"); }else{ sb.append("DELETE WHERE { GRAPH ?ctx { ?s ?p ?o .}}"); } SPARQLQueryDefinition qdef = sparqlManager.newQueryDefinition(sb.toString()); if(notNull(baseURI) && !baseURI.isEmpty()){ qdef.setBaseUri(baseURI);} if(notNull(subject)) qdef.withBinding("s", subject.stringValue()); if(notNull(predicate)) qdef.withBinding("p", predicate.stringValue()); if(notNull(object)) bindObject(qdef, "o", object); sparqlManager.executeUpdate(qdef, tx); } /** * clears triples from named graph * * @param tx * @param contexts */ public void performClear(Transaction tx, Resource... contexts) { if(notNull(contexts)) { for (int i = 0; i < contexts.length; i++) { if (notNull(contexts[i])) { graphManager.delete(contexts[i].stringValue(), tx); } else { graphManager.delete(DEFAULT_GRAPH_URI, tx); } } }else{ graphManager.delete(DEFAULT_GRAPH_URI, tx); } } /** * clears all triples * * @param tx */ public void performClearAll(Transaction tx) { graphManager.deleteGraphs(tx); } /** * getter rulesets * * @return */ public SPARQLRuleset[] getRulesets() { return this.ruleset; } /** * setter for rulesets, filters out nulls * * @param rulesets */ public void setRulesets(SPARQLRuleset ... rulesets) { if(notNull(rulesets)) { List<SPARQLRuleset> list = new ArrayList<>(); for(Object r : rulesets) { if(r != null && rulesets.length > 0) { list.add((SPARQLRuleset)r); } } this.ruleset = list.toArray(new SPARQLRuleset[list.size()]); }else{ this.ruleset = null; } } /** * setter for graph permissions * * @param graphPerms */ public void setGraphPerms(GraphPermissions graphPerms) { this.graphPerms = graphPerms; } /** * getter for graph permissions * * @return */ public GraphPermissions getGraphPerms() { return this.graphPerms; } /** * setter for ConstrainingQueryDefinition * * @param constrainingQueryDefinition */ public void setConstrainingQueryDefinition(QueryDefinition constrainingQueryDefinition) { this.constrainingQueryDef = constrainingQueryDefinition; } /** * getter for ConstrainingQueryDefinition * * @return */ public QueryDefinition getConstrainingQueryDefinition() { return this.constrainingQueryDef; } /** * close client * * @return */ public void close() { if (this.databaseClient != null) { try { this.databaseClient.release(); } catch (Exception e) { logger.info("Failed releasing DB client", e); } } } /////////////////////////////////////////////////////////////////////////////////////////////// /** * converts Sesame BindingSet to java api client SPARQLBindings * * @param bindings * @return */ protected SPARQLBindings getSPARQLBindings(SPARQLQueryBindingSet bindings) { SPARQLBindings sps = new SPARQLBindingsImpl(); for (Binding binding : bindings) { sps.bind(binding.getName(), binding.getValue().stringValue()); } return sps; } /////////////////////////////////////////////////////////////////////////////////////////////// /** * bind object * * @param qdef * @param variableName * @param object * @return * @throws MarkLogicSesameException */ private static SPARQLQueryDefinition bindObject(SPARQLQueryDefinition qdef, String variableName, Value object) throws MarkLogicSesameException{ SPARQLBindings bindings = qdef.getBindings(); if(object != null){ if (object instanceof URI) { bindings.bind(variableName, object.stringValue()); } else if (object instanceof Literal) { Literal lit = (Literal) object; if (lit.getLanguage() != null) { String languageTag = lit.getLanguage(); bindings.bind(variableName, lit.getLabel(), Locale.forLanguageTag(languageTag)); }else if (((Literal) object).getDatatype() != null) { try { String xsdType = lit.getDatatype().toString(); String fragment = new java.net.URI(xsdType).getFragment(); bindings.bind(variableName,lit.getLabel(),RDFTypes.valueOf(fragment.toUpperCase())); } catch (URISyntaxException e) { throw new MarkLogicSesameException("Problem with object datatype."); } }else { // assume we have a string value bindings.bind(variableName, lit.getLabel(), RDFTypes.STRING); } } qdef.setBindings(bindings); } return qdef; } /** * tedious utility for checking if object is null or not * * @param item * @return */ private static Boolean notNull(Object item) { return item != null; } }
#326 copy options name from strucutured query definition to boolean and graph query definition
marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClientImpl.java
#326 copy options name from strucutured query definition to boolean and graph query definition
Java
apache-2.0
95cea065e6482f90bb05cfff0eab517532ba2365
0
pubudu538/product-private-paas,wso2/product-private-paas,Vishanth/product-private-paas,gayangunarathne/private-paas,pubudu538/product-private-paas,pubudu538/product-private-paas,pubudu538/product-private-paas,Thanu/product-private-paas,gayangunarathne/private-paas,liurl3/product-private-paas,wso2/product-private-paas,nishadi/product-private-paas,Vishanth/product-private-paas,Thanu/product-private-paas,wso2/product-private-paas,nishadi/product-private-paas,Vishanth/product-private-paas,wso2/product-private-paas,Thanu/product-private-paas,liurl3/product-private-paas,wso2/product-private-paas,pubudu538/product-private-paas,nishadi/product-private-paas,gayangunarathne/private-paas,pubudu538/product-private-paas,wso2/product-private-paas,liurl3/product-private-paas,Thanu/product-private-paas,gayangunarathne/private-paas,Thanu/product-private-paas,nishadi/product-private-paas,gayangunarathne/private-paas,Vishanth/product-private-paas,gayangunarathne/private-paas,nishadi/product-private-paas,Vishanth/product-private-paas,Vishanth/product-private-paas,Thanu/product-private-paas,nishadi/product-private-paas,liurl3/product-private-paas
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.rest.endpoint.services; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy; import org.apache.stratos.cloud.controller.stub.pojo.CartridgeConfig; import org.apache.stratos.cloud.controller.stub.pojo.CartridgeInfo; import org.apache.stratos.cloud.controller.stub.pojo.Property; import org.apache.stratos.autoscaler.stub.AutoScalerServiceInvalidPartitionExceptionException; import org.apache.stratos.autoscaler.stub.AutoScalerServiceInvalidPolicyExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidCartridgeDefinitionExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidCartridgeTypeExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidIaasProviderExceptionException; import org.apache.stratos.manager.client.AutoscalerServiceClient; import org.apache.stratos.manager.client.CloudControllerServiceClient; import org.apache.stratos.manager.deploy.service.Service; import org.apache.stratos.manager.deploy.service.ServiceDeploymentManager; import org.apache.stratos.manager.dto.Cartridge; import org.apache.stratos.manager.dto.SubscriptionInfo; import org.apache.stratos.manager.exception.*; import org.apache.stratos.manager.manager.CartridgeSubscriptionManager; import org.apache.stratos.manager.repository.RepositoryNotification; import org.apache.stratos.manager.subscription.CartridgeSubscription; import org.apache.stratos.manager.subscription.DataCartridgeSubscription; import org.apache.stratos.manager.subscription.PersistenceContext; import org.apache.stratos.manager.subscription.SubscriptionData; import org.apache.stratos.manager.subscription.SubscriptionDomain; import org.apache.stratos.manager.topology.model.TopologyClusterInformationModel; import org.apache.stratos.manager.utils.ApplicationManagementUtil; import org.apache.stratos.manager.utils.CartridgeConstants; import org.apache.stratos.messaging.domain.topology.Cluster; import org.apache.stratos.messaging.domain.topology.Member; import org.apache.stratos.messaging.domain.topology.MemberStatus; import org.apache.stratos.messaging.message.receiver.topology.TopologyManager; import org.apache.stratos.messaging.util.Constants; import org.apache.stratos.rest.endpoint.bean.CartridgeInfoBean; import org.apache.stratos.rest.endpoint.bean.StratosAdminResponse; import org.apache.stratos.rest.endpoint.bean.SubscriptionDomainRequest; import org.apache.stratos.rest.endpoint.bean.autoscaler.partition.Partition; import org.apache.stratos.rest.endpoint.bean.autoscaler.partition.PartitionGroup; import org.apache.stratos.rest.endpoint.bean.autoscaler.policy.autoscale.AutoscalePolicy; import org.apache.stratos.rest.endpoint.bean.cartridge.definition.CartridgeDefinitionBean; import org.apache.stratos.rest.endpoint.bean.cartridge.definition.ServiceDefinitionBean; import org.apache.stratos.rest.endpoint.bean.repositoryNotificationInfoBean.Payload; import org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean; import org.apache.stratos.rest.endpoint.bean.util.converter.PojoConverter; import org.apache.stratos.rest.endpoint.exception.RestAPIException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.rmi.RemoteException; import java.util.*; import java.util.regex.Pattern; public class ServiceUtils { public static final String IS_VOLUME_REQUIRED = "volume.required"; public static final String SHOULD_DELETE_VOLUME = "volume.delete.on.unsubscription"; public static final String VOLUME_SIZE = "volume.size.gb"; public static final String DEVICE_NAME = "volume.device.name"; private static Log log = LogFactory.getLog(ServiceUtils.class); private static CartridgeSubscriptionManager cartridgeSubsciptionManager = new CartridgeSubscriptionManager(); private static ServiceDeploymentManager serviceDeploymentManager = new ServiceDeploymentManager(); static StratosAdminResponse deployCartridge (CartridgeDefinitionBean cartridgeDefinitionBean, ConfigurationContext ctxt, String userName, String tenantDomain) throws RestAPIException { log.info("Starting to deploy a Cartridge [type] "+cartridgeDefinitionBean.type); CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient != null) { CartridgeConfig cartridgeConfig = PojoConverter.populateCartridgeConfigPojo(cartridgeDefinitionBean); if(cartridgeConfig == null) { throw new RestAPIException("Populated CartridgeConfig instance is null, cartridge deployment aborted"); } // call CC try { cloudControllerServiceClient .deployCartridgeDefinition(cartridgeConfig); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (CloudControllerServiceInvalidCartridgeDefinitionExceptionException e) { String message = e.getFaultMessage().getInvalidCartridgeDefinitionException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } catch (CloudControllerServiceInvalidIaasProviderExceptionException e) { String message = e.getFaultMessage().getInvalidIaasProviderException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } log.info("Successfully deployed Cartridge [type] "+cartridgeDefinitionBean.type); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed cartridge definition with type " + cartridgeDefinitionBean.type); return stratosAdminResponse; } @SuppressWarnings("unused") private static DeploymentPolicy[] intersection( DeploymentPolicy[] cartridgeDepPolicies, DeploymentPolicy[] lbCartridgeDepPolicies) { List<DeploymentPolicy> commonPolicies = new ArrayList<DeploymentPolicy>(); for (DeploymentPolicy policy1 : cartridgeDepPolicies) { for (DeploymentPolicy policy2 : lbCartridgeDepPolicies) { if(policy1.equals(policy2)) { commonPolicies.add(policy1); } } } return commonPolicies.toArray(new DeploymentPolicy[0]); } static StratosAdminResponse undeployCartridge(String cartridgeType) throws RestAPIException { CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient != null) { try { cloudControllerServiceClient.unDeployCartridgeDefinition(cartridgeType); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (CloudControllerServiceInvalidCartridgeTypeExceptionException e) { String msg = e.getFaultMessage().getInvalidCartridgeTypeException().getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully undeployed cartridge definition with type " + cartridgeType); return stratosAdminResponse; } public static StratosAdminResponse deployPartition(Partition partitionBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition = PojoConverter.convertToCCPartitionPojo(partitionBean); try { autoscalerServiceClient.deployPartition(partition); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPartitionExceptionException e) { String message = e.getFaultMessage().getInvalidPartitionException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed partition definition with id " + partitionBean.id); return stratosAdminResponse; } public static StratosAdminResponse deployAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy autoscalePolicy = PojoConverter. convertToCCAutoscalerPojo(autoscalePolicyBean); try { autoscalerServiceClient .deployAutoscalingPolicy(autoscalePolicy); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPolicyExceptionException e) { String message = e.getFaultMessage() .getInvalidPolicyException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed autoscaling policy definition with id " + autoscalePolicyBean.getId()); return stratosAdminResponse; } public static StratosAdminResponse deployDeploymentPolicy( org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy deploymentPolicy = PojoConverter.convetToCCDeploymentPolicyPojo(deploymentPolicyBean); try { autoscalerServiceClient .deployDeploymentPolicy(deploymentPolicy); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPolicyExceptionException e) { String message = e.getFaultMessage().getInvalidPolicyException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed deployment policy definition with type " + deploymentPolicyBean.id); return stratosAdminResponse; } private static CloudControllerServiceClient getCloudControllerServiceClient () throws RestAPIException { try { return CloudControllerServiceClient.getServiceClient(); } catch (AxisFault axisFault) { String errorMsg = "Error while getting CloudControllerServiceClient instance to connect to the " + "Cloud Controller. Cause: "+axisFault.getMessage(); log.error(errorMsg, axisFault); throw new RestAPIException(errorMsg, axisFault); } } public static Partition[] getAvailablePartitions () throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getAvailablePartitions(); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition[] getPartitionsOfDeploymentPolicy(String deploymentPolicyId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getPartitionsOfDeploymentPolicy(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions for deployment policy id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition[] getPartitionsOfGroup(String deploymentPolicyId, String groupId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getPartitionsOfGroup(deploymentPolicyId, groupId); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions for deployment policy id " + deploymentPolicyId + ", group id " + groupId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition getPartition (String partitionId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partition = autoscalerServiceClient.getPartition(partitionId); } catch (RemoteException e) { String errorMsg = "Error while getting partition for id " + partitionId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojo(partition); } private static AutoscalerServiceClient getAutoscalerServiceClient () throws RestAPIException { try { return AutoscalerServiceClient.getServiceClient(); } catch (AxisFault axisFault) { String errorMsg = "Error while getting AutoscalerServiceClient instance to connect to the " + "Autoscaler. Cause: "+axisFault.getMessage(); log.error(errorMsg, axisFault); throw new RestAPIException(errorMsg, axisFault); } } public static AutoscalePolicy[] getAutoScalePolicies () throws RestAPIException { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy[] autoscalePolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { autoscalePolicies = autoscalerServiceClient.getAutoScalePolicies(); } catch (RemoteException e) { String errorMsg = "Error while getting available autoscaling policies. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateAutoscalePojos(autoscalePolicies); } public static AutoscalePolicy getAutoScalePolicy (String autoscalePolicyId) throws RestAPIException { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy autoscalePolicy = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { autoscalePolicy = autoscalerServiceClient.getAutoScalePolicy(autoscalePolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting information for autoscaling policy with id " + autoscalePolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateAutoscalePojo(autoscalePolicy); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[] getDeploymentPolicies () throws RestAPIException { DeploymentPolicy [] deploymentPolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(); } catch (RemoteException e) { String errorMsg = "Error getting available deployment policies. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[] getDeploymentPolicies (String cartridgeType) throws RestAPIException { DeploymentPolicy [] deploymentPolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(cartridgeType); } catch (RemoteException e) { String errorMsg = "Error while getting available deployment policies for cartridge type " + cartridgeType+". Cause: "+e.getMessage();; log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } if(deploymentPolicies.length == 0) { String errorMsg = "Cannot find any matching deployment policy for Cartridge [type] "+cartridgeType; log.error(errorMsg); throw new RestAPIException(errorMsg); } return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy getDeploymentPolicy(String deploymentPolicyId) throws RestAPIException { DeploymentPolicy deploymentPolicy = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicy = autoscalerServiceClient.getDeploymentPolicy(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting deployment policy with id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } if(deploymentPolicy == null) { String errorMsg = "Cannot find a matching deployment policy for [id] "+deploymentPolicyId; log.error(errorMsg); throw new RestAPIException(errorMsg); } return PojoConverter.populateDeploymentPolicyPojo(deploymentPolicy); } public static PartitionGroup[] getPartitionGroups (String deploymentPolicyId) throws RestAPIException{ org.apache.stratos.autoscaler.partition.PartitionGroup [] partitionGroups = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitionGroups = autoscalerServiceClient.getPartitionGroups(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error getting available partition groups for deployment policy id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionGroupPojos(partitionGroups); } static Cartridge getAvailableCartridgeInfo(String cartridgeType, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext); for(Cartridge cartridge : cartridges) { if(cartridge.getCartridgeType().equals(cartridgeType)) { return cartridge; } } String msg = "Unavailable cartridge type: " + cartridgeType; log.error(msg); throw new RestAPIException(msg) ; } static List<Cartridge> getAvailableLbCartridges(Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext); List<Cartridge> lbCartridges = new ArrayList<Cartridge>(); for (Cartridge cartridge : cartridges) { if (cartridge.isLoadBalancer()) { lbCartridges.add(cartridge); } } /*if(lbCartridges == null || lbCartridges.isEmpty()) { String msg = "Load balancer Cartridges are not available."; log.error(msg); throw new RestAPIException(msg) ; }*/ return lbCartridges; } static List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = new ArrayList<Cartridge>(); if (log.isDebugEnabled()) { log.debug("Getting available cartridges. Search String: " + cartridgeSearchString + ", Multi-Tenant: " + multiTenant); } boolean allowMultipleSubscription = new Boolean( System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED)); try { Pattern searchPattern = getSearchStringPattern(cartridgeSearchString); String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges(); if (availableCartridges != null) { for (String cartridgeType : availableCartridges) { CartridgeInfo cartridgeInfo = null; try { cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: " + e.getMessage()); } } if (cartridgeInfo == null) { // This cannot happen. But continue if (log.isDebugEnabled()) { log.debug("Cartridge Info not found: " + cartridgeType); } continue; } if (multiTenant != null && !multiTenant && cartridgeInfo.getMultiTenant()) { // Need only Single-Tenant cartridges continue; } else if (multiTenant != null && multiTenant && !cartridgeInfo.getMultiTenant()) { // Need only Multi-Tenant cartridges continue; } if (!ServiceUtils.cartridgeMatches(cartridgeInfo, searchPattern)) { continue; } Cartridge cartridge = new Cartridge(); cartridge.setCartridgeType(cartridgeType); cartridge.setProvider(cartridgeInfo.getProvider()); cartridge.setDisplayName(cartridgeInfo.getDisplayName()); cartridge.setDescription(cartridgeInfo.getDescription()); cartridge.setVersion(cartridgeInfo.getVersion()); cartridge.setMultiTenant(cartridgeInfo.getMultiTenant()); cartridge.setHostName(cartridgeInfo.getHostName()); cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy()); cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy()); //cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED); cartridge.setCartridgeAlias("-"); cartridge.setPersistence(cartridgeInfo.getPersistence()); cartridge.setServiceGroup(cartridgeInfo.getServiceGroup()); if(cartridgeInfo.getLbConfig() != null && cartridgeInfo.getProperties() != null) { for(Property property: cartridgeInfo.getProperties()) { if(property.getName().equals("load.balancer")) { cartridge.setLoadBalancer(true); } } } //cartridge.setActiveInstances(0); cartridges.add(cartridge); if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) { // If the cartridge is multi-tenant. We should not let users // createSubscription twice. if (isAlreadySubscribed(cartridgeType, ApplicationManagementUtil.getTenantId(configurationContext))) { if (log.isDebugEnabled()) { log.debug("Already subscribed to " + cartridgeType + ". This multi-tenant cartridge will not be available to createSubscription"); } //cartridge.setStatus(CartridgeConstants.SUBSCRIBED); } } } } else { if (log.isDebugEnabled()) { log.debug("There are no available cartridges"); } } } catch (Exception e) { String msg = "Error while getting available cartridges. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } Collections.sort(cartridges); if (log.isDebugEnabled()) { log.debug("Returning available cartridges " + cartridges.size()); } return cartridges; } private static boolean isAlreadySubscribed(String cartridgeType, int tenantId) { Collection<CartridgeSubscription> subscriptionList = cartridgeSubsciptionManager.isCartridgeSubscribed(tenantId, cartridgeType); if(subscriptionList == null || subscriptionList.isEmpty()){ return false; }else { return true; } } public static List<ServiceDefinitionBean> getdeployedServiceInformation () throws RestAPIException { Collection<Service> services = null; try { services = serviceDeploymentManager.getServices(); } catch (ADCException e) { String msg = "Unable to get deployed service information. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } if (services != null && !services.isEmpty()) { return PojoConverter.convertToServiceDefinitionBeans(services); } return null; } public static ServiceDefinitionBean getDeployedServiceInformation (String type) throws RestAPIException { Service service = null; try { service = serviceDeploymentManager.getService(type); } catch (ADCException e) { String msg = "Unable to get deployed service information for [type]: " + type+". Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } if (service != null) { return PojoConverter.convertToServiceDefinitionBean(service); } return new ServiceDefinitionBean(); } public static List<Cartridge> getActiveDeployedServiceInformation (ConfigurationContext configurationContext) throws RestAPIException { Collection<Service> services = null; try { services = serviceDeploymentManager.getServices(); } catch (ADCException e) { String msg = "Unable to get deployed service information. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } List<Cartridge> availableMultitenantCartridges = new ArrayList<Cartridge>(); int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); //getting the services for the tenantId for(Service service : services) { String tenantRange = service.getTenantRange(); if(tenantRange.equals(Constants.TENANT_RANGE_ALL)) { //check whether any active instances found for this service in the Topology Cluster cluster = TopologyManager.getTopology().getService(service.getType()). getCluster(service.getClusterId()); boolean activeMemberFound = false; for(Member member : cluster.getMembers()) { if(member.isActive()) { activeMemberFound = true; break; } } if(activeMemberFound) { availableMultitenantCartridges.add(getAvailableCartridgeInfo(null, true, configurationContext)); } } else { //TODO have to check for the serivces which has correct tenant range } } /*if (availableMultitenantCartridges.isEmpty()) { String msg = "Cannot find any active deployed service for tenant [id] "+tenantId; log.error(msg); throw new RestAPIException(msg); }*/ return availableMultitenantCartridges; } static List<Cartridge> getSubscriptions (String cartridgeSearchString, String serviceGroup, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = new ArrayList<Cartridge>(); if (log.isDebugEnabled()) { log.debug("Getting subscribed cartridges. Search String: " + cartridgeSearchString); } try { Pattern searchPattern = getSearchStringPattern(cartridgeSearchString); Collection<CartridgeSubscription> subscriptions = cartridgeSubsciptionManager.getCartridgeSubscriptions(ApplicationManagementUtil. getTenantId(configurationContext), null); if (subscriptions != null && !subscriptions.isEmpty()) { for (CartridgeSubscription subscription : subscriptions) { if (!cartridgeMatches(subscription.getCartridgeInfo(), subscription, searchPattern)) { continue; } Cartridge cartridge = getCartridgeFromSubscription(subscription); if (cartridge == null) { continue; } Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridge.getCartridgeType(), cartridge.getCartridgeAlias()); String cartridgeStatus = "Inactive"; int activeMemberCount = 0; if (cluster != null) { Collection<Member> members = cluster.getMembers(); for (Member member : members) { if (member.isActive()) { cartridgeStatus = "Active"; activeMemberCount++; } } } cartridge.setActiveInstances(activeMemberCount); cartridge.setStatus(cartridgeStatus); // Ignoring the LB cartridges since they are not shown to the user. if(cartridge.isLoadBalancer()) continue; if(StringUtils.isNotEmpty(serviceGroup) && cartridge.getServiceGroup() != null && !cartridge.getServiceGroup().equals(serviceGroup)){ continue; } cartridges.add(cartridge); } } else { if (log.isDebugEnabled()) { log.debug("There are no subscribed cartridges"); } } } catch (Exception e) { String msg = "Error while getting subscribed cartridges. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } Collections.sort(cartridges); if (log.isDebugEnabled()) { log.debug("Returning subscribed cartridges " + cartridges.size()); } /*if(cartridges.isEmpty()) { String msg = "Cannot find any subscribed Cartridge, matching the given string: "+cartridgeSearchString; log.error(msg); throw new RestAPIException(msg); }*/ return cartridges; } static Cartridge getSubscription(String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException { Cartridge cartridge = getCartridgeFromSubscription(cartridgeSubsciptionManager.getCartridgeSubscription(ApplicationManagementUtil. getTenantId(configurationContext), cartridgeAlias)); if (cartridge == null) { String message = "Unregistered [alias]: "+cartridgeAlias+"! Please enter a valid alias."; log.error(message); throw new RestAPIException(Response.Status.NOT_FOUND, message); } Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridge.getCartridgeType(), cartridge.getCartridgeAlias()); String cartridgeStatus = "Inactive"; int activeMemberCount = 0; // cluster might not be created yet, so need to check if (cluster != null) { Collection<Member> members = cluster.getMembers(); if (members != null ) { for (Member member : members) { if(member.isActive()) { cartridgeStatus = "Active"; activeMemberCount++; } } } } cartridge.setActiveInstances(activeMemberCount); cartridge.setStatus(cartridgeStatus); return cartridge; } static int getActiveInstances(String cartridgeType, String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException { int noOfActiveInstances = 0; Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridgeType , cartridgeAlias); if(cluster == null) { String message = "No Cluster found for cartridge [type] "+cartridgeType+", [alias] "+cartridgeAlias; log.error(message); throw new RestAPIException(message); } for(Member member : cluster.getMembers()) { if(member.getStatus().toString().equals(MemberStatus.Activated)) { noOfActiveInstances ++; } } return noOfActiveInstances; } private static Cartridge getCartridgeFromSubscription(CartridgeSubscription subscription) throws RestAPIException { if (subscription == null) { return null; } try { Cartridge cartridge = new Cartridge(); cartridge.setCartridgeType(subscription.getCartridgeInfo() .getType()); cartridge.setMultiTenant(subscription.getCartridgeInfo() .getMultiTenant()); cartridge .setProvider(subscription.getCartridgeInfo().getProvider()); cartridge.setVersion(subscription.getCartridgeInfo().getVersion()); cartridge.setDescription(subscription.getCartridgeInfo() .getDescription()); cartridge.setDisplayName(subscription.getCartridgeInfo() .getDisplayName()); cartridge.setCartridgeAlias(subscription.getAlias()); cartridge.setHostName(subscription.getHostName()); cartridge.setMappedDomain(subscription.getMappedDomain()); if (subscription.getRepository() != null) { cartridge.setRepoURL(subscription.getRepository().getUrl()); } if (subscription instanceof DataCartridgeSubscription) { DataCartridgeSubscription dataCartridgeSubscription = (DataCartridgeSubscription) subscription; cartridge.setDbHost(dataCartridgeSubscription.getDBHost()); cartridge.setDbUserName(dataCartridgeSubscription .getDBUsername()); cartridge .setPassword(dataCartridgeSubscription.getDBPassword()); } if (subscription.getLbClusterId() != null && !subscription.getLbClusterId().isEmpty()) { cartridge.setLbClusterId(subscription.getLbClusterId()); } cartridge.setStatus(subscription.getSubscriptionStatus()); cartridge.setPortMappings(subscription.getCartridgeInfo() .getPortMappings()); if(subscription.getCartridgeInfo().getLbConfig() != null && subscription.getCartridgeInfo().getProperties() != null) { for(Property property: subscription.getCartridgeInfo().getProperties()) { if(property.getName().equals("load.balancer")) { cartridge.setLoadBalancer(true); } } } if(subscription.getCartridgeInfo().getServiceGroup() != null) { cartridge.setServiceGroup(subscription.getCartridgeInfo().getServiceGroup()); } return cartridge; } catch (Exception e) { String msg = "Unable to extract the Cartridge from subscription. Cause: "+e.getMessage(); log.error(msg); throw new RestAPIException(msg); } } static Pattern getSearchStringPattern(String searchString) { if (log.isDebugEnabled()) { log.debug("Creating search pattern for " + searchString); } if (searchString != null) { // Copied from org.wso2.carbon.webapp.mgt.WebappAdmin.doesWebappSatisfySearchString(WebApplication, String) String regex = searchString.toLowerCase().replace("..?", ".?").replace("..*", ".*").replaceAll("\\?", ".?") .replaceAll("\\*", ".*?"); if (log.isDebugEnabled()) { log.debug("Created regex: " + regex + " for search string " + searchString); } Pattern pattern = Pattern.compile(regex); return pattern; } return null; } static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, Pattern pattern) { if (pattern != null) { boolean matches = false; if (cartridgeInfo.getDisplayName() != null) { matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find(); } if (!matches && cartridgeInfo.getDescription() != null) { matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find(); } return matches; } return true; } static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, CartridgeSubscription cartridgeSubscription, Pattern pattern) { if (pattern != null) { boolean matches = false; if (cartridgeInfo.getDisplayName() != null) { matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find(); } if (!matches && cartridgeInfo.getDescription() != null) { matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find(); } if (!matches && cartridgeSubscription.getType() != null) { matches = pattern.matcher(cartridgeSubscription.getType().toLowerCase()).find(); } if (!matches && cartridgeSubscription.getAlias() != null) { matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find(); } return matches; } return true; } public static CartridgeSubscription getCartridgeSubscription(String alias, ConfigurationContext configurationContext) { return cartridgeSubsciptionManager.getCartridgeSubscription(ApplicationManagementUtil.getTenantId(configurationContext), alias); } static SubscriptionInfo subscribeToCartridge (CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain) throws RestAPIException { try { return subscribe(cartridgeInfoBean, configurationContext, tenantUsername, tenantDomain); } catch (Exception e) { throw new RestAPIException(e.getMessage(), e); } } private static SubscriptionInfo subscribe (CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain) throws ADCException, PolicyException, UnregisteredCartridgeException, InvalidCartridgeAliasException, DuplicateCartridgeAliasException, RepositoryRequiredException, AlreadySubscribedException, RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException, RestAPIException { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setCartridgeType(cartridgeInfoBean.getCartridgeType()); subscriptionData.setCartridgeAlias(cartridgeInfoBean.getAlias().trim()); subscriptionData.setAutoscalingPolicyName(cartridgeInfoBean.getAutoscalePolicy()); subscriptionData.setDeploymentPolicyName(cartridgeInfoBean.getDeploymentPolicy()); subscriptionData.setTenantDomain(tenantDomain); subscriptionData.setTenantId(ApplicationManagementUtil.getTenantId(configurationContext)); subscriptionData.setTenantAdminUsername(tenantUsername); subscriptionData.setRepositoryType("git"); subscriptionData.setRepositoryURL(cartridgeInfoBean.getRepoURL()); subscriptionData.setRepositoryUsername(cartridgeInfoBean.getRepoUsername()); subscriptionData.setRepositoryPassword(cartridgeInfoBean.getRepoPassword()); subscriptionData.setCommitsEnabled(cartridgeInfoBean.isCommitsEnabled()); subscriptionData.setServiceGroup(cartridgeInfoBean.getServiceGroup()); //subscriptionData.setServiceName(cartridgeInfoBean.getServiceName()); // For MT cartridges if (cartridgeInfoBean.isPersistanceRequired()) { // Add persistence related properties to PersistenceContext PersistenceContext persistenceContext = new PersistenceContext(); persistenceContext.setPersistanceRequiredProperty(IS_VOLUME_REQUIRED, String.valueOf(cartridgeInfoBean.isPersistanceRequired())); persistenceContext.setSizeProperty(VOLUME_SIZE, cartridgeInfoBean.getSize()); persistenceContext.setDeleteOnTerminationProperty(SHOULD_DELETE_VOLUME, String.valueOf(cartridgeInfoBean.isRemoveOnTermination())); subscriptionData.setPersistanceCtxt(persistenceContext); } //subscribe return cartridgeSubsciptionManager.subscribeToCartridgeWithProperties(subscriptionData); } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster getCluster (String cartridgeType, String subscriptionAlias, ConfigurationContext configurationContext) throws RestAPIException { Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridgeType , subscriptionAlias); if(cluster == null) { throw new RestAPIException("No matching cluster found for [cartridge type]: "+cartridgeType+ " [alias] "+subscriptionAlias); } else{ return PojoConverter.populateClusterPojos(cluster); } } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForTenant (ConfigurationContext configurationContext) { Set<Cluster> clusterSet = TopologyClusterInformationModel.getInstance().getClusters(ApplicationManagementUtil. getTenantId(configurationContext), null); ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for(Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters.size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForTenantAndCartridgeType (ConfigurationContext configurationContext, String cartridgeType) { Set<Cluster> clusterSet = TopologyClusterInformationModel.getInstance().getClusters(ApplicationManagementUtil. getTenantId(configurationContext), cartridgeType); List<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for(Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters.size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForCartridgeType(String cartridgeType) { Set<Cluster> clusterSet = TopologyClusterInformationModel .getInstance() .getClusters(cartridgeType); List<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for (Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters .size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } // return the cluster id for the lb. This is a temp fix. /*private static String subscribeToLb(String cartridgeType, String loadBalancedCartridgeType, String lbAlias, String defaultAutoscalingPolicy, String deploymentPolicy, ConfigurationContext configurationContext, String userName, String tenantDomain, Property[] props) throws ADCException { CartridgeSubscription cartridgeSubscription; try { if(log.isDebugEnabled()) { log.debug("Subscribing to a load balancer [cartridge] "+cartridgeType+" [alias] "+lbAlias); } SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setCartridgeType(cartridgeType); subscriptionData.setCartridgeAlias(lbAlias.trim()); subscriptionData.setAutoscalingPolicyName(defaultAutoscalingPolicy); subscriptionData.setDeploymentPolicyName(deploymentPolicy); subscriptionData.setTenantDomain(tenantDomain); subscriptionData.setTenantId(ApplicationManagementUtil.getTenantId(configurationContext)); subscriptionData.setTenantAdminUsername(userName); subscriptionData.setRepositoryType("git"); //subscriptionData.setProperties(props); subscriptionData.setPrivateRepository(false); cartridgeSubscription = cartridgeSubsciptionManager.subscribeToCartridgeWithProperties(subscriptionData); //set a payload parameter to indicate the load balanced cartridge type cartridgeSubscription.getPayloadData().add("LOAD_BALANCED_SERVICE_TYPE", loadBalancedCartridgeType); Properties lbProperties = new Properties(); lbProperties.setProperties(props); cartridgeSubsciptionManager.registerCartridgeSubscription(cartridgeSubscription, lbProperties); if(log.isDebugEnabled()) { log.debug("Successfully subscribed to a load balancer [cartridge] "+cartridgeType+" [alias] "+lbAlias); } } catch (Exception e) { String msg = "Error while subscribing to load balancer cartridge [type] "+cartridgeType+". Cause: "+e.getMessage(); log.error(msg, e); throw new ADCException(msg, e); } return cartridgeSubscription.getClusterDomain(); } */ static StratosAdminResponse unsubscribe(String alias, String tenantDomain) throws RestAPIException { try { cartridgeSubsciptionManager.unsubscribeFromCartridge(tenantDomain, alias); } catch (ADCException e) { String msg = "Failed to unsubscribe from [alias] "+alias+". Cause: "+ e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } catch (NotSubscribedException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully terminated the subscription with alias " + alias); return stratosAdminResponse; } /** * * Super tenant will deploy multitenant service. * * get domain , subdomain as well.. * @param clusterDomain * @param clusterSubdomain * */ static StratosAdminResponse deployService(String cartridgeType, String alias, String autoscalingPolicy, String deploymentPolicy, String tenantDomain, String tenantUsername, int tenantId, String clusterDomain, String clusterSubdomain, String tenantRange) throws RestAPIException { log.info("Deploying service.."); try { serviceDeploymentManager.deployService(cartridgeType, autoscalingPolicy, deploymentPolicy, tenantId, tenantRange, tenantDomain, tenantUsername); } catch (Exception e) { String msg = String.format("Failed to deploy the Service [Cartridge type] %s [alias] %s . Cause: %s", cartridgeType, alias, e.getMessage()); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed service cluster definition with type " + cartridgeType); return stratosAdminResponse; } static StratosAdminResponse undeployService(String serviceType) throws RestAPIException { try { serviceDeploymentManager.undeployService(serviceType); } catch (Exception e) { String msg = "Failed to undeploy service cluster definition of type " + serviceType+" Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully undeployed service cluster definition for service type " + serviceType); return stratosAdminResponse; } static void getGitRepositoryNotification(Payload payload) throws RestAPIException { try { RepositoryNotification repoNotification = new RepositoryNotification(); repoNotification.updateRepository(payload.getRepository().getUrl()); } catch (Exception e) { String msg = "Failed to get git repository notifications. Cause : " + e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } } static StratosAdminResponse synchronizeRepository(CartridgeSubscription cartridgeSubscription) throws RestAPIException { try { RepositoryNotification repoNotification = new RepositoryNotification(); repoNotification.updateRepository(cartridgeSubscription); } catch (Exception e) { String msg = "Failed to get git repository notifications. Cause : " + e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully sent the repository synchronization request for " + cartridgeSubscription.getAlias()); return stratosAdminResponse; } public static StratosAdminResponse addSubscriptionDomains(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, SubscriptionDomainRequest request) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) { cartridgeSubsciptionManager.addSubscriptionDomain(tenantId, subscriptionAlias, subscriptionDomain.domainName, subscriptionDomain.applicationContext); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully added domains to cartridge subscription"); return stratosAdminResponse; } public static List<SubscriptionDomainBean> getSubscriptionDomains(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); return PojoConverter.populateSubscriptionDomainPojos(cartridgeSubsciptionManager.getSubscriptionDomains(tenantId, subscriptionAlias)); } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } } public static SubscriptionDomainBean getSubscriptionDomain(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, String domain) throws RestAPIException { try { int tenantId = ApplicationManagementUtil .getTenantId(configurationContext); SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(cartridgeSubsciptionManager.getSubscriptionDomain(tenantId, subscriptionAlias, domain)); if (subscriptionDomain == null) { String message = "Could not find a subscription [domain] "+domain+ " for Cartridge [type] " +cartridgeType+ " and [alias] "+subscriptionAlias; log.error(message); throw new RestAPIException(Status.NOT_FOUND, message); } return subscriptionDomain; } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } } public static StratosAdminResponse removeSubscriptionDomain(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, String domain) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); cartridgeSubsciptionManager.removeSubscriptionDomain(tenantId, subscriptionAlias, domain); } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully removed domains from cartridge subscription"); return stratosAdminResponse; } }
source/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/services/ServiceUtils.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.rest.endpoint.services; import org.apache.axis2.AxisFault; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy; import org.apache.stratos.cloud.controller.stub.pojo.CartridgeConfig; import org.apache.stratos.cloud.controller.stub.pojo.CartridgeInfo; import org.apache.stratos.cloud.controller.stub.pojo.Property; import org.apache.stratos.autoscaler.stub.AutoScalerServiceInvalidPartitionExceptionException; import org.apache.stratos.autoscaler.stub.AutoScalerServiceInvalidPolicyExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidCartridgeDefinitionExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidCartridgeTypeExceptionException; import org.apache.stratos.cloud.controller.stub.CloudControllerServiceInvalidIaasProviderExceptionException; import org.apache.stratos.manager.client.AutoscalerServiceClient; import org.apache.stratos.manager.client.CloudControllerServiceClient; import org.apache.stratos.manager.deploy.service.Service; import org.apache.stratos.manager.deploy.service.ServiceDeploymentManager; import org.apache.stratos.manager.dto.Cartridge; import org.apache.stratos.manager.dto.SubscriptionInfo; import org.apache.stratos.manager.exception.*; import org.apache.stratos.manager.manager.CartridgeSubscriptionManager; import org.apache.stratos.manager.repository.RepositoryNotification; import org.apache.stratos.manager.subscription.CartridgeSubscription; import org.apache.stratos.manager.subscription.DataCartridgeSubscription; import org.apache.stratos.manager.subscription.PersistenceContext; import org.apache.stratos.manager.subscription.SubscriptionData; import org.apache.stratos.manager.subscription.SubscriptionDomain; import org.apache.stratos.manager.topology.model.TopologyClusterInformationModel; import org.apache.stratos.manager.utils.ApplicationManagementUtil; import org.apache.stratos.manager.utils.CartridgeConstants; import org.apache.stratos.messaging.domain.topology.Cluster; import org.apache.stratos.messaging.domain.topology.Member; import org.apache.stratos.messaging.domain.topology.MemberStatus; import org.apache.stratos.messaging.message.receiver.topology.TopologyManager; import org.apache.stratos.messaging.util.Constants; import org.apache.stratos.rest.endpoint.bean.CartridgeInfoBean; import org.apache.stratos.rest.endpoint.bean.StratosAdminResponse; import org.apache.stratos.rest.endpoint.bean.SubscriptionDomainRequest; import org.apache.stratos.rest.endpoint.bean.autoscaler.partition.Partition; import org.apache.stratos.rest.endpoint.bean.autoscaler.partition.PartitionGroup; import org.apache.stratos.rest.endpoint.bean.autoscaler.policy.autoscale.AutoscalePolicy; import org.apache.stratos.rest.endpoint.bean.cartridge.definition.CartridgeDefinitionBean; import org.apache.stratos.rest.endpoint.bean.cartridge.definition.ServiceDefinitionBean; import org.apache.stratos.rest.endpoint.bean.repositoryNotificationInfoBean.Payload; import org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean; import org.apache.stratos.rest.endpoint.bean.util.converter.PojoConverter; import org.apache.stratos.rest.endpoint.exception.RestAPIException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.rmi.RemoteException; import java.util.*; import java.util.regex.Pattern; public class ServiceUtils { public static final String IS_VOLUME_REQUIRED = "volume.required"; public static final String SHOULD_DELETE_VOLUME = "volume.delete.on.unsubscription"; public static final String VOLUME_SIZE = "volume.size.gb"; public static final String DEVICE_NAME = "volume.device.name"; private static Log log = LogFactory.getLog(ServiceUtils.class); private static CartridgeSubscriptionManager cartridgeSubsciptionManager = new CartridgeSubscriptionManager(); private static ServiceDeploymentManager serviceDeploymentManager = new ServiceDeploymentManager(); static StratosAdminResponse deployCartridge (CartridgeDefinitionBean cartridgeDefinitionBean, ConfigurationContext ctxt, String userName, String tenantDomain) throws RestAPIException { log.info("Starting to deploy a Cartridge [type] "+cartridgeDefinitionBean.type); CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient != null) { CartridgeConfig cartridgeConfig = PojoConverter.populateCartridgeConfigPojo(cartridgeDefinitionBean); if(cartridgeConfig == null) { throw new RestAPIException("Populated CartridgeConfig instance is null, cartridge deployment aborted"); } // call CC try { cloudControllerServiceClient .deployCartridgeDefinition(cartridgeConfig); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (CloudControllerServiceInvalidCartridgeDefinitionExceptionException e) { String message = e.getFaultMessage().getInvalidCartridgeDefinitionException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } catch (CloudControllerServiceInvalidIaasProviderExceptionException e) { String message = e.getFaultMessage().getInvalidIaasProviderException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } log.info("Successfully deployed Cartridge [type] "+cartridgeDefinitionBean.type); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed cartridge definition with type " + cartridgeDefinitionBean.type); return stratosAdminResponse; } @SuppressWarnings("unused") private static DeploymentPolicy[] intersection( DeploymentPolicy[] cartridgeDepPolicies, DeploymentPolicy[] lbCartridgeDepPolicies) { List<DeploymentPolicy> commonPolicies = new ArrayList<DeploymentPolicy>(); for (DeploymentPolicy policy1 : cartridgeDepPolicies) { for (DeploymentPolicy policy2 : lbCartridgeDepPolicies) { if(policy1.equals(policy2)) { commonPolicies.add(policy1); } } } return commonPolicies.toArray(new DeploymentPolicy[0]); } static StratosAdminResponse undeployCartridge(String cartridgeType) throws RestAPIException { CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient != null) { try { cloudControllerServiceClient.unDeployCartridgeDefinition(cartridgeType); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (CloudControllerServiceInvalidCartridgeTypeExceptionException e) { String msg = e.getFaultMessage().getInvalidCartridgeTypeException().getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully undeployed cartridge definition with type " + cartridgeType); return stratosAdminResponse; } public static StratosAdminResponse deployPartition(Partition partitionBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition = PojoConverter.convertToCCPartitionPojo(partitionBean); try { autoscalerServiceClient.deployPartition(partition); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPartitionExceptionException e) { String message = e.getFaultMessage().getInvalidPartitionException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed partition definition with id " + partitionBean.id); return stratosAdminResponse; } public static StratosAdminResponse deployAutoscalingPolicy(AutoscalePolicy autoscalePolicyBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy autoscalePolicy = PojoConverter. convertToCCAutoscalerPojo(autoscalePolicyBean); try { autoscalerServiceClient .deployAutoscalingPolicy(autoscalePolicy); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPolicyExceptionException e) { String message = e.getFaultMessage() .getInvalidPolicyException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed autoscaling policy definition with id " + autoscalePolicyBean.getId()); return stratosAdminResponse; } public static StratosAdminResponse deployDeploymentPolicy( org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy deploymentPolicyBean) throws RestAPIException { //log.info("***** " + cartridgeDefinitionBean.toString() + " *****"); AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { org.apache.stratos.autoscaler.deployment.policy.DeploymentPolicy deploymentPolicy = PojoConverter.convetToCCDeploymentPolicyPojo(deploymentPolicyBean); try { autoscalerServiceClient .deployDeploymentPolicy(deploymentPolicy); } catch (RemoteException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } catch (AutoScalerServiceInvalidPolicyExceptionException e) { String message = e.getFaultMessage().getInvalidPolicyException().getMessage(); log.error(message, e); throw new RestAPIException(message, e); } } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed deployment policy definition with type " + deploymentPolicyBean.id); return stratosAdminResponse; } private static CloudControllerServiceClient getCloudControllerServiceClient () throws RestAPIException { try { return CloudControllerServiceClient.getServiceClient(); } catch (AxisFault axisFault) { String errorMsg = "Error while getting CloudControllerServiceClient instance to connect to the " + "Cloud Controller. Cause: "+axisFault.getMessage(); log.error(errorMsg, axisFault); throw new RestAPIException(errorMsg, axisFault); } } public static Partition[] getAvailablePartitions () throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getAvailablePartitions(); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition[] getPartitionsOfDeploymentPolicy(String deploymentPolicyId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getPartitionsOfDeploymentPolicy(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions for deployment policy id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition[] getPartitionsOfGroup(String deploymentPolicyId, String groupId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition[] partitions = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitions = autoscalerServiceClient.getPartitionsOfGroup(deploymentPolicyId, groupId); } catch (RemoteException e) { String errorMsg = "Error while getting available partitions for deployment policy id " + deploymentPolicyId + ", group id " + groupId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojos(partitions); } public static Partition getPartition (String partitionId) throws RestAPIException { org.apache.stratos.cloud.controller.stub.deployment.partition.Partition partition = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partition = autoscalerServiceClient.getPartition(partitionId); } catch (RemoteException e) { String errorMsg = "Error while getting partition for id " + partitionId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionPojo(partition); } private static AutoscalerServiceClient getAutoscalerServiceClient () throws RestAPIException { try { return AutoscalerServiceClient.getServiceClient(); } catch (AxisFault axisFault) { String errorMsg = "Error while getting AutoscalerServiceClient instance to connect to the " + "Autoscaler. Cause: "+axisFault.getMessage(); log.error(errorMsg, axisFault); throw new RestAPIException(errorMsg, axisFault); } } public static AutoscalePolicy[] getAutoScalePolicies () throws RestAPIException { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy[] autoscalePolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { autoscalePolicies = autoscalerServiceClient.getAutoScalePolicies(); } catch (RemoteException e) { String errorMsg = "Error while getting available autoscaling policies. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateAutoscalePojos(autoscalePolicies); } public static AutoscalePolicy getAutoScalePolicy (String autoscalePolicyId) throws RestAPIException { org.apache.stratos.autoscaler.policy.model.AutoscalePolicy autoscalePolicy = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { autoscalePolicy = autoscalerServiceClient.getAutoScalePolicy(autoscalePolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting information for autoscaling policy with id " + autoscalePolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateAutoscalePojo(autoscalePolicy); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[] getDeploymentPolicies () throws RestAPIException { DeploymentPolicy [] deploymentPolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(); } catch (RemoteException e) { String errorMsg = "Error getting available deployment policies. Cause : " + e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy[] getDeploymentPolicies (String cartridgeType) throws RestAPIException { DeploymentPolicy [] deploymentPolicies = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicies = autoscalerServiceClient.getDeploymentPolicies(cartridgeType); } catch (RemoteException e) { String errorMsg = "Error while getting available deployment policies for cartridge type " + cartridgeType+". Cause: "+e.getMessage();; log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } if(deploymentPolicies.length == 0) { String errorMsg = "Cannot find any matching deployment policy for Cartridge [type] "+cartridgeType; log.error(errorMsg); throw new RestAPIException(errorMsg); } return PojoConverter.populateDeploymentPolicyPojos(deploymentPolicies); } public static org.apache.stratos.rest.endpoint.bean.autoscaler.policy.deployment.DeploymentPolicy getDeploymentPolicy(String deploymentPolicyId) throws RestAPIException { DeploymentPolicy deploymentPolicy = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { deploymentPolicy = autoscalerServiceClient.getDeploymentPolicy(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error while getting deployment policy with id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } if(deploymentPolicy == null) { String errorMsg = "Cannot find a matching deployment policy for [id] "+deploymentPolicyId; log.error(errorMsg); throw new RestAPIException(errorMsg); } return PojoConverter.populateDeploymentPolicyPojo(deploymentPolicy); } public static PartitionGroup[] getPartitionGroups (String deploymentPolicyId) throws RestAPIException{ org.apache.stratos.autoscaler.partition.PartitionGroup [] partitionGroups = null; AutoscalerServiceClient autoscalerServiceClient = getAutoscalerServiceClient(); if (autoscalerServiceClient != null) { try { partitionGroups = autoscalerServiceClient.getPartitionGroups(deploymentPolicyId); } catch (RemoteException e) { String errorMsg = "Error getting available partition groups for deployment policy id " + deploymentPolicyId+". Cause: "+e.getMessage(); log.error(errorMsg, e); throw new RestAPIException(errorMsg, e); } } return PojoConverter.populatePartitionGroupPojos(partitionGroups); } static Cartridge getAvailableCartridgeInfo(String cartridgeType, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext); for(Cartridge cartridge : cartridges) { if(cartridge.getCartridgeType().equals(cartridgeType)) { return cartridge; } } String msg = "Unavailable cartridge type: " + cartridgeType; log.error(msg); throw new RestAPIException(msg) ; } static List<Cartridge> getAvailableLbCartridges(Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = getAvailableCartridges(null, multiTenant, configurationContext); List<Cartridge> lbCartridges = new ArrayList<Cartridge>(); for (Cartridge cartridge : cartridges) { if (cartridge.isLoadBalancer()) { lbCartridges.add(cartridge); } } /*if(lbCartridges == null || lbCartridges.isEmpty()) { String msg = "Load balancer Cartridges are not available."; log.error(msg); throw new RestAPIException(msg) ; }*/ return lbCartridges; } static List<Cartridge> getAvailableCartridges(String cartridgeSearchString, Boolean multiTenant, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = new ArrayList<Cartridge>(); if (log.isDebugEnabled()) { log.debug("Getting available cartridges. Search String: " + cartridgeSearchString + ", Multi-Tenant: " + multiTenant); } boolean allowMultipleSubscription = new Boolean( System.getProperty(CartridgeConstants.FEATURE_MULTI_TENANT_MULTIPLE_SUBSCRIPTION_ENABLED)); try { Pattern searchPattern = getSearchStringPattern(cartridgeSearchString); String[] availableCartridges = CloudControllerServiceClient.getServiceClient().getRegisteredCartridges(); if (availableCartridges != null) { for (String cartridgeType : availableCartridges) { CartridgeInfo cartridgeInfo = null; try { cartridgeInfo = CloudControllerServiceClient.getServiceClient().getCartridgeInfo(cartridgeType); } catch (Exception e) { if (log.isWarnEnabled()) { log.warn("Error when calling getCartridgeInfo for " + cartridgeType + ", Error: " + e.getMessage()); } } if (cartridgeInfo == null) { // This cannot happen. But continue if (log.isDebugEnabled()) { log.debug("Cartridge Info not found: " + cartridgeType); } continue; } if (multiTenant != null && !multiTenant && cartridgeInfo.getMultiTenant()) { // Need only Single-Tenant cartridges continue; } else if (multiTenant != null && multiTenant && !cartridgeInfo.getMultiTenant()) { // Need only Multi-Tenant cartridges continue; } if (!ServiceUtils.cartridgeMatches(cartridgeInfo, searchPattern)) { continue; } Cartridge cartridge = new Cartridge(); cartridge.setCartridgeType(cartridgeType); cartridge.setProvider(cartridgeInfo.getProvider()); cartridge.setDisplayName(cartridgeInfo.getDisplayName()); cartridge.setDescription(cartridgeInfo.getDescription()); cartridge.setVersion(cartridgeInfo.getVersion()); cartridge.setMultiTenant(cartridgeInfo.getMultiTenant()); cartridge.setHostName(cartridgeInfo.getHostName()); cartridge.setDefaultAutoscalingPolicy(cartridgeInfo.getDefaultAutoscalingPolicy()); cartridge.setDefaultDeploymentPolicy(cartridgeInfo.getDefaultDeploymentPolicy()); //cartridge.setStatus(CartridgeConstants.NOT_SUBSCRIBED); cartridge.setCartridgeAlias("-"); cartridge.setPersistence(cartridgeInfo.getPersistence()); cartridge.setServiceGroup(cartridgeInfo.getServiceGroup()); if(cartridgeInfo.getLbConfig() != null && cartridgeInfo.getProperties() != null) { for(Property property: cartridgeInfo.getProperties()) { if(property.getName().equals("load.balancer")) { cartridge.setLoadBalancer(true); } } } //cartridge.setActiveInstances(0); cartridges.add(cartridge); if (cartridgeInfo.getMultiTenant() && !allowMultipleSubscription) { // If the cartridge is multi-tenant. We should not let users // createSubscription twice. if (isAlreadySubscribed(cartridgeType, ApplicationManagementUtil.getTenantId(configurationContext))) { if (log.isDebugEnabled()) { log.debug("Already subscribed to " + cartridgeType + ". This multi-tenant cartridge will not be available to createSubscription"); } //cartridge.setStatus(CartridgeConstants.SUBSCRIBED); } } } } else { if (log.isDebugEnabled()) { log.debug("There are no available cartridges"); } } } catch (Exception e) { String msg = "Error while getting available cartridges. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } Collections.sort(cartridges); if (log.isDebugEnabled()) { log.debug("Returning available cartridges " + cartridges.size()); } return cartridges; } private static boolean isAlreadySubscribed(String cartridgeType, int tenantId) { Collection<CartridgeSubscription> subscriptionList = cartridgeSubsciptionManager.isCartridgeSubscribed(tenantId, cartridgeType); if(subscriptionList == null || subscriptionList.isEmpty()){ return false; }else { return true; } } public static List<ServiceDefinitionBean> getdeployedServiceInformation () throws RestAPIException { Collection<Service> services = null; try { services = serviceDeploymentManager.getServices(); } catch (ADCException e) { String msg = "Unable to get deployed service information. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } if (services != null && !services.isEmpty()) { return PojoConverter.convertToServiceDefinitionBeans(services); } return null; } public static ServiceDefinitionBean getDeployedServiceInformation (String type) throws RestAPIException { Service service = null; try { service = serviceDeploymentManager.getService(type); } catch (ADCException e) { String msg = "Unable to get deployed service information for [type]: " + type+". Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } if (service != null) { return PojoConverter.convertToServiceDefinitionBean(service); } return new ServiceDefinitionBean(); } public static List<Cartridge> getActiveDeployedServiceInformation (ConfigurationContext configurationContext) throws RestAPIException { Collection<Service> services = null; try { services = serviceDeploymentManager.getServices(); } catch (ADCException e) { String msg = "Unable to get deployed service information. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } List<Cartridge> availableMultitenantCartridges = new ArrayList<Cartridge>(); int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); //getting the services for the tenantId for(Service service : services) { String tenantRange = service.getTenantRange(); if(tenantRange.equals(Constants.TENANT_RANGE_ALL)) { //check whether any active instances found for this service in the Topology Cluster cluster = TopologyManager.getTopology().getService(service.getType()). getCluster(service.getClusterId()); boolean activeMemberFound = false; for(Member member : cluster.getMembers()) { if(member.isActive()) { activeMemberFound = true; break; } } if(activeMemberFound) { availableMultitenantCartridges.add(getAvailableCartridgeInfo(null, true, configurationContext)); } } else { //TODO have to check for the serivces which has correct tenant range } } /*if (availableMultitenantCartridges.isEmpty()) { String msg = "Cannot find any active deployed service for tenant [id] "+tenantId; log.error(msg); throw new RestAPIException(msg); }*/ return availableMultitenantCartridges; } static List<Cartridge> getSubscriptions (String cartridgeSearchString, String serviceGroup, ConfigurationContext configurationContext) throws RestAPIException { List<Cartridge> cartridges = new ArrayList<Cartridge>(); if (log.isDebugEnabled()) { log.debug("Getting subscribed cartridges. Search String: " + cartridgeSearchString); } try { Pattern searchPattern = getSearchStringPattern(cartridgeSearchString); Collection<CartridgeSubscription> subscriptions = cartridgeSubsciptionManager.getCartridgeSubscriptions(ApplicationManagementUtil. getTenantId(configurationContext), null); if (subscriptions != null && !subscriptions.isEmpty()) { for (CartridgeSubscription subscription : subscriptions) { if (!cartridgeMatches(subscription.getCartridgeInfo(), subscription, searchPattern)) { continue; } Cartridge cartridge = getCartridgeFromSubscription(subscription); if (cartridge == null) { continue; } Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridge.getCartridgeType(), cartridge.getCartridgeAlias()); String cartridgeStatus = "Inactive"; int activeMemberCount = 0; if (cluster != null) { Collection<Member> members = cluster.getMembers(); for (Member member : members) { if (member.isActive()) { cartridgeStatus = "Active"; activeMemberCount++; } } } cartridge.setActiveInstances(activeMemberCount); cartridge.setStatus(cartridgeStatus); // Ignoring the LB cartridges since they are not shown to the user. if(cartridge.isLoadBalancer()) continue; if(StringUtils.isNotEmpty(serviceGroup) && !cartridge.getServiceGroup().equals(serviceGroup)){ continue; } cartridges.add(cartridge); } } else { if (log.isDebugEnabled()) { log.debug("There are no subscribed cartridges"); } } } catch (Exception e) { String msg = "Error while getting subscribed cartridges. Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } Collections.sort(cartridges); if (log.isDebugEnabled()) { log.debug("Returning subscribed cartridges " + cartridges.size()); } /*if(cartridges.isEmpty()) { String msg = "Cannot find any subscribed Cartridge, matching the given string: "+cartridgeSearchString; log.error(msg); throw new RestAPIException(msg); }*/ return cartridges; } static Cartridge getSubscription(String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException { Cartridge cartridge = getCartridgeFromSubscription(cartridgeSubsciptionManager.getCartridgeSubscription(ApplicationManagementUtil. getTenantId(configurationContext), cartridgeAlias)); if (cartridge == null) { String message = "Unregistered [alias]: "+cartridgeAlias+"! Please enter a valid alias."; log.error(message); throw new RestAPIException(Response.Status.NOT_FOUND, message); } Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridge.getCartridgeType(), cartridge.getCartridgeAlias()); String cartridgeStatus = "Inactive"; int activeMemberCount = 0; // cluster might not be created yet, so need to check if (cluster != null) { Collection<Member> members = cluster.getMembers(); if (members != null ) { for (Member member : members) { if(member.isActive()) { cartridgeStatus = "Active"; activeMemberCount++; } } } } cartridge.setActiveInstances(activeMemberCount); cartridge.setStatus(cartridgeStatus); return cartridge; } static int getActiveInstances(String cartridgeType, String cartridgeAlias, ConfigurationContext configurationContext) throws RestAPIException { int noOfActiveInstances = 0; Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridgeType , cartridgeAlias); if(cluster == null) { String message = "No Cluster found for cartridge [type] "+cartridgeType+", [alias] "+cartridgeAlias; log.error(message); throw new RestAPIException(message); } for(Member member : cluster.getMembers()) { if(member.getStatus().toString().equals(MemberStatus.Activated)) { noOfActiveInstances ++; } } return noOfActiveInstances; } private static Cartridge getCartridgeFromSubscription(CartridgeSubscription subscription) throws RestAPIException { if (subscription == null) { return null; } try { Cartridge cartridge = new Cartridge(); cartridge.setCartridgeType(subscription.getCartridgeInfo() .getType()); cartridge.setMultiTenant(subscription.getCartridgeInfo() .getMultiTenant()); cartridge .setProvider(subscription.getCartridgeInfo().getProvider()); cartridge.setVersion(subscription.getCartridgeInfo().getVersion()); cartridge.setDescription(subscription.getCartridgeInfo() .getDescription()); cartridge.setDisplayName(subscription.getCartridgeInfo() .getDisplayName()); cartridge.setCartridgeAlias(subscription.getAlias()); cartridge.setHostName(subscription.getHostName()); cartridge.setMappedDomain(subscription.getMappedDomain()); if (subscription.getRepository() != null) { cartridge.setRepoURL(subscription.getRepository().getUrl()); } if (subscription instanceof DataCartridgeSubscription) { DataCartridgeSubscription dataCartridgeSubscription = (DataCartridgeSubscription) subscription; cartridge.setDbHost(dataCartridgeSubscription.getDBHost()); cartridge.setDbUserName(dataCartridgeSubscription .getDBUsername()); cartridge .setPassword(dataCartridgeSubscription.getDBPassword()); } if (subscription.getLbClusterId() != null && !subscription.getLbClusterId().isEmpty()) { cartridge.setLbClusterId(subscription.getLbClusterId()); } cartridge.setStatus(subscription.getSubscriptionStatus()); cartridge.setPortMappings(subscription.getCartridgeInfo() .getPortMappings()); if(subscription.getCartridgeInfo().getLbConfig() != null && subscription.getCartridgeInfo().getProperties() != null) { for(Property property: subscription.getCartridgeInfo().getProperties()) { if(property.getName().equals("load.balancer")) { cartridge.setLoadBalancer(true); } } } if(subscription.getCartridgeInfo().getServiceGroup() != null) { cartridge.setServiceGroup(subscription.getCartridgeInfo().getServiceGroup()); } return cartridge; } catch (Exception e) { String msg = "Unable to extract the Cartridge from subscription. Cause: "+e.getMessage(); log.error(msg); throw new RestAPIException(msg); } } static Pattern getSearchStringPattern(String searchString) { if (log.isDebugEnabled()) { log.debug("Creating search pattern for " + searchString); } if (searchString != null) { // Copied from org.wso2.carbon.webapp.mgt.WebappAdmin.doesWebappSatisfySearchString(WebApplication, String) String regex = searchString.toLowerCase().replace("..?", ".?").replace("..*", ".*").replaceAll("\\?", ".?") .replaceAll("\\*", ".*?"); if (log.isDebugEnabled()) { log.debug("Created regex: " + regex + " for search string " + searchString); } Pattern pattern = Pattern.compile(regex); return pattern; } return null; } static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, Pattern pattern) { if (pattern != null) { boolean matches = false; if (cartridgeInfo.getDisplayName() != null) { matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find(); } if (!matches && cartridgeInfo.getDescription() != null) { matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find(); } return matches; } return true; } static boolean cartridgeMatches(CartridgeInfo cartridgeInfo, CartridgeSubscription cartridgeSubscription, Pattern pattern) { if (pattern != null) { boolean matches = false; if (cartridgeInfo.getDisplayName() != null) { matches = pattern.matcher(cartridgeInfo.getDisplayName().toLowerCase()).find(); } if (!matches && cartridgeInfo.getDescription() != null) { matches = pattern.matcher(cartridgeInfo.getDescription().toLowerCase()).find(); } if (!matches && cartridgeSubscription.getType() != null) { matches = pattern.matcher(cartridgeSubscription.getType().toLowerCase()).find(); } if (!matches && cartridgeSubscription.getAlias() != null) { matches = pattern.matcher(cartridgeSubscription.getAlias().toLowerCase()).find(); } return matches; } return true; } public static CartridgeSubscription getCartridgeSubscription(String alias, ConfigurationContext configurationContext) { return cartridgeSubsciptionManager.getCartridgeSubscription(ApplicationManagementUtil.getTenantId(configurationContext), alias); } static SubscriptionInfo subscribeToCartridge (CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain) throws RestAPIException { try { return subscribe(cartridgeInfoBean, configurationContext, tenantUsername, tenantDomain); } catch (Exception e) { throw new RestAPIException(e.getMessage(), e); } } private static SubscriptionInfo subscribe (CartridgeInfoBean cartridgeInfoBean, ConfigurationContext configurationContext, String tenantUsername, String tenantDomain) throws ADCException, PolicyException, UnregisteredCartridgeException, InvalidCartridgeAliasException, DuplicateCartridgeAliasException, RepositoryRequiredException, AlreadySubscribedException, RepositoryCredentialsRequiredException, InvalidRepositoryException, RepositoryTransportException, RestAPIException { SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setCartridgeType(cartridgeInfoBean.getCartridgeType()); subscriptionData.setCartridgeAlias(cartridgeInfoBean.getAlias().trim()); subscriptionData.setAutoscalingPolicyName(cartridgeInfoBean.getAutoscalePolicy()); subscriptionData.setDeploymentPolicyName(cartridgeInfoBean.getDeploymentPolicy()); subscriptionData.setTenantDomain(tenantDomain); subscriptionData.setTenantId(ApplicationManagementUtil.getTenantId(configurationContext)); subscriptionData.setTenantAdminUsername(tenantUsername); subscriptionData.setRepositoryType("git"); subscriptionData.setRepositoryURL(cartridgeInfoBean.getRepoURL()); subscriptionData.setRepositoryUsername(cartridgeInfoBean.getRepoUsername()); subscriptionData.setRepositoryPassword(cartridgeInfoBean.getRepoPassword()); subscriptionData.setCommitsEnabled(cartridgeInfoBean.isCommitsEnabled()); subscriptionData.setServiceGroup(cartridgeInfoBean.getServiceGroup()); //subscriptionData.setServiceName(cartridgeInfoBean.getServiceName()); // For MT cartridges if (cartridgeInfoBean.isPersistanceRequired()) { // Add persistence related properties to PersistenceContext PersistenceContext persistenceContext = new PersistenceContext(); persistenceContext.setPersistanceRequiredProperty(IS_VOLUME_REQUIRED, String.valueOf(cartridgeInfoBean.isPersistanceRequired())); persistenceContext.setSizeProperty(VOLUME_SIZE, cartridgeInfoBean.getSize()); persistenceContext.setDeleteOnTerminationProperty(SHOULD_DELETE_VOLUME, String.valueOf(cartridgeInfoBean.isRemoveOnTermination())); subscriptionData.setPersistanceCtxt(persistenceContext); } //subscribe return cartridgeSubsciptionManager.subscribeToCartridgeWithProperties(subscriptionData); } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster getCluster (String cartridgeType, String subscriptionAlias, ConfigurationContext configurationContext) throws RestAPIException { Cluster cluster = TopologyClusterInformationModel.getInstance().getCluster(ApplicationManagementUtil.getTenantId(configurationContext) ,cartridgeType , subscriptionAlias); if(cluster == null) { throw new RestAPIException("No matching cluster found for [cartridge type]: "+cartridgeType+ " [alias] "+subscriptionAlias); } else{ return PojoConverter.populateClusterPojos(cluster); } } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForTenant (ConfigurationContext configurationContext) { Set<Cluster> clusterSet = TopologyClusterInformationModel.getInstance().getClusters(ApplicationManagementUtil. getTenantId(configurationContext), null); ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for(Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters.size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForTenantAndCartridgeType (ConfigurationContext configurationContext, String cartridgeType) { Set<Cluster> clusterSet = TopologyClusterInformationModel.getInstance().getClusters(ApplicationManagementUtil. getTenantId(configurationContext), cartridgeType); List<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for(Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters.size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } public static org.apache.stratos.rest.endpoint.bean.topology.Cluster[] getClustersForCartridgeType(String cartridgeType) { Set<Cluster> clusterSet = TopologyClusterInformationModel .getInstance() .getClusters(cartridgeType); List<org.apache.stratos.rest.endpoint.bean.topology.Cluster> clusters = new ArrayList<org.apache.stratos.rest.endpoint.bean.topology.Cluster>(); for (Cluster cluster : clusterSet) { clusters.add(PojoConverter.populateClusterPojos(cluster)); } org.apache.stratos.rest.endpoint.bean.topology.Cluster[] arrCluster = new org.apache.stratos.rest.endpoint.bean.topology.Cluster[clusters .size()]; arrCluster = clusters.toArray(arrCluster); return arrCluster; } // return the cluster id for the lb. This is a temp fix. /*private static String subscribeToLb(String cartridgeType, String loadBalancedCartridgeType, String lbAlias, String defaultAutoscalingPolicy, String deploymentPolicy, ConfigurationContext configurationContext, String userName, String tenantDomain, Property[] props) throws ADCException { CartridgeSubscription cartridgeSubscription; try { if(log.isDebugEnabled()) { log.debug("Subscribing to a load balancer [cartridge] "+cartridgeType+" [alias] "+lbAlias); } SubscriptionData subscriptionData = new SubscriptionData(); subscriptionData.setCartridgeType(cartridgeType); subscriptionData.setCartridgeAlias(lbAlias.trim()); subscriptionData.setAutoscalingPolicyName(defaultAutoscalingPolicy); subscriptionData.setDeploymentPolicyName(deploymentPolicy); subscriptionData.setTenantDomain(tenantDomain); subscriptionData.setTenantId(ApplicationManagementUtil.getTenantId(configurationContext)); subscriptionData.setTenantAdminUsername(userName); subscriptionData.setRepositoryType("git"); //subscriptionData.setProperties(props); subscriptionData.setPrivateRepository(false); cartridgeSubscription = cartridgeSubsciptionManager.subscribeToCartridgeWithProperties(subscriptionData); //set a payload parameter to indicate the load balanced cartridge type cartridgeSubscription.getPayloadData().add("LOAD_BALANCED_SERVICE_TYPE", loadBalancedCartridgeType); Properties lbProperties = new Properties(); lbProperties.setProperties(props); cartridgeSubsciptionManager.registerCartridgeSubscription(cartridgeSubscription, lbProperties); if(log.isDebugEnabled()) { log.debug("Successfully subscribed to a load balancer [cartridge] "+cartridgeType+" [alias] "+lbAlias); } } catch (Exception e) { String msg = "Error while subscribing to load balancer cartridge [type] "+cartridgeType+". Cause: "+e.getMessage(); log.error(msg, e); throw new ADCException(msg, e); } return cartridgeSubscription.getClusterDomain(); } */ static StratosAdminResponse unsubscribe(String alias, String tenantDomain) throws RestAPIException { try { cartridgeSubsciptionManager.unsubscribeFromCartridge(tenantDomain, alias); } catch (ADCException e) { String msg = "Failed to unsubscribe from [alias] "+alias+". Cause: "+ e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } catch (NotSubscribedException e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully terminated the subscription with alias " + alias); return stratosAdminResponse; } /** * * Super tenant will deploy multitenant service. * * get domain , subdomain as well.. * @param clusterDomain * @param clusterSubdomain * */ static StratosAdminResponse deployService(String cartridgeType, String alias, String autoscalingPolicy, String deploymentPolicy, String tenantDomain, String tenantUsername, int tenantId, String clusterDomain, String clusterSubdomain, String tenantRange) throws RestAPIException { log.info("Deploying service.."); try { serviceDeploymentManager.deployService(cartridgeType, autoscalingPolicy, deploymentPolicy, tenantId, tenantRange, tenantDomain, tenantUsername); } catch (Exception e) { String msg = String.format("Failed to deploy the Service [Cartridge type] %s [alias] %s . Cause: %s", cartridgeType, alias, e.getMessage()); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully deployed service cluster definition with type " + cartridgeType); return stratosAdminResponse; } static StratosAdminResponse undeployService(String serviceType) throws RestAPIException { try { serviceDeploymentManager.undeployService(serviceType); } catch (Exception e) { String msg = "Failed to undeploy service cluster definition of type " + serviceType+" Cause: "+e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully undeployed service cluster definition for service type " + serviceType); return stratosAdminResponse; } static void getGitRepositoryNotification(Payload payload) throws RestAPIException { try { RepositoryNotification repoNotification = new RepositoryNotification(); repoNotification.updateRepository(payload.getRepository().getUrl()); } catch (Exception e) { String msg = "Failed to get git repository notifications. Cause : " + e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } } static StratosAdminResponse synchronizeRepository(CartridgeSubscription cartridgeSubscription) throws RestAPIException { try { RepositoryNotification repoNotification = new RepositoryNotification(); repoNotification.updateRepository(cartridgeSubscription); } catch (Exception e) { String msg = "Failed to get git repository notifications. Cause : " + e.getMessage(); log.error(msg, e); throw new RestAPIException(msg, e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully sent the repository synchronization request for " + cartridgeSubscription.getAlias()); return stratosAdminResponse; } public static StratosAdminResponse addSubscriptionDomains(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, SubscriptionDomainRequest request) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); for (org.apache.stratos.rest.endpoint.bean.subscription.domain.SubscriptionDomainBean subscriptionDomain : request.domains) { cartridgeSubsciptionManager.addSubscriptionDomain(tenantId, subscriptionAlias, subscriptionDomain.domainName, subscriptionDomain.applicationContext); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully added domains to cartridge subscription"); return stratosAdminResponse; } public static List<SubscriptionDomainBean> getSubscriptionDomains(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); return PojoConverter.populateSubscriptionDomainPojos(cartridgeSubsciptionManager.getSubscriptionDomains(tenantId, subscriptionAlias)); } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } } public static SubscriptionDomainBean getSubscriptionDomain(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, String domain) throws RestAPIException { try { int tenantId = ApplicationManagementUtil .getTenantId(configurationContext); SubscriptionDomainBean subscriptionDomain = PojoConverter.populateSubscriptionDomainPojo(cartridgeSubsciptionManager.getSubscriptionDomain(tenantId, subscriptionAlias, domain)); if (subscriptionDomain == null) { String message = "Could not find a subscription [domain] "+domain+ " for Cartridge [type] " +cartridgeType+ " and [alias] "+subscriptionAlias; log.error(message); throw new RestAPIException(Status.NOT_FOUND, message); } return subscriptionDomain; } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } } public static StratosAdminResponse removeSubscriptionDomain(ConfigurationContext configurationContext, String cartridgeType, String subscriptionAlias, String domain) throws RestAPIException { try { int tenantId = ApplicationManagementUtil.getTenantId(configurationContext); cartridgeSubsciptionManager.removeSubscriptionDomain(tenantId, subscriptionAlias, domain); } catch (Exception e) { log.error(e.getMessage(), e); throw new RestAPIException(e.getMessage(), e); } StratosAdminResponse stratosAdminResponse = new StratosAdminResponse(); stratosAdminResponse.setMessage("Successfully removed domains from cartridge subscription"); return stratosAdminResponse; } }
Fixing NPE in ServiceUtils
source/components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/services/ServiceUtils.java
Fixing NPE in ServiceUtils
Java
apache-2.0
491c7ce82310619600c6d00ff734878d60a0e76c
0
dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller,dalmirdasilva/dom-distiller
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* * Parts of this file are adapted from Readability. * * Readability is Copyright (c) 2010 Src90 Inc * and licenced under the Apache License, Version 2.0. */ package com.dom_distiller.client; import com.dom_distiller.proto.DomDistillerProtos; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.user.client.Window; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This class finds the next and previous page links for the distilled document. The functionality * for next page links is migrated from readability.getArticleTitle() in chromium codebase's * third_party/readability/js/readability.js, and then expanded for previous page links; boilerpipe * doesn't have such capability. * First, it determines the base URL of the document. Then, for each anchor in the document, its * href and text are compared to the base URL and examined for next- or previous-paging-related * information. If it passes, its score is then determined by applying various heuristics on its * href, text, class name and ID, Lastly, the page link with the highest score of at least 50 is * considered to have enough confidence as the next or previous page link. */ public class PagingLinksFinder { // Match for next page: next, continue, >, >>, » but not >|, »| as those usually mean last. private static final RegExp REG_NEXT_LINK = RegExp.compile("(next|weiter|continue|>([^\\|]|$)|»([^\\|]|$))", "i"); private static final RegExp REG_PREV_LINK = RegExp.compile("(prev|early|old|new|<|«)", "i"); private static final RegExp REG_POSITIVE = RegExp.compile( "article|body|content|entry|hentry|main|page|pagination|post|text|blog|story", "i"); private static final RegExp REG_NEGATIVE = RegExp.compile( "combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta" + "|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags" + "|tool|widget", "i"); private static final RegExp REG_EXTRANEOUS = RegExp.compile( "print|archive|comment|discuss|e[\\-]?mail|share|reply|all|login|sign|single", "i"); private static final RegExp REG_PAGINATION = RegExp.compile("pag(e|ing|inat)", "i"); private static final RegExp REG_LINK_PAGINATION = RegExp.compile("p(a|g|ag)?(e|ing|ination)?(=|\\/)[0-9]{1,2}", "i"); private static final RegExp REG_FIRST_LAST = RegExp.compile("(first|last)", "i"); private static final RegExp REG_IS_HTTP_HTTPS = RegExp.compile("^https?://", "i"); // Examples that match PAGE_NUMBER_REGEX are: "_p3", "-pg3", "p3", "_1", "-12-2". // Examples that don't match PAGE_NUMBER_REGEX are: "_p3 ", "p", "p123". private static final RegExp REG_PAGE_NUMBER = RegExp.compile("((_|-)?p[a-z]*|(_|-))[0-9]{1,2}$", "gi"); private static final RegExp REG_HREF_CLEANER = RegExp.compile("/?(#.*)?$"); public static DomDistillerProtos.PaginationInfo getPaginationInfo(String original_domain) { DomDistillerProtos.PaginationInfo info = DomDistillerProtos.PaginationInfo.create(); String next = findNext(Document.get().getDocumentElement(), original_domain); if (next != null) { info.setNextPage(next); } return info; } /** * @param original_domain The original domain of the page being processed if it's a file://. * @return The next page link for the document. */ public static String findNext(Element root, String original_domain) { return findPagingLink(root, original_domain, PageLink.NEXT); } /** * @param original_domain The original domain of the page being processed if it's a file://. * @return The previous page link for the document. */ public static String findPrevious(Element root, String original_domain) { return findPagingLink(root, original_domain, PageLink.PREV); } private static String findPagingLink(Element root, String original_domain, PageLink pageLink) { // findPagingLink() is static, so clear mLinkDebugInfo before processing the links. if (LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) { mLinkDebugInfo.clear(); } String baseUrl = findBaseUrl(original_domain); // Remove trailing '/' from window location href, because it'll be used to compare with // other href's whose trailing '/' are also removed. String wndLocationHref = StringUtil.findAndReplace(Window.Location.getHref(), "\\/$", ""); NodeList<Element> allLinks = root.getElementsByTagName("A"); Map<String, PagingLinkObj> possiblePages = new HashMap<String, PagingLinkObj>(); // Loop through all links, looking for hints that they may be next- or previous- page links. // Things like having "page" in their textContent, className or id, or being a child of a // node with a page-y className or id. // Also possible: levenshtein distance? longest common subsequence? // After we do that, assign each page a score. for (int i = 0; i < allLinks.getLength(); i++) { AnchorElement link = AnchorElement.as(allLinks.getItem(i)); int width = link.getOffsetWidth(); int height = link.getOffsetHeight(); if (width == 0 || height == 0) { appendDbgStrForLink(link, "ignored: sz=" + width + "x" + height); continue; } if (!DomUtil.isVisible(link)) { appendDbgStrForLink(link, "ignored: invisible"); continue; } // Remove url anchor and then trailing '/' from link's href. // Note that AnchorElement.getHref() returns the absolute URI, so there's no need to // worry about relative links. String linkHref = REG_HREF_CLEANER.replace(link.getHref(), ""); // Ignore page link that is empty, not http/https, or same as current window location. // If the page link is same as the base URL: // - next page link: ignore it, since we would already have seen it. // - previous page link: don't ignore it, since some sites will simply have the same // base URL for the first page. if (linkHref.isEmpty() || !REG_IS_HTTP_HTTPS.test(linkHref) || linkHref.equalsIgnoreCase(wndLocationHref) || (pageLink == PageLink.NEXT && linkHref.equalsIgnoreCase(baseUrl))) { appendDbgStrForLink( link, "ignored: empty or same as current or base url " + baseUrl); continue; } // If it's on a different domain, skip it. String[] urlSlashes = StringUtil.split(linkHref, "\\/+"); if (urlSlashes.length < 3 || // Expect at least the protocol, domain, and path. !getLocationHost(original_domain).equalsIgnoreCase(urlSlashes[1])) { appendDbgStrForLink(link, "ignored: different domain"); continue; } // Use javascript innerText (instead of javascript textContent) to only get visible // text. String linkText = DomUtil.getInnerText(link); // If the linkText looks like it's not the next or previous page, skip it. if (REG_EXTRANEOUS.test(linkText) || linkText.length() > 25) { appendDbgStrForLink(link, "ignored: one of extra"); continue; } // For next page link, if the initial part of the URL is identical to the base URL, but // the rest of it doesn't contain any digits, it's certainly not a next page link. // However, this doesn't apply to previous page link, because most sites will just have // the base URL for the first page. // TODO(kuan): baseUrl (returned by findBaseUrl()) is NOT the prefix of the current // window location, even though it appears to be so the way it's used here. // TODO(kuan): do we need to apply this heuristic to previous page links if current page // number is not 2? if (pageLink == PageLink.NEXT) { String linkHrefRemaining = StringUtil.findAndReplace(linkHref, baseUrl, ""); if (!StringUtil.match(linkHrefRemaining, "\\d")) { appendDbgStrForLink(link, "ignored: no number beyond base url " + baseUrl); continue; } } PagingLinkObj linkObj = null; if (!possiblePages.containsKey(linkHref)) { // Have not encountered this href. linkObj = new PagingLinkObj(i, 0, linkText, linkHref); possiblePages.put(linkHref, linkObj); } else { // Have already encountered this href, append its text to existing entry's. linkObj = possiblePages.get(linkHref); linkObj.mLinkText += " | " + linkText; } // If the base URL isn't part of this URL, penalize this link. It could still be the // link, but the odds are lower. // Example: http://www.actionscript.org/resources/articles/745/1/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page1.html. // TODO(kuan): again, baseUrl (returned by findBaseUrl()) is NOT the prefix of the // current window location, even though it appears to be so the way it's used here. if (linkHref.indexOf(baseUrl) != 0) { linkObj.mScore -= 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": not part of base url " + baseUrl); } // Concatenate the link text with class name and id, and determine the score based on // existence of various paging-related words. String linkData = linkText + " " + link.getClassName() + " " + link.getId(); appendDbgStrForLink(link, "txt+class+id=" + linkData); if (pageLink == PageLink.NEXT ? REG_NEXT_LINK.test(linkData) : REG_PREV_LINK.test(linkData)) { linkObj.mScore += 50; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has " + (pageLink == PageLink.NEXT ? "next" : "prev" + " regex")); } if (REG_PAGINATION.test(linkData)) { linkObj.mScore += 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has pag* word"); } if (REG_FIRST_LAST.test(linkData)) { // -65 is enough to negate any bonuses gotten from a > or » in the text. // If we already matched on "next", last is probably fine. // If we didn't, then it's bad. Penalize. // Same for "prev". if ((pageLink == PageLink.NEXT && !REG_NEXT_LINK.test(linkObj.mLinkText)) || (pageLink == PageLink.PREV && !REG_PREV_LINK.test(linkObj.mLinkText))) { linkObj.mScore -= 65; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has first|last but no " + (pageLink == PageLink.NEXT ? "next" : "prev") + " regex"); } } if (REG_NEGATIVE.test(linkData) || REG_EXTRANEOUS.test(linkData)) { linkObj.mScore -= 50; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has neg or extra regex"); } if (pageLink == PageLink.NEXT ? REG_PREV_LINK.test(linkData) : REG_NEXT_LINK.test(linkData)) { linkObj.mScore -= 200; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has opp of " + (pageLink == PageLink.NEXT ? "next" : "prev") + " regex"); } // Check if a parent element contains page or paging or paginate. boolean positiveMatch = false, negativeMatch = false; Element parent = link.getParentElement(); while (parent != null && (positiveMatch == false || negativeMatch == false)) { String parentClassAndId = parent.getClassName() + " " + parent.getId(); if (!positiveMatch && REG_PAGINATION.test(parentClassAndId)) { linkObj.mScore += 25; positiveMatch = true; appendDbgStrForLink(link,"score=" + linkObj.mScore + ": posParent - " + parentClassAndId); } // TODO(kuan): to get 1st page for prev page link, this can't be applied; however, // the non-application might be the cause of recursive prev page being returned, // i.e. for page 1, it may incorrectly return page 3 for prev page link. if (!negativeMatch && REG_NEGATIVE.test(parentClassAndId)) { // If this is just something like "footer", give it a negative. // If it's something like "body-and-footer", leave it be. if (!REG_POSITIVE.test(parentClassAndId)) { linkObj.mScore -= 25; negativeMatch = true; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": negParent - " + parentClassAndId); } } parent = parent.getParentElement(); } // If the URL looks like it has paging in it, add to the score. // Things like /page/2/, /pagenum/2, ?p=3, ?page=11, ?pagination=34. if (REG_LINK_PAGINATION.test(linkHref) || REG_PAGINATION.test(linkHref)) { linkObj.mScore += 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has paging info"); } // If the URL contains negative values, give a slight decrease. if (REG_EXTRANEOUS.test(linkHref)) { linkObj.mScore -= 15; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has extra regex"); } // If the link text can be parsed as a number, give it a minor bonus, with a slight bias // towards lower numbered pages. This is so that pages that might not have 'next' in // their text can still get scored, and sorted properly by score. // TODO(kuan): it might be wrong to assume that it knows about other pages in the // document and that it starts on the first page. int linkTextAsNumber = JavaScript.parseInt(linkText, 10); if (linkTextAsNumber > 0) { // Punish 1 since we're either already there, or it's probably before what we // want anyway. if (linkTextAsNumber == 1) { linkObj.mScore -= 10; } else { linkObj.mScore += Math.max(0, 10 - linkTextAsNumber); } appendDbgStrForLink(link, "score=" + linkObj.mScore + ": linktxt is a num"); } } // for all links // Loop through all of the possible pages from above and find the top candidate for the next // page URL. Require at least a score of 50, which is a relatively high confidence that // this page is the next link. PagingLinkObj topPage = null; if (!possiblePages.isEmpty()) { for (PagingLinkObj pageObj : possiblePages.values()) { if (pageObj.mScore >= 50 && (topPage == null || topPage.mScore < pageObj.mScore)) { topPage = pageObj; } } } String pagingHref = null; if (topPage != null) { pagingHref = StringUtil.findAndReplace(topPage.mLinkHref, "\\/$", ""); appendDbgStrForLink(allLinks.getItem(topPage.mLinkIndex), "found: score=" + topPage.mScore + ", txt=[" + topPage.mLinkText + "], " + pagingHref); } if (LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) { logDbgInfoToConsole(pageLink, pagingHref, allLinks); } return pagingHref; } private static String getLocationHost(String original_domain) { return original_domain.isEmpty() ? Window.Location.getHost() : original_domain; } private static String findBaseUrl(String original_domain) { // This extracts relevant parts from the window location's path based on various heuristics // to determine the path of the base URL of the document. This path is then appended to the // window location protocol and host to form the base URL of the document. This base URL is // then used as reference for comparison against an anchor's href to to determine if the // anchor is a next or previous paging link. // First, from the window's location's path, extract the segments delimited by '/'. Then, // because the later segments probably contain less relevant information for the base URL, // reverse the segments for easier processing. // Note: '?' is a special character in RegEx, so enclose it within [] to specify the actual // character. String noUrlParams = Window.Location.getPath(); String[] urlSlashes = StringUtil.split(noUrlParams, "/"); Collections.reverse(Arrays.asList(urlSlashes)); // Now, process each segment by extracting relevant information based on various heuristics. List<String> cleanedSegments = new ArrayList<String>(); for (int i = 0; i < urlSlashes.length; i++) { String segment = urlSlashes[i]; // Split off and save anything that looks like a file type. if (segment.indexOf(".") != -1) { // Because '.' is a special character in RegEx, enclose it within [] to specify the // actual character. String possibleType = StringUtil.split(segment, "[.]")[1]; // If the type isn't alpha-only, it's probably not actually a file extension. if (!StringUtil.match(possibleType, "[^a-zA-Z]")) { segment = StringUtil.split(segment, "[.]")[0]; } } // EW-CMS specific segment replacement. Ugly. // Example: http://www.ew.com/ew/article/0,,20313460_20369436,00.html. segment = StringUtil.findAndReplace(segment, ",00", ""); // If the first or second segment has anything looking like a page number, remove it. if (i < 2) { segment = REG_PAGE_NUMBER.replace(segment, ""); } // Ignore an empty segment. if (segment.isEmpty()) continue; // If this is purely a number in the first or second segment, it's probably a page // number, ignore it. if (i < 2 && StringUtil.match(segment, "^\\d{1,2}$")) continue; // If this is the first segment and it's just "index", ignore it. if (i == 0 && segment.equalsIgnoreCase("index")) continue; // If the first or second segment is shorter than 3 characters, and the first // segment was purely alphas, ignore it. if (i < 2 && segment.length() < 3 && !StringUtil.match(urlSlashes[0], "[a-z]")) { continue; } // If we got here, append the segment to cleanedSegments. cleanedSegments.add(segment); } // for all urlSlashes return Window.Location.getProtocol() + "//" + getLocationHost(original_domain) + "/" + reverseJoin(cleanedSegments, "/"); } private static String reverseJoin(List<String> array, String delim) { // As per http://stackoverflow.com/questions/5748044/gwt-string-concatenation-operator-vs-stringbuffer, // + operator is faster for javascript than StringBuffer/StringBuilder. String joined = ""; for (int i = array.size() - 1; i >= 0; i--) { joined += array.get(i); if (i > 0) joined += delim; } return joined; } private static void appendDbgStrForLink(Element link, String message) { if (!LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) return; // |message| is concatenated with the existing debug string for |link| (delimited by ";") in // mLinkDebugInfo. String dbgStr = ""; if (mLinkDebugInfo.containsKey(link)) dbgStr = mLinkDebugInfo.get(link); if (!dbgStr.isEmpty()) dbgStr += "; "; dbgStr += message; mLinkDebugInfo.put(link, dbgStr); } private static void logDbgInfoToConsole(PageLink pageLink, String pagingHref, NodeList<Element> allLinks) { // This logs the following to the console: // - number of links processed // - the next or previous page link found // - for each link: its href, text, concatenated debug string. // Location of logging output is different when running in different modes: // - "ant test.dev": test output file. // - chrome browser distiller viewer: chrome logfile. // (TODO)kuan): investigate how to get logging when running "ant test.prod" - currently, // nothing appears. In the meantime, throwing an exception with a log message at suspicious // codepoints can produce a call stack and help debugging, albeit tediously. LogUtil.logToConsole("numLinks=" + allLinks.getLength() + ", found " + (pageLink == PageLink.NEXT ? "next: " : "prev: ") + (pagingHref != null ? pagingHref : "null")); for (int i = 0; i < allLinks.getLength(); i++) { AnchorElement link = AnchorElement.as(allLinks.getItem(i)); // Use javascript innerText (instead of javascript textContent) to get only visible // text. String text = DomUtil.getInnerText(link); // Trim unnecessary whitespaces from text. String[] words = StringUtil.split(text, "\\s+"); text = ""; for (int w = 0; w < words.length; w++) { text += words[w]; if (w < words.length - 1) text += " "; } LogUtil.logToConsole(i + ")" + link.getHref() + ", txt=[" + text + "], dbg=[" + mLinkDebugInfo.get(link) + "]"); } } private static class PagingLinkObj { private int mLinkIndex = -1; private int mScore = 0; private String mLinkText; private final String mLinkHref; PagingLinkObj(int linkIndex, int score, String linkText, String linkHref) { mLinkIndex = linkIndex; mScore = score; mLinkText = linkText; mLinkHref = linkHref; } } private enum PageLink { NEXT, PREV, } private static final Map<Element, String> mLinkDebugInfo = new HashMap<Element, String>(); }
src/com/dom_distiller/client/PagingLinksFinder.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /* * Parts of this file are adapted from Readability. * * Readability is Copyright (c) 2010 Src90 Inc * and licenced under the Apache License, Version 2.0. */ package com.dom_distiller.client; import com.dom_distiller.proto.DomDistillerProtos; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; import com.google.gwt.user.client.Window; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This class finds the next and previous page links for the distilled document. The functionality * for next page links is migrated from readability.getArticleTitle() in chromium codebase's * third_party/readability/js/readability.js, and then expanded for previous page links; boilerpipe * doesn't have such capability. * First, it determines the base URL of the document. Then, for each anchor in the document, its * href and text are compared to the base URL and examined for next- or previous-paging-related * information. If it passes, its score is then determined by applying various heuristics on its * href, text, class name and ID, Lastly, the page link with the highest score of at least 50 is * considered to have enough confidence as the next or previous page link. */ public class PagingLinksFinder { // Match for next page: next, continue, >, >>, » but not >|, »| as those usually mean last. private static final String NEXT_LINK_REGEX = "(next|weiter|continue|>([^\\|]|$)|»([^\\|]|$))"; private static final String PREV_LINK_REGEX = "(prev|early|old|new|<|«)"; private static final String POSITIVE_REGEX = "article|body|content|entry|hentry|main|page|pagination|post|text|blog|story"; private static final String NEGATIVE_REGEX = "combx|comment|com-|contact|foot|footer|footnote|masthead|media|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget"; private static final String EXTRANEOUS_REGEX = "print|archive|comment|discuss|e[\\-]?mail|share|reply|all|login|sign|single"; // Examples that match PAGE_NUMBER_REGEX are: "_p3", "-pg3", "p3", "_1", "-12-2". // Examples that don't match PAGE_NUMBER_REGEX are: "_p3 ", "p", "p123". private static final String PAGE_NUMBER_REGEX = "((_|-)?p[a-z]*|(_|-))[0-9]{1,2}$"; public static DomDistillerProtos.PaginationInfo getPaginationInfo(String original_domain) { DomDistillerProtos.PaginationInfo info = DomDistillerProtos.PaginationInfo.create(); String next = findNext(Document.get().getDocumentElement(), original_domain); if (next != null) { info.setNextPage(next); } return info; } /** * @param original_domain The original domain of the page being processed if it's a file://. * @return The next page link for the document. */ public static String findNext(Element root, String original_domain) { return findPagingLink(root, original_domain, PageLink.NEXT); } /** * @param original_domain The original domain of the page being processed if it's a file://. * @return The previous page link for the document. */ public static String findPrevious(Element root, String original_domain) { return findPagingLink(root, original_domain, PageLink.PREV); } private static String findPagingLink(Element root, String original_domain, PageLink pageLink) { // findPagingLink() is static, so clear mLinkDebugInfo before processing the links. if (LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) { mLinkDebugInfo.clear(); } String baseUrl = findBaseUrl(original_domain); // Remove trailing '/' from window location href, because it'll be used to compare with // other href's whose trailing '/' are also removed. String wndLocationHref = StringUtil.findAndReplace(Window.Location.getHref(), "\\/$", ""); NodeList<Element> allLinks = root.getElementsByTagName("A"); Map<String, PagingLinkObj> possiblePages = new HashMap<String, PagingLinkObj>(); // Loop through all links, looking for hints that they may be next- or previous- page links. // Things like having "page" in their textContent, className or id, or being a child of a // node with a page-y className or id. // Also possible: levenshtein distance? longest common subsequence? // After we do that, assign each page a score. for (int i = 0; i < allLinks.getLength(); i++) { AnchorElement link = AnchorElement.as(allLinks.getItem(i)); int width = link.getOffsetWidth(); int height = link.getOffsetHeight(); if (width == 0 || height == 0) { appendDbgStrForLink(link, "ignored: sz=" + width + "x" + height); continue; } if (!DomUtil.isVisible(link)) { appendDbgStrForLink(link, "ignored: invisible"); continue; } // Remove url anchor and then trailing '/' from link's href. // Note that AnchorElement.getHref() returns the absolute URI, so there's no need to // worry about relative links. String linkHref = StringUtil.findAndReplace( StringUtil.findAndReplace(link.getHref(), "#.*$", ""), "\\/$", ""); // Ignore page link that is empty, not http/https, or same as current window location. // If the page link is same as the base URL: // - next page link: ignore it, since we would already have seen it. // - previous page link: don't ignore it, since some sites will simply have the same // base URL for the first page. if (linkHref.isEmpty() || !StringUtil.match(linkHref, "^https?://") || linkHref.equalsIgnoreCase(wndLocationHref) || (pageLink == PageLink.NEXT && linkHref.equalsIgnoreCase(baseUrl))) { appendDbgStrForLink(link, "ignored: empty or same as current or base url" + baseUrl); continue; } // If it's on a different domain, skip it. String[] urlSlashes = StringUtil.split(linkHref, "\\/+"); if (urlSlashes.length < 3 || // Expect at least the protocol, domain, and path. !getLocationHost(original_domain).equalsIgnoreCase(urlSlashes[1])) { appendDbgStrForLink(link, "ignored: different domain"); continue; } // Use javascript innerText (instead of javascript textContent) to only get visible // text. String linkText = DomUtil.getInnerText(link); // If the linkText looks like it's not the next or previous page, skip it. if (StringUtil.match(linkText, EXTRANEOUS_REGEX) || linkText.length() > 25) { appendDbgStrForLink(link, "ignored: one of extra"); continue; } // For next page link, if the initial part of the URL is identical to the base URL, but // the rest of it doesn't contain any digits, it's certainly not a next page link. // However, this doesn't apply to previous page link, because most sites will just have // the base URL for the first page. // TODO(kuan): baseUrl (returned by findBaseUrl()) is NOT the prefix of the current // window location, even though it appears to be so the way it's used here. // TODO(kuan): do we need to apply this heuristic to previous page links if current page // number is not 2? if (pageLink == PageLink.NEXT) { String linkHrefRemaining = StringUtil.findAndReplace(linkHref, baseUrl, ""); if (!StringUtil.match(linkHrefRemaining, "\\d")) { appendDbgStrForLink(link, "ignored: no number beyond base url " + baseUrl); continue; } } PagingLinkObj linkObj = null; if (!possiblePages.containsKey(linkHref)) { // Have not encountered this href. linkObj = new PagingLinkObj(i, 0, linkText, linkHref); possiblePages.put(linkHref, linkObj); } else { // Have already encountered this href, append its text to existing entry's. linkObj = possiblePages.get(linkHref); linkObj.mLinkText += " | " + linkText; } // If the base URL isn't part of this URL, penalize this link. It could still be the // link, but the odds are lower. // Example: http://www.actionscript.org/resources/articles/745/1/JavaScript-and-VBScript-Injection-in-ActionScript-3/Page1.html. // TODO(kuan): again, baseUrl (returned by findBaseUrl()) is NOT the prefix of the // current window location, even though it appears to be so the way it's used here. if (linkHref.indexOf(baseUrl) != 0) { linkObj.mScore -= 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": not part of base url " + baseUrl); } // Concatenate the link text with class name and id, and determine the score based on // existence of various paging-related words. String linkData = linkText + " " + link.getClassName() + " " + link.getId(); appendDbgStrForLink(link, "txt+class+id=" + linkData); if (StringUtil.match(linkData, pageLink == PageLink.NEXT ? NEXT_LINK_REGEX : PREV_LINK_REGEX)) { linkObj.mScore += 50; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has " + (pageLink == PageLink.NEXT ? "next" : "prev" + " regex")); } if (StringUtil.match(linkData, "pag(e|ing|inat)")) { linkObj.mScore += 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has pag* word"); } if (StringUtil.match(linkData, "(first|last)")) { // -65 is enough to negate any bonuses gotten from a > or » in the text. // If we already matched on "next", last is probably fine. // If we didn't, then it's bad. Penalize. // Same for "prev". if ((pageLink == PageLink.NEXT && !StringUtil.match(linkObj.mLinkText, NEXT_LINK_REGEX)) || (pageLink == PageLink.PREV && !StringUtil.match(linkObj.mLinkText, PREV_LINK_REGEX))) { linkObj.mScore -= 65; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has first|last but no " + (pageLink == PageLink.NEXT ? "next" : "prev") + " regex"); } } if (StringUtil.match(linkData, NEGATIVE_REGEX) || StringUtil.match(linkData, EXTRANEOUS_REGEX)) { linkObj.mScore -= 50; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has neg or extra regex"); } if (StringUtil.match(linkData, pageLink == PageLink.NEXT ? PREV_LINK_REGEX : NEXT_LINK_REGEX)) { linkObj.mScore -= 200; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has opp of " + (pageLink == PageLink.NEXT ? "next" : "prev") + " regex"); } // Check if a parent element contains page or paging or paginate. boolean positiveMatch = false, negativeMatch = false; Element parent = link.getParentElement(); while (parent != null && (positiveMatch == false || negativeMatch == false)) { String parentClassAndId = parent.getClassName() + " " + parent.getId(); if (!positiveMatch && StringUtil.match(parentClassAndId, "pag(e|ing|inat)")) { linkObj.mScore += 25; positiveMatch = true; appendDbgStrForLink(link,"score=" + linkObj.mScore + ": posParent - " + parentClassAndId); } // TODO(kuan): to get 1st page for prev page link, this can't be applied; however, // the non-application might be the cause of recursive prev page being returned, // i.e. for page 1, it may incorrectly return page 3 for prev page link. if (!negativeMatch && StringUtil.match(parentClassAndId, NEGATIVE_REGEX)) { // If this is just something like "footer", give it a negative. // If it's something like "body-and-footer", leave it be. if (!StringUtil.match(parentClassAndId, POSITIVE_REGEX)) { linkObj.mScore -= 25; negativeMatch = true; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": negParent - " + parentClassAndId); } } parent = parent.getParentElement(); } // If the URL looks like it has paging in it, add to the score. // Things like /page/2/, /pagenum/2, ?p=3, ?page=11, ?pagination=34. if (StringUtil.match(linkHref, "p(a|g|ag)?(e|ing|ination)?(=|\\/)[0-9]{1,2}") || StringUtil.match(linkHref, "(page|paging)")) { linkObj.mScore += 25; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has paging info"); } // If the URL contains negative values, give a slight decrease. if (StringUtil.match(linkHref, EXTRANEOUS_REGEX)) { linkObj.mScore -= 15; appendDbgStrForLink(link, "score=" + linkObj.mScore + ": has extra regex"); } // If the link text can be parsed as a number, give it a minor bonus, with a slight bias // towards lower numbered pages. This is so that pages that might not have 'next' in // their text can still get scored, and sorted properly by score. // TODO(kuan): it might be wrong to assume that it knows about other pages in the // document and that it starts on the first page. int linkTextAsNumber = JavaScript.parseInt(linkText, 10); if (linkTextAsNumber > 0) { // Punish 1 since we're either already there, or it's probably before what we // want anyway. if (linkTextAsNumber == 1) { linkObj.mScore -= 10; } else { linkObj.mScore += Math.max(0, 10 - linkTextAsNumber); } appendDbgStrForLink(link, "score=" + linkObj.mScore + ": linktxt is a num"); } } // for all links // Loop through all of the possible pages from above and find the top candidate for the next // page URL. Require at least a score of 50, which is a relatively high confidence that // this page is the next link. PagingLinkObj topPage = null; if (!possiblePages.isEmpty()) { Collection<PagingLinkObj> possiblePageObjs = possiblePages.values(); Iterator<PagingLinkObj> iter = possiblePageObjs.iterator(); while (iter.hasNext()) { PagingLinkObj pageObj = iter.next(); if (pageObj.mScore >= 50 && (topPage == null || topPage.mScore < pageObj.mScore)) { topPage = pageObj; } } } String pagingHref = null; if (topPage != null) { pagingHref = StringUtil.findAndReplace(topPage.mLinkHref, "\\/$", ""); appendDbgStrForLink(allLinks.getItem(topPage.mLinkIndex), "found: score=" + topPage.mScore + ", txt=[" + topPage.mLinkText + "], " + pagingHref); } if (LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) { logDbgInfoToConsole(pageLink, pagingHref, allLinks); } return pagingHref; } private static String getLocationHost(String original_domain) { return original_domain.isEmpty() ? Window.Location.getHost() : original_domain; } private static String findBaseUrl(String original_domain) { // This extracts relevant parts from the window location's path based on various heuristics // to determine the path of the base URL of the document. This path is then appended to the // window location protocol and host to form the base URL of the document. This base URL is // then used as reference for comparison against an anchor's href to to determine if the // anchor is a next or previous paging link. // First, from the window's location's path, extract the segments delimited by '/'. Then, // because the later segments probably contain less relevant information for the base URL, // reverse the segments for easier processing. // Note: '?' is a special character in RegEx, so enclose it within [] to specify the actual // character. String noUrlParams = Window.Location.getPath(); String[] urlSlashes = StringUtil.split(noUrlParams, "/"); Collections.reverse(Arrays.asList(urlSlashes)); // Now, process each segment by extracting relevant information based on various heuristics. List<String> cleanedSegments = new ArrayList<String>(); for (int i = 0; i < urlSlashes.length; i++) { String segment = urlSlashes[i]; // Split off and save anything that looks like a file type. if (segment.indexOf(".") != -1) { // Because '.' is a special character in RegEx, enclose it within [] to specify the // actual character. String possibleType = StringUtil.split(segment, "[.]")[1]; // If the type isn't alpha-only, it's probably not actually a file extension. if (!StringUtil.match(possibleType, "[^a-zA-Z]")) { segment = StringUtil.split(segment, "[.]")[0]; } } // EW-CMS specific segment replacement. Ugly. // Example: http://www.ew.com/ew/article/0,,20313460_20369436,00.html. segment = StringUtil.findAndReplace(segment, ",00", ""); // If the first or second segment has anything looking like a page number, remove it. if (i < 2) segment = StringUtil.findAndReplace(segment, PAGE_NUMBER_REGEX, ""); // Ignore an empty segment. if (segment.isEmpty()) continue; // If this is purely a number in the first or second segment, it's probably a page // number, ignore it. if (i < 2 && StringUtil.match(segment, "^\\d{1,2}$")) continue; // If this is the first segment and it's just "index", ignore it. if (i == 0 && segment.equalsIgnoreCase("index")) continue; // If the first or second segment is shorter than 3 characters, and the first // segment was purely alphas, ignore it. if (i < 2 && segment.length() < 3 && !StringUtil.match(urlSlashes[0], "[a-z]")) { continue; } // If we got here, append the segment to cleanedSegments. cleanedSegments.add(segment); } // for all urlSlashes return Window.Location.getProtocol() + "//" + getLocationHost(original_domain) + "/" + reverseJoin(cleanedSegments, "/"); } private static String reverseJoin(List<String> array, String delim) { // As per http://stackoverflow.com/questions/5748044/gwt-string-concatenation-operator-vs-stringbuffer, // + operator is faster for javascript than StringBuffer/StringBuilder. String joined = ""; for (int i = array.size() - 1; i >= 0; i--) { joined += array.get(i); if (i > 0) joined += delim; } return joined; } private static void appendDbgStrForLink(Element link, String message) { if (!LogUtil.isLoggable(LogUtil.DEBUG_LEVEL_PAGING_INFO)) return; // |message| is concatenated with the existing debug string for |link| (delimited by ";") in // mLinkDebugInfo. String dbgStr = ""; if (mLinkDebugInfo.containsKey(link)) dbgStr = mLinkDebugInfo.get(link); if (!dbgStr.isEmpty()) dbgStr += "; "; dbgStr += message; mLinkDebugInfo.put(link, dbgStr); } private static void logDbgInfoToConsole(PageLink pageLink, String pagingHref, NodeList<Element> allLinks) { // This logs the following to the console: // - number of links processed // - the next or previous page link found // - for each link: its href, text, concatenated debug string. // Location of logging output is different when running in different modes: // - "ant test.dev": test output file. // - chrome browser distiller viewer: chrome logfile. // (TODO)kuan): investigate how to get logging when running "ant test.prod" - currently, // nothing appears. In the meantime, throwing an exception with a log message at suspicious // codepoints can produce a call stack and help debugging, albeit tediously. LogUtil.logToConsole("numLinks=" + allLinks.getLength() + ", found " + (pageLink == PageLink.NEXT ? "next: " : "prev: ") + (pagingHref != null ? pagingHref : "null")); for (int i = 0; i < allLinks.getLength(); i++) { AnchorElement link = AnchorElement.as(allLinks.getItem(i)); // Use javascript innerText (instead of javascript textContent) to get only visible // text. String text = DomUtil.getInnerText(link); // Trim unnecessary whitespaces from text. String[] words = StringUtil.split(text, "\\s+"); text = ""; for (int w = 0; w < words.length; w++) { text += words[w]; if (w < words.length - 1) text += " "; } LogUtil.logToConsole(i + ")" + link.getHref() + ", txt=[" + text + "], dbg=[" + mLinkDebugInfo.get(link) + "]"); } } private static class PagingLinkObj { private int mLinkIndex = -1; private int mScore = 0; private String mLinkText; private final String mLinkHref; PagingLinkObj(int linkIndex, int score, String linkText, String linkHref) { mLinkIndex = linkIndex; mScore = score; mLinkText = linkText; mLinkHref = linkHref; } } private enum PageLink { NEXT, PREV, } private static final Map<Element, String> mLinkDebugInfo = new HashMap<Element, String>(); }
Use pre-compiled regexes for many things in PagingLinksFinder BUG=440977 R=wychen@chromium.org Review URL: https://codereview.chromium.org/837193006
src/com/dom_distiller/client/PagingLinksFinder.java
Use pre-compiled regexes for many things in PagingLinksFinder
Java
apache-2.0
4fbb4979e8274346f865b6e20b22663a146738e5
0
jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient
package org.sagebionetworks.web.client.widget.entity.renderer; import static org.sagebionetworks.web.client.SynapseJSNIUtilsImpl._unmountComponentAtNode; import java.util.List; import org.gwtbootstrap3.client.ui.Anchor; import org.gwtbootstrap3.client.ui.html.Div; import org.gwtbootstrap3.client.ui.html.Span; import org.sagebionetworks.web.client.plotly.AxisType; import org.sagebionetworks.web.client.plotly.PlotlyTraceWrapper; import org.sagebionetworks.web.client.widget.LoadingSpinner; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class PlotlyWidgetViewImpl implements PlotlyWidgetView { public interface Binder extends UiBinder<Widget, PlotlyWidgetViewImpl> {} @UiField Div chartContainer; @UiField Div synAlertContainer; @UiField LoadingSpinner loadingUI; Widget w; Presenter presenter; @UiField Anchor sourceDataAnchor; @UiField Span loadingMessage; @Inject public PlotlyWidgetViewImpl(Binder binder) { w=binder.createAndBindUi(this); chartContainer.setWidth("100%"); w.addAttachHandler(event -> { if (!event.isAttached()) { //detach event, clean up react component _unmountComponentAtNode(chartContainer.getElement()); } }); } @Override public void setPresenter(Presenter p) { presenter = p; } @Override public Widget asWidget() { return w; } @Override public void setSynAlertWidget(IsWidget w) { synAlertContainer.clear(); synAlertContainer.add(w); } @Override public void clearChart() { chartContainer.clear(); } @Override public void showChart( String title, String xTitle, String yTitle, List<PlotlyTraceWrapper> xyData, String barMode, AxisType xAxisType, AxisType yAxisType, boolean showLegend) { chartContainer.clear(); String xAxisTypeString = AxisType.AUTO.equals(xAxisType) ? "-" : xAxisType.toString().toLowerCase(); String yAxisTypeString = AxisType.AUTO.equals(yAxisType) ? "-" : yAxisType.toString().toLowerCase(); _showChart(chartContainer.getElement(), getPlotlyTraceArray(xyData), barMode, title, xTitle, yTitle, xAxisTypeString, yAxisTypeString, showLegend); } public static JavaScriptObject[] getPlotlyTraceArray(List<PlotlyTraceWrapper> l) { if (l == null) { return null; } JavaScriptObject[] d = new JavaScriptObject[l.size()]; for (int i = 0; i < l.size(); i++) { d[i] = l.get(i).getTrace(); } return d; } private static native void _showChart( Element el, JavaScriptObject[] xyData, String barMode, String plotTitle, String xTitle, String yTitle, String xAxisType, String yAxisType, boolean showLegend) /*-{ var plot = $wnd.createPlotlyComponent($wnd.Plotly); // SWC-3668: We must manually construct an Object from the parent window Object prototype. This is a general GWT js integration issue. // If we define the layout in the standard way, like "xaxis: {title:"mytitle"}", then Object.getPrototypeOf(obj) === Object.prototype is false. // And if this condition is false, then plotly clears our input layout params object. It instead uses defaults (based on the data). var xAxisLayoutObject = new $wnd.Object(); xAxisLayoutObject.title = xTitle; xAxisLayoutObject.type = xAxisType; var yAxisLayoutObject = new $wnd.Object(); yAxisLayoutObject.title = yTitle; yAxisLayoutObject.type = yAxisType; var props = { data: xyData, fit: true, layout: { title: plotTitle, xaxis: xAxisLayoutObject, yaxis: yAxisLayoutObject, barmode: barMode, showlegend: showLegend }, // note: we'd like to just hide the "save and edit plot in cloud" command, // but the parameter provided in the docs (showLink: false) has no effect. // hide the entire bar by setting displayModeBar to false. config: {displayModeBar: false} }; $wnd.ReactDOM.render( $wnd.React.createElement(plot, props), el ); }-*/; @Override public void setLoadingVisible(boolean visible) { loadingUI.setVisible(visible); loadingMessage.setVisible(visible); } @Override public void setLoadingMessage(String message) { loadingMessage.setText(message); } @Override public boolean isAttached() { return w.isAttached(); } @Override public void setSourceDataLink(String url) { sourceDataAnchor.setHref(url); } @Override public void setSourceDataLinkVisible(boolean visible) { sourceDataAnchor.setVisible(visible); } }
src/main/java/org/sagebionetworks/web/client/widget/entity/renderer/PlotlyWidgetViewImpl.java
package org.sagebionetworks.web.client.widget.entity.renderer; import static org.sagebionetworks.web.client.SynapseJSNIUtilsImpl._unmountComponentAtNode; import java.util.List; import org.gwtbootstrap3.client.ui.Anchor; import org.gwtbootstrap3.client.ui.html.Div; import org.gwtbootstrap3.client.ui.html.Span; import org.sagebionetworks.web.client.plotly.AxisType; import org.sagebionetworks.web.client.plotly.PlotlyTraceWrapper; import org.sagebionetworks.web.client.widget.LoadingSpinner; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; public class PlotlyWidgetViewImpl implements PlotlyWidgetView { public interface Binder extends UiBinder<Widget, PlotlyWidgetViewImpl> {} @UiField Div chartContainer; @UiField Div synAlertContainer; @UiField LoadingSpinner loadingUI; Widget w; Presenter presenter; @UiField Anchor sourceDataAnchor; @UiField Span loadingMessage; @Inject public PlotlyWidgetViewImpl(Binder binder) { w=binder.createAndBindUi(this); chartContainer.setWidth("100%"); w.addAttachHandler(event -> { if (!event.isAttached()) { //detach event, clean up react component _unmountComponentAtNode(chartContainer.getElement()); } }); } @Override public void setPresenter(Presenter p) { presenter = p; } @Override public Widget asWidget() { return w; } @Override public void setSynAlertWidget(IsWidget w) { synAlertContainer.clear(); synAlertContainer.add(w); } @Override public void clearChart() { chartContainer.clear(); } @Override public void showChart( String title, String xTitle, String yTitle, List<PlotlyTraceWrapper> xyData, String barMode, AxisType xAxisType, AxisType yAxisType, boolean showLegend) { chartContainer.clear(); String xAxisTypeString = AxisType.AUTO.equals(xAxisType) ? "-" : xAxisType.toString().toLowerCase(); String yAxisTypeString = AxisType.AUTO.equals(yAxisType) ? "-" : yAxisType.toString().toLowerCase(); _showChart(chartContainer.getElement(), getPlotlyTraceArray(xyData), barMode, title, xTitle, yTitle, xAxisTypeString, yAxisTypeString, showLegend); } public static JavaScriptObject[] getPlotlyTraceArray(List<PlotlyTraceWrapper> l) { if (l == null) { return null; } JavaScriptObject[] d = new JavaScriptObject[l.size()]; for (int i = 0; i < l.size(); i++) { d[i] = l.get(i).getTrace(); } return d; } private static native void _showChart( Element el, JavaScriptObject[] xyData, String barMode, String plotTitle, String xTitle, String yTitle, String xAxisType, String yAxisType, boolean showLegend) /*-{ var plot = $wnd.createPlotlyComponent($wnd.Plotly); var xAxisLayoutObject = new $wnd.Object(); xAxisLayoutObject.title = xTitle; xAxisLayoutObject.type = xAxisType; var yAxisLayoutObject = new $wnd.Object(); yAxisLayoutObject.title = yTitle; yAxisLayoutObject.type = yAxisType; var props = { data: xyData, fit: true, layout: { title: plotTitle, xaxis: xAxisLayoutObject, yaxis: yAxisLayoutObject, barmode: barMode, showlegend: showLegend }, // note: we'd like to just hide the "save and edit plot in cloud" command, // but the parameter provided in the docs (showLink: false) has no effect. // hide the entire bar by setting displayModeBar to false. config: {displayModeBar: false} }; $wnd.ReactDOM.render( $wnd.React.createElement(plot, props), el ); }-*/; @Override public void setLoadingVisible(boolean visible) { loadingUI.setVisible(visible); loadingMessage.setVisible(visible); } @Override public void setLoadingMessage(String message) { loadingMessage.setText(message); } @Override public boolean isAttached() { return w.isAttached(); } @Override public void setSourceDataLink(String url) { sourceDataAnchor.setHref(url); } @Override public void setSourceDataLinkVisible(boolean visible) { sourceDataAnchor.setVisible(visible); } }
add comment
src/main/java/org/sagebionetworks/web/client/widget/entity/renderer/PlotlyWidgetViewImpl.java
add comment
Java
apache-2.0
91ec9b4cb8874b8ba0a0ac02cd43db27f55fa578
0
benfortuna/copper-engine,copper-engine/copper-engine,copper-engine/copper-engine,benfortuna/copper-engine
/* * Copyright 2002-2013 SCOOP Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.scoopgmbh.copper.monitoring.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.util.ArrayList; import java.util.Date; import java.util.Random; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferInputStream; import com.esotericsoftware.kryo.io.ByteBufferOutputStream; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import de.scoopgmbh.copper.monitoring.core.model.MonitoringData; public class MonitoringDataStorageTest { static final String filename = "test"; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void testSimpleCase() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(2),"2")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(5),"5"), new MonitoringDataDummy(new Date(6),"6")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } static class HugeData implements MonitoringData { byte[] b; public HugeData() { b = new byte[1024*2048]; new Random().nextBytes(b); } @Override public Date getTimeStamp() { return new Date(1); } } @Test public void testHugeData() throws IOException { File tmpDir = testFolder.newFolder(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); storage.write(new HugeData()); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(1, read.size()); Assert.assertTrue(read.get(0) instanceof HugeData); } @Test public void testSortedRead() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("2", ((MonitoringDataDummy)read.get(1)).value); Assert.assertEquals("3", ((MonitoringDataDummy)read.get(2)).value); Assert.assertEquals("4", ((MonitoringDataDummy)read.get(3)).value); Assert.assertEquals("5", ((MonitoringDataDummy)read.get(4)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } @Test public void testSkipSome() throws IOException { File tmpDir = testFolder.newFolder("montoringdatastoragetest"); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } @Test public void testSortedReadReverse() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.readReverse(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(5)).value); Assert.assertEquals("2", ((MonitoringDataDummy)read.get(4)).value); Assert.assertEquals("3", ((MonitoringDataDummy)read.get(3)).value); Assert.assertEquals("4", ((MonitoringDataDummy)read.get(2)).value); Assert.assertEquals("5", ((MonitoringDataDummy)read.get(1)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(0)).value); } private String getDummyString(long length){ StringBuilder builder = new StringBuilder(); for (int i=0;i<length;i++){ builder.append("X"); } return builder.toString(); } @Test public void testHouseKeeping() throws Exception { File tmpDir = testFolder.newFolder(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename,9000000,TimeUnit.DAYS,10); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); storage.close(); File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(2, files.length); } @Test public void testHousekeepingDate() throws Exception { File tmpDir = testFolder.newFolder(); long now = System.currentTimeMillis(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename,Long.MAX_VALUE,TimeUnit.MINUTES,1); storage.write(new MonitoringDataDummy(new Date(now-60001),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); storage.close(); File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(4, files.length); } @Test public void testFileReuse() throws Exception { File tmpDir = testFolder.newFolder(); long d = System.currentTimeMillis(); for (int i = 0; i < 127; ++i) { MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); storage.write(new MonitoringDataDummy(new Date(d++),getDummyString((byte)i))); storage.close(); Thread.yield(); } File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(1, files.length); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); int i = 0; for (MonitoringData in : storage.read(null,null)) { Assert.assertEquals(i++,((MonitoringDataDummy)in).value.length()); } Assert.assertEquals(127, i); storage.close(); } private void writeFile(File f, MonitoringData ... values) throws IOException { RandomAccessFile ranAccess = new RandomAccessFile(f,"rw"); MappedByteBuffer b = ranAccess.getChannel().map(MapMode.READ_WRITE, 0, 1024); long earliest = Long.MAX_VALUE; long latest = Long.MIN_VALUE; for (MonitoringData d : values) { earliest = Math.min(d.getTimeStamp().getTime(), earliest); latest = Math.max(d.getTimeStamp().getTime(), latest); } Kryo kryo = SerializeUtil.createKryo(); b.position(MonitoringDataStorage.FIRST_RECORD_POSITION); Output output = new Output(new ByteBufferOutputStream(b)); for (MonitoringData data : values) { kryo.writeClassAndObject(output, data); } output.close(); int limit = b.position(); b.putLong(MonitoringDataStorage.EARLIEST_POSITION, earliest); b.putLong(MonitoringDataStorage.LATEST_POSITION, latest); b.putInt(MonitoringDataStorage.LIMIT_POSITION, limit); ranAccess.close(); } @Test public void test_Kryo() throws IOException{ final File newFile = testFolder.newFile(); writeFile(newFile, new MonitoringDataDummy(new Date(42),"blabla1"), new MonitoringDataDummy(new Date(43),"blabla2")); RandomAccessFile ranAccess = new RandomAccessFile(newFile,"rw"); MappedByteBuffer b = ranAccess.getChannel().map(MapMode.READ_WRITE, 0, 218); long earliestTimestamp = b.getLong(MonitoringDataStorage.EARLIEST_POSITION); long latestTimestamp = b.getLong(MonitoringDataStorage.LATEST_POSITION); assertEquals(42, earliestTimestamp); assertEquals(43, latestTimestamp); Kryo kryo = new Kryo(); Input input = new Input(new ByteBufferInputStream(b)); input.setPosition(MonitoringDataStorage.FIRST_RECORD_POSITION); assertEquals("blabla1",((MonitoringDataDummy)kryo.readClassAndObject(input)).value); assertEquals("blabla2",((MonitoringDataDummy)kryo.readClassAndObject(input)).value); assertNull(kryo.readClassAndObject(input)); b.putInt(MonitoringDataStorage.LIMIT_POSITION, b.position()); b.position(0); ranAccess.close(); } @Test public void test_microbenchmark() throws IOException{ File tmpDir = testFolder.newFolder(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<Long> delats= new ArrayList<Long>(); for (int i=0;i<40000;i++) { long start=System.nanoTime(); storage.write(new MonitoringDataDummy(new Date(42),"X")); delats.add(System.nanoTime()-start); } // double sum=0; // for (Long time : delats) { // sum +=time; // } // // System.out.println((sum/delats.size())/(1000*1000)); } }
projects/copper-monitoring/copper-monitoring-core/src/test/java/de/scoopgmbh/copper/monitoring/core/data/MonitoringDataStorageTest.java
/* * Copyright 2002-2013 SCOOP Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.scoopgmbh.copper.monitoring.core.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel.MapMode; import java.util.ArrayList; import java.util.Date; import java.util.Random; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.ByteBufferInputStream; import com.esotericsoftware.kryo.io.ByteBufferOutputStream; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import de.scoopgmbh.copper.monitoring.core.model.MonitoringData; public class MonitoringDataStorageTest { static final String filename = "test"; @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Test public void testSimpleCase() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(2),"2")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(5),"5"), new MonitoringDataDummy(new Date(6),"6")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } static class HugeData implements MonitoringData { byte[] b; public HugeData() { b = new byte[1024*2048]; new Random().nextBytes(b); } @Override public Date getTimeStamp() { return new Date(1); } } @Test public void testHugeData() throws IOException { File tmpDir = testFolder.newFolder(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); storage.write(new HugeData()); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(1, read.size()); Assert.assertTrue(read.get(0) instanceof HugeData); } @Test public void testSortedRead() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("2", ((MonitoringDataDummy)read.get(1)).value); Assert.assertEquals("3", ((MonitoringDataDummy)read.get(2)).value); Assert.assertEquals("4", ((MonitoringDataDummy)read.get(3)).value); Assert.assertEquals("5", ((MonitoringDataDummy)read.get(4)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } @Test public void testSkipSome() throws IOException { File tmpDir = testFolder.newFolder("montoringdatastoragetest"); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.read(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(0)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(5)).value); } @Test public void testSortedReadReverse() throws IOException { File tmpDir = testFolder.newFolder(); File f1 = new File(tmpDir, filename+".1"); writeFile(f1, new MonitoringDataDummy(new Date(1),"1"), new MonitoringDataDummy(new Date(6),"6")); File f2 = new File(tmpDir, filename+".2"); writeFile(f2, new MonitoringDataDummy(new Date(2),"2"), new MonitoringDataDummy(new Date(5),"5")); File f3 = new File(tmpDir, filename+".3"); writeFile(f3, new MonitoringDataDummy(new Date(3),"3"), new MonitoringDataDummy(new Date(4),"4")); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); ArrayList<MonitoringData> read = new ArrayList<MonitoringData>(); for (MonitoringData in : storage.readReverse(new Date(1), new Date(6))) { read.add(in); } Assert.assertEquals(6, read.size()); Assert.assertEquals("1", ((MonitoringDataDummy)read.get(5)).value); Assert.assertEquals("2", ((MonitoringDataDummy)read.get(4)).value); Assert.assertEquals("3", ((MonitoringDataDummy)read.get(3)).value); Assert.assertEquals("4", ((MonitoringDataDummy)read.get(2)).value); Assert.assertEquals("5", ((MonitoringDataDummy)read.get(1)).value); Assert.assertEquals("6", ((MonitoringDataDummy)read.get(0)).value); } private String getDummyString(long length){ StringBuilder builder = new StringBuilder(); for (int i=0;i<length;i++){ builder.append("X"); } return builder.toString(); } @Test public void testHouseKeeping() throws Exception { File tmpDir = testFolder.newFolder(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename,9000000,TimeUnit.DAYS,10); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); storage.close(); File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(2, files.length); } @Test public void testHousekeepingDate() throws Exception { File tmpDir = testFolder.newFolder(); long now = System.currentTimeMillis(); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename,Long.MAX_VALUE,TimeUnit.MINUTES,1); storage.write(new MonitoringDataDummy(new Date(now-60001),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); Thread.sleep(100); System.gc(); Runtime.getRuntime().runFinalization(); storage.write(new MonitoringDataDummy(new Date(now),getDummyString(MonitoringDataStorage.FILE_CHUNK_SIZE-1000))); storage.close(); File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(4, files.length); } @Test public void testFileReuse() throws Exception { File tmpDir = testFolder.newFolder(); long d = System.currentTimeMillis(); for (int i = 0; i < 127; ++i) { MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); storage.write(new MonitoringDataDummy(new Date(d++),getDummyString((byte)i))); storage.close(); Thread.yield(); } File[] files = tmpDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().startsWith(filename); } }); Assert.assertEquals(1, files.length); MonitoringDataStorage storage = new MonitoringDataStorage(tmpDir, filename); int i = 0; for (MonitoringData in : storage.read(null,null)) { Assert.assertEquals(i++,((MonitoringDataDummy)in).value.length()); } Assert.assertEquals(127, i); storage.close(); } private void writeFile(File f, MonitoringData ... values) throws IOException { RandomAccessFile ranAccess = new RandomAccessFile(f,"rw"); MappedByteBuffer b = ranAccess.getChannel().map(MapMode.READ_WRITE, 0, 1024); long earliest = Long.MAX_VALUE; long latest = Long.MIN_VALUE; for (MonitoringData d : values) { earliest = Math.min(d.getTimeStamp().getTime(), earliest); latest = Math.max(d.getTimeStamp().getTime(), latest); } Kryo kryo = SerializeUtil.createKryo(); b.position(MonitoringDataStorage.FIRST_RECORD_POSITION); Output output = new Output(new ByteBufferOutputStream(b)); for (MonitoringData data : values) { kryo.writeClassAndObject(output, data); } output.close(); int limit = b.position(); b.putLong(MonitoringDataStorage.EARLIEST_POSITION, earliest); b.putLong(MonitoringDataStorage.LATEST_POSITION, latest); b.putInt(MonitoringDataStorage.LIMIT_POSITION, limit); ranAccess.close(); } @Test public void test_Kryo() throws IOException{ final File newFile = testFolder.newFile(); writeFile(newFile, new MonitoringDataDummy(new Date(42),"blabla1"), new MonitoringDataDummy(new Date(43),"blabla2")); RandomAccessFile ranAccess = new RandomAccessFile(newFile,"rw"); MappedByteBuffer b = ranAccess.getChannel().map(MapMode.READ_WRITE, 0, 218); long earliestTimestamp = b.getLong(MonitoringDataStorage.EARLIEST_POSITION); long latestTimestamp = b.getLong(MonitoringDataStorage.LATEST_POSITION); assertEquals(42, earliestTimestamp); assertEquals(43, latestTimestamp); Kryo kryo = new Kryo(); Input input = new Input(new ByteBufferInputStream(b)); input.setPosition(MonitoringDataStorage.FIRST_RECORD_POSITION); assertEquals("blabla1",((MonitoringDataDummy)kryo.readClassAndObject(input)).value); assertEquals("blabla2",((MonitoringDataDummy)kryo.readClassAndObject(input)).value); assertNull(kryo.readClassAndObject(input)); b.putInt(MonitoringDataStorage.LIMIT_POSITION, b.position()); b.position(0); ranAccess.close(); } }
Annimation fix
projects/copper-monitoring/copper-monitoring-core/src/test/java/de/scoopgmbh/copper/monitoring/core/data/MonitoringDataStorageTest.java
Annimation fix
Java
apache-2.0
54f89a767b21db26d5f7b3e8032d3efcddb239f9
0
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.annotation.download.header; import uk.ac.ebi.quickgo.annotation.download.TSVDownload; import java.io.IOException; import java.util.*; import java.util.function.BiConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; import static uk.ac.ebi.quickgo.annotation.download.TSVDownload.*; /** * Produce a header for TSV downloaded files. Only the (selected) column names are required. Or all columns if none * are selected. * * @author Tony Wardell * Date: 25/01/2017 * Time: 10:09 * Created with IntelliJ IDEA. */ public class TSVHeaderCreator extends AbstractHeaderCreator { private static final Logger LOGGER = LoggerFactory.getLogger(TSVHeaderCreator.class); static final String GENE_PRODUCT_DB = "GENE PRODUCT DB"; static final String GENE_PRODUCT_ID = "GENE PRODUCT ID"; static final String SYMBOL = "SYMBOL"; static final String QUALIFIER = "QUALIFIER"; static final String GO_TERM = "GO TERM"; static final String GO_ASPECT = "GO ASPECT"; static final String GO_NAME = "GO NAME"; static final String SLIMMED_FROM = "SLIMMED FROM"; static final String ECO_ID = "ECO ID"; static final String GO_EVIDENCE_CODE = "GO EVIDENCE CODE"; static final String REFERENCE = "REFERENCE"; static final String WITH_FROM = "WITH/FROM"; static final String TAXON_ID = "TAXON ID"; static final String ASSIGNED_BY = "ASSIGNED BY"; static final String ANNOTATION_EXTENSION = "ANNOTATION EXTENSION"; static final String DATE = "DATE"; static final String TAXON_NAME = "TAXON NAME"; static final String GENE_PRODUCT_NAME = "GENE_PRODUCT_NAME"; static final String GENE_PRODUCT_SYNONYMS = "GENE_PRODUCT_SYNONYMS"; static final String GENE_PRODUCT_TYPE = "GENE_PRODUCT_TYPE"; private static final String OUTPUT_DELIMITER = "\t"; private static final Map<String, BiConsumer<HeaderContent, StringJoiner>> selected2Content; static { selected2Content = new HashMap<>(); initialiseContentMappings(); } private static void initialiseContentMappings() { selected2Content.put(GENE_PRODUCT_FIELD_NAME, (hc, j) -> { j.add(GENE_PRODUCT_DB); j.add(GENE_PRODUCT_ID); }); selected2Content.put(SYMBOL_FIELD_NAME, (hc, j) -> j.add(SYMBOL)); selected2Content.put(QUALIFIER_FIELD_NAME, (hc, j) -> j.add(QUALIFIER)); selected2Content.put(GO_TERM_FIELD_NAME, (hc, j) -> { j.add(GO_TERM); if (hc.isSlimmed()) { j.add(SLIMMED_FROM); } }); selected2Content.put(GO_ASPECT_FIELD_NAME, (hc, j) -> j.add(GO_ASPECT)); selected2Content.put(GO_NAME_FIELD_NAME, (hc, j) -> j.add(GO_NAME)); selected2Content.put(ECO_ID_FIELD_NAME, (hc, j) -> j.add(ECO_ID)); selected2Content.put(GO_EVIDENCE_CODE_FIELD_NAME, (hc, j) -> j.add(GO_EVIDENCE_CODE)); selected2Content.put(REFERENCE_FIELD_NAME, (hc, j) -> j.add(REFERENCE)); selected2Content.put(WITH_FROM_FIELD_NAME, (hc, j) -> j.add(WITH_FROM)); selected2Content.put(TAXON_ID_FIELD_NAME, (hc, j) -> j.add(TAXON_ID)); selected2Content.put(ASSIGNED_BY_FIELD_NAME, (hc, j) -> j.add(ASSIGNED_BY)); selected2Content.put(ANNOTATION_EXTENSION_FIELD_NAME, (hc, j) -> j.add(ANNOTATION_EXTENSION)); selected2Content.put(DATE_FIELD_NAME, (hc, j) -> j.add(DATE)); selected2Content.put(TAXON_NAME_FIELD_NAME, (hc, j) -> j.add(TAXON_NAME)); selected2Content.put(GENE_PRODUCT_NAME_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_NAME)); selected2Content.put(GENE_PRODUCT_SYNONYMS_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_SYNONYMS)); selected2Content.put(GENE_PRODUCT_TYPE_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_TYPE)); } /** * Send the contents of the header to the ResponseBodyEmitter instance. * @param emitter streams the header content to the client * @param content holds values used to control or populate the header output.; */ @Override protected void output(ResponseBodyEmitter emitter, HeaderContent content) throws IOException { StringJoiner tsvJoiner = new StringJoiner(OUTPUT_DELIMITER); List<String> selectedFields = TSVDownload.whichColumnsWillWeShow(content.getSelectedFields()); LOGGER.debug("Requested which fields will we show from " + content.getSelectedFields() + " and will show " + selectedFields); for (String selectedField : selectedFields) { selected2Content.get(selectedField).accept(content, tsvJoiner); } emitter.send(tsvJoiner.toString() + "\n", MediaType.TEXT_PLAIN); } }
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/header/TSVHeaderCreator.java
package uk.ac.ebi.quickgo.annotation.download.header; import uk.ac.ebi.quickgo.annotation.download.TSVDownload; import java.io.IOException; import java.util.*; import java.util.function.BiConsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter; import static uk.ac.ebi.quickgo.annotation.download.TSVDownload.*; /** * Produce a header for TSV downloaded files. Only the (selected) column names are required. Or all columns if none * are selected. * * @author Tony Wardell * Date: 25/01/2017 * Time: 10:09 * Created with IntelliJ IDEA. */ public class TSVHeaderCreator extends AbstractHeaderCreator { private static final Logger LOGGER = LoggerFactory.getLogger(TSVHeaderCreator.class); static final String GENE_PRODUCT_DB = "GENE PRODUCT DB"; static final String GENE_PRODUCT_ID = "GENE PRODUCT ID"; static final String SYMBOL = "SYMBOL"; static final String QUALIFIER = "QUALIFIER"; static final String GO_TERM = "GO TERM"; static final String GO_ASPECT = "GO ASPECT"; static final String GO_NAME = "GO NAME"; static final String SLIMMED_FROM = "SLIMMED FROM"; static final String ECO_ID = "ECO_ID"; static final String GO_EVIDENCE_CODE = "GO EVIDENCE CODE"; static final String REFERENCE = "REFERENCE"; static final String WITH_FROM = "WITH/FROM"; static final String TAXON_ID = "TAXON ID"; static final String ASSIGNED_BY = "ASSIGNED BY"; static final String ANNOTATION_EXTENSION = "ANNOTATION EXTENSION"; static final String DATE = "DATE"; static final String TAXON_NAME = "TAXON NAME"; static final String GENE_PRODUCT_NAME = "GENE_PRODUCT_NAME"; static final String GENE_PRODUCT_SYNONYMS = "GENE_PRODUCT_SYNONYMS"; static final String GENE_PRODUCT_TYPE = "GENE_PRODUCT_TYPE"; private static final String OUTPUT_DELIMITER = "\t"; private static final Map<String, BiConsumer<HeaderContent, StringJoiner>> selected2Content; static { selected2Content = new HashMap<>(); initialiseContentMappings(); } private static void initialiseContentMappings() { selected2Content.put(GENE_PRODUCT_FIELD_NAME, (hc, j) -> { j.add(GENE_PRODUCT_DB); j.add(GENE_PRODUCT_ID); }); selected2Content.put(SYMBOL_FIELD_NAME, (hc, j) -> j.add(SYMBOL)); selected2Content.put(QUALIFIER_FIELD_NAME, (hc, j) -> j.add(QUALIFIER)); selected2Content.put(GO_TERM_FIELD_NAME, (hc, j) -> { j.add(GO_TERM); if (hc.isSlimmed()) { j.add(SLIMMED_FROM); } }); selected2Content.put(GO_ASPECT_FIELD_NAME, (hc, j) -> j.add(GO_ASPECT)); selected2Content.put(GO_NAME_FIELD_NAME, (hc, j) -> j.add(GO_NAME)); selected2Content.put(ECO_ID_FIELD_NAME, (hc, j) -> j.add(ECO_ID)); selected2Content.put(GO_EVIDENCE_CODE_FIELD_NAME, (hc, j) -> j.add(GO_EVIDENCE_CODE)); selected2Content.put(REFERENCE_FIELD_NAME, (hc, j) -> j.add(REFERENCE)); selected2Content.put(WITH_FROM_FIELD_NAME, (hc, j) -> j.add(WITH_FROM)); selected2Content.put(TAXON_ID_FIELD_NAME, (hc, j) -> j.add(TAXON_ID)); selected2Content.put(ASSIGNED_BY_FIELD_NAME, (hc, j) -> j.add(ASSIGNED_BY)); selected2Content.put(ANNOTATION_EXTENSION_FIELD_NAME, (hc, j) -> j.add(ANNOTATION_EXTENSION)); selected2Content.put(DATE_FIELD_NAME, (hc, j) -> j.add(DATE)); selected2Content.put(TAXON_NAME_FIELD_NAME, (hc, j) -> j.add(TAXON_NAME)); selected2Content.put(GENE_PRODUCT_NAME_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_NAME)); selected2Content.put(GENE_PRODUCT_SYNONYMS_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_SYNONYMS)); selected2Content.put(GENE_PRODUCT_TYPE_FIELD_NAME, (hc, j) -> j.add(GENE_PRODUCT_TYPE)); } /** * Send the contents of the header to the ResponseBodyEmitter instance. * @param emitter streams the header content to the client * @param content holds values used to control or populate the header output.; */ @Override protected void output(ResponseBodyEmitter emitter, HeaderContent content) throws IOException { StringJoiner tsvJoiner = new StringJoiner(OUTPUT_DELIMITER); List<String> selectedFields = TSVDownload.whichColumnsWillWeShow(content.getSelectedFields()); LOGGER.debug("Requested which fields will we show from " + content.getSelectedFields() + " and will show " + selectedFields); for (String selectedField : selectedFields) { selected2Content.get(selectedField).accept(content, tsvJoiner); } emitter.send(tsvJoiner.toString() + "\n", MediaType.TEXT_PLAIN); } }
Remove wayward underscore from column name.
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/header/TSVHeaderCreator.java
Remove wayward underscore from column name.
Java
apache-2.0
964def0e320bcab1b5e46ab657a71f3222d8a7dc
0
hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,HubSpot/Singularity,HubSpot/Singularity,HubSpot/Singularity
package com.hubspot.singularity.mesos; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.hubspot.mesos.JavaUtils; import com.hubspot.mesos.Resources; import com.hubspot.mesos.json.MesosAgentMetricsSnapshotObject; import com.hubspot.singularity.AgentMatchState; import com.hubspot.singularity.RequestType; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityAction; import com.hubspot.singularity.SingularityAgentUsage; import com.hubspot.singularity.SingularityAgentUsageWithId; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityDeployStatistics; import com.hubspot.singularity.SingularityManagedThreadPoolFactory; import com.hubspot.singularity.SingularityPendingTaskId; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.async.CompletableFutures; import com.hubspot.singularity.config.CustomExecutorConfiguration; import com.hubspot.singularity.config.MesosConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.DisasterManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.usage.UsageManager; import com.hubspot.singularity.helpers.MesosUtils; import com.hubspot.singularity.helpers.SingularityMesosTaskHolder; import com.hubspot.singularity.mesos.SingularityAgentAndRackManager.CheckResult; import com.hubspot.singularity.mesos.SingularityAgentUsageWithCalculatedScores.MaxProbableUsage; import com.hubspot.singularity.mesos.SingularityOfferCache.CachedOffer; import com.hubspot.singularity.scheduler.SingularityLeaderCache; import com.hubspot.singularity.scheduler.SingularityScheduler; import com.hubspot.singularity.scheduler.SingularityUsageHelper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; import java.util.stream.Collectors; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.Offer; import org.apache.mesos.v1.Protos.OfferID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class SingularityMesosOfferScheduler { private static final Logger LOG = LoggerFactory.getLogger( SingularityMesosOfferScheduler.class ); private final Resources defaultResources; private final Resources defaultCustomExecutorResources; private final TaskManager taskManager; private final SingularityMesosTaskPrioritizer taskPrioritizer; private final SingularityScheduler scheduler; private final SingularityConfiguration configuration; private final MesosConfiguration mesosConfiguration; private final SingularityMesosTaskBuilder mesosTaskBuilder; private final SingularityAgentAndRackManager agentAndRackManager; private final SingularityAgentAndRackHelper agentAndRackHelper; private final SingularityTaskSizeOptimizer taskSizeOptimizer; private final SingularityUsageHelper usageHelper; private final UsageManager usageManager; private final DeployManager deployManager; private final SingularitySchedulerLock lock; private final SingularityLeaderCache leaderCache; private final boolean offerCacheEnabled; private final DisasterManager disasterManager; private final SingularityMesosSchedulerClient mesosSchedulerClient; private final OfferCache offerCache; private final double normalizedCpuWeight; private final double normalizedMemWeight; private final double normalizedDiskWeight; private final ExecutorService offerScoringExecutor; @Inject public SingularityMesosOfferScheduler( MesosConfiguration mesosConfiguration, CustomExecutorConfiguration customExecutorConfiguration, TaskManager taskManager, SingularityMesosTaskPrioritizer taskPrioritizer, SingularityScheduler scheduler, SingularityConfiguration configuration, SingularityMesosTaskBuilder mesosTaskBuilder, SingularityAgentAndRackManager agentAndRackManager, SingularityTaskSizeOptimizer taskSizeOptimizer, SingularityAgentAndRackHelper agentAndRackHelper, SingularityLeaderCache leaderCache, SingularityUsageHelper usageHelper, UsageManager usageManager, DeployManager deployManager, SingularitySchedulerLock lock, SingularityManagedThreadPoolFactory threadPoolFactory, DisasterManager disasterManager, SingularityMesosSchedulerClient mesosSchedulerClient, OfferCache offerCache ) { this.defaultResources = new Resources( mesosConfiguration.getDefaultCpus(), mesosConfiguration.getDefaultMemory(), 0, mesosConfiguration.getDefaultDisk() ); this.defaultCustomExecutorResources = new Resources( customExecutorConfiguration.getNumCpus(), customExecutorConfiguration.getMemoryMb(), 0, customExecutorConfiguration.getDiskMb() ); this.taskManager = taskManager; this.scheduler = scheduler; this.configuration = configuration; this.mesosConfiguration = mesosConfiguration; this.mesosTaskBuilder = mesosTaskBuilder; this.agentAndRackManager = agentAndRackManager; this.taskSizeOptimizer = taskSizeOptimizer; this.leaderCache = leaderCache; this.offerCacheEnabled = configuration.isCacheOffers(); this.disasterManager = disasterManager; this.mesosSchedulerClient = mesosSchedulerClient; this.offerCache = offerCache; this.usageHelper = usageHelper; this.agentAndRackHelper = agentAndRackHelper; this.taskPrioritizer = taskPrioritizer; this.usageManager = usageManager; this.deployManager = deployManager; this.lock = lock; double cpuWeight = mesosConfiguration.getCpuWeight(); double memWeight = mesosConfiguration.getMemWeight(); double diskWeight = mesosConfiguration.getDiskWeight(); if (cpuWeight + memWeight + diskWeight != 1) { this.normalizedCpuWeight = cpuWeight / (cpuWeight + memWeight + diskWeight); this.normalizedMemWeight = memWeight / (cpuWeight + memWeight + diskWeight); this.normalizedDiskWeight = diskWeight / (cpuWeight + memWeight + diskWeight); } else { this.normalizedCpuWeight = cpuWeight; this.normalizedMemWeight = memWeight; this.normalizedDiskWeight = diskWeight; } this.offerScoringExecutor = threadPoolFactory.get("offer-scoring", configuration.getCoreThreadpoolSize()); } public void resourceOffers(List<Offer> uncached) { final long start = System.currentTimeMillis(); LOG.info("Received {} offer(s)", uncached.size()); scheduler.checkForDecomissions(); boolean declineImmediately = false; if (disasterManager.isDisabled(SingularityAction.PROCESS_OFFERS)) { LOG.info( "Processing offers is currently disabled, declining {} offers", uncached.size() ); declineImmediately = true; } if (declineImmediately) { mesosSchedulerClient.decline( uncached.stream().map(Offer::getId).collect(Collectors.toList()) ); return; } if (offerCacheEnabled) { if (disasterManager.isDisabled(SingularityAction.CACHE_OFFERS)) { offerCache.disableOfferCache(); } else { offerCache.enableOfferCache(); } } Map<String, Offer> offersToCheck = uncached .stream() .filter( o -> { if (!isValidOffer(o)) { if (o.getId() != null && o.getId().getValue() != null) { LOG.warn("Got invalid offer {}", o); mesosSchedulerClient.decline(Collections.singletonList(o.getId())); } else { LOG.warn( "Offer {} was not valid, but we can't decline it because we have no offer ID!", o ); } return false; } return true; } ) .collect( Collectors.toConcurrentMap(o -> o.getId().getValue(), Function.identity()) ); List<CachedOffer> cachedOfferList = offerCache.checkoutOffers(); Map<String, CachedOffer> cachedOffers = new ConcurrentHashMap<>(); for (CachedOffer cachedOffer : cachedOfferList) { if (isValidOffer(cachedOffer.getOffer())) { cachedOffers.put(cachedOffer.getOfferId(), cachedOffer); offersToCheck.put(cachedOffer.getOfferId(), cachedOffer.getOffer()); } else if ( cachedOffer.getOffer().getId() != null && cachedOffer.getOffer().getId().getValue() != null ) { mesosSchedulerClient.decline( Collections.singletonList(cachedOffer.getOffer().getId()) ); offerCache.rescindOffer(cachedOffer.getOffer().getId()); } else { LOG.warn( "Offer {} was not valid, but we can't decline it because we have no offer ID!", cachedOffer ); } } List<CompletableFuture<Void>> checkFutures = new ArrayList<>(); uncached.forEach( offer -> checkFutures.add(runAsync(() -> checkOfferAndAgent(offer, offersToCheck))) ); CompletableFutures.allOf(checkFutures).join(); final Set<OfferID> acceptedOffers = Sets.newHashSetWithExpectedSize( offersToCheck.size() ); try { Collection<SingularityOfferHolder> offerHolders = checkOffers(offersToCheck, start); for (SingularityOfferHolder offerHolder : offerHolders) { if (!offerHolder.getAcceptedTasks().isEmpty()) { List<Offer> leftoverOffers = offerHolder.launchTasksAndGetUnusedOffers( mesosSchedulerClient ); leftoverOffers.forEach( o -> { if (cachedOffers.containsKey(o.getId().getValue())) { offerCache.returnOffer(cachedOffers.remove(o.getId().getValue())); } else { offerCache.cacheOffer(start, o); } } ); List<Offer> offersAcceptedFrom = offerHolder.getOffers(); offersAcceptedFrom.removeAll(leftoverOffers); offersAcceptedFrom .stream() .filter(offer -> cachedOffers.containsKey(offer.getId().getValue())) .map(o -> cachedOffers.remove(o.getId().getValue())) .forEach(offerCache::useOffer); acceptedOffers.addAll( offersAcceptedFrom.stream().map(Offer::getId).collect(Collectors.toList()) ); } else { offerHolder .getOffers() .forEach( o -> { if (cachedOffers.containsKey(o.getId().getValue())) { offerCache.returnOffer(cachedOffers.remove(o.getId().getValue())); } else { offerCache.cacheOffer(start, o); } } ); } } LOG.info( "{} remaining offers not accounted for in offer check", cachedOffers.size() ); cachedOffers.values().forEach(offerCache::returnOffer); } catch (Throwable t) { LOG.error( "Received fatal error while handling offers - will decline all available offers", t ); mesosSchedulerClient.decline( offersToCheck .values() .stream() .filter( o -> { if (o == null || o.getId() == null || o.getId().getValue() == null) { LOG.warn("Got bad offer {} while trying to decline offers!", o); return false; } return true; } ) .filter( o -> !acceptedOffers.contains(o.getId()) && !cachedOffers.containsKey(o.getId().getValue()) ) .map(Offer::getId) .collect(Collectors.toList()) ); offersToCheck.forEach( (id, o) -> { if (cachedOffers.containsKey(id)) { offerCache.returnOffer(cachedOffers.get(id)); } } ); throw t; } LOG.info( "Finished handling {} new offer(s) {} from cache ({}), {} accepted, {} declined/cached", uncached.size(), cachedOffers.size(), JavaUtils.duration(start), acceptedOffers.size(), uncached.size() + cachedOffers.size() - acceptedOffers.size() ); } private void checkOfferAndAgent(Offer offer, Map<String, Offer> offersToCheck) { String rolesInfo = MesosUtils.getRoles(offer).toString(); LOG.debug( "Received offer ID {} with roles {} from {} ({}) for {} cpu(s), {} memory, {} ports, and {} disk", offer.getId().getValue(), rolesInfo, offer.getHostname(), offer.getAgentId().getValue(), MesosUtils.getNumCpus(offer), MesosUtils.getMemory(offer), MesosUtils.getNumPorts(offer), MesosUtils.getDisk(offer) ); CheckResult checkResult = agentAndRackManager.checkOffer(offer); if (checkResult == CheckResult.NOT_ACCEPTING_TASKS) { mesosSchedulerClient.decline(Collections.singletonList(offer.getId())); offersToCheck.remove(offer.getId().getValue()); LOG.debug( "Will decline offer {}, agent {} is not currently in a state to launch tasks", offer.getId().getValue(), offer.getHostname() ); } } private boolean isValidOffer(Offer offer) { if (offer.getId() == null || offer.getId().getValue() == null) { LOG.warn("Received offer with null ID, skipping ({})", offer); return false; } if (offer.getAgentId() == null || offer.getAgentId().getValue() == null) { LOG.warn("Received offer with null agent ID, skipping ({})", offer); return false; } return true; } Collection<SingularityOfferHolder> checkOffers( final Map<String, Offer> offers, long start ) { if (offers.isEmpty()) { LOG.debug("No offers to check"); return Collections.emptyList(); } final List<SingularityTaskRequestHolder> sortedTaskRequestHolders = getSortedDueTaskRequests(); final int numDueTasks = sortedTaskRequestHolders.size(); final Map<String, SingularityOfferHolder> offerHolders = offers .values() .stream() .collect(Collectors.groupingBy(o -> o.getAgentId().getValue())) .entrySet() .stream() .filter(e -> e.getValue().size() > 0) .map( e -> { List<Offer> offersList = e.getValue(); String agentId = e.getKey(); return new SingularityOfferHolder( offersList, numDueTasks, agentAndRackHelper.getRackIdOrDefault(offersList.get(0)), agentId, offersList.get(0).getHostname(), agentAndRackHelper.getTextAttributes(offersList.get(0)), agentAndRackHelper.getReservedAgentAttributes(offersList.get(0)) ); } ) .collect(Collectors.toMap(SingularityOfferHolder::getAgentId, Function.identity())); if (sortedTaskRequestHolders.isEmpty()) { return offerHolders.values(); } final AtomicInteger tasksScheduled = new AtomicInteger(0); Map<String, RequestUtilization> requestUtilizations = usageManager.getRequestUtilizations( false ); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIds(); Map<String, SingularityAgentUsageWithId> currentUsages = usageManager.getAllCurrentAgentUsage(); List<CompletableFuture<Void>> currentUsagesFutures = new ArrayList<>(); for (SingularityOfferHolder offerHolder : offerHolders.values()) { currentUsagesFutures.add( runAsync( () -> { String agentId = offerHolder.getAgentId(); Optional<SingularityAgentUsageWithId> maybeUsage = Optional.ofNullable( currentUsages.get(agentId) ); if ( configuration.isReCheckMetricsForLargeNewTaskCount() && maybeUsage.isPresent() ) { long newTaskCount = taskManager .getActiveTaskIds() .stream() .filter( t -> t.getStartedAt() > maybeUsage.get().getTimestamp() && t.getSanitizedHost().equals(offerHolder.getSanitizedHost()) ) .count(); if (newTaskCount >= maybeUsage.get().getNumTasks() / 2) { try { MesosAgentMetricsSnapshotObject metricsSnapshot = usageHelper.getMetricsSnapshot( offerHolder.getHostname() ); if ( metricsSnapshot.getSystemLoad5Min() / metricsSnapshot.getSystemCpusTotal() > mesosConfiguration.getRecheckMetricsLoad1Threshold() || metricsSnapshot.getSystemLoad1Min() / metricsSnapshot.getSystemCpusTotal() > mesosConfiguration.getRecheckMetricsLoad5Threshold() ) { // Come back to this agent after we have collected more metrics LOG.info( "Skipping evaluation of {} until new metrics are collected. Current load is load1: {}, load5: {}", offerHolder.getHostname(), metricsSnapshot.getSystemLoad1Min(), metricsSnapshot.getSystemLoad5Min() ); currentUsages.remove(agentId); } } catch (Throwable t) { LOG.warn( "Could not check metrics for host {}, skipping", offerHolder.getHostname() ); currentUsages.remove(agentId); } } } } ) ); } CompletableFutures.allOf(currentUsagesFutures).join(); List<CompletableFuture<Void>> usagesWithScoresFutures = new ArrayList<>(); Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById = new ConcurrentHashMap<>(); for (SingularityAgentUsageWithId usage : currentUsages.values()) { if (offerHolders.containsKey(usage.getAgentId())) { usagesWithScoresFutures.add( runAsync( () -> currentUsagesById.put( usage.getAgentId(), new SingularityAgentUsageWithCalculatedScores( usage, mesosConfiguration.getScoreUsingSystemLoad(), getMaxProbableUsageForAgent( activeTaskIds, requestUtilizations, offerHolders.get(usage.getAgentId()).getSanitizedHost() ), mesosConfiguration.getLoad5OverloadedThreshold(), mesosConfiguration.getLoad1OverloadedThreshold(), usage.getTimestamp() ) ) ) ); } } CompletableFutures.allOf(usagesWithScoresFutures).join(); long startCheck = System.currentTimeMillis(); LOG.debug("Found agent usages and scores after {}ms", startCheck - start); Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache = new ConcurrentHashMap<>(); Set<String> overloadedHosts = Sets.newConcurrentHashSet(); AtomicInteger noMatches = new AtomicInteger(); // We spend much of the offer check loop for request level locks. Wait for the locks in parallel, but ensure that actual offer checks // are done in serial to not over commit a single offer ReentrantLock offerCheckTempLock = new ReentrantLock(true); CompletableFutures .allOf( sortedTaskRequestHolders .stream() .collect(Collectors.groupingBy(t -> t.getTaskRequest().getRequest().getId())) .entrySet() .stream() .map( entry -> runAsync( () -> { lock.runWithRequestLock( () -> { offerCheckTempLock.lock(); try { long startRequest = System.currentTimeMillis(); int evaluated = 0; for (SingularityTaskRequestHolder taskRequestHolder : entry.getValue()) { if ( System.currentTimeMillis() - startRequest > TimeUnit.SECONDS.toMillis(30) && // TODO - make configurable evaluated > 1 ) { LOG.warn( "{} is holding the offer lock for too long, skipping remaining {} tasks for scheduling", taskRequestHolder.getTaskRequest().getRequest().getId(), entry.getValue().size() - evaluated ); break; } evaluated++; List<SingularityTaskId> activeTaskIdsForRequest = leaderCache.getActiveTaskIdsForRequest( taskRequestHolder.getTaskRequest().getRequest().getId() ); if ( isTooManyInstancesForRequest( taskRequestHolder.getTaskRequest(), activeTaskIdsForRequest ) ) { LOG.debug( "Skipping pending task {}, too many instances already running", taskRequestHolder .getTaskRequest() .getPendingTask() .getPendingTaskId() ); continue; } Map<String, Double> scorePerOffer = new ConcurrentHashMap<>(); for (SingularityOfferHolder offerHolder : offerHolders.values()) { if (!isOfferFull(offerHolder)) { if ( calculateScore( requestUtilizations, currentUsagesById, taskRequestHolder, scorePerOffer, activeTaskIdsForRequest, offerHolder, deployStatsCache, overloadedHosts ) > mesosConfiguration.getGoodEnoughScoreThreshold() ) { break; } } } if (!scorePerOffer.isEmpty()) { SingularityOfferHolder bestOffer = offerHolders.get( Collections .max( scorePerOffer.entrySet(), Map.Entry.comparingByValue() ) .getKey() ); LOG.info( "Best offer {}/1 is on {}", scorePerOffer.get(bestOffer.getAgentId()), bestOffer.getSanitizedHost() ); SingularityMesosTaskHolder taskHolder = acceptTask( bestOffer, taskRequestHolder ); tasksScheduled.getAndIncrement(); bestOffer.addMatchedTask(taskHolder); updateAgentUsageScores( taskRequestHolder, currentUsagesById, bestOffer.getAgentId(), requestUtilizations ); } else { noMatches.getAndIncrement(); } } } finally { offerCheckTempLock.unlock(); } }, entry.getKey(), String.format("%s#%s", getClass().getSimpleName(), "checkOffers") ); } ) ) .collect(Collectors.toList()) ) .join(); LOG.info( "{} tasks scheduled, {} tasks remaining after examining {} offers ({} overloaded hosts, {} had no offer matches)", tasksScheduled, numDueTasks - tasksScheduled.get(), offers.size(), overloadedHosts.size(), noMatches.get() ); return offerHolders.values(); } private CompletableFuture<Void> runAsync(Runnable runnable) { return CompletableFuture.runAsync(runnable, offerScoringExecutor); } private double calculateScore( Map<String, RequestUtilization> requestUtilizations, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, SingularityTaskRequestHolder taskRequestHolder, Map<String, Double> scorePerOffer, List<SingularityTaskId> activeTaskIdsForRequest, SingularityOfferHolder offerHolder, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { String agentId = offerHolder.getAgentId(); double score = calculateScore( offerHolder, currentUsagesById, taskRequestHolder, activeTaskIdsForRequest, requestUtilizations.get(taskRequestHolder.getTaskRequest().getRequest().getId()), deployStatsCache, overloadedHosts ); if (score != 0) { scorePerOffer.put(agentId, score); } return score; } private MaxProbableUsage getMaxProbableUsageForAgent( List<SingularityTaskId> activeTaskIds, Map<String, RequestUtilization> requestUtilizations, String sanitizedHostname ) { double cpu = 0; double memBytes = 0; double diskBytes = 0; for (SingularityTaskId taskId : activeTaskIds) { if (taskId.getSanitizedHost().equals(sanitizedHostname)) { if (requestUtilizations.containsKey(taskId.getRequestId())) { RequestUtilization utilization = requestUtilizations.get(taskId.getRequestId()); cpu += agentAndRackHelper.getEstimatedCpuUsageForRequest(utilization); memBytes += utilization.getMaxMemBytesUsed(); diskBytes += utilization.getMaxDiskBytesUsed(); } else { Optional<SingularityTask> maybeTask = taskManager.getTask(taskId); if (maybeTask.isPresent()) { Resources resources = maybeTask .get() .getTaskRequest() .getPendingTask() .getResources() .orElse( maybeTask .get() .getTaskRequest() .getDeploy() .getResources() .orElse(defaultResources) ); cpu += resources.getCpus(); memBytes += resources.getMemoryMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE; diskBytes += resources.getDiskMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE; } } } } return new MaxProbableUsage(cpu, memBytes, diskBytes); } private boolean isOfferFull(SingularityOfferHolder offerHolder) { return ( configuration.getMaxTasksPerOffer() > 0 && offerHolder.getAcceptedTasks().size() >= configuration.getMaxTasksPerOffer() ); } private void updateAgentUsageScores( SingularityTaskRequestHolder taskHolder, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, String agentId, Map<String, RequestUtilization> requestUtilizations ) { Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage = Optional.ofNullable( currentUsagesById.get(agentId) ); if (maybeUsage.isPresent() && !maybeUsage.get().isMissingUsageData()) { SingularityAgentUsageWithCalculatedScores usage = maybeUsage.get(); usage.addEstimatedCpuReserved(taskHolder.getTotalResources().getCpus()); usage.addEstimatedMemoryReserved(taskHolder.getTotalResources().getMemoryMb()); usage.addEstimatedDiskReserved(taskHolder.getTotalResources().getDiskMb()); if ( requestUtilizations.containsKey(taskHolder.getTaskRequest().getRequest().getId()) ) { RequestUtilization requestUtilization = requestUtilizations.get( taskHolder.getTaskRequest().getRequest().getId() ); usage.addEstimatedCpuUsage(requestUtilization.getMaxCpuUsed()); usage.addEstimatedMemoryBytesUsage(requestUtilization.getMaxMemBytesUsed()); usage.addEstimatedDiskBytesUsage(requestUtilization.getMaxDiskBytesUsed()); } else { usage.addEstimatedCpuUsage(taskHolder.getTotalResources().getCpus()); usage.addEstimatedMemoryBytesUsage( taskHolder.getTotalResources().getMemoryMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE ); usage.addEstimatedDiskBytesUsage( taskHolder.getTotalResources().getDiskMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE ); } usage.recalculateScores(); } } private double calculateScore( SingularityOfferHolder offerHolder, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, SingularityTaskRequestHolder taskRequestHolder, List<SingularityTaskId> activeTaskIdsForRequest, RequestUtilization requestUtilization, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage = Optional.ofNullable( currentUsagesById.get(offerHolder.getAgentId()) ); double score = score( offerHolder, taskRequestHolder, maybeUsage, activeTaskIdsForRequest, requestUtilization, deployStatsCache, overloadedHosts ); if (LOG.isTraceEnabled()) { LOG.trace( "Scored {} | Task {} | Offer - mem {} - cpu {} | Agent {} | maybeUsage - {}", score, taskRequestHolder.getTaskRequest().getPendingTask().getPendingTaskId().getId(), MesosUtils.getMemory(offerHolder.getCurrentResources(), Optional.empty()), MesosUtils.getNumCpus(offerHolder.getCurrentResources(), Optional.empty()), offerHolder.getHostname(), maybeUsage ); } return score; } private List<SingularityTaskRequestHolder> getSortedDueTaskRequests() { final List<SingularityTaskRequest> taskRequests = taskPrioritizer.getSortedDueTasks( scheduler.getDueTasks() ); taskRequests.forEach( taskRequest -> LOG.trace("Task {} is due", taskRequest.getPendingTask().getPendingTaskId()) ); taskPrioritizer.removeTasksAffectedByPriorityFreeze(taskRequests); return taskRequests .stream() .map( taskRequest -> new SingularityTaskRequestHolder( taskRequest, defaultResources, defaultCustomExecutorResources ) ) .collect(Collectors.toList()); } private double score( SingularityOfferHolder offerHolder, SingularityTaskRequestHolder taskRequestHolder, Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage, List<SingularityTaskId> activeTaskIdsForRequest, RequestUtilization requestUtilization, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { final SingularityTaskRequest taskRequest = taskRequestHolder.getTaskRequest(); final SingularityPendingTaskId pendingTaskId = taskRequest .getPendingTask() .getPendingTaskId(); double estimatedCpusToAdd = taskRequestHolder.getTotalResources().getCpus(); if (requestUtilization != null) { estimatedCpusToAdd = agentAndRackHelper.getEstimatedCpuUsageForRequest(requestUtilization); } if ( mesosConfiguration.isOmitOverloadedHosts() && maybeUsage.isPresent() && maybeUsage.get().isCpuOverloaded(estimatedCpusToAdd) ) { overloadedHosts.add(offerHolder.getHostname()); LOG.debug( "Agent {} is overloaded (load5 {}/{}, load1 {}/{}, estimated cpus to add: {}, already committed cpus: {}), ignoring offer", offerHolder.getHostname(), maybeUsage.get().getAgentUsage().getSystemLoad5Min(), maybeUsage.get().getAgentUsage().getSystemCpusTotal(), maybeUsage.get().getAgentUsage().getSystemLoad1Min(), maybeUsage.get().getAgentUsage().getSystemCpusTotal(), estimatedCpusToAdd, maybeUsage.get().getEstimatedAddedCpusUsage() ); return 0; } if (LOG.isTraceEnabled()) { LOG.trace( "Attempting to match task {} resources {} with required role '{}' ({} for task + {} for executor) with remaining offer resources {}", pendingTaskId, taskRequestHolder.getTotalResources(), taskRequest.getRequest().getRequiredRole().orElse("*"), taskRequestHolder.getTaskResources(), taskRequestHolder.getExecutorResources(), MesosUtils.formatForLogging(offerHolder.getCurrentResources()) ); } final boolean matchesResources = MesosUtils.doesOfferMatchResources( taskRequest.getRequest().getRequiredRole(), taskRequestHolder.getTotalResources(), offerHolder.getCurrentResources(), taskRequestHolder.getRequestedPorts() ); if (!matchesResources) { return 0; } final AgentMatchState agentMatchState = agentAndRackManager.doesOfferMatch( offerHolder, taskRequest, activeTaskIdsForRequest, isPreemptibleTask(taskRequest, deployStatsCache), requestUtilization ); if (agentMatchState.isMatchAllowed()) { return score(offerHolder.getHostname(), maybeUsage, agentMatchState); } else if (LOG.isTraceEnabled()) { LOG.trace( "Ignoring offer on host {} with roles {} on {} for task {}; matched resources: {}, agent match state: {}", offerHolder.getHostname(), offerHolder.getRoles(), offerHolder.getHostname(), pendingTaskId, matchesResources, agentMatchState ); } return 0; } private boolean isPreemptibleTask( SingularityTaskRequest taskRequest, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache ) { // A long running task can be replaced + killed easily if (taskRequest.getRequest().getRequestType().isLongRunning()) { return true; } // A short, non-long-running task Optional<SingularityDeployStatistics> deployStatistics = deployStatsCache.computeIfAbsent( new SingularityDeployKey( taskRequest.getRequest().getId(), taskRequest.getDeploy().getId() ), key -> deployManager.getDeployStatistics( taskRequest.getRequest().getId(), taskRequest.getDeploy().getId() ) ); return ( deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() && deployStatistics.get().getAverageRuntimeMillis().get() < configuration.getPreemptibleTaskMaxExpectedRuntimeMs() ); } @VisibleForTesting double score( String hostname, Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage, AgentMatchState agentMatchState ) { if (!maybeUsage.isPresent() || maybeUsage.get().isMissingUsageData()) { if (mesosConfiguration.isOmitForMissingUsageData()) { LOG.info("Skipping agent {} with missing usage data ({})", hostname, maybeUsage); return 0.0; } else { LOG.info( "Agent {} has missing usage data ({}). Will default to {}", hostname, maybeUsage, 0.5 ); return 0.5; } } SingularityAgentUsageWithCalculatedScores agentUsageWithScores = maybeUsage.get(); double calculatedScore = calculateScore( 1 - agentUsageWithScores.getMemAllocatedScore(), agentUsageWithScores.getMemInUseScore(), 1 - agentUsageWithScores.getCpusAllocatedScore(), agentUsageWithScores.getCpusInUseScore(), 1 - agentUsageWithScores.getDiskAllocatedScore(), agentUsageWithScores.getDiskInUseScore(), mesosConfiguration.getInUseResourceWeight(), mesosConfiguration.getAllocatedResourceWeight() ); if (agentMatchState == AgentMatchState.PREFERRED_AGENT) { LOG.debug( "Agent {} is preferred, will scale score by {}", hostname, configuration.getPreferredAgentScaleFactor() ); calculatedScore *= configuration.getPreferredAgentScaleFactor(); } return calculatedScore; } private double calculateScore( double memAllocatedScore, double memInUseScore, double cpusAllocatedScore, double cpusInUseScore, double diskAllocatedScore, double diskInUseScore, double inUseResourceWeight, double allocatedResourceWeight ) { double score = 0; score += (normalizedCpuWeight * allocatedResourceWeight) * cpusAllocatedScore; score += (normalizedMemWeight * allocatedResourceWeight) * memAllocatedScore; score += (normalizedDiskWeight * allocatedResourceWeight) * diskAllocatedScore; score += (normalizedCpuWeight * inUseResourceWeight) * cpusInUseScore; score += (normalizedMemWeight * inUseResourceWeight) * memInUseScore; score += (normalizedDiskWeight * inUseResourceWeight) * diskInUseScore; return score; } private SingularityMesosTaskHolder acceptTask( SingularityOfferHolder offerHolder, SingularityTaskRequestHolder taskRequestHolder ) { final SingularityTaskRequest taskRequest = taskRequestHolder.getTaskRequest(); final SingularityMesosTaskHolder taskHolder = mesosTaskBuilder.buildTask( offerHolder, offerHolder.getCurrentResources(), taskRequest, taskRequestHolder.getTaskResources(), taskRequestHolder.getExecutorResources() ); final SingularityTask zkTask = taskSizeOptimizer.getSizeOptimizedTask(taskHolder); LOG.trace("Accepted and built task {}", zkTask); LOG.info( "Launching task {} slot on agent {} ({})", taskHolder.getTask().getTaskId(), offerHolder.getAgentId(), offerHolder.getHostname() ); taskManager.createTaskAndDeletePendingTask(zkTask); return taskHolder; } private boolean isTooManyInstancesForRequest( SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest ) { if (taskRequest.getRequest().getRequestType() == RequestType.ON_DEMAND) { int maxActiveOnDemandTasks = taskRequest .getRequest() .getInstances() .orElse(configuration.getMaxActiveOnDemandTasksPerRequest()); if (maxActiveOnDemandTasks > 0) { int activeTasksForRequest = activeTaskIdsForRequest.size(); LOG.debug( "Running {} instances for request {}. Max is {}", activeTasksForRequest, taskRequest.getRequest().getId(), maxActiveOnDemandTasks ); if (activeTasksForRequest >= maxActiveOnDemandTasks) { return true; } } } return false; } }
SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java
package com.hubspot.singularity.mesos; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.hubspot.mesos.JavaUtils; import com.hubspot.mesos.Resources; import com.hubspot.mesos.json.MesosAgentMetricsSnapshotObject; import com.hubspot.singularity.AgentMatchState; import com.hubspot.singularity.RequestType; import com.hubspot.singularity.RequestUtilization; import com.hubspot.singularity.SingularityAction; import com.hubspot.singularity.SingularityAgentUsage; import com.hubspot.singularity.SingularityAgentUsageWithId; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityDeployStatistics; import com.hubspot.singularity.SingularityManagedThreadPoolFactory; import com.hubspot.singularity.SingularityPendingTaskId; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskRequest; import com.hubspot.singularity.async.CompletableFutures; import com.hubspot.singularity.config.CustomExecutorConfiguration; import com.hubspot.singularity.config.MesosConfiguration; import com.hubspot.singularity.config.SingularityConfiguration; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.DisasterManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.usage.UsageManager; import com.hubspot.singularity.helpers.MesosUtils; import com.hubspot.singularity.helpers.SingularityMesosTaskHolder; import com.hubspot.singularity.mesos.SingularityAgentAndRackManager.CheckResult; import com.hubspot.singularity.mesos.SingularityAgentUsageWithCalculatedScores.MaxProbableUsage; import com.hubspot.singularity.mesos.SingularityOfferCache.CachedOffer; import com.hubspot.singularity.scheduler.SingularityLeaderCache; import com.hubspot.singularity.scheduler.SingularityScheduler; import com.hubspot.singularity.scheduler.SingularityUsageHelper; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Function; import java.util.stream.Collectors; import javax.inject.Singleton; import org.apache.mesos.v1.Protos.Offer; import org.apache.mesos.v1.Protos.OfferID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class SingularityMesosOfferScheduler { private static final Logger LOG = LoggerFactory.getLogger( SingularityMesosOfferScheduler.class ); private final Resources defaultResources; private final Resources defaultCustomExecutorResources; private final TaskManager taskManager; private final SingularityMesosTaskPrioritizer taskPrioritizer; private final SingularityScheduler scheduler; private final SingularityConfiguration configuration; private final MesosConfiguration mesosConfiguration; private final SingularityMesosTaskBuilder mesosTaskBuilder; private final SingularityAgentAndRackManager agentAndRackManager; private final SingularityAgentAndRackHelper agentAndRackHelper; private final SingularityTaskSizeOptimizer taskSizeOptimizer; private final SingularityUsageHelper usageHelper; private final UsageManager usageManager; private final DeployManager deployManager; private final SingularitySchedulerLock lock; private final SingularityLeaderCache leaderCache; private final boolean offerCacheEnabled; private final DisasterManager disasterManager; private final SingularityMesosSchedulerClient mesosSchedulerClient; private final OfferCache offerCache; private final double normalizedCpuWeight; private final double normalizedMemWeight; private final double normalizedDiskWeight; private final ExecutorService offerScoringExecutor; @Inject public SingularityMesosOfferScheduler( MesosConfiguration mesosConfiguration, CustomExecutorConfiguration customExecutorConfiguration, TaskManager taskManager, SingularityMesosTaskPrioritizer taskPrioritizer, SingularityScheduler scheduler, SingularityConfiguration configuration, SingularityMesosTaskBuilder mesosTaskBuilder, SingularityAgentAndRackManager agentAndRackManager, SingularityTaskSizeOptimizer taskSizeOptimizer, SingularityAgentAndRackHelper agentAndRackHelper, SingularityLeaderCache leaderCache, SingularityUsageHelper usageHelper, UsageManager usageManager, DeployManager deployManager, SingularitySchedulerLock lock, SingularityManagedThreadPoolFactory threadPoolFactory, DisasterManager disasterManager, SingularityMesosSchedulerClient mesosSchedulerClient, OfferCache offerCache ) { this.defaultResources = new Resources( mesosConfiguration.getDefaultCpus(), mesosConfiguration.getDefaultMemory(), 0, mesosConfiguration.getDefaultDisk() ); this.defaultCustomExecutorResources = new Resources( customExecutorConfiguration.getNumCpus(), customExecutorConfiguration.getMemoryMb(), 0, customExecutorConfiguration.getDiskMb() ); this.taskManager = taskManager; this.scheduler = scheduler; this.configuration = configuration; this.mesosConfiguration = mesosConfiguration; this.mesosTaskBuilder = mesosTaskBuilder; this.agentAndRackManager = agentAndRackManager; this.taskSizeOptimizer = taskSizeOptimizer; this.leaderCache = leaderCache; this.offerCacheEnabled = configuration.isCacheOffers(); this.disasterManager = disasterManager; this.mesosSchedulerClient = mesosSchedulerClient; this.offerCache = offerCache; this.usageHelper = usageHelper; this.agentAndRackHelper = agentAndRackHelper; this.taskPrioritizer = taskPrioritizer; this.usageManager = usageManager; this.deployManager = deployManager; this.lock = lock; double cpuWeight = mesosConfiguration.getCpuWeight(); double memWeight = mesosConfiguration.getMemWeight(); double diskWeight = mesosConfiguration.getDiskWeight(); if (cpuWeight + memWeight + diskWeight != 1) { this.normalizedCpuWeight = cpuWeight / (cpuWeight + memWeight + diskWeight); this.normalizedMemWeight = memWeight / (cpuWeight + memWeight + diskWeight); this.normalizedDiskWeight = diskWeight / (cpuWeight + memWeight + diskWeight); } else { this.normalizedCpuWeight = cpuWeight; this.normalizedMemWeight = memWeight; this.normalizedDiskWeight = diskWeight; } this.offerScoringExecutor = threadPoolFactory.get("offer-scoring", configuration.getCoreThreadpoolSize()); } public void resourceOffers(List<Offer> uncached) { final long start = System.currentTimeMillis(); LOG.info("Received {} offer(s)", uncached.size()); scheduler.checkForDecomissions(); boolean declineImmediately = false; if (disasterManager.isDisabled(SingularityAction.PROCESS_OFFERS)) { LOG.info( "Processing offers is currently disabled, declining {} offers", uncached.size() ); declineImmediately = true; } if (declineImmediately) { mesosSchedulerClient.decline( uncached.stream().map(Offer::getId).collect(Collectors.toList()) ); return; } if (offerCacheEnabled) { if (disasterManager.isDisabled(SingularityAction.CACHE_OFFERS)) { offerCache.disableOfferCache(); } else { offerCache.enableOfferCache(); } } Map<String, Offer> offersToCheck = uncached .stream() .filter( o -> { if (!isValidOffer(o)) { if (o.getId() != null && o.getId().getValue() != null) { LOG.warn("Got invalid offer {}", o); mesosSchedulerClient.decline(Collections.singletonList(o.getId())); } else { LOG.warn( "Offer {} was not valid, but we can't decline it because we have no offer ID!", o ); } return false; } return true; } ) .collect( Collectors.toConcurrentMap(o -> o.getId().getValue(), Function.identity()) ); List<CachedOffer> cachedOfferList = offerCache.checkoutOffers(); Map<String, CachedOffer> cachedOffers = new ConcurrentHashMap<>(); for (CachedOffer cachedOffer : cachedOfferList) { if (isValidOffer(cachedOffer.getOffer())) { cachedOffers.put(cachedOffer.getOfferId(), cachedOffer); offersToCheck.put(cachedOffer.getOfferId(), cachedOffer.getOffer()); } else if ( cachedOffer.getOffer().getId() != null && cachedOffer.getOffer().getId().getValue() != null ) { mesosSchedulerClient.decline( Collections.singletonList(cachedOffer.getOffer().getId()) ); offerCache.rescindOffer(cachedOffer.getOffer().getId()); } else { LOG.warn( "Offer {} was not valid, but we can't decline it because we have no offer ID!", cachedOffer ); } } List<CompletableFuture<Void>> checkFutures = new ArrayList<>(); uncached.forEach( offer -> checkFutures.add(runAsync(() -> checkOfferAndAgent(offer, offersToCheck))) ); CompletableFutures.allOf(checkFutures).join(); final Set<OfferID> acceptedOffers = Sets.newHashSetWithExpectedSize( offersToCheck.size() ); try { Collection<SingularityOfferHolder> offerHolders = checkOffers(offersToCheck, start); for (SingularityOfferHolder offerHolder : offerHolders) { if (!offerHolder.getAcceptedTasks().isEmpty()) { List<Offer> leftoverOffers = offerHolder.launchTasksAndGetUnusedOffers( mesosSchedulerClient ); leftoverOffers.forEach( o -> { if (cachedOffers.containsKey(o.getId().getValue())) { offerCache.returnOffer(cachedOffers.remove(o.getId().getValue())); } else { offerCache.cacheOffer(start, o); } } ); List<Offer> offersAcceptedFrom = offerHolder.getOffers(); offersAcceptedFrom.removeAll(leftoverOffers); offersAcceptedFrom .stream() .filter(offer -> cachedOffers.containsKey(offer.getId().getValue())) .map(o -> cachedOffers.remove(o.getId().getValue())) .forEach(offerCache::useOffer); acceptedOffers.addAll( offersAcceptedFrom.stream().map(Offer::getId).collect(Collectors.toList()) ); } else { offerHolder .getOffers() .forEach( o -> { if (cachedOffers.containsKey(o.getId().getValue())) { offerCache.returnOffer(cachedOffers.remove(o.getId().getValue())); } else { offerCache.cacheOffer(start, o); } } ); } } LOG.info( "{} remaining offers not accounted for in offer check", cachedOffers.size() ); cachedOffers.values().forEach(offerCache::returnOffer); } catch (Throwable t) { LOG.error( "Received fatal error while handling offers - will decline all available offers", t ); mesosSchedulerClient.decline( offersToCheck .values() .stream() .filter( o -> { if (o == null || o.getId() == null || o.getId().getValue() == null) { LOG.warn("Got bad offer {} while trying to decline offers!", o); return false; } return true; } ) .filter( o -> !acceptedOffers.contains(o.getId()) && !cachedOffers.containsKey(o.getId().getValue()) ) .map(Offer::getId) .collect(Collectors.toList()) ); offersToCheck.forEach( (id, o) -> { if (cachedOffers.containsKey(id)) { offerCache.returnOffer(cachedOffers.get(id)); } } ); throw t; } LOG.info( "Finished handling {} new offer(s) {} from cache ({}), {} accepted, {} declined/cached", uncached.size(), cachedOffers.size(), JavaUtils.duration(start), acceptedOffers.size(), uncached.size() + cachedOffers.size() - acceptedOffers.size() ); } private void checkOfferAndAgent(Offer offer, Map<String, Offer> offersToCheck) { String rolesInfo = MesosUtils.getRoles(offer).toString(); LOG.debug( "Received offer ID {} with roles {} from {} ({}) for {} cpu(s), {} memory, {} ports, and {} disk", offer.getId().getValue(), rolesInfo, offer.getHostname(), offer.getAgentId().getValue(), MesosUtils.getNumCpus(offer), MesosUtils.getMemory(offer), MesosUtils.getNumPorts(offer), MesosUtils.getDisk(offer) ); CheckResult checkResult = agentAndRackManager.checkOffer(offer); if (checkResult == CheckResult.NOT_ACCEPTING_TASKS) { mesosSchedulerClient.decline(Collections.singletonList(offer.getId())); offersToCheck.remove(offer.getId().getValue()); LOG.debug( "Will decline offer {}, agent {} is not currently in a state to launch tasks", offer.getId().getValue(), offer.getHostname() ); } } private boolean isValidOffer(Offer offer) { if (offer.getId() == null || offer.getId().getValue() == null) { LOG.warn("Received offer with null ID, skipping ({})", offer); return false; } if (offer.getAgentId() == null || offer.getAgentId().getValue() == null) { LOG.warn("Received offer with null agent ID, skipping ({})", offer); return false; } return true; } Collection<SingularityOfferHolder> checkOffers( final Map<String, Offer> offers, long start ) { if (offers.isEmpty()) { LOG.debug("No offers to check"); return Collections.emptyList(); } final List<SingularityTaskRequestHolder> sortedTaskRequestHolders = getSortedDueTaskRequests(); final int numDueTasks = sortedTaskRequestHolders.size(); final Map<String, SingularityOfferHolder> offerHolders = offers .values() .stream() .collect(Collectors.groupingBy(o -> o.getAgentId().getValue())) .entrySet() .stream() .filter(e -> e.getValue().size() > 0) .map( e -> { List<Offer> offersList = e.getValue(); String agentId = e.getKey(); return new SingularityOfferHolder( offersList, numDueTasks, agentAndRackHelper.getRackIdOrDefault(offersList.get(0)), agentId, offersList.get(0).getHostname(), agentAndRackHelper.getTextAttributes(offersList.get(0)), agentAndRackHelper.getReservedAgentAttributes(offersList.get(0)) ); } ) .collect(Collectors.toMap(SingularityOfferHolder::getAgentId, Function.identity())); if (sortedTaskRequestHolders.isEmpty()) { return offerHolders.values(); } final AtomicInteger tasksScheduled = new AtomicInteger(0); Map<String, RequestUtilization> requestUtilizations = usageManager.getRequestUtilizations( false ); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIds(); Map<String, SingularityAgentUsageWithId> currentUsages = usageManager.getAllCurrentAgentUsage(); List<CompletableFuture<Void>> currentUsagesFutures = new ArrayList<>(); for (SingularityOfferHolder offerHolder : offerHolders.values()) { currentUsagesFutures.add( runAsync( () -> { String agentId = offerHolder.getAgentId(); Optional<SingularityAgentUsageWithId> maybeUsage = Optional.ofNullable( currentUsages.get(agentId) ); if ( configuration.isReCheckMetricsForLargeNewTaskCount() && maybeUsage.isPresent() ) { long newTaskCount = taskManager .getActiveTaskIds() .stream() .filter( t -> t.getStartedAt() > maybeUsage.get().getTimestamp() && t.getSanitizedHost().equals(offerHolder.getSanitizedHost()) ) .count(); if (newTaskCount >= maybeUsage.get().getNumTasks() / 2) { try { MesosAgentMetricsSnapshotObject metricsSnapshot = usageHelper.getMetricsSnapshot( offerHolder.getHostname() ); if ( metricsSnapshot.getSystemLoad5Min() / metricsSnapshot.getSystemCpusTotal() > mesosConfiguration.getRecheckMetricsLoad1Threshold() || metricsSnapshot.getSystemLoad1Min() / metricsSnapshot.getSystemCpusTotal() > mesosConfiguration.getRecheckMetricsLoad5Threshold() ) { // Come back to this agent after we have collected more metrics LOG.info( "Skipping evaluation of {} until new metrics are collected. Current load is load1: {}, load5: {}", offerHolder.getHostname(), metricsSnapshot.getSystemLoad1Min(), metricsSnapshot.getSystemLoad5Min() ); currentUsages.remove(agentId); } } catch (Throwable t) { LOG.warn( "Could not check metrics for host {}, skipping", offerHolder.getHostname() ); currentUsages.remove(agentId); } } } } ) ); } CompletableFutures.allOf(currentUsagesFutures).join(); List<CompletableFuture<Void>> usagesWithScoresFutures = new ArrayList<>(); Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById = new ConcurrentHashMap<>(); for (SingularityAgentUsageWithId usage : currentUsages.values()) { if (offerHolders.containsKey(usage.getAgentId())) { usagesWithScoresFutures.add( runAsync( () -> currentUsagesById.put( usage.getAgentId(), new SingularityAgentUsageWithCalculatedScores( usage, mesosConfiguration.getScoreUsingSystemLoad(), getMaxProbableUsageForAgent( activeTaskIds, requestUtilizations, offerHolders.get(usage.getAgentId()).getSanitizedHost() ), mesosConfiguration.getLoad5OverloadedThreshold(), mesosConfiguration.getLoad1OverloadedThreshold(), usage.getTimestamp() ) ) ) ); } } CompletableFutures.allOf(usagesWithScoresFutures).join(); long startCheck = System.currentTimeMillis(); LOG.debug("Found agent usages and scores after {}ms", startCheck - start); Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache = new ConcurrentHashMap<>(); Set<String> overloadedHosts = Sets.newConcurrentHashSet(); AtomicInteger noMatches = new AtomicInteger(); // We spend much of the offer check loop for request level locks. Wait for the locks in parallel, but ensure that actual offer checks // are done in serial to not over commit a single offer ReentrantLock offerCheckTempLock = new ReentrantLock(true); CompletableFutures .allOf( sortedTaskRequestHolders .stream() .collect(Collectors.groupingBy(t -> t.getTaskRequest().getRequest().getId())) .entrySet() .stream() .map( entry -> runAsync( () -> { lock.runWithRequestLock( () -> { offerCheckTempLock.lock(); try { for (SingularityTaskRequestHolder taskRequestHolder : entry.getValue()) { List<SingularityTaskId> activeTaskIdsForRequest = leaderCache.getActiveTaskIdsForRequest( taskRequestHolder.getTaskRequest().getRequest().getId() ); if ( isTooManyInstancesForRequest( taskRequestHolder.getTaskRequest(), activeTaskIdsForRequest ) ) { LOG.debug( "Skipping pending task {}, too many instances already running", taskRequestHolder .getTaskRequest() .getPendingTask() .getPendingTaskId() ); continue; } Map<String, Double> scorePerOffer = new ConcurrentHashMap<>(); for (SingularityOfferHolder offerHolder : offerHolders.values()) { if (!isOfferFull(offerHolder)) { if ( calculateScore( requestUtilizations, currentUsagesById, taskRequestHolder, scorePerOffer, activeTaskIdsForRequest, offerHolder, deployStatsCache, overloadedHosts ) > mesosConfiguration.getGoodEnoughScoreThreshold() ) { break; } } } if (!scorePerOffer.isEmpty()) { SingularityOfferHolder bestOffer = offerHolders.get( Collections .max( scorePerOffer.entrySet(), Map.Entry.comparingByValue() ) .getKey() ); LOG.info( "Best offer {}/1 is on {}", scorePerOffer.get(bestOffer.getAgentId()), bestOffer.getSanitizedHost() ); SingularityMesosTaskHolder taskHolder = acceptTask( bestOffer, taskRequestHolder ); tasksScheduled.getAndIncrement(); bestOffer.addMatchedTask(taskHolder); updateAgentUsageScores( taskRequestHolder, currentUsagesById, bestOffer.getAgentId(), requestUtilizations ); } else { noMatches.getAndIncrement(); } } } finally { offerCheckTempLock.unlock(); } }, entry.getKey(), String.format("%s#%s", getClass().getSimpleName(), "checkOffers") ); } ) ) .collect(Collectors.toList()) ) .join(); LOG.info( "{} tasks scheduled, {} tasks remaining after examining {} offers ({} overloaded hosts, {} had no offer matches)", tasksScheduled, numDueTasks - tasksScheduled.get(), offers.size(), overloadedHosts.size(), noMatches.get() ); return offerHolders.values(); } private CompletableFuture<Void> runAsync(Runnable runnable) { return CompletableFuture.runAsync(runnable, offerScoringExecutor); } private double calculateScore( Map<String, RequestUtilization> requestUtilizations, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, SingularityTaskRequestHolder taskRequestHolder, Map<String, Double> scorePerOffer, List<SingularityTaskId> activeTaskIdsForRequest, SingularityOfferHolder offerHolder, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { String agentId = offerHolder.getAgentId(); double score = calculateScore( offerHolder, currentUsagesById, taskRequestHolder, activeTaskIdsForRequest, requestUtilizations.get(taskRequestHolder.getTaskRequest().getRequest().getId()), deployStatsCache, overloadedHosts ); if (score != 0) { scorePerOffer.put(agentId, score); } return score; } private MaxProbableUsage getMaxProbableUsageForAgent( List<SingularityTaskId> activeTaskIds, Map<String, RequestUtilization> requestUtilizations, String sanitizedHostname ) { double cpu = 0; double memBytes = 0; double diskBytes = 0; for (SingularityTaskId taskId : activeTaskIds) { if (taskId.getSanitizedHost().equals(sanitizedHostname)) { if (requestUtilizations.containsKey(taskId.getRequestId())) { RequestUtilization utilization = requestUtilizations.get(taskId.getRequestId()); cpu += agentAndRackHelper.getEstimatedCpuUsageForRequest(utilization); memBytes += utilization.getMaxMemBytesUsed(); diskBytes += utilization.getMaxDiskBytesUsed(); } else { Optional<SingularityTask> maybeTask = taskManager.getTask(taskId); if (maybeTask.isPresent()) { Resources resources = maybeTask .get() .getTaskRequest() .getPendingTask() .getResources() .orElse( maybeTask .get() .getTaskRequest() .getDeploy() .getResources() .orElse(defaultResources) ); cpu += resources.getCpus(); memBytes += resources.getMemoryMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE; diskBytes += resources.getDiskMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE; } } } } return new MaxProbableUsage(cpu, memBytes, diskBytes); } private boolean isOfferFull(SingularityOfferHolder offerHolder) { return ( configuration.getMaxTasksPerOffer() > 0 && offerHolder.getAcceptedTasks().size() >= configuration.getMaxTasksPerOffer() ); } private void updateAgentUsageScores( SingularityTaskRequestHolder taskHolder, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, String agentId, Map<String, RequestUtilization> requestUtilizations ) { Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage = Optional.ofNullable( currentUsagesById.get(agentId) ); if (maybeUsage.isPresent() && !maybeUsage.get().isMissingUsageData()) { SingularityAgentUsageWithCalculatedScores usage = maybeUsage.get(); usage.addEstimatedCpuReserved(taskHolder.getTotalResources().getCpus()); usage.addEstimatedMemoryReserved(taskHolder.getTotalResources().getMemoryMb()); usage.addEstimatedDiskReserved(taskHolder.getTotalResources().getDiskMb()); if ( requestUtilizations.containsKey(taskHolder.getTaskRequest().getRequest().getId()) ) { RequestUtilization requestUtilization = requestUtilizations.get( taskHolder.getTaskRequest().getRequest().getId() ); usage.addEstimatedCpuUsage(requestUtilization.getMaxCpuUsed()); usage.addEstimatedMemoryBytesUsage(requestUtilization.getMaxMemBytesUsed()); usage.addEstimatedDiskBytesUsage(requestUtilization.getMaxDiskBytesUsed()); } else { usage.addEstimatedCpuUsage(taskHolder.getTotalResources().getCpus()); usage.addEstimatedMemoryBytesUsage( taskHolder.getTotalResources().getMemoryMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE ); usage.addEstimatedDiskBytesUsage( taskHolder.getTotalResources().getDiskMb() * SingularityAgentUsage.BYTES_PER_MEGABYTE ); } usage.recalculateScores(); } } private double calculateScore( SingularityOfferHolder offerHolder, Map<String, SingularityAgentUsageWithCalculatedScores> currentUsagesById, SingularityTaskRequestHolder taskRequestHolder, List<SingularityTaskId> activeTaskIdsForRequest, RequestUtilization requestUtilization, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage = Optional.ofNullable( currentUsagesById.get(offerHolder.getAgentId()) ); double score = score( offerHolder, taskRequestHolder, maybeUsage, activeTaskIdsForRequest, requestUtilization, deployStatsCache, overloadedHosts ); if (LOG.isTraceEnabled()) { LOG.trace( "Scored {} | Task {} | Offer - mem {} - cpu {} | Agent {} | maybeUsage - {}", score, taskRequestHolder.getTaskRequest().getPendingTask().getPendingTaskId().getId(), MesosUtils.getMemory(offerHolder.getCurrentResources(), Optional.empty()), MesosUtils.getNumCpus(offerHolder.getCurrentResources(), Optional.empty()), offerHolder.getHostname(), maybeUsage ); } return score; } private List<SingularityTaskRequestHolder> getSortedDueTaskRequests() { final List<SingularityTaskRequest> taskRequests = taskPrioritizer.getSortedDueTasks( scheduler.getDueTasks() ); taskRequests.forEach( taskRequest -> LOG.trace("Task {} is due", taskRequest.getPendingTask().getPendingTaskId()) ); taskPrioritizer.removeTasksAffectedByPriorityFreeze(taskRequests); return taskRequests .stream() .map( taskRequest -> new SingularityTaskRequestHolder( taskRequest, defaultResources, defaultCustomExecutorResources ) ) .collect(Collectors.toList()); } private double score( SingularityOfferHolder offerHolder, SingularityTaskRequestHolder taskRequestHolder, Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage, List<SingularityTaskId> activeTaskIdsForRequest, RequestUtilization requestUtilization, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache, Set<String> overloadedHosts ) { final SingularityTaskRequest taskRequest = taskRequestHolder.getTaskRequest(); final SingularityPendingTaskId pendingTaskId = taskRequest .getPendingTask() .getPendingTaskId(); double estimatedCpusToAdd = taskRequestHolder.getTotalResources().getCpus(); if (requestUtilization != null) { estimatedCpusToAdd = agentAndRackHelper.getEstimatedCpuUsageForRequest(requestUtilization); } if ( mesosConfiguration.isOmitOverloadedHosts() && maybeUsage.isPresent() && maybeUsage.get().isCpuOverloaded(estimatedCpusToAdd) ) { overloadedHosts.add(offerHolder.getHostname()); LOG.debug( "Agent {} is overloaded (load5 {}/{}, load1 {}/{}, estimated cpus to add: {}, already committed cpus: {}), ignoring offer", offerHolder.getHostname(), maybeUsage.get().getAgentUsage().getSystemLoad5Min(), maybeUsage.get().getAgentUsage().getSystemCpusTotal(), maybeUsage.get().getAgentUsage().getSystemLoad1Min(), maybeUsage.get().getAgentUsage().getSystemCpusTotal(), estimatedCpusToAdd, maybeUsage.get().getEstimatedAddedCpusUsage() ); return 0; } if (LOG.isTraceEnabled()) { LOG.trace( "Attempting to match task {} resources {} with required role '{}' ({} for task + {} for executor) with remaining offer resources {}", pendingTaskId, taskRequestHolder.getTotalResources(), taskRequest.getRequest().getRequiredRole().orElse("*"), taskRequestHolder.getTaskResources(), taskRequestHolder.getExecutorResources(), MesosUtils.formatForLogging(offerHolder.getCurrentResources()) ); } final boolean matchesResources = MesosUtils.doesOfferMatchResources( taskRequest.getRequest().getRequiredRole(), taskRequestHolder.getTotalResources(), offerHolder.getCurrentResources(), taskRequestHolder.getRequestedPorts() ); if (!matchesResources) { return 0; } final AgentMatchState agentMatchState = agentAndRackManager.doesOfferMatch( offerHolder, taskRequest, activeTaskIdsForRequest, isPreemptibleTask(taskRequest, deployStatsCache), requestUtilization ); if (agentMatchState.isMatchAllowed()) { return score(offerHolder.getHostname(), maybeUsage, agentMatchState); } else if (LOG.isTraceEnabled()) { LOG.trace( "Ignoring offer on host {} with roles {} on {} for task {}; matched resources: {}, agent match state: {}", offerHolder.getHostname(), offerHolder.getRoles(), offerHolder.getHostname(), pendingTaskId, matchesResources, agentMatchState ); } return 0; } private boolean isPreemptibleTask( SingularityTaskRequest taskRequest, Map<SingularityDeployKey, Optional<SingularityDeployStatistics>> deployStatsCache ) { // A long running task can be replaced + killed easily if (taskRequest.getRequest().getRequestType().isLongRunning()) { return true; } // A short, non-long-running task Optional<SingularityDeployStatistics> deployStatistics = deployStatsCache.computeIfAbsent( new SingularityDeployKey( taskRequest.getRequest().getId(), taskRequest.getDeploy().getId() ), key -> deployManager.getDeployStatistics( taskRequest.getRequest().getId(), taskRequest.getDeploy().getId() ) ); return ( deployStatistics.isPresent() && deployStatistics.get().getAverageRuntimeMillis().isPresent() && deployStatistics.get().getAverageRuntimeMillis().get() < configuration.getPreemptibleTaskMaxExpectedRuntimeMs() ); } @VisibleForTesting double score( String hostname, Optional<SingularityAgentUsageWithCalculatedScores> maybeUsage, AgentMatchState agentMatchState ) { if (!maybeUsage.isPresent() || maybeUsage.get().isMissingUsageData()) { if (mesosConfiguration.isOmitForMissingUsageData()) { LOG.info("Skipping agent {} with missing usage data ({})", hostname, maybeUsage); return 0.0; } else { LOG.info( "Agent {} has missing usage data ({}). Will default to {}", hostname, maybeUsage, 0.5 ); return 0.5; } } SingularityAgentUsageWithCalculatedScores agentUsageWithScores = maybeUsage.get(); double calculatedScore = calculateScore( 1 - agentUsageWithScores.getMemAllocatedScore(), agentUsageWithScores.getMemInUseScore(), 1 - agentUsageWithScores.getCpusAllocatedScore(), agentUsageWithScores.getCpusInUseScore(), 1 - agentUsageWithScores.getDiskAllocatedScore(), agentUsageWithScores.getDiskInUseScore(), mesosConfiguration.getInUseResourceWeight(), mesosConfiguration.getAllocatedResourceWeight() ); if (agentMatchState == AgentMatchState.PREFERRED_AGENT) { LOG.debug( "Agent {} is preferred, will scale score by {}", hostname, configuration.getPreferredAgentScaleFactor() ); calculatedScore *= configuration.getPreferredAgentScaleFactor(); } return calculatedScore; } private double calculateScore( double memAllocatedScore, double memInUseScore, double cpusAllocatedScore, double cpusInUseScore, double diskAllocatedScore, double diskInUseScore, double inUseResourceWeight, double allocatedResourceWeight ) { double score = 0; score += (normalizedCpuWeight * allocatedResourceWeight) * cpusAllocatedScore; score += (normalizedMemWeight * allocatedResourceWeight) * memAllocatedScore; score += (normalizedDiskWeight * allocatedResourceWeight) * diskAllocatedScore; score += (normalizedCpuWeight * inUseResourceWeight) * cpusInUseScore; score += (normalizedMemWeight * inUseResourceWeight) * memInUseScore; score += (normalizedDiskWeight * inUseResourceWeight) * diskInUseScore; return score; } private SingularityMesosTaskHolder acceptTask( SingularityOfferHolder offerHolder, SingularityTaskRequestHolder taskRequestHolder ) { final SingularityTaskRequest taskRequest = taskRequestHolder.getTaskRequest(); final SingularityMesosTaskHolder taskHolder = mesosTaskBuilder.buildTask( offerHolder, offerHolder.getCurrentResources(), taskRequest, taskRequestHolder.getTaskResources(), taskRequestHolder.getExecutorResources() ); final SingularityTask zkTask = taskSizeOptimizer.getSizeOptimizedTask(taskHolder); LOG.trace("Accepted and built task {}", zkTask); LOG.info( "Launching task {} slot on agent {} ({})", taskHolder.getTask().getTaskId(), offerHolder.getAgentId(), offerHolder.getHostname() ); taskManager.createTaskAndDeletePendingTask(zkTask); return taskHolder; } private boolean isTooManyInstancesForRequest( SingularityTaskRequest taskRequest, List<SingularityTaskId> activeTaskIdsForRequest ) { if (taskRequest.getRequest().getRequestType() == RequestType.ON_DEMAND) { int maxActiveOnDemandTasks = taskRequest .getRequest() .getInstances() .orElse(configuration.getMaxActiveOnDemandTasksPerRequest()); if (maxActiveOnDemandTasks > 0) { int activeTasksForRequest = activeTaskIdsForRequest.size(); LOG.debug( "Running {} instances for request {}. Max is {}", activeTasksForRequest, taskRequest.getRequest().getId(), maxActiveOnDemandTasks ); if (activeTasksForRequest >= maxActiveOnDemandTasks) { return true; } } } return false; } }
Add timeout within offer loop for single request taking too long
SingularityService/src/main/java/com/hubspot/singularity/mesos/SingularityMesosOfferScheduler.java
Add timeout within offer loop for single request taking too long