gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/** * 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.drill; import static org.junit.Assert.assertEquals; import org.apache.drill.categories.PlannerTest; import org.apache.drill.categories.SqlTest; import org.apache.drill.categories.UnlikelyTest; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import java.nio.file.Paths; @Category({SqlTest.class, PlannerTest.class}) public class TestPartitionFilter extends PlanTestBase { private static void testExcludeFilter(String query, int expectedNumFiles, String excludedFilterPattern, int expectedRowCount) throws Exception { int actualRowCount = testSql(query); assertEquals(expectedRowCount, actualRowCount); String numFilesPattern = "numFiles=" + expectedNumFiles; testPlanMatchingPatterns(query, new String[]{numFilesPattern}, new String[]{excludedFilterPattern}); } private static void testIncludeFilter(String query, int expectedNumFiles, String includedFilterPattern, int expectedRowCount) throws Exception { int actualRowCount = testSql(query); assertEquals(expectedRowCount, actualRowCount); String numFilesPattern = "numFiles=" + expectedNumFiles; testPlanMatchingPatterns(query, new String[]{numFilesPattern, includedFilterPattern}, new String[]{}); } @BeforeClass public static void createParquetTable() throws Exception { dirTestWatcher.copyResourceToRoot(Paths.get("multilevel")); test("alter session set `planner.disable_exchanges` = true"); test("create table dfs.tmp.parquet partition by (yr, qrtr) as select o_orderkey, o_custkey, " + "o_orderstatus, o_totalprice, o_orderdate, o_orderpriority, o_clerk, o_shippriority, o_comment, cast(dir0 as int) yr, dir1 qrtr " + "from dfs.`multilevel/parquet`"); test("alter session set `planner.disable_exchanges` = false"); } @Test //Parquet: basic test with dir0 and dir1 filters public void testPartitionFilter1_Parquet() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/parquet` where dir0=1994 and dir1='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test //Parquet: basic test with dir0 and dir1 filters public void testPartitionFilter1_Parquet_from_CTAS() throws Exception { String query = "select yr, qrtr, o_custkey, o_orderdate from dfs.tmp.parquet where yr=1994 and qrtr='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test //Json: basic test with dir0 and dir1 filters public void testPartitionFilter1_Json() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/json` where dir0=1994 and dir1='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test //Json: basic test with dir0 and dir1 filters public void testPartitionFilter1_JsonFileMixDir() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/jsonFileMixDir` where dir0=1995 and dir1='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test //Json: basic test with dir0 = and dir1 is null filters public void testPartitionFilterIsNull_JsonFileMixDir() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/jsonFileMixDir` where dir0=1995 and dir1 is null"; testExcludeFilter(query, 1, "Filter\\(", 5); } @Test //Json: basic test with dir0 = and dir1 is not null filters public void testPartitionFilterIsNotNull_JsonFileMixDir() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/jsonFileMixDir` where dir0=1995 and dir1 is not null"; testExcludeFilter(query, 4, "Filter\\(", 40); } @Test //CSV: basic test with dir0 and dir1 filters in public void testPartitionFilter1_Csv() throws Exception { String query = "select * from dfs.`multilevel/csv` where dir0=1994 and dir1='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test //Parquet: partition filters are combined with regular columns in an AND public void testPartitionFilter2_Parquet() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/parquet` where o_custkey < 1000 and dir0=1994 and dir1='Q1'"; testIncludeFilter(query, 1, "Filter\\(", 5); } @Test //Parquet: partition filters are combined with regular columns in an AND public void testPartitionFilter2_Parquet_from_CTAS() throws Exception { String query = "select yr, qrtr, o_custkey, o_orderdate from dfs.tmp.parquet where o_custkey < 1000 and yr=1994 and qrtr='Q1'"; testIncludeFilter(query, 1, "Filter\\(", 5); } @Test //Json: partition filters are combined with regular columns in an AND public void testPartitionFilter2_Json() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/json` where o_custkey < 1000 and dir0=1994 and dir1='Q1'"; testIncludeFilter(query, 1, "Filter\\(", 5); } @Test //CSV: partition filters are combined with regular columns in an AND public void testPartitionFilter2_Csv() throws Exception { String query = "select * from dfs.`multilevel/csv` where columns[1] < 1000 and dir0=1994 and dir1='Q1'"; testIncludeFilter(query, 1, "Filter\\(", 5); } @Test //Parquet: partition filters are ANDed and belong to a top-level OR public void testPartitionFilter3_Parquet() throws Exception { String query = "select * from dfs.`multilevel/parquet` where (dir0=1994 and dir1='Q1' and o_custkey < 500) or (dir0=1995 and dir1='Q2' and o_custkey > 500)"; testIncludeFilter(query, 2, "Filter\\(", 8); } @Test //Parquet: partition filters are ANDed and belong to a top-level OR public void testPartitionFilter3_Parquet_from_CTAS() throws Exception { String query = "select * from dfs.tmp.parquet where (yr=1994 and qrtr='Q1' and o_custkey < 500) or (yr=1995 and qrtr='Q2' and o_custkey > 500)"; testIncludeFilter(query, 2, "Filter\\(", 8); } @Test //Json: partition filters are ANDed and belong to a top-level OR public void testPartitionFilter3_Json() throws Exception { String query = "select * from dfs.`multilevel/json` where (dir0=1994 and dir1='Q1' and o_custkey < 500) or (dir0=1995 and dir1='Q2' and o_custkey > 500)"; testIncludeFilter(query, 2, "Filter\\(", 8); } @Test //CSV: partition filters are ANDed and belong to a top-level OR public void testPartitionFilter3_Csv() throws Exception { String query = "select * from dfs.`multilevel/csv` where (dir0=1994 and dir1='Q1' and columns[1] < 500) or (dir0=1995 and dir1='Q2' and columns[1] > 500)"; testIncludeFilter(query, 2, "Filter\\(", 8); } @Test //Parquet: filters contain join conditions and partition filters public void testPartitionFilter4_Parquet() throws Exception { String query1 = "select t1.dir0, t1.dir1, t1.o_custkey, t1.o_orderdate, cast(t2.c_name as varchar(10)) from dfs.`multilevel/parquet` t1, cp.`tpch/customer.parquet` t2 where" + " t1.o_custkey = t2.c_custkey and t1.dir0=1994 and t1.dir1='Q1'"; test(query1); } @Test //Parquet: filters contain join conditions and partition filters public void testPartitionFilter4_Parquet_from_CTAS() throws Exception { String query1 = "select t1.dir0, t1.dir1, t1.o_custkey, t1.o_orderdate, cast(t2.c_name as varchar(10)) from dfs.tmp.parquet t1, cp.`tpch/customer.parquet` t2 where " + "t1.o_custkey = t2.c_custkey and t1.yr=1994 and t1.qrtr='Q1'"; test(query1); } @Test //Json: filters contain join conditions and partition filters public void testPartitionFilter4_Json() throws Exception { String query1 = "select t1.dir0, t1.dir1, t1.o_custkey, t1.o_orderdate, cast(t2.c_name as varchar(10)) from dfs.`multilevel/json` t1, cp.`tpch/customer.parquet` t2 where " + "cast(t1.o_custkey as bigint) = cast(t2.c_custkey as bigint) and t1.dir0=1994 and t1.dir1='Q1'"; test(query1); } @Test //CSV: filters contain join conditions and partition filters public void testPartitionFilter4_Csv() throws Exception { String query1 = "select t1.dir0, t1.dir1, t1.columns[1] as o_custkey, t1.columns[4] as o_orderdate, cast(t2.c_name as varchar(10)) from dfs.`multilevel/csv` t1, cp" + ".`tpch/customer.parquet` t2 where cast(t1.columns[1] as bigint) = cast(t2.c_custkey as bigint) and t1.dir0=1994 and t1.dir1='Q1'"; test(query1); } @Test // Parquet: IN filter public void testPartitionFilter5_Parquet() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/parquet` where dir0 in (1995, 1996)"; testExcludeFilter(query, 8, "Filter\\(", 80); } @Test // Parquet: IN filter public void testPartitionFilter5_Parquet_from_CTAS() throws Exception { String query = "select yr, qrtr, o_custkey, o_orderdate from dfs.tmp.parquet where yr in (1995, 1996)"; testExcludeFilter(query, 8, "Filter\\(", 80); } @Test // Json: IN filter public void testPartitionFilter5_Json() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/json` where dir0 in (1995, 1996)"; testExcludeFilter(query, 8, "Filter\\(", 80); } @Test // CSV: IN filter public void testPartitionFilter5_Csv() throws Exception { String query = "select * from dfs.`multilevel/csv` where dir0 in (1995, 1996)"; testExcludeFilter(query, 8, "Filter\\(", 80); } @Test // Parquet: one side of OR has partition filter only, other side has both partition filter and non-partition filter public void testPartitionFilter6_Parquet() throws Exception { String query = "select * from dfs.`multilevel/parquet` where (dir0=1995 and o_totalprice < 40000) or dir0=1996"; testIncludeFilter(query, 8, "Filter\\(", 46); } @Test // Parquet: one side of OR has partition filter only, other side has both partition filter and non-partition filter public void testPartitionFilter6_Parquet_from_CTAS() throws Exception { String query = "select * from dfs.tmp.parquet where (yr=1995 and o_totalprice < 40000) or yr=1996"; // Parquet RG filter pushdown further reduces to 6 files. testIncludeFilter(query, 6, "Filter\\(", 46); } @Test // Parquet: trivial case with 1 partition filter public void testPartitionFilter7_Parquet() throws Exception { String query = "select * from dfs.`multilevel/parquet` where dir0=1995"; testExcludeFilter(query, 4, "Filter\\(", 40); } @Test // Parquet: trivial case with 1 partition filter public void testPartitionFilter7_Parquet_from_CTAS() throws Exception { String query = "select * from dfs.tmp.parquet where yr=1995"; testExcludeFilter(query, 4, "Filter\\(", 40); } @Test // Parquet: partition filter on subdirectory only public void testPartitionFilter8_Parquet() throws Exception { String query = "select * from dfs.`multilevel/parquet` where dir1 in ('Q1','Q4')"; testExcludeFilter(query, 6, "Filter\\(", 60); } @Test public void testPartitionFilter8_Parquet_from_CTAS() throws Exception { String query = "select * from dfs.tmp.parquet where qrtr in ('Q1','Q4')"; testExcludeFilter(query, 6, "Filter\\(", 60); } @Test // Parquet: partition filter on subdirectory only plus non-partition filter public void testPartitionFilter9_Parquet() throws Exception { String query = "select * from dfs.`multilevel/parquet` where dir1 in ('Q1','Q4') and o_totalprice < 40000"; // Parquet RG filter pushdown further reduces to 4 files. testIncludeFilter(query, 4, "Filter\\(", 9); } @Test public void testPartitionFilter9_Parquet_from_CTAS() throws Exception { String query = "select * from dfs.tmp.parquet where qrtr in ('Q1','Q4') and o_totalprice < 40000"; // Parquet RG filter pushdown further reduces to 4 files. testIncludeFilter(query, 4, "Filter\\(", 9); } @Test public void testPartitoinFilter10_Parquet() throws Exception { String query = "select max(o_orderprice) from dfs.`multilevel/parquet` where dir0=1994 and dir1='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 1); } @Test public void testPartitoinFilter10_Parquet_from_CTAS() throws Exception { String query = "select max(o_orderprice) from dfs.tmp.parquet where yr=1994 and qrtr='Q1'"; testExcludeFilter(query, 1, "Filter\\(", 1); } @Test // see DRILL-2712 @Category(UnlikelyTest.class) public void testMainQueryFalseCondition() throws Exception { String query = "select * from (select dir0, o_custkey from dfs.`multilevel/parquet` where dir0='1994') t where 1 = 0"; // the 1 = 0 becomes limit 0, which will require to read only one parquet file, in stead of 4 for year '1994'. testExcludeFilter(query, 1, "Filter\\(", 0); } @Test // see DRILL-2712 @Category(UnlikelyTest.class) public void testMainQueryTrueCondition() throws Exception { String query = "select * from (select dir0, o_custkey from dfs.`multilevel/parquet` where dir0='1994' ) t where 0 = 0"; testExcludeFilter(query, 4, "Filter\\(", 40); } @Test // see DRILL-2712 public void testMainQueryFilterRegularColumn() throws Exception { String query = "select * from (select dir0, o_custkey from dfs.`multilevel/parquet` where dir0='1994' and o_custkey = 10) t limit 0"; // with Parquet RG filter pushdown, reduce to 1 file ( o_custkey all > 10). testIncludeFilter(query, 1, "Filter\\(", 0); } @Test // see DRILL-2852 and DRILL-3591 @Category(UnlikelyTest.class) public void testPartitionFilterWithCast() throws Exception { String query = "select myyear, myquarter, o_totalprice from (select cast(dir0 as varchar(10)) as myyear, " + " cast(dir1 as varchar(10)) as myquarter, o_totalprice from dfs.`multilevel/parquet`) where myyear = cast('1995' as varchar(10)) " + " and myquarter = cast('Q2' as varchar(10)) and o_totalprice < 40000.0 order by o_totalprice"; testIncludeFilter(query, 1, "Filter\\(", 3); } @Test public void testPPWithNestedExpression() throws Exception { String query = "select * from dfs.`multilevel/parquet` where dir0 not in(1994) and o_orderpriority = '2-HIGH'"; testIncludeFilter(query, 8, "Filter\\(", 24); } @Test public void testPPWithCase() throws Exception { String query = "select 1 from (select CASE WHEN '07' = '13' THEN '13' ELSE CAST(dir0 as VARCHAR(4)) END as YEAR_FILTER from dfs.`multilevel/parquet` " + "where o_orderpriority = '2-HIGH') subq where subq.YEAR_FILTER not in('1994')"; testIncludeFilter(query, 8, "Filter\\(", 24); } @Test // DRILL-3702 @Category(UnlikelyTest.class) public void testPartitionFilterWithNonNullabeFilterExpr() throws Exception { String query = "select dir0, dir1, o_custkey, o_orderdate from dfs.`multilevel/parquet` where concat(dir0, '') = '1994' and concat(dir1, '') = 'Q1'"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test // DRILL-2748 public void testPartitionFilterAfterPushFilterPastAgg() throws Exception { String query = "select dir0, dir1, cnt from (select dir0, dir1, count(*) cnt from dfs.`multilevel/parquet` group by dir0, dir1) where dir0 = '1994' and dir1 = 'Q1'"; testExcludeFilter(query, 1, "Filter\\(", 1); } // Coalesce filter is on the non directory column. DRILL-4071 @Test public void testPartitionWithCoalesceFilter_1() throws Exception { String query = "select 1 from dfs.`multilevel/parquet` where dir0=1994 and dir1='Q1' and coalesce(o_custkey, 0) = 890"; testIncludeFilter(query, 1, "Filter\\(", 1); } // Coalesce filter is on the directory column @Test public void testPartitionWithCoalesceFilter_2() throws Exception { String query = "select 1 from dfs.`multilevel/parquet` where dir0=1994 and o_custkey = 890 and coalesce(dir1, 'NA') = 'Q1'"; testIncludeFilter(query, 1, "Filter\\(", 1); } @Test //DRILL-4021: Json with complex type and nested flatten functions: dir0 and dir1 filters plus filter involves filter refering to output from nested flatten functions. @Category(UnlikelyTest.class) public void testPartitionFilter_Json_WithFlatten() throws Exception { // this query expects to have the partition filter pushded. // With partition pruning, we will end with one file, and one row returned from the query. final String query = " select dir0, dir1, o_custkey, o_orderdate, provider from " + " ( select dir0, dir1, o_custkey, o_orderdate, flatten(items['providers']) as provider " + " from (" + " select dir0, dir1, o_custkey, o_orderdate, flatten(o_items) items " + " from dfs.`multilevel/jsoncomplex`) ) " + " where dir0=1995 " + // should be pushed down and used as partitioning filter " and dir1='Q1' " + // should be pushed down and used as partitioning filter " and provider = 'BestBuy'"; // should NOT be pushed down. testIncludeFilter(query, 1, "Filter\\(", 1); } @Test public void testLogicalDirPruning() throws Exception { // 1995/Q1 contains one valid parquet, while 1996/Q1 contains bad format parquet. // If dir pruning happens in logical, the query will run fine, since the bad parquet has been pruned before we build ParquetGroupScan. String query = "select dir0, o_custkey from dfs.`multilevel/parquetWithBadFormat` where dir0=1995"; testExcludeFilter(query, 1, "Filter\\(", 10); } @Test public void testLogicalDirPruning2() throws Exception { // 1995/Q1 contains one valid parquet, while 1996/Q1 contains bad format parquet. // If dir pruning happens in logical, the query will run fine, since the bad parquet has been pruned before we build ParquetGroupScan. String query = "select dir0, o_custkey from dfs.`multilevel/parquetWithBadFormat` where dir0=1995 and o_custkey > 0"; testIncludeFilter(query, 1, "Filter\\(", 10); } @Test //DRILL-4665: Partition pruning should occur when LIKE predicate on non-partitioning column public void testPartitionFilterWithLike() throws Exception { // Also should be insensitive to the order of the predicates String query1 = "select yr, qrtr from dfs.tmp.parquet where yr=1994 and o_custkey LIKE '%5%'"; String query2 = "select yr, qrtr from dfs.tmp.parquet where o_custkey LIKE '%5%' and yr=1994"; testIncludeFilter(query1, 4, "Filter\\(", 9); testIncludeFilter(query2, 4, "Filter\\(", 9); // Test when LIKE predicate on partitioning column String query3 = "select yr, qrtr from dfs.tmp.parquet where yr LIKE '%1995%' and o_custkey LIKE '%3%'"; String query4 = "select yr, qrtr from dfs.tmp.parquet where o_custkey LIKE '%3%' and yr LIKE '%1995%'"; testIncludeFilter(query3, 4, "Filter\\(", 16); testIncludeFilter(query4, 4, "Filter\\(", 16); } @Test //DRILL-3710 Partition pruning should occur with varying IN-LIST size public void testPartitionFilterWithInSubquery() throws Exception { String query = "select * from dfs.`multilevel/parquet` where cast (dir0 as int) IN (1994, 1994, 1994, 1994, 1994, 1994)"; /* In list size exceeds threshold - no partition pruning since predicate converted to join */ test("alter session set `planner.in_subquery_threshold` = 2"); testExcludeFilter(query, 12, "Filter\\(", 40); /* In list size does not exceed threshold - partition pruning */ test("alter session set `planner.in_subquery_threshold` = 10"); testExcludeFilter(query, 4, "Filter\\(", 40); } @Test // DRILL-4825: querying same table with different filter in UNION ALL. public void testPruneSameTableInUnionAll() throws Exception { final String query = "select count(*) as cnt from " + "( select dir0 from dfs.`multilevel/parquet` where dir0 in ('1994') union all " + " select dir0 from dfs.`multilevel/parquet` where dir0 in ('1995', '1996') )"; String [] excluded = {"Filter\\("}; // verify plan that filter is applied in partition pruning. testPlanMatchingPatterns(query, null, excluded); // verify we get correct count(*). testBuilder() .sqlQuery(query) .unOrdered() .baselineColumns("cnt") .baselineValues((long)120) .build() .run(); } @Test // DRILL-4825: querying same table with different filter in Join. public void testPruneSameTableInJoin() throws Exception { final String query = "select * from " + "( select sum(o_custkey) as x from dfs.`multilevel/parquet` where dir0 in ('1994') ) join " + " ( select sum(o_custkey) as y from dfs.`multilevel/parquet` where dir0 in ('1995', '1996')) " + " on x = y "; String [] excluded = {"Filter\\("}; // verify plan that filter is applied in partition pruning. testPlanMatchingPatterns(query, null, excluded); // verify we get empty result. testBuilder() .sqlQuery(query) .expectsEmptyResultSet() .build() .run(); } }
/* * $URL: https://source.sakaiproject.org/svn/basiclti/tags/sakai-10.6/basiclti-util/src/java/org/imsglobal/lti2/LTI2Util.java $ * $Id: LTI2Util.java 134448 2014-02-12 18:32:12Z csev@umich.edu $ * * Copyright (c) 2013 IMS GLobal Learning Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.imsglobal.lti2; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.imsglobal.basiclti.BasicLTIUtil; import org.imsglobal.lti2.objects.Service_offered; import org.imsglobal.lti2.objects.StandardServices; import org.imsglobal.lti2.objects.ToolConsumer; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class LTI2Util { // We use the built-in Java logger because this code needs to be very generic private static Logger M_log = Logger.getLogger(LTI2Util.class.toString()); public static final String SCOPE_LtiLink = "LtiLink"; public static final String SCOPE_ToolProxyBinding = "ToolProxyBinding"; public static final String SCOPE_ToolProxy = "ToolProxy"; private static final String EMPTY_JSON_OBJECT = "{\n}\n"; // Validate the incoming tool_services against a tool consumer public static String validateServices(ToolConsumer consumer, JSONObject providerProfile) { // Mostly to catch casting errors from bad JSON try { JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if ( security_contract == null ) { return "JSON missing security_contract"; } JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); List<Service_offered> services_offered = consumer.getService_offered(); if ( tool_services != null ) for (Object o : tool_services) { JSONObject tool_service = (JSONObject) o; String json_service = (String) tool_service.get(LTI2Constants.SERVICE); boolean found = false; for (Service_offered service : services_offered ) { String service_endpoint = service.getEndpoint(); if ( service_endpoint.equals(json_service) ) { found = true; break; } } if ( ! found ) return "Service not allowed: "+json_service; } return null; } catch (Exception e) { return "Exception:"+ e.getLocalizedMessage(); } } // Validate incoming capabilities requested against out ToolConsumer public static String validateCapabilities(ToolConsumer consumer, JSONObject providerProfile) { List<Properties> theTools = new ArrayList<Properties> (); Properties info = new Properties(); // Mostly to catch casting errors from bad JSON try { String retval = parseToolProfile(theTools, info, providerProfile); if ( retval != null ) return retval; if ( theTools.size() < 1 ) return "No tools found in profile"; // Check all the capabilities requested by all the tools comparing against consumer List<String> capabilities = consumer.getCapability_offered(); for ( Properties theTool : theTools ) { String ec = (String) theTool.get("enabled_capability"); JSONArray enabled_capability = (JSONArray) JSONValue.parse(ec); if ( enabled_capability != null ) for (Object o : enabled_capability) { ec = (String) o; if ( capabilities.contains(ec) ) continue; return "Capability not permitted="+ec; } } return null; } catch (Exception e ) { return "Exception:"+ e.getLocalizedMessage(); } } public static void allowEmail(List<String> capabilities) { capabilities.add("Person.email.primary"); } public static void allowName(List<String> capabilities) { capabilities.add("User.username"); capabilities.add("Person.name.fullname"); capabilities.add("Person.name.given"); capabilities.add("Person.name.family"); capabilities.add("Person.name.full"); } public static void allowResult(List<String> capabilities) { capabilities.add("Result.sourcedId"); capabilities.add("Result.autocreate"); capabilities.add("Result.url"); } public static void allowSettings(List<String> capabilities) { capabilities.add("LtiLink.custom.url"); capabilities.add("ToolProxy.custom.url"); capabilities.add("ToolProxyBinding.custom.url"); } // If this code looks like a hack - it is because the spec is a hack. // There are five possible scenarios for GET and two possible scenarios // for PUT. I begged to simplify the business logic but was overrulled. // So we write obtuse code. @SuppressWarnings({ "unchecked", "unused" }) public static Object getSettings(HttpServletRequest request, String scope, JSONObject link_settings, JSONObject binding_settings, JSONObject proxy_settings, String link_url, String binding_url, String proxy_url) { // Check to see if we are doing the bubble String bubbleStr = request.getParameter("bubble"); String acceptHdr = request.getHeader("Accept"); String contentHdr = request.getContentType(); if ( bubbleStr != null && bubbleStr.equals("all") && acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) < 0 ) { return "Simple format does not allow bubble=all"; } if ( SCOPE_LtiLink.equals(scope) || SCOPE_ToolProxyBinding.equals(scope) || SCOPE_ToolProxy.equals(scope) ) { // All good } else { return "Bad Setttings Scope="+scope; } boolean bubble = bubbleStr != null && "GET".equals(request.getMethod()); boolean distinct = bubbleStr != null && "distinct".equals(bubbleStr); boolean bubbleAll = bubbleStr != null && "all".equals(bubbleStr); // Check our output format boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0; if ( distinct && link_settings != null && scope.equals(SCOPE_LtiLink) ) { Iterator<String> i = link_settings.keySet().iterator(); while ( i.hasNext() ) { String key = (String) i.next(); if ( binding_settings != null ) binding_settings.remove(key); if ( proxy_settings != null ) proxy_settings.remove(key); } } if ( distinct && binding_settings != null && scope.equals(SCOPE_ToolProxyBinding) ) { Iterator<String> i = binding_settings.keySet().iterator(); while ( i.hasNext() ) { String key = (String) i.next(); if ( proxy_settings != null ) proxy_settings.remove(key); } } // Lets get this party started... JSONObject jsonResponse = null; if ( (distinct || bubbleAll) && acceptComplex ) { jsonResponse = new JSONObject(); jsonResponse.put(LTI2Constants.CONTEXT,StandardServices.TOOLSETTINGS_CONTEXT); JSONArray graph = new JSONArray(); boolean started = false; if ( link_settings != null && SCOPE_LtiLink.equals(scope) ) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID,link_url); cjson.put(LTI2Constants.TYPE,SCOPE_LtiLink); cjson.put(LTI2Constants.CUSTOM,link_settings); graph.add(cjson); started = true; } if ( binding_settings != null && ( started || SCOPE_ToolProxyBinding.equals(scope) ) ) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID,binding_url); cjson.put(LTI2Constants.TYPE,SCOPE_ToolProxyBinding); cjson.put(LTI2Constants.CUSTOM,binding_settings); graph.add(cjson); started = true; } if ( proxy_settings != null && ( started || SCOPE_ToolProxy.equals(scope) ) ) { JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID,proxy_url); cjson.put(LTI2Constants.TYPE,SCOPE_ToolProxy); cjson.put(LTI2Constants.CUSTOM,proxy_settings); graph.add(cjson); } jsonResponse.put(LTI2Constants.GRAPH,graph); } else if ( distinct ) { // Simple format output jsonResponse = proxy_settings; if ( SCOPE_LtiLink.equals(scope) ) { jsonResponse.putAll(binding_settings); jsonResponse.putAll(link_settings); } else if ( SCOPE_ToolProxyBinding.equals(scope) ) { jsonResponse.putAll(binding_settings); } } else { // bubble not specified jsonResponse = new JSONObject(); jsonResponse.put(LTI2Constants.CONTEXT,StandardServices.TOOLSETTINGS_CONTEXT); JSONObject theSettings = null; String endpoint = null; if ( SCOPE_LtiLink.equals(scope) ) { endpoint = link_url; theSettings = link_settings; } else if ( SCOPE_ToolProxyBinding.equals(scope) ) { endpoint = binding_url; theSettings = binding_settings; } if ( SCOPE_ToolProxy.equals(scope) ) { endpoint = proxy_url; theSettings = proxy_settings; } if ( acceptComplex ) { JSONArray graph = new JSONArray(); JSONObject cjson = new JSONObject(); cjson.put(LTI2Constants.JSONLD_ID,endpoint); cjson.put(LTI2Constants.TYPE,scope); cjson.put(LTI2Constants.CUSTOM,theSettings); graph.add(cjson); jsonResponse.put(LTI2Constants.GRAPH,graph); } else { jsonResponse = theSettings; } } return jsonResponse; } // Parse a provider profile with lots of error checking... public static String parseToolProfile(List<Properties> theTools, Properties info, JSONObject jsonObject) { try { return parseToolProfileInternal(theTools, info, jsonObject); } catch (Exception e) { M_log.warning("Internal error parsing tool proxy\n"+jsonObject.toString()); e.printStackTrace(); return "Internal error parsing tool proxy:"+e.getLocalizedMessage(); } } // Parse a provider profile with lots of error checking... @SuppressWarnings("unused") private static String parseToolProfileInternal(List<Properties> theTools, Properties info, JSONObject jsonObject) { Object o = null; JSONObject tool_profile = (JSONObject) jsonObject.get("tool_profile"); if ( tool_profile == null ) { return "JSON missing tool_profile"; } JSONObject product_instance = (JSONObject) tool_profile.get("product_instance"); if ( product_instance == null ) { return "JSON missing product_instance"; } String instance_guid = (String) product_instance.get("guid"); if ( instance_guid == null ) { return "JSON missing product_info / guid"; } info.put("instance_guid",instance_guid); JSONObject product_info = (JSONObject) product_instance.get("product_info"); if ( product_info == null ) { return "JSON missing product_info"; } // Look for required fields JSONObject product_name = product_info == null ? null : (JSONObject) product_info.get("product_name"); String productTitle = product_name == null ? null : (String) product_name.get("default_value"); JSONObject description = product_info == null ? null : (JSONObject) product_info.get("description"); String productDescription = description == null ? null : (String) description.get("default_value"); JSONObject product_family = product_info == null ? null : (JSONObject) product_info.get("product_family"); String productCode = product_family == null ? null : (String) product_family.get("code"); JSONObject product_vendor = product_family == null ? null : (JSONObject) product_family.get("vendor"); description = product_vendor == null ? null : (JSONObject) product_vendor.get("description"); String vendorDescription = description == null ? null : (String) description.get("default_value"); String vendorCode = product_vendor == null ? null : (String) product_vendor.get("code"); if ( productTitle == null || productDescription == null ) { return "JSON missing product_name or description "; } if ( productCode == null || vendorCode == null || vendorDescription == null ) { return "JSON missing product code, vendor code or description"; } info.put("product_name", productTitle); info.put("description", productDescription); // Backwards compatibility info.put("product_description", productDescription); info.put("product_code", productCode); info.put("vendor_code", vendorCode); info.put("vendor_description", vendorDescription); o = tool_profile.get("base_url_choice"); if ( ! (o instanceof JSONArray)|| o == null ) { return "JSON missing base_url_choices"; } JSONArray base_url_choices = (JSONArray) o; String secure_base_url = null; String default_base_url = null; for ( Object i : base_url_choices ) { JSONObject url_choice = (JSONObject) i; secure_base_url = (String) url_choice.get("secure_base_url"); default_base_url = (String) url_choice.get("default_base_url"); } String launch_url = secure_base_url; if ( launch_url == null ) launch_url = default_base_url; if ( launch_url == null ) { return "Unable to determine launch URL"; } o = (JSONArray) tool_profile.get("resource_handler"); if ( ! (o instanceof JSONArray)|| o == null ) { return "JSON missing resource_handlers"; } JSONArray resource_handlers = (JSONArray) o; // Loop through resource handlers, read, and check for errors for(Object i : resource_handlers ) { JSONObject resource_handler = (JSONObject) i; JSONObject resource_type_json = (JSONObject) resource_handler.get("resource_type"); String resource_type_code = (String) resource_type_json.get("code"); if ( resource_type_code == null ) { return "JSON missing resource_type code"; } o = (JSONArray) resource_handler.get("message"); if ( ! (o instanceof JSONArray)|| o == null ) { return "JSON missing resource_handler / message"; } JSONArray messages = (JSONArray) o; JSONObject titleObject = (JSONObject) resource_handler.get("name"); String title = titleObject == null ? null : (String) titleObject.get("default_value"); if ( title == null || titleObject == null ) { return "JSON missing resource_handler / name / default_value"; } JSONObject buttonObject = (JSONObject) resource_handler.get("short_name"); String button = buttonObject == null ? null : (String) buttonObject.get("default_value"); JSONObject descObject = (JSONObject) resource_handler.get("description"); String resourceDescription = descObject == null ? null : (String) descObject.get("default_value"); String path = null; JSONArray parameter = null; JSONArray enabled_capability = null; for ( Object m : messages ) { JSONObject message = (JSONObject) m; String message_type = (String) message.get("message_type"); if ( ! "basic-lti-launch-request".equals(message_type) ) continue; if ( path != null ) { return "A resource_handler cannot have more than one basic-lti-launch-request message RT="+resource_type_code; } path = (String) message.get("path"); if ( path == null ) { return "A basic-lti-launch-request message must have a path RT="+resource_type_code; } o = (JSONArray) message.get("parameter"); if ( ! (o instanceof JSONArray)) { return "Must be an array: parameter RT="+resource_type_code; } parameter = (JSONArray) o; o = (JSONArray) message.get("enabled_capability"); if ( ! (o instanceof JSONArray)) { return "Must be an array: enabled_capability RT="+resource_type_code; } enabled_capability = (JSONArray) o; } // Ignore everything except launch handlers if ( path == null ) continue; // Check the URI String thisLaunch = launch_url; if ( ! thisLaunch.endsWith("/") && ! path.startsWith("/") ) thisLaunch = thisLaunch + "/"; thisLaunch = thisLaunch + path; try { URL url = new URL(thisLaunch); } catch ( Exception e ) { return "Bad launch URL="+thisLaunch; } // Passed all the tests... Lets keep it... Properties theTool = new Properties(); theTool.put("resource_type", resource_type_code); // Backwards compatibility theTool.put("resource_type_code", resource_type_code); if ( title == null ) title = productTitle; if ( title != null ) theTool.put("title", title); if ( button != null ) theTool.put("button", button); if ( resourceDescription == null ) resourceDescription = productDescription; if ( resourceDescription != null ) theTool.put("description", resourceDescription); if ( parameter != null ) theTool.put("parameter", parameter.toString()); if ( enabled_capability != null ) theTool.put("enabled_capability", enabled_capability.toString()); theTool.put("launch", thisLaunch); theTools.add(theTool); } return null; // All good } public static JSONObject parseSettings(String settings) { if ( settings == null || settings.length() < 1 ) { settings = EMPTY_JSON_OBJECT; } return (JSONObject) JSONValue.parse(settings); } /* Two possible formats: key=val;key2=val2; key=val key2=val2 */ public static boolean mergeLTI1Custom(Properties custom, String customstr) { if ( customstr == null || customstr.length() < 1 ) return true; String [] params = customstr.split("[\n;]"); for (int i = 0 ; i < params.length; i++ ) { String param = params[i]; if ( param == null ) continue; if ( param.length() < 1 ) continue; int pos = param.indexOf("="); if ( pos < 1 ) continue; if ( pos+1 > param.length() ) continue; String key = mapKeyName(param.substring(0,pos)); if ( key == null ) continue; if ( custom.containsKey(key) ) continue; String value = param.substring(pos+1); if ( value == null ) continue; value = value.trim(); if ( value.length() < 1 ) continue; setProperty(custom, key, value); } return true; } /* "custom" : { "isbn" : "978-0321558145", "style" : "jazzy" } */ public static boolean mergeLTI2Custom(Properties custom, String customstr) { if ( customstr == null || customstr.length() < 1 ) return true; JSONObject json = null; try { json = (JSONObject) JSONValue.parse(customstr.trim()); } catch(Exception e) { M_log.warning("mergeLTI2Custom could not parse\n"+customstr); M_log.warning(e.getLocalizedMessage()); return false; } // This could happen if the old settings service was used // on an LTI 2.x placement to put in settings that are not // JSON - we just ignore it. if ( json == null ) return false; Iterator<?> keys = json.keySet().iterator(); while( keys.hasNext() ){ String key = (String)keys.next(); if ( custom.containsKey(key) ) continue; Object value = json.get(key); if ( value instanceof String ){ setProperty(custom, key, (String) value); } } return true; } /* "parameter" : [ { "name" : "result_url", "variable" : "Result.url" }, { "name" : "discipline", "fixed" : "chemistry" } ] */ public static boolean mergeLTI2Parameters(Properties custom, String customstr) { if ( customstr == null || customstr.length() < 1 ) return true; JSONArray json = null; try { json = (JSONArray) JSONValue.parse(customstr.trim()); } catch(Exception e) { M_log.warning("mergeLTI2Parameters could not parse\n"+customstr); M_log.warning(e.getLocalizedMessage()); return false; } Iterator<?> parameters = json.iterator(); while( parameters.hasNext() ){ Object o = parameters.next(); JSONObject parameter = null; try { parameter = (JSONObject) o; } catch(Exception e) { M_log.warning("mergeLTI2Parameters did not find list of objects\n"+customstr); M_log.warning(e.getLocalizedMessage()); return false; } String name = (String) parameter.get("name"); if ( name == null ) continue; if ( custom.containsKey(name) ) continue; String fixed = (String) parameter.get("fixed"); String variable = (String) parameter.get("variable"); if ( variable != null ) { setProperty(custom, name, variable); continue; } if ( fixed != null ) { setProperty(custom, name, fixed); } } return true; } public static void substituteCustom(Properties custom, Properties lti2subst) { if ( custom == null || lti2subst == null ) return; Enumeration<?> e = custom.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String value = custom.getProperty(key); if ( value == null || value.length() < 1 ) continue; String newValue = lti2subst.getProperty(value); if ( newValue == null || newValue.length() < 1 ) continue; setProperty(custom, key, (String) newValue); } } // Place the custom values into the launch public static void addCustomToLaunch(Properties ltiProps, Properties custom) { Enumeration<?> e = custom.propertyNames(); while (e.hasMoreElements()) { String keyStr = (String) e.nextElement(); String value = custom.getProperty(keyStr); setProperty(ltiProps,"custom_"+keyStr,value); } } @SuppressWarnings("deprecation") public static void setProperty(Properties props, String key, String value) { BasicLTIUtil.setProperty(props, key, value); } public static String mapKeyName(String keyname) { return BasicLTIUtil.mapKeyName(keyname); } }
/* * 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.document.blob; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import com.google.common.collect.ImmutableList; import org.apache.jackrabbit.oak.commons.StringUtils; import org.apache.jackrabbit.oak.plugins.document.rdb.RDBBlobStore; import org.apache.jackrabbit.oak.plugins.document.rdb.RDBBlobStoreFriend; import org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; /** * Tests the RDBBlobStore implementation. */ @RunWith(Parameterized.class) public class RDBBlobStoreTest extends AbstractBlobStoreTest { @Override protected boolean supportsStatsCollection() { return true; } @Parameterized.Parameters(name="{0}") public static Collection<Object[]> fixtures() { Collection<Object[]> result = new ArrayList<Object[]>(); RDBBlobStoreFixture candidates[] = new RDBBlobStoreFixture[] { RDBBlobStoreFixture.RDB_DB2, RDBBlobStoreFixture.RDB_H2, RDBBlobStoreFixture.RDB_DERBY, RDBBlobStoreFixture.RDB_MSSQL, RDBBlobStoreFixture.RDB_MYSQL, RDBBlobStoreFixture.RDB_ORACLE, RDBBlobStoreFixture.RDB_PG }; for (RDBBlobStoreFixture bsf : candidates) { if (bsf.isAvailable()) { result.add(new Object[] { bsf }); } } return result; } private RDBBlobStore blobStore; private String blobStoreName; private static final Logger LOG = LoggerFactory.getLogger(RDBBlobStoreTest.class); public RDBBlobStoreTest(RDBBlobStoreFixture bsf) { blobStore = bsf.createRDBBlobStore(); blobStoreName = bsf.getName(); } @Before @Override public void setUp() throws Exception { blobStore.setBlockSize(128); blobStore.setBlockSizeMin(48); this.store = blobStore; empty(blobStore); } @After @Override public void tearDown() throws Exception { super.tearDown(); if (blobStore != null) { empty(blobStore); blobStore.close(); } } private static void empty(RDBBlobStore blobStore) throws Exception { Iterator<String> iter = blobStore.getAllChunkIds(0); List<String> ids = Lists.newArrayList(); while (iter.hasNext()) { ids.add(iter.next()); } blobStore.deleteChunks(ids, 0); } @Test public void testBigBlob() throws Exception { int min = 0; int max = 8 * 1024 * 1024; int test = 0; while (max - min > 256) { if (test == 0) { test = max; // try largest first } else { test = (max + min) / 2; } byte[] data = new byte[test]; Random r = new Random(0); r.nextBytes(data); byte[] digest = getDigest(data); try { RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); byte[] data2 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest); if (!Arrays.equals(data, data2)) { throw new Exception("data mismatch for length " + data.length); } min = test; } catch (Exception ex) { max = test; } } LOG.info("max blob length for " + blobStoreName + " was " + test); int expected = Math.max(blobStore.getBlockSize(), 2 * 1024 * 1024); assertTrue(blobStoreName + ": expected supported block size is " + expected + ", but measured: " + test, test >= expected); } @Test public void testDeleteManyBlobs() throws Exception { // see https://issues.apache.org/jira/browse/OAK-3807 int count = 3000; List<String> toDelete = new ArrayList<String>(); for (int i = 0; i < count; i++) { byte[] data = new byte[256]; Random r = new Random(0); r.nextBytes(data); byte[] digest = getDigest(data); RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); byte[] data2 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest); if (!Arrays.equals(data, data2)) { throw new Exception("data mismatch for length " + data.length); } String id = StringUtils.convertBytesToHex(digest); toDelete.add(id); } RDBBlobStoreFriend.deleteChunks(blobStore, toDelete, System.currentTimeMillis() + 1000); } @Test public void testUpdateAndDelete() throws Exception { byte[] data = new byte[256]; Random r = new Random(0); r.nextBytes(data); byte[] digest = getDigest(data); RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); String id = StringUtils.convertBytesToHex(digest); long until = System.currentTimeMillis() + 1000; while (System.currentTimeMillis() < until) { try { Thread.sleep(100); } catch (InterruptedException e) { } } // Force update to update timestamp long beforeUpdateTs = System.currentTimeMillis() - 100; RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); // Metadata row should not have been touched Assert.assertFalse("entry was cleaned although it shouldn't have", blobStore.deleteChunks(ImmutableList.of(id), beforeUpdateTs)); // Actual data row should still be present Assert.assertNotNull(RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest)); } @Test public void testDeleteChunks() throws Exception { byte[] data1 = new byte[256]; Random r = new Random(0); r.nextBytes(data1); byte[] digest1 = getDigest(data1); RDBBlobStoreFriend.storeBlock(blobStore, digest1, 0, data1); String id1 = StringUtils.convertBytesToHex(digest1); long now = System.currentTimeMillis(); long until = System.currentTimeMillis() + 10; while (System.currentTimeMillis() < until) { try { Thread.sleep(5); } catch (InterruptedException e) { } } byte[] data2 = new byte[256]; r.nextBytes(data2); byte[] digest2 = getDigest(data2); RDBBlobStoreFriend.storeBlock(blobStore, digest2, 0, data2); Assert.assertEquals("meta entry was not removed", 1, blobStore.countDeleteChunks(ImmutableList.of(id1), now)); Assert.assertFalse("data entry was not removed", RDBBlobStoreFriend.isDataEntryPresent(blobStore, digest1)); } @Test public void testResilienceMissingMetaEntry() throws Exception { int test = 1024 * 1024; byte[] data = new byte[test]; Random r = new Random(0); r.nextBytes(data); byte[] digest = getDigest(data); RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); byte[] data2 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest); if (!Arrays.equals(data, data2)) { throw new Exception("data mismatch"); } RDBBlobStoreFriend.killMetaEntry(blobStore, digest); // retry RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data); byte[] data3 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest); if (!Arrays.equals(data, data3)) { throw new Exception("data mismatch"); } } private byte[] getDigest(byte[] bytes) throws IOException { MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } messageDigest.update(bytes, 0, bytes.length); return messageDigest.digest(); } }
/** * 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. */ /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.airavata.model.appcatalog.userresourceprofile; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)") public class UserStoragePreference implements org.apache.thrift.TBase<UserStoragePreference, UserStoragePreference._Fields>, java.io.Serializable, Cloneable, Comparable<UserStoragePreference> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("UserStoragePreference"); private static final org.apache.thrift.protocol.TField STORAGE_RESOURCE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("storageResourceId", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField LOGIN_USER_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("loginUserName", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField FILE_SYSTEM_ROOT_LOCATION_FIELD_DESC = new org.apache.thrift.protocol.TField("fileSystemRootLocation", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN_FIELD_DESC = new org.apache.thrift.protocol.TField("resourceSpecificCredentialStoreToken", org.apache.thrift.protocol.TType.STRING, (short)4); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new UserStoragePreferenceStandardSchemeFactory()); schemes.put(TupleScheme.class, new UserStoragePreferenceTupleSchemeFactory()); } private String storageResourceId; // required private String loginUserName; // optional private String fileSystemRootLocation; // optional private String resourceSpecificCredentialStoreToken; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { STORAGE_RESOURCE_ID((short)1, "storageResourceId"), LOGIN_USER_NAME((short)2, "loginUserName"), FILE_SYSTEM_ROOT_LOCATION((short)3, "fileSystemRootLocation"), RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN((short)4, "resourceSpecificCredentialStoreToken"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // STORAGE_RESOURCE_ID return STORAGE_RESOURCE_ID; case 2: // LOGIN_USER_NAME return LOGIN_USER_NAME; case 3: // FILE_SYSTEM_ROOT_LOCATION return FILE_SYSTEM_ROOT_LOCATION; case 4: // RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN return RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final _Fields optionals[] = {_Fields.LOGIN_USER_NAME,_Fields.FILE_SYSTEM_ROOT_LOCATION,_Fields.RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.STORAGE_RESOURCE_ID, new org.apache.thrift.meta_data.FieldMetaData("storageResourceId", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.LOGIN_USER_NAME, new org.apache.thrift.meta_data.FieldMetaData("loginUserName", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.FILE_SYSTEM_ROOT_LOCATION, new org.apache.thrift.meta_data.FieldMetaData("fileSystemRootLocation", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN, new org.apache.thrift.meta_data.FieldMetaData("resourceSpecificCredentialStoreToken", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(UserStoragePreference.class, metaDataMap); } public UserStoragePreference() { } public UserStoragePreference( String storageResourceId) { this(); this.storageResourceId = storageResourceId; } /** * Performs a deep copy on <i>other</i>. */ public UserStoragePreference(UserStoragePreference other) { if (other.isSetStorageResourceId()) { this.storageResourceId = other.storageResourceId; } if (other.isSetLoginUserName()) { this.loginUserName = other.loginUserName; } if (other.isSetFileSystemRootLocation()) { this.fileSystemRootLocation = other.fileSystemRootLocation; } if (other.isSetResourceSpecificCredentialStoreToken()) { this.resourceSpecificCredentialStoreToken = other.resourceSpecificCredentialStoreToken; } } public UserStoragePreference deepCopy() { return new UserStoragePreference(this); } @Override public void clear() { this.storageResourceId = null; this.loginUserName = null; this.fileSystemRootLocation = null; this.resourceSpecificCredentialStoreToken = null; } public String getStorageResourceId() { return this.storageResourceId; } public void setStorageResourceId(String storageResourceId) { this.storageResourceId = storageResourceId; } public void unsetStorageResourceId() { this.storageResourceId = null; } /** Returns true if field storageResourceId is set (has been assigned a value) and false otherwise */ public boolean isSetStorageResourceId() { return this.storageResourceId != null; } public void setStorageResourceIdIsSet(boolean value) { if (!value) { this.storageResourceId = null; } } public String getLoginUserName() { return this.loginUserName; } public void setLoginUserName(String loginUserName) { this.loginUserName = loginUserName; } public void unsetLoginUserName() { this.loginUserName = null; } /** Returns true if field loginUserName is set (has been assigned a value) and false otherwise */ public boolean isSetLoginUserName() { return this.loginUserName != null; } public void setLoginUserNameIsSet(boolean value) { if (!value) { this.loginUserName = null; } } public String getFileSystemRootLocation() { return this.fileSystemRootLocation; } public void setFileSystemRootLocation(String fileSystemRootLocation) { this.fileSystemRootLocation = fileSystemRootLocation; } public void unsetFileSystemRootLocation() { this.fileSystemRootLocation = null; } /** Returns true if field fileSystemRootLocation is set (has been assigned a value) and false otherwise */ public boolean isSetFileSystemRootLocation() { return this.fileSystemRootLocation != null; } public void setFileSystemRootLocationIsSet(boolean value) { if (!value) { this.fileSystemRootLocation = null; } } public String getResourceSpecificCredentialStoreToken() { return this.resourceSpecificCredentialStoreToken; } public void setResourceSpecificCredentialStoreToken(String resourceSpecificCredentialStoreToken) { this.resourceSpecificCredentialStoreToken = resourceSpecificCredentialStoreToken; } public void unsetResourceSpecificCredentialStoreToken() { this.resourceSpecificCredentialStoreToken = null; } /** Returns true if field resourceSpecificCredentialStoreToken is set (has been assigned a value) and false otherwise */ public boolean isSetResourceSpecificCredentialStoreToken() { return this.resourceSpecificCredentialStoreToken != null; } public void setResourceSpecificCredentialStoreTokenIsSet(boolean value) { if (!value) { this.resourceSpecificCredentialStoreToken = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case STORAGE_RESOURCE_ID: if (value == null) { unsetStorageResourceId(); } else { setStorageResourceId((String)value); } break; case LOGIN_USER_NAME: if (value == null) { unsetLoginUserName(); } else { setLoginUserName((String)value); } break; case FILE_SYSTEM_ROOT_LOCATION: if (value == null) { unsetFileSystemRootLocation(); } else { setFileSystemRootLocation((String)value); } break; case RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN: if (value == null) { unsetResourceSpecificCredentialStoreToken(); } else { setResourceSpecificCredentialStoreToken((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case STORAGE_RESOURCE_ID: return getStorageResourceId(); case LOGIN_USER_NAME: return getLoginUserName(); case FILE_SYSTEM_ROOT_LOCATION: return getFileSystemRootLocation(); case RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN: return getResourceSpecificCredentialStoreToken(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case STORAGE_RESOURCE_ID: return isSetStorageResourceId(); case LOGIN_USER_NAME: return isSetLoginUserName(); case FILE_SYSTEM_ROOT_LOCATION: return isSetFileSystemRootLocation(); case RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN: return isSetResourceSpecificCredentialStoreToken(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof UserStoragePreference) return this.equals((UserStoragePreference)that); return false; } public boolean equals(UserStoragePreference that) { if (that == null) return false; boolean this_present_storageResourceId = true && this.isSetStorageResourceId(); boolean that_present_storageResourceId = true && that.isSetStorageResourceId(); if (this_present_storageResourceId || that_present_storageResourceId) { if (!(this_present_storageResourceId && that_present_storageResourceId)) return false; if (!this.storageResourceId.equals(that.storageResourceId)) return false; } boolean this_present_loginUserName = true && this.isSetLoginUserName(); boolean that_present_loginUserName = true && that.isSetLoginUserName(); if (this_present_loginUserName || that_present_loginUserName) { if (!(this_present_loginUserName && that_present_loginUserName)) return false; if (!this.loginUserName.equals(that.loginUserName)) return false; } boolean this_present_fileSystemRootLocation = true && this.isSetFileSystemRootLocation(); boolean that_present_fileSystemRootLocation = true && that.isSetFileSystemRootLocation(); if (this_present_fileSystemRootLocation || that_present_fileSystemRootLocation) { if (!(this_present_fileSystemRootLocation && that_present_fileSystemRootLocation)) return false; if (!this.fileSystemRootLocation.equals(that.fileSystemRootLocation)) return false; } boolean this_present_resourceSpecificCredentialStoreToken = true && this.isSetResourceSpecificCredentialStoreToken(); boolean that_present_resourceSpecificCredentialStoreToken = true && that.isSetResourceSpecificCredentialStoreToken(); if (this_present_resourceSpecificCredentialStoreToken || that_present_resourceSpecificCredentialStoreToken) { if (!(this_present_resourceSpecificCredentialStoreToken && that_present_resourceSpecificCredentialStoreToken)) return false; if (!this.resourceSpecificCredentialStoreToken.equals(that.resourceSpecificCredentialStoreToken)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_storageResourceId = true && (isSetStorageResourceId()); list.add(present_storageResourceId); if (present_storageResourceId) list.add(storageResourceId); boolean present_loginUserName = true && (isSetLoginUserName()); list.add(present_loginUserName); if (present_loginUserName) list.add(loginUserName); boolean present_fileSystemRootLocation = true && (isSetFileSystemRootLocation()); list.add(present_fileSystemRootLocation); if (present_fileSystemRootLocation) list.add(fileSystemRootLocation); boolean present_resourceSpecificCredentialStoreToken = true && (isSetResourceSpecificCredentialStoreToken()); list.add(present_resourceSpecificCredentialStoreToken); if (present_resourceSpecificCredentialStoreToken) list.add(resourceSpecificCredentialStoreToken); return list.hashCode(); } @Override public int compareTo(UserStoragePreference other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetStorageResourceId()).compareTo(other.isSetStorageResourceId()); if (lastComparison != 0) { return lastComparison; } if (isSetStorageResourceId()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.storageResourceId, other.storageResourceId); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetLoginUserName()).compareTo(other.isSetLoginUserName()); if (lastComparison != 0) { return lastComparison; } if (isSetLoginUserName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.loginUserName, other.loginUserName); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetFileSystemRootLocation()).compareTo(other.isSetFileSystemRootLocation()); if (lastComparison != 0) { return lastComparison; } if (isSetFileSystemRootLocation()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fileSystemRootLocation, other.fileSystemRootLocation); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetResourceSpecificCredentialStoreToken()).compareTo(other.isSetResourceSpecificCredentialStoreToken()); if (lastComparison != 0) { return lastComparison; } if (isSetResourceSpecificCredentialStoreToken()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.resourceSpecificCredentialStoreToken, other.resourceSpecificCredentialStoreToken); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("UserStoragePreference("); boolean first = true; sb.append("storageResourceId:"); if (this.storageResourceId == null) { sb.append("null"); } else { sb.append(this.storageResourceId); } first = false; if (isSetLoginUserName()) { if (!first) sb.append(", "); sb.append("loginUserName:"); if (this.loginUserName == null) { sb.append("null"); } else { sb.append(this.loginUserName); } first = false; } if (isSetFileSystemRootLocation()) { if (!first) sb.append(", "); sb.append("fileSystemRootLocation:"); if (this.fileSystemRootLocation == null) { sb.append("null"); } else { sb.append(this.fileSystemRootLocation); } first = false; } if (isSetResourceSpecificCredentialStoreToken()) { if (!first) sb.append(", "); sb.append("resourceSpecificCredentialStoreToken:"); if (this.resourceSpecificCredentialStoreToken == null) { sb.append("null"); } else { sb.append(this.resourceSpecificCredentialStoreToken); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (!isSetStorageResourceId()) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'storageResourceId' is unset! Struct:" + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class UserStoragePreferenceStandardSchemeFactory implements SchemeFactory { public UserStoragePreferenceStandardScheme getScheme() { return new UserStoragePreferenceStandardScheme(); } } private static class UserStoragePreferenceStandardScheme extends StandardScheme<UserStoragePreference> { public void read(org.apache.thrift.protocol.TProtocol iprot, UserStoragePreference struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // STORAGE_RESOURCE_ID if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.storageResourceId = iprot.readString(); struct.setStorageResourceIdIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // LOGIN_USER_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.loginUserName = iprot.readString(); struct.setLoginUserNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // FILE_SYSTEM_ROOT_LOCATION if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.fileSystemRootLocation = iprot.readString(); struct.setFileSystemRootLocationIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.resourceSpecificCredentialStoreToken = iprot.readString(); struct.setResourceSpecificCredentialStoreTokenIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, UserStoragePreference struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.storageResourceId != null) { oprot.writeFieldBegin(STORAGE_RESOURCE_ID_FIELD_DESC); oprot.writeString(struct.storageResourceId); oprot.writeFieldEnd(); } if (struct.loginUserName != null) { if (struct.isSetLoginUserName()) { oprot.writeFieldBegin(LOGIN_USER_NAME_FIELD_DESC); oprot.writeString(struct.loginUserName); oprot.writeFieldEnd(); } } if (struct.fileSystemRootLocation != null) { if (struct.isSetFileSystemRootLocation()) { oprot.writeFieldBegin(FILE_SYSTEM_ROOT_LOCATION_FIELD_DESC); oprot.writeString(struct.fileSystemRootLocation); oprot.writeFieldEnd(); } } if (struct.resourceSpecificCredentialStoreToken != null) { if (struct.isSetResourceSpecificCredentialStoreToken()) { oprot.writeFieldBegin(RESOURCE_SPECIFIC_CREDENTIAL_STORE_TOKEN_FIELD_DESC); oprot.writeString(struct.resourceSpecificCredentialStoreToken); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class UserStoragePreferenceTupleSchemeFactory implements SchemeFactory { public UserStoragePreferenceTupleScheme getScheme() { return new UserStoragePreferenceTupleScheme(); } } private static class UserStoragePreferenceTupleScheme extends TupleScheme<UserStoragePreference> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, UserStoragePreference struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; oprot.writeString(struct.storageResourceId); BitSet optionals = new BitSet(); if (struct.isSetLoginUserName()) { optionals.set(0); } if (struct.isSetFileSystemRootLocation()) { optionals.set(1); } if (struct.isSetResourceSpecificCredentialStoreToken()) { optionals.set(2); } oprot.writeBitSet(optionals, 3); if (struct.isSetLoginUserName()) { oprot.writeString(struct.loginUserName); } if (struct.isSetFileSystemRootLocation()) { oprot.writeString(struct.fileSystemRootLocation); } if (struct.isSetResourceSpecificCredentialStoreToken()) { oprot.writeString(struct.resourceSpecificCredentialStoreToken); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, UserStoragePreference struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.storageResourceId = iprot.readString(); struct.setStorageResourceIdIsSet(true); BitSet incoming = iprot.readBitSet(3); if (incoming.get(0)) { struct.loginUserName = iprot.readString(); struct.setLoginUserNameIsSet(true); } if (incoming.get(1)) { struct.fileSystemRootLocation = iprot.readString(); struct.setFileSystemRootLocationIsSet(true); } if (incoming.get(2)) { struct.resourceSpecificCredentialStoreToken = iprot.readString(); struct.setResourceSpecificCredentialStoreTokenIsSet(true); } } } }
/** * Copyright 2012 Twitter, 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 parquet.column.values.dictionary; import static parquet.Log.DEBUG; import static parquet.bytes.BytesInput.concat; import static parquet.column.Encoding.PLAIN_DICTIONARY; import it.unimi.dsi.fastutil.doubles.Double2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.doubles.Double2IntMap; import it.unimi.dsi.fastutil.doubles.DoubleIterator; import it.unimi.dsi.fastutil.floats.Float2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.floats.Float2IntMap; import it.unimi.dsi.fastutil.floats.FloatIterator; import it.unimi.dsi.fastutil.ints.Int2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.ints.Int2IntMap; import it.unimi.dsi.fastutil.longs.Long2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.longs.Long2IntMap; import it.unimi.dsi.fastutil.longs.LongIterator; import it.unimi.dsi.fastutil.objects.Object2IntLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2IntMap; import it.unimi.dsi.fastutil.objects.ObjectIterator; import java.io.IOException; import java.util.Iterator; import parquet.Log; import parquet.bytes.BytesInput; import parquet.bytes.BytesUtils; import parquet.column.Encoding; import parquet.column.page.DictionaryPage; import parquet.column.values.ValuesWriter; import parquet.column.values.dictionary.IntList.IntIterator; import parquet.column.values.plain.PlainValuesWriter; import parquet.column.values.rle.RunLengthBitPackingHybridEncoder; import parquet.io.ParquetEncodingException; import parquet.io.api.Binary; /** * Will attempt to encode values using a dictionary and fall back to plain encoding * if the dictionary gets too big * * @author Julien Le Dem * */ public abstract class DictionaryValuesWriter extends ValuesWriter { private static final Log LOG = Log.getLog(DictionaryValuesWriter.class); /* max entries allowed for the dictionary will fail over to plain encoding if reached */ private static final int MAX_DICTIONARY_ENTRIES = Integer.MAX_VALUE - 1; /* maximum size in bytes allowed for the dictionary will fail over to plain encoding if reached */ protected final int maxDictionaryByteSize; /* contains the values encoded in plain if the dictionary grows too big */ protected final PlainValuesWriter plainValuesWriter; /* will become true if the dictionary becomes too big */ protected boolean dictionaryTooBig; /* current size in bytes the dictionary will take once serialized */ protected int dictionaryByteSize; /* size in bytes of the dictionary at the end of last dictionary encoded page (in case the current page falls back to PLAIN) */ protected int lastUsedDictionaryByteSize; /* size in items of the dictionary at the end of last dictionary encoded page (in case the current page falls back to PLAIN) */ protected int lastUsedDictionarySize; /* dictionary encoded values */ protected IntList encodedValues = new IntList(); /* size of raw data, even if dictionary is used, it will not have effect on raw data size, it is used to decide * if fall back to plain encoding is better by comparing rawDataByteSize with Encoded data size * It's also used in getBufferedSize, so the page will be written based on raw data size */ protected long rawDataByteSize = 0; /** indicates if this is the first page being processed */ protected boolean firstPage = true; /** * @param maxDictionaryByteSize * @param initialSize */ protected DictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { this.maxDictionaryByteSize = maxDictionaryByteSize; this.plainValuesWriter = new PlainValuesWriter(initialSize); } /** * check the size constraints of the dictionary and fail over to plain values encoding if threshold reached */ protected void checkAndFallbackIfNeeded() { if (dictionaryByteSize > maxDictionaryByteSize || getDictionarySize() > MAX_DICTIONARY_ENTRIES) { // if the dictionary reaches the max byte size or the values can not be encoded on 4 bytes anymore. fallBackToPlainEncoding(); } } private void fallBackToPlainEncoding() { if (DEBUG) LOG.debug("dictionary is now too big, falling back to plain: " + dictionaryByteSize + "B and " + getDictionarySize() + " entries"); dictionaryTooBig = true; fallBackDictionaryEncodedData(); if (lastUsedDictionarySize == 0) { // if we never used the dictionary // we free dictionary encoded data clearDictionaryContent(); dictionaryByteSize = 0; encodedValues = new IntList(); } } protected abstract void fallBackDictionaryEncodedData(); @Override public long getBufferedSize() { // use raw data size to decide if we want to flush the page // so the acutual size of the page written could be much more smaller // due to dictionary encoding. This prevents page being to big when fallback happens. return rawDataByteSize; } @Override public long getAllocatedSize() { // size used in memory return encodedValues.size() * 4 + dictionaryByteSize + plainValuesWriter.getAllocatedSize(); } @Override public BytesInput getBytes() { if (!dictionaryTooBig && getDictionarySize() > 0) { int maxDicId = getDictionarySize() - 1; if (DEBUG) LOG.debug("max dic id " + maxDicId); int bitWidth = BytesUtils.getWidthFromMaxInt(maxDicId); // TODO: what is a good initialCapacity? RunLengthBitPackingHybridEncoder encoder = new RunLengthBitPackingHybridEncoder(bitWidth, 64 * 1024); IntIterator iterator = encodedValues.iterator(); try { while (iterator.hasNext()) { encoder.writeInt(iterator.next()); } // encodes the bit width byte[] bytesHeader = new byte[] { (byte) bitWidth }; BytesInput rleEncodedBytes = encoder.toBytes(); if (DEBUG) LOG.debug("rle encoded bytes " + rleEncodedBytes.size()); BytesInput bytes = concat(BytesInput.from(bytesHeader), rleEncodedBytes); if (firstPage && ((bytes.size() + dictionaryByteSize) > rawDataByteSize)) { fallBackToPlainEncoding(); } else { // remember size of dictionary when we last wrote a page lastUsedDictionarySize = getDictionarySize(); lastUsedDictionaryByteSize = dictionaryByteSize; return bytes; } } catch (IOException e) { throw new ParquetEncodingException("could not encode the values", e); } } return plainValuesWriter.getBytes(); } @Override public Encoding getEncoding() { firstPage = false; if (!dictionaryTooBig && getDictionarySize() > 0) { return PLAIN_DICTIONARY; } return plainValuesWriter.getEncoding(); } @Override public void reset() { encodedValues = new IntList(); plainValuesWriter.reset(); rawDataByteSize = 0; } @Override public void resetDictionary() { lastUsedDictionaryByteSize = 0; lastUsedDictionarySize = 0; dictionaryTooBig = false; clearDictionaryContent(); } /** * clear/free the underlying dictionary content */ protected abstract void clearDictionaryContent(); /** * @return size in items */ protected abstract int getDictionarySize(); @Override public String memUsageString(String prefix) { return String.format( "%s DictionaryValuesWriter{\n%s\n%s\n%s\n%s}\n", prefix, plainValuesWriter. memUsageString(prefix + " plain:"), prefix + " dict:" + dictionaryByteSize, prefix + " values:" + String.valueOf(encodedValues.size() * 4), prefix ); } /** * */ public static class PlainBinaryDictionaryValuesWriter extends DictionaryValuesWriter { /* type specific dictionary content */ private Object2IntMap<Binary> binaryDictionaryContent = new Object2IntLinkedOpenHashMap<Binary>(); /** * @param maxDictionaryByteSize * @param initialSize */ public PlainBinaryDictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { super(maxDictionaryByteSize, initialSize); binaryDictionaryContent.defaultReturnValue(-1); } @Override public void writeBytes(Binary v) { if (!dictionaryTooBig) { int id = binaryDictionaryContent.getInt(v); if (id == -1) { id = binaryDictionaryContent.size(); binaryDictionaryContent.put(v, id); // length as int (4 bytes) + actual bytes dictionaryByteSize += 4 + v.length(); } encodedValues.add(id); checkAndFallbackIfNeeded(); } else { plainValuesWriter.writeBytes(v); } //for rawdata, length(4 bytes int) is stored, followed by the binary content itself rawDataByteSize += v.length() + 4; } @Override public DictionaryPage createDictionaryPage() { if (lastUsedDictionarySize > 0) { // return a dictionary only if we actually used it PlainValuesWriter dictionaryEncoder = new PlainValuesWriter(lastUsedDictionaryByteSize); Iterator<Binary> binaryIterator = binaryDictionaryContent.keySet().iterator(); // write only the part of the dict that we used for (int i = 0; i < lastUsedDictionarySize; i++) { Binary entry = binaryIterator.next(); dictionaryEncoder.writeBytes(entry); } return new DictionaryPage(dictionaryEncoder.getBytes(), lastUsedDictionarySize, PLAIN_DICTIONARY); } return plainValuesWriter.createDictionaryPage(); } @Override public int getDictionarySize() { return binaryDictionaryContent.size(); } @Override protected void clearDictionaryContent() { binaryDictionaryContent.clear(); } @Override protected void fallBackDictionaryEncodedData() { //build reverse dictionary Binary[] reverseDictionary = new Binary[getDictionarySize()]; ObjectIterator<Object2IntMap.Entry<Binary>> entryIterator = binaryDictionaryContent.object2IntEntrySet().iterator(); while (entryIterator.hasNext()) { Object2IntMap.Entry<Binary> entry = entryIterator.next(); reverseDictionary[entry.getIntValue()] = entry.getKey(); } //fall back to plain encoding IntIterator iterator = encodedValues.iterator(); while (iterator.hasNext()) { int id = iterator.next(); plainValuesWriter.writeBytes(reverseDictionary[id]); } } } /** * */ public static class PlainLongDictionaryValuesWriter extends DictionaryValuesWriter { /* type specific dictionary content */ private Long2IntMap longDictionaryContent = new Long2IntLinkedOpenHashMap(); /** * @param maxDictionaryByteSize * @param initialSize */ public PlainLongDictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { super(maxDictionaryByteSize, initialSize); longDictionaryContent.defaultReturnValue(-1); } @Override public void writeLong(long v) { if (!dictionaryTooBig) { int id = longDictionaryContent.get(v); if (id == -1) { id = longDictionaryContent.size(); longDictionaryContent.put(v, id); dictionaryByteSize += 8; } encodedValues.add(id); checkAndFallbackIfNeeded(); } else { plainValuesWriter.writeLong(v); } rawDataByteSize += 8; } @Override public DictionaryPage createDictionaryPage() { if (lastUsedDictionarySize > 0) { // return a dictionary only if we actually used it PlainValuesWriter dictionaryEncoder = new PlainValuesWriter(lastUsedDictionaryByteSize); LongIterator longIterator = longDictionaryContent.keySet().iterator(); // write only the part of the dict that we used for (int i = 0; i < lastUsedDictionarySize; i++) { dictionaryEncoder.writeLong(longIterator.nextLong()); } return new DictionaryPage(dictionaryEncoder.getBytes(), lastUsedDictionarySize, PLAIN_DICTIONARY); } return plainValuesWriter.createDictionaryPage(); } @Override public int getDictionarySize() { return longDictionaryContent.size(); } @Override protected void clearDictionaryContent() { longDictionaryContent.clear(); } @Override protected void fallBackDictionaryEncodedData() { //build reverse dictionary long[] reverseDictionary = new long[getDictionarySize()]; ObjectIterator<Long2IntMap.Entry> entryIterator = longDictionaryContent.long2IntEntrySet().iterator(); while (entryIterator.hasNext()) { Long2IntMap.Entry entry = entryIterator.next(); reverseDictionary[entry.getIntValue()] = entry.getLongKey(); } //fall back to plain encoding IntIterator iterator = encodedValues.iterator(); while (iterator.hasNext()) { int id = iterator.next(); plainValuesWriter.writeLong(reverseDictionary[id]); } } } /** * */ public static class PlainDoubleDictionaryValuesWriter extends DictionaryValuesWriter { /* type specific dictionary content */ private Double2IntMap doubleDictionaryContent = new Double2IntLinkedOpenHashMap(); /** * @param maxDictionaryByteSize * @param initialSize */ public PlainDoubleDictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { super(maxDictionaryByteSize, initialSize); doubleDictionaryContent.defaultReturnValue(-1); } @Override public void writeDouble(double v) { if (!dictionaryTooBig) { int id = doubleDictionaryContent.get(v); if (id == -1) { id = doubleDictionaryContent.size(); doubleDictionaryContent.put(v, id); dictionaryByteSize += 8; } encodedValues.add(id); checkAndFallbackIfNeeded(); } else { plainValuesWriter.writeDouble(v); } rawDataByteSize += 8; } @Override public DictionaryPage createDictionaryPage() { if (lastUsedDictionarySize > 0) { // return a dictionary only if we actually used it PlainValuesWriter dictionaryEncoder = new PlainValuesWriter(lastUsedDictionaryByteSize); DoubleIterator doubleIterator = doubleDictionaryContent.keySet().iterator(); // write only the part of the dict that we used for (int i = 0; i < lastUsedDictionarySize; i++) { dictionaryEncoder.writeDouble(doubleIterator.nextDouble()); } return new DictionaryPage(dictionaryEncoder.getBytes(), lastUsedDictionarySize, PLAIN_DICTIONARY); } return plainValuesWriter.createDictionaryPage(); } @Override public int getDictionarySize() { return doubleDictionaryContent.size(); } @Override protected void clearDictionaryContent() { doubleDictionaryContent.clear(); } @Override protected void fallBackDictionaryEncodedData() { //build reverse dictionary double[] reverseDictionary = new double[getDictionarySize()]; ObjectIterator<Double2IntMap.Entry> entryIterator = doubleDictionaryContent.double2IntEntrySet().iterator(); while (entryIterator.hasNext()) { Double2IntMap.Entry entry = entryIterator.next(); reverseDictionary[entry.getIntValue()] = entry.getDoubleKey(); } //fall back to plain encoding IntIterator iterator = encodedValues.iterator(); while (iterator.hasNext()) { int id = iterator.next(); plainValuesWriter.writeDouble(reverseDictionary[id]); } } } /** * */ public static class PlainIntegerDictionaryValuesWriter extends DictionaryValuesWriter { /* type specific dictionary content */ private Int2IntMap intDictionaryContent = new Int2IntLinkedOpenHashMap(); /** * @param maxDictionaryByteSize * @param initialSize */ public PlainIntegerDictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { super(maxDictionaryByteSize, initialSize); intDictionaryContent.defaultReturnValue(-1); } @Override public void writeInteger(int v) { if (!dictionaryTooBig) { int id = intDictionaryContent.get(v); if (id == -1) { id = intDictionaryContent.size(); intDictionaryContent.put(v, id); dictionaryByteSize += 4; } encodedValues.add(id); checkAndFallbackIfNeeded(); } else { plainValuesWriter.writeInteger(v); } //Each integer takes 4 bytes as raw data(plain encoding) rawDataByteSize += 4; } @Override public DictionaryPage createDictionaryPage() { if (lastUsedDictionarySize > 0) { // return a dictionary only if we actually used it PlainValuesWriter dictionaryEncoder = new PlainValuesWriter(lastUsedDictionaryByteSize); it.unimi.dsi.fastutil.ints.IntIterator intIterator = intDictionaryContent.keySet().iterator(); // write only the part of the dict that we used for (int i = 0; i < lastUsedDictionarySize; i++) { dictionaryEncoder.writeInteger(intIterator.nextInt()); } return new DictionaryPage(dictionaryEncoder.getBytes(), lastUsedDictionarySize, PLAIN_DICTIONARY); } return plainValuesWriter.createDictionaryPage(); } @Override public int getDictionarySize() { return intDictionaryContent.size(); } @Override protected void clearDictionaryContent() { intDictionaryContent.clear(); } @Override protected void fallBackDictionaryEncodedData() { //build reverse dictionary int[] reverseDictionary = new int[getDictionarySize()]; ObjectIterator<Int2IntMap.Entry> entryIterator = intDictionaryContent.int2IntEntrySet().iterator(); while (entryIterator.hasNext()) { Int2IntMap.Entry entry = entryIterator.next(); reverseDictionary[entry.getIntValue()] = entry.getIntKey(); } //fall back to plain encoding IntIterator iterator = encodedValues.iterator(); while (iterator.hasNext()) { int id = iterator.next(); plainValuesWriter.writeInteger(reverseDictionary[id]); } } } /** * */ public static class PlainFloatDictionaryValuesWriter extends DictionaryValuesWriter { /* type specific dictionary content */ private Float2IntMap floatDictionaryContent = new Float2IntLinkedOpenHashMap(); /** * @param maxDictionaryByteSize * @param initialSize */ public PlainFloatDictionaryValuesWriter(int maxDictionaryByteSize, int initialSize) { super(maxDictionaryByteSize, initialSize); floatDictionaryContent.defaultReturnValue(-1); } @Override public void writeFloat(float v) { if (!dictionaryTooBig) { int id = floatDictionaryContent.get(v); if (id == -1) { id = floatDictionaryContent.size(); floatDictionaryContent.put(v, id); dictionaryByteSize += 4; } encodedValues.add(id); checkAndFallbackIfNeeded(); } else { plainValuesWriter.writeFloat(v); } rawDataByteSize += 4; } @Override public DictionaryPage createDictionaryPage() { if (lastUsedDictionarySize > 0) { // return a dictionary only if we actually used it PlainValuesWriter dictionaryEncoder = new PlainValuesWriter(lastUsedDictionaryByteSize); FloatIterator floatIterator = floatDictionaryContent.keySet().iterator(); // write only the part of the dict that we used for (int i = 0; i < lastUsedDictionarySize; i++) { dictionaryEncoder.writeFloat(floatIterator.nextFloat()); } return new DictionaryPage(dictionaryEncoder.getBytes(), lastUsedDictionarySize, PLAIN_DICTIONARY); } return plainValuesWriter.createDictionaryPage(); } @Override public int getDictionarySize() { return floatDictionaryContent.size(); } @Override protected void clearDictionaryContent() { floatDictionaryContent.clear(); } @Override protected void fallBackDictionaryEncodedData() { //build reverse dictionary float[] reverseDictionary = new float[getDictionarySize()]; ObjectIterator<Float2IntMap.Entry> entryIterator = floatDictionaryContent.float2IntEntrySet().iterator(); while (entryIterator.hasNext()) { Float2IntMap.Entry entry = entryIterator.next(); reverseDictionary[entry.getIntValue()] = entry.getFloatKey(); } //fall back to plain encoding IntIterator iterator = encodedValues.iterator(); while (iterator.hasNext()) { int id = iterator.next(); plainValuesWriter.writeFloat(reverseDictionary[id]); } } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.models.cache.infinispan; import org.keycloak.models.ClientModel; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleContainerModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserConsentModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserModel; import org.keycloak.models.cache.CachedUserModel; import org.keycloak.models.cache.infinispan.entities.CachedUser; import org.keycloak.models.cache.infinispan.entities.CachedUserConsent; import org.keycloak.models.utils.KeycloakModelUtils; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class UserAdapter implements CachedUserModel { protected UserModel updated; protected CachedUser cached; protected UserCacheSession userProviderCache; protected KeycloakSession keycloakSession; protected RealmModel realm; public UserAdapter(CachedUser cached, UserCacheSession userProvider, KeycloakSession keycloakSession, RealmModel realm) { this.cached = cached; this.userProviderCache = userProvider; this.keycloakSession = keycloakSession; this.realm = realm; } protected void getDelegateForUpdate() { if (updated == null) { userProviderCache.registerUserInvalidation(realm, cached); updated = userProviderCache.getDelegate().getUserById(getId(), realm); if (updated == null) throw new IllegalStateException("Not found in database"); } } @Override public void invalidate() { getDelegateForUpdate(); } @Override public long getCacheTimestamp() { return cached.getCacheTimestamp(); } @Override public ConcurrentHashMap getCachedWith() { return cached.getCachedWith(); } @Override public String getId() { if (updated != null) return updated.getId(); return cached.getId(); } @Override public String getUsername() { if (updated != null) return updated.getUsername(); return cached.getUsername(); } @Override public void setUsername(String username) { getDelegateForUpdate(); username = KeycloakModelUtils.toLowerCaseSafe(username); updated.setUsername(username); } @Override public Long getCreatedTimestamp() { // get from cached always as it is immutable return cached.getCreatedTimestamp(); } @Override public void setCreatedTimestamp(Long timestamp) { // nothing to do as this value is immutable } @Override public boolean isEnabled() { if (updated != null) return updated.isEnabled(); return cached.isEnabled(); } @Override public boolean isOtpEnabled() { if (updated != null) return updated.isOtpEnabled(); return cached.isTotp(); } @Override public void setEnabled(boolean enabled) { getDelegateForUpdate(); updated.setEnabled(enabled); } @Override public void setSingleAttribute(String name, String value) { getDelegateForUpdate(); updated.setSingleAttribute(name, value); } @Override public void setAttribute(String name, List<String> values) { getDelegateForUpdate(); updated.setAttribute(name, values); } @Override public void removeAttribute(String name) { getDelegateForUpdate(); updated.removeAttribute(name); } @Override public String getFirstAttribute(String name) { if (updated != null) return updated.getFirstAttribute(name); return cached.getAttributes().getFirst(name); } @Override public List<String> getAttribute(String name) { if (updated != null) return updated.getAttribute(name); List<String> result = cached.getAttributes().get(name); return (result == null) ? Collections.<String>emptyList() : result; } @Override public Map<String, List<String>> getAttributes() { if (updated != null) return updated.getAttributes(); return cached.getAttributes(); } @Override public Set<String> getRequiredActions() { if (updated != null) return updated.getRequiredActions(); return cached.getRequiredActions(); } @Override public void addRequiredAction(RequiredAction action) { getDelegateForUpdate(); updated.addRequiredAction(action); } @Override public void removeRequiredAction(RequiredAction action) { getDelegateForUpdate(); updated.removeRequiredAction(action); } @Override public void addRequiredAction(String action) { getDelegateForUpdate(); updated.addRequiredAction(action); } @Override public void removeRequiredAction(String action) { getDelegateForUpdate(); updated.removeRequiredAction(action); } @Override public String getFirstName() { if (updated != null) return updated.getFirstName(); return cached.getFirstName(); } @Override public void setFirstName(String firstName) { getDelegateForUpdate(); updated.setFirstName(firstName); } @Override public String getLastName() { if (updated != null) return updated.getLastName(); return cached.getLastName(); } @Override public void setLastName(String lastName) { getDelegateForUpdate(); updated.setLastName(lastName); } @Override public String getEmail() { if (updated != null) return updated.getEmail(); return cached.getEmail(); } @Override public void setEmail(String email) { getDelegateForUpdate(); email = KeycloakModelUtils.toLowerCaseSafe(email); updated.setEmail(email); } @Override public boolean isEmailVerified() { if (updated != null) return updated.isEmailVerified(); return cached.isEmailVerified(); } @Override public void setEmailVerified(boolean verified) { getDelegateForUpdate(); updated.setEmailVerified(verified); } @Override public void setOtpEnabled(boolean totp) { getDelegateForUpdate(); updated.setOtpEnabled(totp); } @Override public void updateCredential(UserCredentialModel cred) { getDelegateForUpdate(); updated.updateCredential(cred); } @Override public List<UserCredentialValueModel> getCredentialsDirectly() { if (updated != null) return updated.getCredentialsDirectly(); return cached.getCredentials(); } @Override public void updateCredentialDirectly(UserCredentialValueModel cred) { getDelegateForUpdate(); updated.updateCredentialDirectly(cred); } @Override public String getFederationLink() { if (updated != null) return updated.getFederationLink(); return cached.getFederationLink(); } @Override public void setFederationLink(String link) { getDelegateForUpdate(); updated.setFederationLink(link); } @Override public String getServiceAccountClientLink() { if (updated != null) return updated.getServiceAccountClientLink(); return cached.getServiceAccountClientLink(); } @Override public void setServiceAccountClientLink(String clientInternalId) { getDelegateForUpdate(); updated.setServiceAccountClientLink(clientInternalId); } @Override public Set<RoleModel> getRealmRoleMappings() { if (updated != null) return updated.getRealmRoleMappings(); Set<RoleModel> roleMappings = getRoleMappings(); Set<RoleModel> realmMappings = new HashSet<RoleModel>(); for (RoleModel role : roleMappings) { RoleContainerModel container = role.getContainer(); if (container instanceof RealmModel) { if (((RealmModel) container).getId().equals(realm.getId())) { realmMappings.add(role); } } } return realmMappings; } @Override public Set<RoleModel> getClientRoleMappings(ClientModel app) { if (updated != null) return updated.getClientRoleMappings(app); Set<RoleModel> roleMappings = getRoleMappings(); Set<RoleModel> appMappings = new HashSet<RoleModel>(); for (RoleModel role : roleMappings) { RoleContainerModel container = role.getContainer(); if (container instanceof ClientModel) { if (((ClientModel) container).getId().equals(app.getId())) { appMappings.add(role); } } } return appMappings; } @Override public boolean hasRole(RoleModel role) { if (updated != null) return updated.hasRole(role); if (cached.getRoleMappings().contains(role.getId())) return true; Set<RoleModel> mappings = getRoleMappings(); for (RoleModel mapping: mappings) { if (mapping.hasRole(role)) return true; } return false; } @Override public void grantRole(RoleModel role) { getDelegateForUpdate(); updated.grantRole(role); } @Override public Set<RoleModel> getRoleMappings() { if (updated != null) return updated.getRoleMappings(); Set<RoleModel> roles = new HashSet<RoleModel>(); for (String id : cached.getRoleMappings()) { RoleModel roleById = keycloakSession.realms().getRoleById(id, realm); if (roleById == null) { // chance that role was removed, so just delete to persistence and get user invalidated getDelegateForUpdate(); return updated.getRoleMappings(); } roles.add(roleById); } return roles; } @Override public void deleteRoleMapping(RoleModel role) { getDelegateForUpdate(); updated.deleteRoleMapping(role); } @Override public Set<GroupModel> getGroups() { if (updated != null) return updated.getGroups(); Set<GroupModel> groups = new HashSet<GroupModel>(); for (String id : cached.getGroups()) { GroupModel groupModel = keycloakSession.realms().getGroupById(id, realm); if (groupModel == null) { // chance that role was removed, so just delete to persistence and get user invalidated getDelegateForUpdate(); return updated.getGroups(); } groups.add(groupModel); } return groups; } @Override public void joinGroup(GroupModel group) { getDelegateForUpdate(); updated.joinGroup(group); } @Override public void leaveGroup(GroupModel group) { getDelegateForUpdate(); updated.leaveGroup(group); } @Override public boolean isMemberOf(GroupModel group) { if (updated != null) return updated.isMemberOf(group); if (cached.getGroups().contains(group.getId())) return true; Set<GroupModel> roles = getGroups(); return KeycloakModelUtils.isMember(roles, group); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof UserModel)) return false; UserModel that = (UserModel) o; return that.getId().equals(getId()); } @Override public int hashCode() { return getId().hashCode(); } }
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the license, or (at your option) any later version. */ package org.gjt.jclasslib.structures; import org.gjt.jclasslib.structures.attributes.*; import org.gjt.jclasslib.structures.constants.ConstantUtf8Info; import java.io.*; /** * Base class for all attribute structures in the <tt>attribute</tt> package. * * @author <a href="mailto:jclasslib@ej-technologies.com">Ingo Kegel</a>, <a href="mailto:vitor.carreira@gmail.com">Vitor Carreira</a> * @version $Revision: 1.1 $ $Date: 2005/11/01 13:18:24 $ */ public class AttributeInfo extends AbstractStructureWithAttributes { /** * Set this JVM System property to true to skip reading of all attributes. * Some class file operations may fail in this case. */ public static final String SYSTEM_PROPERTY_SKIP_ATTRIBUTES = "jclasslib.io.skipAttributes"; private int attributeNameIndex; private int attributeLength; private byte[] info; /** * Factory method for creating <tt>AttributeInfo</tt> structures. <p> * An <tt>AttributeInfo</tt> of the appropriate subtype from the <tt>attributes</tt> package * is created unless the type of the attribute is unknown in which case an instance of * <tt>AttributeInfo</tt> is returned. <p> * <p/> * Attributes are skipped if the environment variable <tt>SYSTEM_PROPERTY_SKIP_ATTRIBUTES</tt> * is set to true. * * @param in the <tt>DataInput</tt> from which to read the <tt>AttributeInfo</tt> structure * @param classFile the parent class file of the structure to be created * @return the new <tt>AttributeInfo</tt> structure * @throws InvalidByteCodeException if the byte code is invalid * @throws IOException if an exception occurs with the <tt>DataInput</tt> */ public static AttributeInfo createOrSkip(DataInput in, ClassFile classFile) throws InvalidByteCodeException, IOException { AttributeInfo attributeInfo = null; if (Boolean.getBoolean(SYSTEM_PROPERTY_SKIP_ATTRIBUTES)) { in.skipBytes(2); in.skipBytes(in.readInt()); } else { int attributeNameIndex = in.readUnsignedShort(); int attributeLength = in.readInt(); ConstantUtf8Info cpInfoName = classFile.getConstantPoolUtf8Entry(attributeNameIndex); String attributeName = null; if (cpInfoName == null) { return null; } attributeName = cpInfoName.getString(); if (ConstantValueAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new ConstantValueAttribute(); } else if (CodeAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new CodeAttribute(); } else if (ExceptionsAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new ExceptionsAttribute(); } else if (InnerClassesAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new InnerClassesAttribute(); } else if (SyntheticAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new SyntheticAttribute(); } else if (SourceFileAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new SourceFileAttribute(); } else if (LineNumberTableAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new LineNumberTableAttribute(); } else if (LocalVariableTableAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new LocalVariableTableAttribute(); } else if (DeprecatedAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new DeprecatedAttribute(); } else if (EnclosingMethodAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new EnclosingMethodAttribute(); } else if (SignatureAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new SignatureAttribute(); } else if (LocalVariableTypeTableAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new LocalVariableTypeTableAttribute(); } else if (RuntimeVisibleAnnotationsAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new RuntimeVisibleAnnotationsAttribute(); } else if (RuntimeInvisibleAnnotationsAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new RuntimeInvisibleAnnotationsAttribute(); } else if (AnnotationDefaultAttribute.ATTRIBUTE_NAME.equals(attributeName)) { attributeInfo = new AnnotationDefaultAttribute(); } else { attributeInfo = new AttributeInfo(attributeLength); } attributeInfo.setAttributeNameIndex(attributeNameIndex); attributeInfo.setClassFile(classFile); attributeInfo.read(in); } return attributeInfo; } /** * Constructor. */ protected AttributeInfo() { } private AttributeInfo(int attributeLength) { this.attributeLength = attributeLength; } /** * Get the constant pool index for the name of the attribute. * * @return the index */ public int getAttributeNameIndex() { return attributeNameIndex; } /** * Set the constant pool index for the name of the attribute. * * @param attributeNameIndex the new index */ public void setAttributeNameIndex(int attributeNameIndex) { this.attributeNameIndex = attributeNameIndex; } /** * Get the raw bytes of the attribute. <p> * <p/> * Is non-null only if attribute is of unknown type. * * @return the byte array */ public byte[] getInfo() { return info; } /** * Set the raw bytes of the attribute. <p> * <p/> * Works only if attribute is an instance of <tt>AttributeInfo</tt>. * * @param info the new byte array */ public void setInfo(byte[] info) { this.info = info; } /** * Get the name of the attribute. * * @return the name * @throws InvalidByteCodeException if the byte code is invalid */ public String getName() throws InvalidByteCodeException { return classFile.getConstantPoolUtf8Entry(attributeNameIndex).getString(); } public void read(DataInput in) throws InvalidByteCodeException, IOException { info = new byte[attributeLength]; in.readFully(info); if (debug) debug("read " + getDebugMessage()); } public void write(DataOutput out) throws InvalidByteCodeException, IOException { out.writeShort(attributeNameIndex); out.writeInt(getAttributeLength()); if (getClass().equals(AttributeInfo.class)) { out.write(info); if (debug) debug("wrote " + getDebugMessage()); } } /** * Get the length of this attribute as a number of bytes. * * @return the length */ public int getAttributeLength() { return getLength(info); } // cannot override debug because subclasses will call super.debug // and expect to call the implementation in AbstractStructure private String getDebugMessage() { String type; try { type = classFile.getConstantPoolUtf8Entry(attributeNameIndex).getString(); } catch (InvalidByteCodeException ex) { type = "(unknown)"; } return "uninterpreted attribute of reported type " + type; } protected String printAccessFlagsVerbose(int accessFlags) { if (accessFlags != 0) throw new RuntimeException("Access flags should be zero: " + Integer.toHexString(accessFlags)); return ""; } }
package org.knowm.xchange.bleutrade.service; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.powermock.api.mockito.PowerMockito.mock; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.bleutrade.BleutradeAssert; import org.knowm.xchange.bleutrade.BleutradeAuthenticated; import org.knowm.xchange.bleutrade.BleutradeExchange; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeCurrenciesReturn; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeCurrency; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeMarket; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeMarketHistoryReturn; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeMarketsReturn; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeOrderBookReturn; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeTicker; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeTickerReturn; import org.knowm.xchange.bleutrade.dto.marketdata.BleutradeTrade; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.exceptions.ExchangeException; import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; @RunWith(PowerMockRunner.class) public class BleutradeMarketDataServiceIntegration extends BleutradeServiceTestSupport { private BleutradeMarketDataService marketDataService; private static final Ticker TICKER = new Ticker.Builder().currencyPair(BLEU_BTC_CP).last(new BigDecimal("0.00101977")) .bid(new BigDecimal("0.00100000")).ask(new BigDecimal("0.00101977")).high(new BigDecimal("0.00105000")).low(new BigDecimal("0.00086000")) .vwap(new BigDecimal("0.00103455")).volume(new BigDecimal("2450.97496015")).timestamp(new Date(1406632770000L)).build(); @Before public void setUp() { BleutradeExchange exchange = (BleutradeExchange) ExchangeFactory.INSTANCE.createExchange(BleutradeExchange.class.getCanonicalName()); exchange.getExchangeSpecification().setUserName(SPECIFICATION_USERNAME); exchange.getExchangeSpecification().setApiKey(SPECIFICATION_API_KEY); exchange.getExchangeSpecification().setSecretKey(SPECIFICATION_SECRET_KEY); marketDataService = new BleutradeMarketDataService(exchange); } @Test public void constructor() { assertThat(Whitebox.getInternalState(marketDataService, "apiKey")).isEqualTo(SPECIFICATION_API_KEY); } @Test public void shouldGetTicker() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(true); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTicker()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTicker("BLEU_BTC")).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when Ticker ticker = marketDataService.getTicker(BLEU_BTC_CP); // then assertThat(ticker.toString()).isEqualTo(EXPECTED_BLEUTRADE_TICKER_STR); BleutradeAssert.assertEquals(ticker, TICKER); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetTicker() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(false); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTicker()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTicker("BLEU_BTC")).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getTicker(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when ticker request was unsuccessful"); } @Test public void shouldGetOrderBook() throws IOException { // given BleutradeOrderBookReturn orderBookReturn1 = new BleutradeOrderBookReturn(); orderBookReturn1.setSuccess(true); orderBookReturn1.setMessage("test message"); orderBookReturn1.setResult(createBleutradeOrderBook(expectedBleutradeLevelBuys(), expectedBleutradeLevelSells())); BleutradeOrderBookReturn orderBookReturn2 = new BleutradeOrderBookReturn(); orderBookReturn2.setSuccess(true); orderBookReturn2.setMessage(""); orderBookReturn2.setResult(createBleutradeOrderBook(Collections.EMPTY_LIST, Collections.EMPTY_LIST)); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeOrderBook("BTC_AUD", "ALL", 30)).thenReturn(orderBookReturn1); PowerMockito.when(bleutrade.getBleutradeOrderBook("BLEU_BTC", "ALL", 50)).thenReturn(orderBookReturn2); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); final LimitOrder[] expectedAsks = expectedAsks(); final LimitOrder[] expectedBids = expectedBids(); // when OrderBook orderBook1 = marketDataService.getOrderBook(CurrencyPair.BTC_AUD, 30); OrderBook orderBook2 = marketDataService.getOrderBook(BLEU_BTC_CP, "test parameter"); // then List<LimitOrder> asks = orderBook1.getAsks(); assertThat(asks).hasSize(4); for (int i = 0; i < asks.size(); i++) { BleutradeAssert.assertEquals(asks.get(i), expectedAsks[i]); } List<LimitOrder> bids = orderBook1.getBids(); assertThat(bids).hasSize(2); for (int i = 0; i < bids.size(); i++) { BleutradeAssert.assertEquals(bids.get(i), expectedBids[i]); } assertThat(orderBook2.getAsks()).isEmpty(); assertThat(orderBook2.getBids()).isEmpty(); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulGetOrderBook() throws IOException { // given BleutradeOrderBookReturn orderBookReturn = new BleutradeOrderBookReturn(); orderBookReturn.setSuccess(false); orderBookReturn.setMessage("test message"); orderBookReturn.setResult(createBleutradeOrderBook(expectedBleutradeLevelBuys(), expectedBleutradeLevelSells())); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeOrderBook("BLEU_BTC", "ALL", 50)).thenReturn(orderBookReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getOrderBook(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when order book request was unsuccessful"); } @Test public void shouldGetTrades() throws IOException { // given final List<BleutradeTrade> expectedBleutradeTrades = expectedBleutradeTrades(); BleutradeMarketHistoryReturn marketHistoryReturn1 = new BleutradeMarketHistoryReturn(); marketHistoryReturn1.setSuccess(true); marketHistoryReturn1.setMessage("test message"); marketHistoryReturn1.setResult(expectedBleutradeTrades); BleutradeMarketHistoryReturn marketHistoryReturn2 = new BleutradeMarketHistoryReturn(); marketHistoryReturn2.setSuccess(true); marketHistoryReturn2.setMessage(""); marketHistoryReturn2.setResult(Collections.EMPTY_LIST); BleutradeMarketHistoryReturn marketHistoryReturn3 = new BleutradeMarketHistoryReturn(); marketHistoryReturn3.setSuccess(true); marketHistoryReturn3.setMessage("test message"); marketHistoryReturn3.setResult(Arrays.asList(expectedBleutradeTrades.get(0))); BleutradeMarketHistoryReturn marketHistoryReturn4 = new BleutradeMarketHistoryReturn(); marketHistoryReturn4.setSuccess(true); marketHistoryReturn4.setMessage("test message"); marketHistoryReturn4.setResult(Arrays.asList(expectedBleutradeTrades.get(1))); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 30)).thenReturn(marketHistoryReturn1); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 50)).thenReturn(marketHistoryReturn2); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 1)).thenReturn(marketHistoryReturn3); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BTC_AUD", 200)).thenReturn(marketHistoryReturn4); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); final Trade[] expectedTrades = expectedTrades(); // when Trades trades1 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 30); Trades trades2 = marketDataService.getTrades(CurrencyPair.BTC_AUD, "test parameter"); Trades trades3 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 0); Trades trades4 = marketDataService.getTrades(CurrencyPair.BTC_AUD, 201); // then List<Trade> tradeList = trades1.getTrades(); assertThat(tradeList).hasSize(2); for (int i = 0; i < tradeList.size(); i++) { BleutradeAssert.assertEquals(tradeList.get(i), expectedTrades[i]); } assertThat(trades2.getTrades()).isEmpty(); assertThat(trades3.getTrades()).hasSize(1); BleutradeAssert.assertEquals(trades3.getTrades().get(0), expectedTrades[0]); assertThat(trades4.getTrades()).hasSize(1); BleutradeAssert.assertEquals(trades4.getTrades().get(0), expectedTrades[1]); } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulGetTrades() throws IOException { // given BleutradeMarketHistoryReturn marketHistoryReturn = new BleutradeMarketHistoryReturn(); marketHistoryReturn.setSuccess(false); marketHistoryReturn.setMessage("test message"); marketHistoryReturn.setResult(expectedBleutradeTrades()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarketHistory("BLEU_BTC", 50)).thenReturn(marketHistoryReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getTrades(BLEU_BTC_CP); // then fail("BleutradeMarketDataService should throw ExchangeException when trades request was unsuccessful"); } @Test public void shouldGetTickers() throws IOException { // given final List<BleutradeTicker> expectedBleutradeTickers = expectedBleutradeTickers(); final String[] expectedBleutradeTickersStr = expectedBleutradeTickersStr(); BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(true); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTickers); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTickers()).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeTicker> tickers = marketDataService.getBleutradeTickers(); // then assertThat(tickers).hasSize(2); for (int i = 0; i < tickers.size(); i++) { BleutradeAssert.assertEquals(tickers.get(i), expectedBleutradeTickers.get(i)); assertThat(tickers.get(i).toString()).isEqualTo(expectedBleutradeTickersStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetTickers() throws IOException { // given BleutradeTickerReturn tickerReturn = new BleutradeTickerReturn(); tickerReturn.setSuccess(false); tickerReturn.setMessage("test message"); tickerReturn.setResult(expectedBleutradeTickers()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeTickers()).thenReturn(tickerReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeTickers(); // then fail("BleutradeMarketDataService should throw ExchangeException when tickers request was unsuccessful"); } @Test public void shouldGetCurrencies() throws IOException { // given final List<BleutradeCurrency> expectedBleutradeCurrencies = expectedBleutradeCurrencies(); final String[] expectedBleutradeCurrenciesStr = expectedBleutradeCurrenciesStr(); BleutradeCurrenciesReturn currenciesReturn = new BleutradeCurrenciesReturn(); currenciesReturn.setSuccess(true); currenciesReturn.setMessage("test message"); currenciesReturn.setResult(expectedBleutradeCurrencies); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeCurrencies()).thenReturn(currenciesReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeCurrency> currencies = marketDataService.getBleutradeCurrencies(); // then assertThat(currencies).hasSize(2); for (int i = 0; i < currencies.size(); i++) { BleutradeAssert.assertEquals(currencies.get(i), expectedBleutradeCurrencies.get(i)); assertThat(currencies.get(i).toString()).isEqualTo(expectedBleutradeCurrenciesStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetCurrencies() throws IOException { // given BleutradeCurrenciesReturn currenciesReturn = new BleutradeCurrenciesReturn(); currenciesReturn.setSuccess(false); currenciesReturn.setMessage("test message"); currenciesReturn.setResult(expectedBleutradeCurrencies()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeCurrencies()).thenReturn(currenciesReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeCurrencies(); // then fail("BleutradeMarketDataService should throw ExchangeException when currencies request was unsuccessful"); } @Test public void shouldGetMarkets() throws IOException { // given final List<BleutradeMarket> expectedBleutradeMarkets = expectedBleutradeMarkets(); final String[] expectedBleutradeMarketsStr = expectedBleutradeMarketsStr(); BleutradeMarketsReturn marketsReturn = new BleutradeMarketsReturn(); marketsReturn.setSuccess(true); marketsReturn.setMessage("test message"); marketsReturn.setResult(expectedBleutradeMarkets); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarkets()).thenReturn(marketsReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when List<BleutradeMarket> markets = marketDataService.getBleutradeMarkets(); // then assertThat(markets).hasSize(2); for (int i = 0; i < markets.size(); i++) { BleutradeAssert.assertEquals(markets.get(i), expectedBleutradeMarkets.get(i)); assertThat(markets.get(i).toString()).isEqualTo(expectedBleutradeMarketsStr[i]); } } @Test(expected = ExchangeException.class) public void shouldFailOnUnsuccesfulGetMarkets() throws IOException { // given BleutradeMarketsReturn marketsReturn = new BleutradeMarketsReturn(); marketsReturn.setSuccess(false); marketsReturn.setMessage("test message"); marketsReturn.setResult(expectedBleutradeMarkets()); BleutradeAuthenticated bleutrade = mock(BleutradeAuthenticated.class); PowerMockito.when(bleutrade.getBleutradeMarkets()).thenReturn(marketsReturn); Whitebox.setInternalState(marketDataService, "bleutrade", bleutrade); // when marketDataService.getBleutradeMarkets(); // then fail("BleutradeMarketDataService should throw ExchangeException when markets request was unsuccessful"); } }
package de.blackcraze.grb.ocr; import static org.bytedeco.javacpp.opencv_core.CV_8U; import static org.bytedeco.javacpp.opencv_core.CV_8UC1; import static org.bytedeco.javacpp.opencv_core.CV_8UC3; import static org.bytedeco.javacpp.opencv_core.LINE_8; import static org.bytedeco.javacpp.opencv_core.NORM_MINMAX; import static org.bytedeco.javacpp.opencv_core.hconcat; import static org.bytedeco.javacpp.opencv_core.inRange; import static org.bytedeco.javacpp.opencv_core.normalize; import static org.bytedeco.javacpp.opencv_core.vconcat; import static org.bytedeco.javacpp.opencv_imgcodecs.imread; import static org.bytedeco.javacpp.opencv_imgcodecs.imwrite; import static org.bytedeco.javacpp.opencv_imgproc.CHAIN_APPROX_SIMPLE; import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2GRAY; import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2HSV; import static org.bytedeco.javacpp.opencv_imgproc.CV_DIST_L2; import static org.bytedeco.javacpp.opencv_imgproc.CV_INTER_CUBIC; import static org.bytedeco.javacpp.opencv_imgproc.CV_THRESH_BINARY; import static org.bytedeco.javacpp.opencv_imgproc.CV_THRESH_BINARY_INV; import static org.bytedeco.javacpp.opencv_imgproc.RETR_CCOMP; import static org.bytedeco.javacpp.opencv_imgproc.boundingRect; import static org.bytedeco.javacpp.opencv_imgproc.cvtColor; import static org.bytedeco.javacpp.opencv_imgproc.distanceTransform; import static org.bytedeco.javacpp.opencv_imgproc.drawContours; import static org.bytedeco.javacpp.opencv_imgproc.findContours; import static org.bytedeco.javacpp.opencv_imgproc.resize; import static org.bytedeco.javacpp.opencv_imgproc.threshold; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.imageio.ImageIO; import org.apache.commons.lang3.StringUtils; import org.bytedeco.javacpp.opencv_core.Mat; import org.bytedeco.javacpp.opencv_core.MatVector; import org.bytedeco.javacpp.opencv_core.Point; import org.bytedeco.javacpp.opencv_core.Rect; import org.bytedeco.javacpp.opencv_core.Scalar; import org.bytedeco.javacpp.opencv_core.Size; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.Device; public class Preprocessor { private static final File TMP_FILE_DIR = new File("./target/tmp/"); static { if (!TMP_FILE_DIR.exists()) { TMP_FILE_DIR.mkdirs(); } } public static List<File> cropMasked(BufferedImage image) throws IOException { // Iterate over the rows and remove the masked areas, since the // text we want to read is underneath it. WritableRaster raster = image.getRaster(); List<Integer> rowsToRemove = new ArrayList<>(); for (int yy = 0; yy < image.getHeight(); yy++) { int masked = 0; for (int xx = 0; xx < image.getWidth(); xx++) { if (matchColor(getPixelValue(raster, xx, yy), Color.MAGENTA)) { masked++; } } float maskAmount = masked > 0 ? (float) masked / (float) image.getWidth() : 0; if (maskAmount > 0.02f) { rowsToRemove.add(yy); } } List<SubImage> subImages = extractSubimageBetweenMaskedRows(rowsToRemove, image.getHeight(), 50); List<File> result = new ArrayList<>(subImages.size() * 3); int i = 0; for (SubImage subImage : subImages) { BufferedImage cut = image.getSubimage(0, subImage.y, image.getWidth(), subImage.height); File tempFile; tempFile = File.createTempFile("subImage_" + i + "_c1", ".png", TMP_FILE_DIR); tempFile.deleteOnExit(); ImageIO.write(cut.getSubimage(50, 0, 200, cut.getHeight()), "png", tempFile); result.add(tempFile); tempFile = File.createTempFile("subImage_" + i + "_c2", ".png", TMP_FILE_DIR); tempFile.deleteOnExit(); ImageIO.write(cut.getSubimage(255, 0, 200, cut.getHeight()), "png", tempFile); result.add(tempFile); tempFile = File.createTempFile("subImage_" + i + "_c3", ".png", TMP_FILE_DIR); tempFile.deleteOnExit(); ImageIO.write(cut.getSubimage(465, 0, 200, cut.getHeight()), "png", tempFile); result.add(tempFile); i++; } return result; } public static BufferedImage cropCenterScreen(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); // One-fourth of screen width is reserved for header stuff (level, coins, // gems, etc.) int headerHeight = width / 4; int footerHeight = width / 2; // One-half of screen width is reserved for footer stuff (sell bar, price, // etc.) return image.getSubimage(0, headerHeight, width, height - headerHeight - footerHeight); } /** * This is a try to mask the icon images from the game screen. Icons do often have white or * black in them (shadows and lights). These areas would be left over from * {@link #monochrome(int, int, WritableRaster)} and are disturbing the OCR. But since the black * and white parts are near colored areas (blue or red or green), we mask an area around the * colored pixels and overpaint the shadows and lights with it. * * @param image * @throws IOException */ public static void maskIconRing(BufferedImage image) throws IOException { // resolution-independent mask box size (720 pixels --> boxsize 10) WritableRaster raster = image.getRaster(); int boxWidth = image.getWidth() / 100; for (int xx = 0; xx < image.getWidth(); xx++) { for (int yy = 0; yy < image.getHeight(); yy++) { int[] pixel = getPixelValue(raster, xx, yy); if (!matchColor(pixel, Color.MAGENTA) && matchIconRing(pixel)) { paintOverArea(xx, yy, boxWidth, Color.MAGENTA, raster); } } } } /** * Change an area of pixels around a pixel to a specified color. */ private static void paintOverArea(int centerX, int centerY, int areaSize, Color color, WritableRaster raster) { for (int x = centerX - areaSize; x < raster.getWidth() && x < centerX + areaSize; x++) { x = x < 0 ? 0 : x; // ArrayOutOfBound protection for (int y = centerY - areaSize; y < raster.getHeight() && y < centerY + areaSize; y++) { y = y < 0 ? 0 : y; // ArrayOutOfBound protection int[] strip = getPixelValue(raster, x, y); changeColor(strip, color); raster.setPixel(x, y, strip); } } } private static boolean matchColor(int[] pixel, Color... colors) { boolean match = false; for (Color color : colors) { match = pixel[0] == color.getRed() && pixel[1] == color.getGreen() && pixel[2] == color.getBlue(); if (match) { break; } } return match; } private static void changeColor(int[] pixel, Color c) { pixel[0] = c.getRed(); pixel[1] = c.getGreen(); pixel[2] = c.getBlue(); } private static int[] getPixelValue(WritableRaster raster, int xx, int yy) { return raster.getPixel(xx, yy, (int[]) null); } private static boolean matchIconRing(int[] pixels) { boolean blueAndroid = 0 <= pixels[0] && pixels[0] <= 50 && // 0 <= pixels[1] && pixels[1] <= 240 && // 180 <= pixels[2] && pixels[2] <= 255; boolean blueIphone = 0 <= pixels[0] && pixels[0] <= 120 && // 180 <= pixels[1] && pixels[1] <= 255 && // 180 <= pixels[2] && pixels[2] <= 255; return blueAndroid || blueIphone; } static final Point getCenterPoint(Mat m) { Rect r = boundingRect(m); return new Point(r.x() + (r.width() / 2), r.y() + (r.height() / 2)); } public static boolean debug = false; private static boolean debug() { return debug; } private static void saveToDisk(Mat mat, String name) throws IOException { if (debug()) { File output = new File(TMP_FILE_DIR, name + ".png"); System.out.println("debug file: " + output.getAbsolutePath()); imwrite(output.getAbsolutePath(), mat); } } public static void saveToDisk(BufferedImage image, String name) throws IOException { if (debug()) { File output = new File(TMP_FILE_DIR, name + ".png"); System.out.println("debug file: " + output.getAbsolutePath()); ImageIO.write(image, "png", output); } } public static List<File> load(InputStream stream) throws IOException { BufferedImage image = ImageIO.read(stream); image = Preprocessor.resizeSource(image); image = Preprocessor.cropCenterScreen(image); Preprocessor.maskIconRing(image); return Preprocessor.cropMasked(image); } private static BufferedImage resizeSource(BufferedImage image) { double factor = 720d / image.getWidth(); int scaledHeight = (int) (image.getHeight() * factor); int scaledWidth = (int) (image.getWidth() * factor); Image tmp = image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH); int type = image.getType(); if (type == 0) type = 5; // hacky but does work BufferedImage dimg = new BufferedImage(scaledWidth, scaledHeight, type); Graphics2D g2d = dimg.createGraphics(); g2d.drawImage(tmp, 0, 0, null); g2d.dispose(); return dimg; } private static File process(File srcFile, Mat maskLow, Mat maskUp, double thresh, int threshSrcBwLow, int threshSrcBwUp, int distTransformThreshMode, String prefix) throws IOException { Mat src = imread(srcFile.getAbsolutePath()); Mat crop = process(src, maskLow, maskUp, thresh, threshSrcBwLow, threshSrcBwUp, distTransformThreshMode, prefix); File result = null; if (crop != null) { result = File.createTempFile(prefix, ".png", TMP_FILE_DIR); result.deleteOnExit(); imwrite(result.getAbsolutePath(), crop); crop.close(); } src.close(); return result; } public static Mat process(Mat src, Mat maskLow, Mat maskUp, double thresh, int threshSrcBwLow, int threshSrcBwUp, int distTransformThreshMode, String prefix) throws IOException { int borderSize = 1; Mat colorFilter = src.clone(); cvtColor(colorFilter, colorFilter, CV_BGR2HSV); saveToDisk(colorFilter, prefix + "_02_brgh"); inRange(colorFilter, maskLow, maskUp, colorFilter); saveToDisk(colorFilter, prefix + "_03_inRange"); threshold(colorFilter, colorFilter, 150, 255, distTransformThreshMode); saveToDisk(colorFilter, prefix + "_04_thresh"); distanceTransform(colorFilter, colorFilter, CV_DIST_L2, 3); // Normalize the distance image for range = {0.0, 1.0} // so we can visualize and threshold it. normalize(colorFilter, colorFilter, 0, 1., NORM_MINMAX, -1, null); threshold(colorFilter, colorFilter, thresh, 1, CV_THRESH_BINARY); Mat dist_8u = new Mat(); colorFilter.convertTo(dist_8u, CV_8U); colorFilter.close(); // Find total markers. MatVector contours = new MatVector(); Mat hierarchy = new Mat(); dist_8u = applyBorders(dist_8u, borderSize, Scalar.WHITE); // to prevent // connect // the // texts connected to the // edge findContours(dist_8u, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); Mat charMask = new Mat(dist_8u.size(), CV_8U, Scalar.BLACK); int minX = 9999999, minY = 9999999; // FIXME int maxX = 0, maxY = 0; int validContours = 0; for (int i = 0; i < contours.size(); i++) { Mat contour = contours.get(i); if (isValidContour(dist_8u, contour)) { drawContours(charMask, contours, i, Scalar.WHITE, -1, LINE_8, hierarchy, 0, null); Rect bounds = boundingRect(contour); int boundsMaxX = bounds.x() + bounds.width() - 1; int boundsMaxY = bounds.y() + bounds.height() - 1; maxX = boundsMaxX > maxX ? boundsMaxX : maxX; maxY = boundsMaxY > maxY ? boundsMaxY : maxY; minX = bounds.x() < minX ? bounds.x() : minX; minY = bounds.y() < minY ? bounds.y() : minY; bounds.close(); validContours++; } contour.close(); } if (debug()) { System.out.println("Found contours: " + contours.size()); System.out.println("Valid contours: " + validContours); } contours.close(); dist_8u.close(); hierarchy.close(); if (validContours == 0) { charMask.close(); return null;// empty part } Rect cutRect = new Rect(minX, minY, maxX - minX, maxY - minY); saveToDisk(charMask, prefix + "_05_contours"); Mat crop = new Mat(charMask.size(), CV_8UC3, Scalar.BLACK); applyBorders(src, borderSize, Scalar.BLACK).copyTo(crop, charMask); crop = crop.apply(cutRect); charMask.close(); cutRect.close(); saveToDisk(crop, prefix + "_06_crop"); Mat result = new Mat(crop.size(), CV_8UC1); cvtColor(crop, result, CV_BGR2GRAY); resize(result, result, new Size(result.size().width() * 4, result.size().height() * 4), 0, 0, CV_INTER_CUBIC); crop.close(); saveToDisk(result, prefix + "_07_scale"); threshold(result, result, threshSrcBwLow, threshSrcBwUp, CV_THRESH_BINARY_INV); saveToDisk(result, prefix + "_08_ocr"); return result; } private static Mat applyBorders(Mat src, int borderSize, Scalar color) { Mat dest = new Mat(); Mat borderH = new Mat(borderSize, src.cols(), src.type(), color); Mat borderV = new Mat(src.rows() + (borderSize * 2), borderSize, src.type(), color); MatVector order = new MatVector(3); order.put(borderH, src, borderH); vconcat(order, dest); order = new MatVector(3); order.put(borderV, dest, borderV); hconcat(order, dest); return dest; } public static File[] extract(File frame, Device userDevice) throws IOException { Mat colorFilterTextLow = new Mat(new double[] {0, 2, 0}); Mat colorFilterNumberLow = new Mat(new double[] {255, 255, 255}); final double threshText = 0.04d; final int threshTextSrcLow = 200; final int threshTextSrcUp = 255; final double threshNum = 0.06d; // iphone 7 Mat colorFilterNumLow; Device device = userDevice != null ? userDevice : Device.ANDROID; switch (device) { case IPHONE: colorFilterNumLow = new Mat(new double[] {25, 175, 50}); break; default: colorFilterNumLow = new Mat(new double[] {25, 255, 50}); break; } Mat colorFilterNumUp = new Mat(new double[] {50, 255, 255}); final int threshNumSrcLow = 180; final int threshNumSrcUp = 255; String prefix = StringUtils.substringBeforeLast(frame.getName(), "_"); File text = process(frame, colorFilterTextLow, colorFilterNumberLow, threshText, threshTextSrcLow, threshTextSrcUp, CV_THRESH_BINARY, prefix + "_text"); File number = process(frame, colorFilterNumLow, colorFilterNumUp, threshNum, threshNumSrcLow, threshNumSrcUp, CV_THRESH_BINARY_INV, prefix + "_num"); colorFilterTextLow.close(); colorFilterNumberLow.close(); colorFilterNumLow.close(); colorFilterNumUp.close(); return new File[] {text, number}; } public static List<SubImage> extractSubimageBetweenMaskedRows(List<Integer> maskedRows, int imageHeight, int minSubImageHeight) { List<SubImage> result = new ArrayList<>(); for (int i = 0; i < maskedRows.size(); i++) { int row = maskedRows.get(i); boolean isFirstIndex = i == 0; boolean isFirstRow = row == 0; boolean connectedToLastIndex = !isFirstIndex && row - 1 == maskedRows.get(i - 1); if (isFirstRow || connectedToLastIndex) { continue; } int lastValidRow = isFirstIndex ? 0 : maskedRows.get(i - 1) + 1; int height = row - lastValidRow; if (height >= minSubImageHeight) { result.add(new SubImage(lastValidRow, height)); } } if (maskedRows.size() == 0) { if (imageHeight >= minSubImageHeight) { result.add(new SubImage(0, imageHeight)); } } else if (maskedRows.get(maskedRows.size() - 1) == imageHeight) { // nothing to do } else { int lastValidRow = maskedRows.get(maskedRows.size() - 1) + 1; int height = imageHeight - lastValidRow; if (height >= minSubImageHeight) { result.add(new SubImage(lastValidRow, height)); } } return result; } private static boolean isValidContour(Mat src, Mat contour) { Rect bounds = boundingRect(contour); int width = bounds.width(); int height = bounds.height(); boolean wholeScreenX = src.cols() <= width + 8; boolean wholeScreenY = src.rows() <= height + 8; boolean artifact = width < 15 && height < 15; return !(wholeScreenX && wholeScreenY) && !artifact; } } class SubImage { public SubImage(int y, int height) { this.y = y; this.height = height; } final int y, height; }
/** * Copyright 2005-2014 The Kuali 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kns.document; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.ojb.broker.core.proxy.ProxyHelper; import org.apache.struts.upload.FormFile; import org.kuali.rice.kns.maintenance.Maintainable; import org.kuali.rice.krad.bo.DocumentAttachment; import org.kuali.rice.kns.bo.GlobalBusinessObject; import org.kuali.rice.krad.bo.MultiDocumentAttachment; import org.kuali.rice.krad.bo.PersistableAttachment; import org.kuali.rice.krad.bo.PersistableAttachmentBase; import org.kuali.rice.krad.bo.PersistableAttachmentList; import org.kuali.rice.krad.rules.rule.event.DocumentEvent; import org.kuali.rice.krad.rules.rule.event.SaveDocumentEvent; import org.kuali.rice.krad.service.BusinessObjectSerializerService; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.KRADServiceLocatorWeb; import org.kuali.rice.krad.util.KRADUtils; import org.kuali.rice.krad.util.ObjectUtils; import javax.persistence.Transient; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * @author Kuali Rice Team (rice.collab@kuali.org) * * @deprecated Use {@link org.kuali.rice.krad.maintenance.MaintenanceDocumentBase}. */ @Deprecated public class MaintenanceDocumentBase extends org.kuali.rice.krad.maintenance.MaintenanceDocumentBase implements MaintenanceDocument { private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MaintenanceDocumentBase.class); @Transient protected transient FormFile fileAttachment; public MaintenanceDocumentBase() { super(); } public MaintenanceDocumentBase(String documentTypeName) { super(documentTypeName); } @Override public Object getDocumentBusinessObject() { return super.getDocumentDataObject(); } /** * Checks old maintainable bo has key values */ public boolean isOldBusinessObjectInDocument() { boolean isOldBusinessObjectInExistence = false; if (getOldMaintainableObject() == null || getOldMaintainableObject().getBusinessObject() == null) { isOldBusinessObjectInExistence = false; } else { isOldBusinessObjectInExistence = getOldMaintainableObject().isOldBusinessObjectInDocument(); } return isOldBusinessObjectInExistence; } public Maintainable getNewMaintainableObject() { return (Maintainable) newMaintainableObject; } public Maintainable getOldMaintainableObject() { return (Maintainable) oldMaintainableObject; } public FormFile getFileAttachment() { return this.fileAttachment; } public void setFileAttachment(FormFile fileAttachment) { this.fileAttachment = fileAttachment; } /** * The attachment BO is proxied in OJB. For some reason when an attachment does not yet exist, * refreshReferenceObject is not returning null and the proxy cannot be materialized. So, this method exists to * properly handle the proxied attachment BO. This is a hack and should be removed post JPA migration. */ protected void refreshAttachment() { if (KRADUtils.isNull(attachment)) { this.refreshReferenceObject("attachment"); final boolean isProxy = attachment != null && ProxyHelper.isProxy(attachment); if (isProxy && ProxyHelper.getRealObject(attachment) == null) { attachment = null; } } } protected void refreshAttachmentList() { if (KRADUtils.isNull(attachments)) { this.refreshReferenceObject("attachments"); final boolean isProxy = attachments != null && ProxyHelper.isProxy(attachments); if (isProxy && ProxyHelper.getRealObject(attachments) == null) { attachments = null; } } } @Override public void populateDocumentAttachment() { refreshAttachment(); if (fileAttachment != null && StringUtils.isNotEmpty(fileAttachment.getFileName())) { //Populate DocumentAttachment BO if (attachment == null) { attachment = new DocumentAttachment(); } byte[] fileContents; try { fileContents = fileAttachment.getFileData(); if (fileContents.length > 0) { attachment.setFileName(fileAttachment.getFileName()); attachment.setContentType(fileAttachment.getContentType()); attachment.setAttachmentContent(fileAttachment.getFileData()); attachment.setObjectId(UUID.randomUUID().toString()); PersistableAttachment boAttachment = (PersistableAttachment) newMaintainableObject.getDataObject(); boAttachment.setAttachmentContent(null); attachment.setDocumentNumber(getDocumentNumber()); } } catch (FileNotFoundException e) { LOG.error("Error while populating the Document Attachment", e); throw new RuntimeException("Could not populate DocumentAttachment object", e); } catch (IOException e) { LOG.error("Error while populating the Document Attachment", e); throw new RuntimeException("Could not populate DocumentAttachment object", e); } } else { //fileAttachment isn't filled, populate from bo if it exists PersistableAttachment boAttachment = (PersistableAttachment) newMaintainableObject.getDataObject(); if (attachment == null && boAttachment != null && boAttachment.getAttachmentContent() != null) { DocumentAttachment newAttachment = new DocumentAttachment(); newAttachment.setDocumentNumber(getDocumentNumber()); newAttachment.setAttachmentContent(boAttachment.getAttachmentContent()); newAttachment.setContentType(boAttachment.getContentType()); newAttachment.setFileName(boAttachment.getFileName()); //null out boAttachment file, will be copied back before final save. boAttachment.setAttachmentContent(null); attachment = newAttachment; } } } @Override public void populateAttachmentForBO() { refreshAttachment(); PersistableAttachment boAttachment = (PersistableAttachment) newMaintainableObject.getDataObject(); if (ObjectUtils.isNotNull(getAttachmentPropertyName())) { String attachmentPropNm = getAttachmentPropertyName(); String attachmentPropNmSetter = "get" + attachmentPropNm.substring(0, 1).toUpperCase() + attachmentPropNm.substring(1, attachmentPropNm.length()); FormFile attachmentFromBusinessObject; if((boAttachment.getFileName() == null) && (boAttachment instanceof PersistableAttachment)) { try { Method[] methods = boAttachment.getClass().getMethods(); for (Method method : methods) { if (method.getName().equals(attachmentPropNmSetter)) { attachmentFromBusinessObject = (FormFile)(boAttachment.getClass().getDeclaredMethod(attachmentPropNmSetter).invoke(boAttachment)); if (attachmentFromBusinessObject != null) { //boAttachment.setAttachmentContent(attachmentFromBusinessObject.getFileData()); boAttachment.setFileName(attachmentFromBusinessObject.getFileName()); boAttachment.setContentType(attachmentFromBusinessObject.getContentType()); } break; } } } catch (Exception e) { LOG.error("Not able to get the attachment " + e.getMessage()); throw new RuntimeException("Not able to get the attachment " + e.getMessage()); } } } if((boAttachment.getFileName() == null) && (boAttachment instanceof PersistableAttachment) && (attachment != null)) { //byte[] fileContents; //fileContents = attachment.getAttachmentContent(); if (attachment.getFileName() != null) { boAttachment.setAttachmentContent(null); boAttachment.setFileName(attachment.getFileName()); boAttachment.setContentType(attachment.getContentType()); } } } @Override public void populateAttachmentBeforeSave() { PersistableAttachment boAttachment = (PersistableAttachment) newMaintainableObject.getDataObject(); if (attachment != null && attachment.getAttachmentContent() != null) { boAttachment.setAttachmentContent(attachment.getAttachmentContent()); } else { boAttachment.setAttachmentContent(null); boAttachment.setFileName(null); boAttachment.setContentType(null); } } @Override public void populateBoAttachmentListBeforeSave() { PersistableAttachmentList<PersistableAttachment> boAttachments = (PersistableAttachmentList<PersistableAttachment>) newMaintainableObject.getDataObject(); if (CollectionUtils.isEmpty(attachments)) { //there are no attachments. Clear out Bo Attachments boAttachments.setAttachments(Collections.<PersistableAttachment>emptyList()); return; } Map<String, MultiDocumentAttachment> files = new HashMap<String, MultiDocumentAttachment>(); for (MultiDocumentAttachment multiAttach : attachments) { String key = new StringBuffer(multiAttach.getFileName()).append("|").append(multiAttach.getContentType()).toString(); files.put(key, multiAttach); } //want to just copy over file if possible, as there can be other fields that are not on PersistableAttachment //these arrays should be somewhat synched by the other populate methods if (CollectionUtils.isNotEmpty(boAttachments.getAttachments())) { for (PersistableAttachment attach : boAttachments.getAttachments()) { //try to get a new instance of the correct object... String key = new StringBuffer(attach.getFileName()).append("|").append(attach.getContentType()).toString(); if (files.containsKey(key)) { attach.setAttachmentContent(files.get(key).getAttachmentContent()); files.remove(key); } } } } @Override public void populateAttachmentListForBO() { refreshAttachmentList(); PersistableAttachmentList<PersistableAttachment> boAttachments = (PersistableAttachmentList<PersistableAttachment>) newMaintainableObject.getDataObject(); if (ObjectUtils.isNotNull(getAttachmentListPropertyName())) { //String collectionName = getAttachmentCollectionName(); String attachmentPropNm = getAttachmentListPropertyName(); String attachmentPropNmSetter = "get" + attachmentPropNm.substring(0, 1).toUpperCase() + attachmentPropNm.substring(1, attachmentPropNm.length()); for (PersistableAttachment persistableAttachment : boAttachments.getAttachments()) { if((persistableAttachment.getFileName() == null)) { try { FormFile attachmentFromBusinessObject = (FormFile)(persistableAttachment.getClass().getDeclaredMethod(attachmentPropNmSetter).invoke(persistableAttachment)); if (attachmentFromBusinessObject != null) { //persistableAttachment.setAttachmentContent( // attachmentFromBusinessObject.getFileData()); persistableAttachment.setFileName(attachmentFromBusinessObject.getFileName()); persistableAttachment.setContentType(attachmentFromBusinessObject.getContentType()); } } catch (Exception e) { LOG.error("Not able to get the attachment " + e.getMessage()); throw new RuntimeException("Not able to get the attachment " + e.getMessage()); } } } } if((CollectionUtils.isEmpty(boAttachments.getAttachments()) && (CollectionUtils.isNotEmpty(attachments)))) { List<PersistableAttachment> attachmentList = new ArrayList<PersistableAttachment>(); for (MultiDocumentAttachment multiAttach : attachments) { //try to get a new instance of the correct object... if (multiAttach.getAttachmentContent().length > 0) { PersistableAttachment persistableAttachment = convertDocToBoAttachment(multiAttach, false); attachmentList.add(persistableAttachment); } } boAttachments.setAttachments(attachmentList); } } private PersistableAttachment convertDocToBoAttachment(MultiDocumentAttachment multiAttach, boolean copyFile) { PersistableAttachment persistableAttachment = new PersistableAttachmentBase(); if (copyFile && multiAttach.getAttachmentContent() != null) { persistableAttachment.setAttachmentContent(multiAttach.getAttachmentContent()); } persistableAttachment.setFileName(multiAttach.getFileName()); persistableAttachment.setContentType(multiAttach.getContentType()); return persistableAttachment; } @Override public void populateDocumentAttachmentList() { refreshAttachmentList(); String attachmentPropNm = getAttachmentListPropertyName(); String attachmentPropNmSetter = "get" + attachmentPropNm.substring(0, 1).toUpperCase() + attachmentPropNm.substring(1, attachmentPropNm.length()); //don't have form fields to use to fill, but they should be populated on the DataObject. grab them from there. PersistableAttachmentList<PersistableAttachment> boAttachmentList = (PersistableAttachmentList<PersistableAttachment>) newMaintainableObject.getDataObject(); if (CollectionUtils.isNotEmpty(boAttachmentList.getAttachments())) { //build map for comparison Map<String, MultiDocumentAttachment> md5Hashes = new HashMap<String, MultiDocumentAttachment>(); if (CollectionUtils.isNotEmpty(attachments)) { for (MultiDocumentAttachment currentAttachment : attachments) { md5Hashes.put(DigestUtils.md5Hex(currentAttachment.getAttachmentContent()), currentAttachment); } } //Populate DocumentAttachment BO attachments = new ArrayList<MultiDocumentAttachment>(); for (PersistableAttachment persistableAttachment : boAttachmentList.getAttachments()) { try { FormFile attachmentFromBusinessObject = (FormFile)(persistableAttachment.getClass().getDeclaredMethod(attachmentPropNmSetter).invoke(persistableAttachment)); if (attachmentFromBusinessObject != null) { // //byte[] fileContents = attachmentFromBusinessObject.getFileData(); String md5Hex = DigestUtils.md5Hex(attachmentFromBusinessObject.getInputStream()); if (md5Hashes.containsKey(md5Hex)) { String newFileName = attachmentFromBusinessObject.getFileName(); MultiDocumentAttachment multiAttach = md5Hashes.get(md5Hex); if (multiAttach.getFileName().equals(newFileName)) { attachments.add(multiAttach); } else { multiAttach.setFileName(attachmentFromBusinessObject.getFileName()); multiAttach.setContentType(attachmentFromBusinessObject.getContentType()); attachments.add(multiAttach); } md5Hashes.remove(md5Hex); } else { MultiDocumentAttachment attach = new MultiDocumentAttachment(); attach.setFileName(attachmentFromBusinessObject.getFileName()); attach.setContentType(attachmentFromBusinessObject.getContentType()); attach.setAttachmentContent(attachmentFromBusinessObject.getFileData()); attach.setDocumentNumber(getDocumentNumber()); attachments.add(attach); } } else { if (persistableAttachment.getFileName() != null && persistableAttachment.getAttachmentContent() != null) { MultiDocumentAttachment attach = new MultiDocumentAttachment(); attach.setFileName(persistableAttachment.getFileName()); attach.setContentType(persistableAttachment.getContentType()); attach.setAttachmentContent(persistableAttachment.getAttachmentContent()); attach.setDocumentNumber(getDocumentNumber()); //set Bo's content to null persistableAttachment.setAttachmentContent(null); attachments.add(attach); } } } catch (Exception e) { LOG.error("Not able to get the attachment " + e.getMessage()); throw new RuntimeException("Not able to get the attachment " + e.getMessage()); } } } } /** * {@inheritDoc} */ @Override protected BusinessObjectSerializerService getBusinessObjectSerializerService() { return KRADServiceLocator.getBusinessObjectSerializerService(); } /** * this needs to happen after the document itself is saved, to preserve consistency of the ver_nbr and in the case * of initial save, because this can't be saved until the document is saved initially * * @see org.kuali.rice.krad.document.DocumentBase#postProcessSave(org.kuali.rice.krad.rules.rule.event.DocumentEvent) */ @Override public void postProcessSave(DocumentEvent event) { Object bo = getNewMaintainableObject().getDataObject(); if (bo instanceof GlobalBusinessObject) { bo = KRADServiceLocatorWeb.getLegacyDataAdapter().save(bo); // KRAD/JPA - have to change the handle to object to that just saved getNewMaintainableObject().setDataObject(bo); } //currently only global documents could change the list of what they're affecting during routing, //so could restrict this to only happening with them, but who knows if that will change, so safest //to always do the delete and re-add...seems a bit inefficient though if nothing has changed, which is //most of the time...could also try to only add/update/delete what's changed, but this is easier if (!(event instanceof SaveDocumentEvent)) { //don't lock until they route getMaintenanceDocumentService().deleteLocks(MaintenanceDocumentBase.this.getDocumentNumber()); getMaintenanceDocumentService().storeLocks(MaintenanceDocumentBase.this.getNewMaintainableObject().generateMaintenanceLocks()); } } }
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.market.surface; import java.io.Serializable; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.impl.direct.DirectFieldsBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaPropertyMap; /** * Surface node metadata used when there is no applicable metadata. */ @BeanDefinition(builderScope = "private") public final class EmptySurfaceParameterMetadata implements SurfaceParameterMetadata, ImmutableBean, Serializable { /** * The singleton instance. */ private static final EmptySurfaceParameterMetadata INSTANCE = new EmptySurfaceParameterMetadata(); /** * The description and identifier. */ private static final String EMPTY = "Empty"; /** * Returns node metadata. * * @return the metadata */ static EmptySurfaceParameterMetadata empty() { return INSTANCE; } //------------------------------------------------------------------------- @Override public String getLabel() { return EMPTY; } /** * Returns 'Empty'. * * @return a simple identifier */ @Override public String getIdentifier() { return EMPTY; } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code EmptySurfaceParameterMetadata}. * @return the meta-bean, not null */ public static EmptySurfaceParameterMetadata.Meta meta() { return EmptySurfaceParameterMetadata.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(EmptySurfaceParameterMetadata.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; private EmptySurfaceParameterMetadata() { } @Override public EmptySurfaceParameterMetadata.Meta metaBean() { return EmptySurfaceParameterMetadata.Meta.INSTANCE; } @Override public <R> Property<R> property(String propertyName) { return metaBean().<R>metaProperty(propertyName).createProperty(this); } @Override public Set<String> propertyNames() { return metaBean().metaPropertyMap().keySet(); } //----------------------------------------------------------------------- @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { return true; } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(32); buf.append("EmptySurfaceParameterMetadata{"); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code EmptySurfaceParameterMetadata}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null); /** * Restricted constructor. */ private Meta() { } @Override public BeanBuilder<? extends EmptySurfaceParameterMetadata> builder() { return new EmptySurfaceParameterMetadata.Builder(); } @Override public Class<? extends EmptySurfaceParameterMetadata> beanType() { return EmptySurfaceParameterMetadata.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- } //----------------------------------------------------------------------- /** * The bean-builder for {@code EmptySurfaceParameterMetadata}. */ private static final class Builder extends DirectFieldsBeanBuilder<EmptySurfaceParameterMetadata> { /** * Restricted constructor. */ private Builder() { } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { throw new NoSuchElementException("Unknown property: " + propertyName); } @Override public Builder set(String propertyName, Object newValue) { throw new NoSuchElementException("Unknown property: " + propertyName); } @Override public Builder set(MetaProperty<?> property, Object value) { super.set(property, value); return this; } @Override public Builder setString(String propertyName, String value) { setString(meta().metaProperty(propertyName), value); return this; } @Override public Builder setString(MetaProperty<?> property, String value) { super.setString(property, value); return this; } @Override public Builder setAll(Map<String, ? extends Object> propertyValueMap) { super.setAll(propertyValueMap); return this; } @Override public EmptySurfaceParameterMetadata build() { return new EmptySurfaceParameterMetadata(); } //----------------------------------------------------------------------- @Override public String toString() { return "EmptySurfaceParameterMetadata.Builder{}"; } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
// ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.servlets; import java.io.IOException; import java.net.URL; import java.util.EnumSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.DispatcherType; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.LocalConnector; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.FilterMapping; import org.eclipse.jetty.testing.HttpTester; import org.eclipse.jetty.testing.ServletTester; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class QoSFilterTest { private static final Logger LOG = Log.getLogger(QoSFilterTest.class); private ServletTester _tester; private LocalConnector[] _connectors; private CountDownLatch _doneRequests; private final int NUM_CONNECTIONS = 8; private final int NUM_LOOPS = 6; private final int MAX_QOS = 4; @Before public void setUp() throws Exception { _tester = new ServletTester(); _tester.setContextPath("/context"); _tester.addServlet(TestServlet.class, "/test"); TestServlet.__maxSleepers=0; TestServlet.__sleepers=0; _connectors = new LocalConnector[NUM_CONNECTIONS]; for(int i = 0; i < _connectors.length; ++i) _connectors[i] = _tester.createLocalConnector(); _doneRequests = new CountDownLatch(NUM_CONNECTIONS*NUM_LOOPS); _tester.start(); } @After public void tearDown() throws Exception { _tester.stop(); } @Test public void testNoFilter() throws Exception { for(int i = 0; i < NUM_CONNECTIONS; ++i ) { new Thread(new Worker(i)).start(); } _doneRequests.await(10,TimeUnit.SECONDS); assertFalse("TEST WAS NOT PARALLEL ENOUGH!",TestServlet.__maxSleepers<=MAX_QOS); assertTrue(TestServlet.__maxSleepers<=NUM_CONNECTIONS); } @Test public void testBlockingQosFilter() throws Exception { FilterHolder holder = new FilterHolder(QoSFilter2.class); holder.setAsyncSupported(true); holder.setInitParameter(QoSFilter.MAX_REQUESTS_INIT_PARAM, ""+MAX_QOS); _tester.getContext().getServletHandler().addFilterWithMapping(holder,"/*",EnumSet.of(DispatcherType.REQUEST,DispatcherType.ASYNC)); for(int i = 0; i < NUM_CONNECTIONS; ++i ) { new Thread(new Worker(i)).start(); } _doneRequests.await(10,TimeUnit.SECONDS); assertFalse("TEST WAS NOT PARALLEL ENOUGH!",TestServlet.__maxSleepers<MAX_QOS); assertTrue(TestServlet.__maxSleepers==MAX_QOS); } @Test public void testQosFilter() throws Exception { FilterHolder holder = new FilterHolder(QoSFilter2.class); holder.setAsyncSupported(true); holder.setInitParameter(QoSFilter.MAX_REQUESTS_INIT_PARAM, ""+MAX_QOS); _tester.getContext().getServletHandler().addFilterWithMapping(holder,"/*",EnumSet.of(DispatcherType.REQUEST,DispatcherType.ASYNC)); for(int i = 0; i < NUM_CONNECTIONS; ++i ) { new Thread(new Worker2(i)).start(); } _doneRequests.await(20,TimeUnit.SECONDS); assertFalse("TEST WAS NOT PARALLEL ENOUGH!",TestServlet.__maxSleepers<MAX_QOS); assertTrue(TestServlet.__maxSleepers<=MAX_QOS); } class Worker implements Runnable { private int _num; public Worker(int num) { _num = num; } public void run() { for (int i=0;i<NUM_LOOPS;i++) { HttpTester request = new HttpTester(); request.setMethod("GET"); request.setHeader("host", "tester"); request.setURI("/context/test?priority="+(_num%QoSFilter.__DEFAULT_MAX_PRIORITY)); request.setHeader("num", _num+""); try { String responseString = _tester.getResponses(request.generate(), _connectors[_num]); if(responseString.indexOf("HTTP")!=-1) { _doneRequests.countDown(); } } catch (Exception x) { assertTrue(false); } } } } class Worker2 implements Runnable { private int _num; public Worker2(int num) { _num = num; } public void run() { URL url=null; try { String addr = _tester.createSocketConnector(true); for (int i=0;i<NUM_LOOPS;i++) { url=new URL(addr+"/context/test?priority="+(_num%QoSFilter.__DEFAULT_MAX_PRIORITY)+"&n="+_num+"&l="+i); // System.err.println(_num+"-"+i+" Try "+url); url.getContent(); _doneRequests.countDown(); // System.err.println(_num+"-"+i+" Got "+IO.toString(in)+" "+_doneRequests.getCount()); } } catch(Exception e) { LOG.warn(String.valueOf(url)); LOG.debug(e); } } } public static class TestServlet extends HttpServlet implements Servlet { private static int __sleepers; private static int __maxSleepers; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { synchronized(TestServlet.class) { __sleepers++; if(__sleepers > __maxSleepers) __maxSleepers = __sleepers; } Thread.sleep(50); synchronized(TestServlet.class) { // System.err.println(_count++); __sleepers--; if(__sleepers > __maxSleepers) __maxSleepers = __sleepers; } response.setContentType("text/plain"); response.getWriter().println("DONE!"); } catch (InterruptedException e) { e.printStackTrace(); response.sendError(500); } } } public static class QoSFilter2 extends QoSFilter { public int getPriority(ServletRequest request) { String p = request.getParameter("priority"); if (p!=null) return Integer.parseInt(p); return 0; } } }
/* * 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.security.internal; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.apache.jackrabbit.oak.commons.PropertiesUtil; import org.apache.jackrabbit.oak.osgi.OsgiWhiteboard; import org.apache.jackrabbit.oak.plugins.tree.RootProvider; import org.apache.jackrabbit.oak.plugins.tree.TreeProvider; import org.apache.jackrabbit.oak.security.authorization.composite.CompositeAuthorizationConfiguration; import org.apache.jackrabbit.oak.security.authorization.restriction.WhiteboardRestrictionProvider; import org.apache.jackrabbit.oak.security.user.UserConfigurationImpl; import org.apache.jackrabbit.oak.security.user.whiteboard.WhiteboardAuthorizableActionProvider; import org.apache.jackrabbit.oak.security.user.whiteboard.WhiteboardAuthorizableNodeName; import org.apache.jackrabbit.oak.security.user.whiteboard.WhiteboardUserAuthenticationFactory; import org.apache.jackrabbit.oak.spi.security.CompositeConfiguration; import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters; import org.apache.jackrabbit.oak.spi.security.SecurityConfiguration; import org.apache.jackrabbit.oak.spi.security.SecurityProvider; import org.apache.jackrabbit.oak.spi.security.authentication.AuthenticationConfiguration; import org.apache.jackrabbit.oak.spi.security.authentication.token.CompositeTokenConfiguration; import org.apache.jackrabbit.oak.spi.security.authentication.token.TokenConfiguration; import org.apache.jackrabbit.oak.spi.security.authorization.AuthorizationConfiguration; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider; import org.apache.jackrabbit.oak.spi.security.principal.CompositePrincipalConfiguration; import org.apache.jackrabbit.oak.spi.security.principal.PrincipalConfiguration; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConfiguration; import org.apache.jackrabbit.oak.spi.security.user.AuthorizableNodeName; import org.apache.jackrabbit.oak.spi.security.user.UserAuthenticationFactory; import org.apache.jackrabbit.oak.spi.security.user.UserConfiguration; import org.apache.jackrabbit.oak.spi.security.user.UserConstants; import org.apache.jackrabbit.oak.spi.security.user.action.AuthorizableActionProvider; import org.jetbrains.annotations.NotNull; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.osgi.service.metatype.annotations.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newCopyOnWriteArrayList; import static org.apache.jackrabbit.oak.spi.security.RegistrationConstants.OAK_SECURITY_NAME; import static org.apache.jackrabbit.oak.spi.security.ConfigurationParameters.EMPTY; @Component(immediate=true) @Designate(ocd = SecurityProviderRegistration.Configuration.class) @SuppressWarnings("unused") public class SecurityProviderRegistration { @ObjectClassDefinition( name = "Apache Jackrabbit Oak SecurityProvider", description = "The default SecurityProvider embedded in Apache Jackrabbit Oak" ) @interface Configuration { @AttributeDefinition( name = "Required Services", description = "The SecurityProvider will not register itself " + "unless the services identified by the following service pids " + "or the oak.security.name properties are registered first. The class name is " + "identified by checking the service.pid property. If that property " + "does not exist, the oak.security.name property is used as a fallback." + "Only implementations of the following interfaces are checked :" + "AuthorizationConfiguration, PrincipalConfiguration, " + "TokenConfiguration, AuthorizableActionProvider, " + "RestrictionProvider and UserAuthenticationFactory." ) String[] requiredServicePids() default { "org.apache.jackrabbit.oak.security.authorization.AuthorizationConfigurationImpl", "org.apache.jackrabbit.oak.security.principal.PrincipalConfigurationImpl", "org.apache.jackrabbit.oak.security.authentication.token.TokenConfigurationImpl", "org.apache.jackrabbit.oak.spi.security.user.action.DefaultAuthorizableActionProvider", "org.apache.jackrabbit.oak.security.authorization.restriction.RestrictionProviderImpl", "org.apache.jackrabbit.oak.security.user.UserAuthenticationFactoryImpl" }; @AttributeDefinition( name = "Authorization Composition Type", description = "The Composite Authorization model uses this flag to determine what type of logic " + "to apply to the existing providers (default value is AND).", options = { @Option(label = "AND", value = "AND"), @Option(label = "OR", value = "OR") } ) String authorizationCompositionType() default "AND"; } private static final Logger log = LoggerFactory.getLogger(SecurityProviderRegistration.class); private AuthenticationConfiguration authenticationConfiguration; private PrivilegeConfiguration privilegeConfiguration; private UserConfiguration userConfiguration; private BundleContext context; private ServiceRegistration registration; private boolean registering; private final Preconditions preconditions = new Preconditions(); private final CompositeAuthorizationConfiguration authorizationConfiguration = new CompositeAuthorizationConfiguration(); private final CompositePrincipalConfiguration principalConfiguration = new CompositePrincipalConfiguration(); private final CompositeTokenConfiguration tokenConfiguration = new CompositeTokenConfiguration(); private final List<AuthorizableNodeName> authorizableNodeNames = newCopyOnWriteArrayList(); private final List<AuthorizableActionProvider> authorizableActionProviders = newCopyOnWriteArrayList(); private final List<RestrictionProvider> restrictionProviders = newCopyOnWriteArrayList(); private final List<UserAuthenticationFactory> userAuthenticationFactories = newCopyOnWriteArrayList(); private RootProvider rootProvider; private TreeProvider treeProvider; //----------------------------------------------------< SCR integration >--- @Activate public void activate(BundleContext context, Configuration configuration) { String[] requiredServicePids = configuration.requiredServicePids(); synchronized (this) { for (String pid : requiredServicePids) { preconditions.addPrecondition(pid); } this.context = context; } this.authorizationConfiguration.withCompositionType(configuration.authorizationCompositionType()); maybeRegister(); } @Modified public void modified(Configuration configuration) { String[] requiredServicePids = configuration.requiredServicePids(); synchronized (this) { preconditions.clearPreconditions(); for (String pid : requiredServicePids) { preconditions.addPrecondition(pid); } } this.authorizationConfiguration.withCompositionType(configuration.authorizationCompositionType()); maybeUnregister(); maybeRegister(); } @Deactivate public void deactivate() { ServiceRegistration registration; synchronized (this) { registration = this.registration; this.registration = null; this.registering = false; this.context = null; this.preconditions.clearPreconditions(); } if (registration != null) { registration.unregister(); } } //--------------------------------------< unary security configurations >--- @Reference(name = "authenticationConfiguration") public void bindAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) { this.authenticationConfiguration = authenticationConfiguration; } public void unbindAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) { this.authenticationConfiguration = null; } @Reference(name = "privilegeConfiguration") public void bindPrivilegeConfiguration(PrivilegeConfiguration privilegeConfiguration) { this.privilegeConfiguration = privilegeConfiguration; } public void unbindPrivilegeConfiguration(PrivilegeConfiguration privilegeConfiguration) { this.privilegeConfiguration = null; } @Reference(name = "userConfiguration") public void bindUserConfiguration(UserConfiguration userConfiguration) { this.userConfiguration = userConfiguration; } public void unbindUserConfiguration(UserConfiguration userConfiguration) { this.userConfiguration = null; } //-------------------------------------------< unary tree/root provider >--- @Reference(name = "rootProvider") public void bindRootProvider(RootProvider rootProvider) { this.rootProvider = rootProvider; } public void unbindRootProvider(RootProvider rootProvider) { this.rootProvider = null; } @Reference(name = "treeProvider") public void bindTreeProvider(TreeProvider treeProvider) { this.treeProvider = treeProvider; } public void unbindTreeProvider(TreeProvider treeProvider) { this.treeProvider = null; } //-----------------------------------< multiple security configurations >--- @Reference( name = "authorizationConfiguration", service = AuthorizationConfiguration.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindAuthorizationConfiguration(AuthorizationConfiguration configuration, Map<String, Object> properties) { bindConfiguration(authorizationConfiguration, configuration, properties); } public void unbindAuthorizationConfiguration(AuthorizationConfiguration configuration, Map<String, Object> properties) { unbindConfiguration(authorizationConfiguration, configuration, properties); } @Reference( name = "principalConfiguration", service = PrincipalConfiguration.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindPrincipalConfiguration(PrincipalConfiguration configuration, Map<String, Object> properties) { bindConfiguration(principalConfiguration, configuration, properties); } public void unbindPrincipalConfiguration(PrincipalConfiguration configuration, Map<String, Object> properties) { unbindConfiguration(principalConfiguration, configuration, properties); } @Reference( name = "tokenConfiguration", service = TokenConfiguration.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindTokenConfiguration(TokenConfiguration configuration, Map<String, Object> properties) { bindConfiguration(tokenConfiguration, configuration, properties); } public void unbindTokenConfiguration(TokenConfiguration configuration, Map<String, Object> properties) { unbindConfiguration(tokenConfiguration, configuration, properties); } private <T extends SecurityConfiguration> void bindConfiguration(@NotNull CompositeConfiguration<T> composite, @NotNull T configuration, Map<String, Object> properties) { synchronized (this) { composite.addConfiguration(configuration, ConfigurationParameters.of(properties)); addCandidate(properties); } maybeRegister(); } private <T extends SecurityConfiguration> void unbindConfiguration(@NotNull CompositeConfiguration<T> composite, @NotNull T configuration, Map<String, Object> properties) { synchronized (this) { composite.removeConfiguration(configuration); removeCandidate(properties); } maybeUnregister(); } //------------------------------------------------------------< add ons >--- @Reference( name = "authorizableNodeName", service = AuthorizableNodeName.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindAuthorizableNodeName(AuthorizableNodeName authorizableNodeName, Map<String, Object> properties) { synchronized (this) { authorizableNodeNames.add(authorizableNodeName); addCandidate(properties); } maybeRegister(); } public void unbindAuthorizableNodeName(AuthorizableNodeName authorizableNodeName, Map<String, Object> properties) { synchronized (this) { authorizableNodeNames.remove(authorizableNodeName); removeCandidate(properties); } maybeUnregister(); } @Reference( name = "authorizableActionProvider", service = AuthorizableActionProvider.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindAuthorizableActionProvider(AuthorizableActionProvider authorizableActionProvider, Map<String, Object> properties) { synchronized (this) { authorizableActionProviders.add(authorizableActionProvider); addCandidate(properties); } maybeRegister(); } public void unbindAuthorizableActionProvider(AuthorizableActionProvider authorizableActionProvider, Map<String, Object> properties) { synchronized (this) { authorizableActionProviders.remove(authorizableActionProvider); removeCandidate(properties); } maybeUnregister(); } @Reference( name = "restrictionProvider", service = RestrictionProvider.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindRestrictionProvider(RestrictionProvider restrictionProvider, Map<String, Object> properties) { synchronized (this) { restrictionProviders.add(restrictionProvider); addCandidate(properties); } maybeRegister(); } public void unbindRestrictionProvider(RestrictionProvider restrictionProvider, Map<String, Object> properties) { synchronized (this) { restrictionProviders.remove(restrictionProvider); removeCandidate(properties); } maybeUnregister(); } @Reference( name = "userAuthenticationFactory", service = UserAuthenticationFactory.class, cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC ) public void bindUserAuthenticationFactory(UserAuthenticationFactory userAuthenticationFactory, Map<String, Object> properties) { synchronized (this) { userAuthenticationFactories.add(userAuthenticationFactory); addCandidate(properties); } maybeRegister(); } public void unbindUserAuthenticationFactory(UserAuthenticationFactory userAuthenticationFactory, Map<String, Object> properties) { synchronized (this) { userAuthenticationFactories.remove(userAuthenticationFactory); removeCandidate(properties); } maybeUnregister(); } private void maybeRegister() { BundleContext context; log.info("Trying to register a SecurityProvider..."); synchronized (this) { // The component is not activated, yet. We have no means of registering // the SecurityProvider. This method will be called again after // activation completes. if (this.context == null) { log.info("Aborting: no BundleContext is available"); return; } // The preconditions are not satisifed. This may happen when this // component is activated but not enough mandatory services are bound // to it. if (!preconditions.areSatisfied()) { log.info("Aborting: preconditions are not satisfied: {}", preconditions); return; } // The SecurityProvider is already registered. This may happen when a // new dependency is added to this component, but the requirements are // already satisfied. if (registration != null) { log.info("Aborting: a SecurityProvider is already registered"); return; } // If the component is in the process of registering an instance of // SecurityProvider, return. This check is necessary because we don't // want to call createSecurityProvider() more than once. That method, // in fact, changes the state of the bound dependencies (it sets a // back-reference from the security configurations to the new // SecurityProvider). We want those dependencies to change state only // when we are sure that we will register the SecurityProvider we // are creating. if (registering) { log.info("Aborting: a SecurityProvider is already being registered"); return; } // Mark the start of a registration process. registering = true; // Save the BundleContext for local usage. context = this.context; } // Register the SecurityProvider. Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("type", "default"); ServiceRegistration registration = context.registerService( SecurityProvider.class.getName(), createSecurityProvider(context), properties ); synchronized (this) { this.registration = registration; this.registering = false; } log.info("SecurityProvider instance registered"); } private void maybeUnregister() { ServiceRegistration registration; log.info("Trying to unregister the SecurityProvider..."); synchronized (this) { // If there is nothing to register, we obviously have nothing to do. if (this.registration == null) { log.info("Aborting: no SecurityProvider is registered"); return; } // The preconditions are still satisfied. This may happen when a // dependency is unbound while not being listed as required service. if (preconditions.areSatisfied()) { log.info("Aborting: preconditions are satisfied"); return; } // Save the ServiceRegistration for local use. registration = this.registration; this.registration = null; } registration.unregister(); log.info("SecurityProvider instance unregistered"); } private SecurityProvider createSecurityProvider(@NotNull BundleContext context) { ConfigurationParameters userParams = ConfigurationParameters.of( ConfigurationParameters.of(UserConstants.PARAM_AUTHORIZABLE_ACTION_PROVIDER, createWhiteboardAuthorizableActionProvider()), ConfigurationParameters.of(UserConstants.PARAM_AUTHORIZABLE_NODE_NAME, createWhiteboardAuthorizableNodeName()), ConfigurationParameters.of(UserConstants.PARAM_USER_AUTHENTICATION_FACTORY, createWhiteboardUserAuthenticationFactory())); ConfigurationParameters authorizationParams = ConfigurationParameters .of(AccessControlConstants.PARAM_RESTRICTION_PROVIDER, createWhiteboardRestrictionProvider()); return SecurityProviderBuilder.newBuilder().withRootProvider(rootProvider).withTreeProvider(treeProvider) .with(authenticationConfiguration, EMPTY, privilegeConfiguration, EMPTY, userConfiguration, userParams, authorizationConfiguration, authorizationParams, principalConfiguration, EMPTY, tokenConfiguration, EMPTY) .withWhiteboard(new OsgiWhiteboard(context)).build(); } private RestrictionProvider createWhiteboardRestrictionProvider() { return new WhiteboardRestrictionProvider() { @Override protected List<RestrictionProvider> getServices() { return newArrayList(restrictionProviders); } }; } private AuthorizableActionProvider createWhiteboardAuthorizableActionProvider() { return new WhiteboardAuthorizableActionProvider() { @Override protected List<AuthorizableActionProvider> getServices() { return newArrayList(authorizableActionProviders); } }; } private AuthorizableNodeName createWhiteboardAuthorizableNodeName() { return new WhiteboardAuthorizableNodeName() { @Override protected List<AuthorizableNodeName> getServices() { return newArrayList(authorizableNodeNames); } }; } private UserAuthenticationFactory createWhiteboardUserAuthenticationFactory() { return new WhiteboardUserAuthenticationFactory(UserConfigurationImpl.getDefaultAuthenticationFactory()) { @Override protected List<UserAuthenticationFactory> getServices() { return newArrayList(userAuthenticationFactories); } }; } private void addCandidate(Map<String, Object> properties) { String pidOrName = getServicePidOrComponentName(properties); if (pidOrName == null) { return; } preconditions.addCandidate(pidOrName); } private void removeCandidate(Map<String, Object> properties) { String pidOrName = getServicePidOrComponentName(properties); if (pidOrName == null) { return; } preconditions.removeCandidate(pidOrName); } private static String getServicePidOrComponentName(Map<String, Object> properties) { String servicePid = PropertiesUtil.toString(properties.get(Constants.SERVICE_PID), null); if ( servicePid != null ) { return servicePid; } return PropertiesUtil.toString(properties.get(OAK_SECURITY_NAME), null); } }
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.io.warc; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.lang.NotImplementedException; import org.archive.io.ArchiveReader; import org.archive.io.ArchiveRecord; /** * WARCReader. * Go via {@link WARCReaderFactory} to get instance. * @author stack * @version $Date: 2006-11-27 18:03:03 -0800 (Mon, 27 Nov 2006) $ $Version$ */ public class WARCReader extends ArchiveReader implements WARCConstants { protected WARCReader() { super(); } @Override protected void initialize(String i) { super.initialize(i); setVersion(WARC_VERSION); } /** * Skip over any trailing new lines at end of the record so we're lined up * ready to read the next. * @param record * @throws IOException */ protected void gotoEOR(ArchiveRecord record) throws IOException { if (record.available() != 0) { throw new IOException("Record should be exhausted before coming " + "in here"); } // Records end in 2*CRLF. Suck it up. readExpectedChar(getIn(), CRLF.charAt(0)); readExpectedChar(getIn(), CRLF.charAt(1)); readExpectedChar(getIn(), CRLF.charAt(0)); readExpectedChar(getIn(), CRLF.charAt(1)); } protected void readExpectedChar(final InputStream is, final int expected) throws IOException { int c = is.read(); if (c != expected) { throw new IOException("Unexpected character " + Integer.toHexString(c) + "(Expecting " + Integer.toHexString(expected) + ")"); } } /** * Create new WARC record. * Encapsulate housekeeping that has to do w/ creating new Record. * @param is InputStream to use. * @param offset Absolute offset into WARC file. * @return A WARCRecord. * @throws IOException */ protected WARCRecord createArchiveRecord(InputStream is, long offset) throws IOException { return (WARCRecord)currentRecord(new WARCRecord(is, getReaderIdentifier(), offset, isDigest(), isStrict())); } @Override public void dump(boolean compress) throws IOException, java.text.ParseException { for (final Iterator<ArchiveRecord> i = iterator(); i.hasNext();) { ArchiveRecord r = i.next(); System.out.println(r.getHeader().toString()); r.dump(); System.out.println(); } } @Override public ArchiveReader getDeleteFileOnCloseReader(final File f) { throw new NotImplementedException("TODO"); } @Override public String getDotFileExtension() { return DOT_WARC_FILE_EXTENSION; } @Override public String getFileExtension() { return WARC_FILE_EXTENSION; } // Static methods follow. Mostly for command-line processing. /** * * @param formatter Help formatter instance. * @param options Usage options. * @param exitCode Exit code. */ private static void usage(HelpFormatter formatter, Options options, int exitCode) { formatter.printHelp("java org.archive.io.arc.WARCReader" + " [--digest=true|false] \\\n" + " [--format=cdx|cdxfile|dump|gzipdump]" + " [--offset=#] \\\n[--strict] [--parse] WARC_FILE|WARC_URL", options); System.exit(exitCode); } /** * Write out the arcfile. * * @param reader * @param format Format to use outputting. * @throws IOException * @throws java.text.ParseException */ protected static void output(WARCReader reader, String format) throws IOException, java.text.ParseException { if (!reader.output(format)) { throw new IOException("Unsupported format: " + format); } } /** * Generate a CDX index file for an ARC file. * * @param urlOrPath The ARC file to generate a CDX index for * @throws IOException * @throws java.text.ParseException */ public static void createCDXIndexFile(String urlOrPath) throws IOException, java.text.ParseException { WARCReader r = WARCReaderFactory.get(urlOrPath); r.setStrict(false); r.setDigest(true); output(r, CDX_FILE); } /** * Command-line interface to WARCReader. * * Here is the command-line interface: * <pre> * usage: java org.archive.io.arc.WARCReader [--offset=#] ARCFILE * -h,--help Prints this message and exits. * -o,--offset Outputs record at this offset into arc file.</pre> * * <p>Outputs using a pseudo-CDX format as described here: * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX * Legent</a> and here * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>. * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'. * Hash is hard-coded straight SHA-1 hash of content. * * @param args Command-line arguments. * @throws ParseException Failed parse of the command line. * @throws IOException * @throws java.text.ParseException */ public static void main(String [] args) throws ParseException, IOException, java.text.ParseException { Options options = getOptions(); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); @SuppressWarnings("unchecked") List<String> cmdlineArgs = cmdline.getArgList(); Option [] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. long offset = -1; boolean digest = false; boolean strict = false; String format = CDX; for (int i = 0; i < cmdlineOptions.length; i++) { switch(cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'o': offset = Long.parseLong(cmdlineOptions[i].getValue()); break; case 's': strict = true; break; case 'd': digest = getTrueOrFalse(cmdlineOptions[i].getValue()); break; case 'f': format = cmdlineOptions[i].getValue().toLowerCase(); boolean match = false; // List of supported formats. final String [] supportedFormats = {CDX, DUMP, GZIP_DUMP, CDX_FILE}; for (int ii = 0; ii < supportedFormats.length; ii++) { if (supportedFormats[ii].equals(format)) { match = true; break; } } if (!match) { usage(formatter, options, 1); } break; default: throw new RuntimeException("Unexpected option: " + + cmdlineOptions[i].getId()); } } if (offset >= 0) { if (cmdlineArgs.size() != 1) { System.out.println("Error: Pass one arcfile only."); usage(formatter, options, 1); } WARCReader r = WARCReaderFactory.get( new File((String)cmdlineArgs.get(0)), offset); r.setStrict(strict); outputRecord(r, format); } else { for (Iterator<String> i = cmdlineArgs.iterator(); i.hasNext();) { String urlOrPath = (String)i.next(); try { WARCReader r = WARCReaderFactory.get(urlOrPath); r.setStrict(strict); r.setDigest(digest); output(r, format); } catch (RuntimeException e) { // Write out name of file we failed on to help with // debugging. Then print stack trace and try to keep // going. We do this for case where we're being fed // a bunch of ARCs; just note the bad one and move // on to the next. System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage()); e.printStackTrace(System.err); System.exit(1); } } } } }
/******************************************************************************* * Copyright (c) 2015 Jeff Martin. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public * License v3.0 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * Jeff Martin - initial API and implementation ******************************************************************************/ package cuchaz.enigma.bytecode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javassist.CtClass; import javassist.bytecode.AttributeInfo; import javassist.bytecode.BadBytecode; import javassist.bytecode.ByteArray; import javassist.bytecode.ClassFile; import javassist.bytecode.CodeAttribute; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.FieldInfo; import javassist.bytecode.InnerClassesAttribute; import javassist.bytecode.LocalVariableTypeAttribute; import javassist.bytecode.MethodInfo; import javassist.bytecode.SignatureAttribute; import javassist.bytecode.SignatureAttribute.ArrayType; import javassist.bytecode.SignatureAttribute.BaseType; import javassist.bytecode.SignatureAttribute.ClassSignature; import javassist.bytecode.SignatureAttribute.ClassType; import javassist.bytecode.SignatureAttribute.MethodSignature; import javassist.bytecode.SignatureAttribute.NestedClassType; import javassist.bytecode.SignatureAttribute.ObjectType; import javassist.bytecode.SignatureAttribute.Type; import javassist.bytecode.SignatureAttribute.TypeArgument; import javassist.bytecode.SignatureAttribute.TypeParameter; import javassist.bytecode.SignatureAttribute.TypeVariable; import cuchaz.enigma.mapping.entry.ClassEntry; import cuchaz.enigma.mapping.impl.ClassNameReplacer; import cuchaz.enigma.mapping.impl.Translator; public class ClassRenamer { private static enum SignatureType { Class { @Override public String rename(String signature, ReplacerClassMap map) { return renameClassSignature(signature, map); } }, Field { @Override public String rename(String signature, ReplacerClassMap map) { return renameFieldSignature(signature, map); } }, Method { @Override public String rename(String signature, ReplacerClassMap map) { return renameMethodSignature(signature, map); } }; public abstract String rename(String signature, ReplacerClassMap map); } private static class ReplacerClassMap extends HashMap<String,String> { private static final long serialVersionUID = 317915213205066168L; private ClassNameReplacer m_replacer; public ReplacerClassMap(ClassNameReplacer replacer) { m_replacer = replacer; } @Override public String get(Object obj) { if (obj instanceof String) { return get((String)obj); } return null; } public String get(String className) { return m_replacer.replace(className); } } public static void renameClasses(CtClass c, final Translator translator) { renameClasses(c, new ClassNameReplacer() { @Override public String replace(String className) { ClassEntry entry = translator.translateEntry(new ClassEntry(className)); if (entry != null) { return entry.getName(); } return null; } }); } public static void moveAllClassesOutOfDefaultPackage(CtClass c, final String newPackageName) { renameClasses(c, new ClassNameReplacer() { @Override public String replace(String className) { ClassEntry entry = new ClassEntry(className); if (entry.isInDefaultPackage()) { return newPackageName + "/" + entry.getName(); } return null; } }); } public static void moveAllClassesIntoDefaultPackage(CtClass c, final String oldPackageName) { renameClasses(c, new ClassNameReplacer() { @Override public String replace(String className) { ClassEntry entry = new ClassEntry(className); if (entry.getPackageName().equals(oldPackageName)) { return entry.getSimpleName(); } return null; } }); } @SuppressWarnings("unchecked") public static void renameClasses(CtClass c, ClassNameReplacer replacer) { // sadly, we can't use CtClass.renameClass() because SignatureAttribute.renameClass() is extremely buggy =( ReplacerClassMap map = new ReplacerClassMap(replacer); ClassFile classFile = c.getClassFile(); // rename the constant pool (covers ClassInfo, MethodTypeInfo, and NameAndTypeInfo) ConstPool constPool = c.getClassFile().getConstPool(); constPool.renameClass(map); // rename class attributes renameAttributes(classFile.getAttributes(), map, SignatureType.Class); // rename methods for (MethodInfo methodInfo : (List<MethodInfo>)classFile.getMethods()) { methodInfo.setDescriptor(Descriptor.rename(methodInfo.getDescriptor(), map)); renameAttributes(methodInfo.getAttributes(), map, SignatureType.Method); } // rename fields for (FieldInfo fieldInfo : (List<FieldInfo>)classFile.getFields()) { fieldInfo.setDescriptor(Descriptor.rename(fieldInfo.getDescriptor(), map)); renameAttributes(fieldInfo.getAttributes(), map, SignatureType.Field); } // rename the class name itself last // NOTE: don't use the map here, because setName() calls the buggy SignatureAttribute.renameClass() // we only want to replace exactly this class name String newName = renameClassName(c.getName(), map); if (newName != null) { c.setName(newName); } // replace simple names in the InnerClasses attribute too InnerClassesAttribute attr = (InnerClassesAttribute)c.getClassFile().getAttribute(InnerClassesAttribute.tag); if (attr != null) { for (int i = 0; i < attr.tableLength(); i++) { // get the inner class full name (which has already been translated) ClassEntry classEntry = new ClassEntry(Descriptor.toJvmName(attr.innerClass(i))); if (attr.innerNameIndex(i) != 0) { // update the inner name attr.setInnerNameIndex(i, constPool.addUtf8Info(classEntry.getInnermostClassName())); } /* DEBUG System.out.println(String.format("\tDEOBF: %s-> ATTR: %s,%s,%s", classEntry, attr.outerClass(i), attr.innerClass(i), attr.innerName(i))); */ } } } @SuppressWarnings("unchecked") private static void renameAttributes(List<AttributeInfo> attributes, ReplacerClassMap map, SignatureType type) { try { // make the rename class method accessible Method renameClassMethod = AttributeInfo.class.getDeclaredMethod("renameClass", Map.class); renameClassMethod.setAccessible(true); for (AttributeInfo attribute : attributes) { if (attribute instanceof SignatureAttribute) { // this has to be handled specially because SignatureAttribute.renameClass() is buggy as hell SignatureAttribute signatureAttribute = (SignatureAttribute)attribute; String newSignature = type.rename(signatureAttribute.getSignature(), map); if (newSignature != null) { signatureAttribute.setSignature(newSignature); } } else if (attribute instanceof CodeAttribute) { // code attributes have signature attributes too (indirectly) CodeAttribute codeAttribute = (CodeAttribute)attribute; renameAttributes(codeAttribute.getAttributes(), map, type); } else if (attribute instanceof LocalVariableTypeAttribute) { // lvt attributes have signature attributes too LocalVariableTypeAttribute localVariableAttribute = (LocalVariableTypeAttribute)attribute; renameLocalVariableTypeAttribute(localVariableAttribute, map); } else { renameClassMethod.invoke(attribute, map); } } } catch(NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new Error("Unable to call javassist methods by reflection!", ex); } } private static void renameLocalVariableTypeAttribute(LocalVariableTypeAttribute attribute, ReplacerClassMap map) { // adapted from LocalVariableAttribute.renameClass() ConstPool cp = attribute.getConstPool(); int n = attribute.tableLength(); byte[] info = attribute.get(); for (int i = 0; i < n; ++i) { int pos = i * 10 + 2; int index = ByteArray.readU16bit(info, pos + 6); if (index != 0) { String signature = cp.getUtf8Info(index); String newSignature = renameLocalVariableSignature(signature, map); if (newSignature != null) { ByteArray.write16bit(cp.addUtf8Info(newSignature), info, pos + 6); } } } } private static String renameLocalVariableSignature(String signature, ReplacerClassMap map) { // for some reason, signatures with . in them don't count as field signatures // looks like anonymous classes delimit with . in stead of $ // convert the . to $, but keep track of how many we replace // we need to put them back after we translate int start = signature.lastIndexOf('$') + 1; int numConverted = 0; StringBuilder buf = new StringBuilder(signature); for (int i=buf.length()-1; i>=start; i--) { char c = buf.charAt(i); if (c == '.') { buf.setCharAt(i, '$'); numConverted++; } } signature = buf.toString(); // translate String newSignature = renameFieldSignature(signature, map); if (newSignature != null) { // put the delimiters back buf = new StringBuilder(newSignature); for (int i=buf.length()-1; i>=0 && numConverted > 0; i--) { char c = buf.charAt(i); if (c == '$') { buf.setCharAt(i, '.'); numConverted--; } } assert(numConverted == 0); newSignature = buf.toString(); return newSignature; } return null; } private static String renameClassSignature(String signature, ReplacerClassMap map) { try { ClassSignature type = renameType(SignatureAttribute.toClassSignature(signature), map); if (type != null) { return type.encode(); } return null; } catch (BadBytecode ex) { throw new Error("Can't parse field signature: " + signature); } } private static String renameFieldSignature(String signature, ReplacerClassMap map) { try { ObjectType type = renameType(SignatureAttribute.toFieldSignature(signature), map); if (type != null) { return type.encode(); } return null; } catch (BadBytecode ex) { throw new Error("Can't parse class signature: " + signature); } } private static String renameMethodSignature(String signature, ReplacerClassMap map) { try { MethodSignature type = renameType(SignatureAttribute.toMethodSignature(signature), map); if (type != null) { return type.encode(); } return null; } catch (BadBytecode ex) { throw new Error("Can't parse method signature: " + signature); } } private static ClassSignature renameType(ClassSignature type, ReplacerClassMap map) { TypeParameter[] typeParamTypes = type.getParameters(); if (typeParamTypes != null) { typeParamTypes = Arrays.copyOf(typeParamTypes, typeParamTypes.length); for (int i=0; i<typeParamTypes.length; i++) { TypeParameter newParamType = renameType(typeParamTypes[i], map); if (newParamType != null) { typeParamTypes[i] = newParamType; } } } ClassType superclassType = type.getSuperClass(); if (superclassType != ClassType.OBJECT) { ClassType newSuperclassType = renameType(superclassType, map); if (newSuperclassType != null) { superclassType = newSuperclassType; } } ClassType[] interfaceTypes = type.getInterfaces(); if (interfaceTypes != null) { interfaceTypes = Arrays.copyOf(interfaceTypes, interfaceTypes.length); for (int i=0; i<interfaceTypes.length; i++) { ClassType newInterfaceType = renameType(interfaceTypes[i], map); if (newInterfaceType != null) { interfaceTypes[i] = newInterfaceType; } } } return new ClassSignature(typeParamTypes, superclassType, interfaceTypes); } private static MethodSignature renameType(MethodSignature type, ReplacerClassMap map) { TypeParameter[] typeParamTypes = type.getTypeParameters(); if (typeParamTypes != null) { typeParamTypes = Arrays.copyOf(typeParamTypes, typeParamTypes.length); for (int i=0; i<typeParamTypes.length; i++) { TypeParameter newParamType = renameType(typeParamTypes[i], map); if (newParamType != null) { typeParamTypes[i] = newParamType; } } } Type[] paramTypes = type.getParameterTypes(); if (paramTypes != null) { paramTypes = Arrays.copyOf(paramTypes, paramTypes.length); for (int i=0; i<paramTypes.length; i++) { Type newParamType = renameType(paramTypes[i], map); if (newParamType != null) { paramTypes[i] = newParamType; } } } Type returnType = type.getReturnType(); if (returnType != null) { Type newReturnType = renameType(returnType, map); if (newReturnType != null) { returnType = newReturnType; } } ObjectType[] exceptionTypes = type.getExceptionTypes(); if (exceptionTypes != null) { exceptionTypes = Arrays.copyOf(exceptionTypes, exceptionTypes.length); for (int i=0; i<exceptionTypes.length; i++) { ObjectType newExceptionType = renameType(exceptionTypes[i], map); if (newExceptionType != null) { exceptionTypes[i] = newExceptionType; } } } return new MethodSignature(typeParamTypes, paramTypes, returnType, exceptionTypes); } private static Type renameType(Type type, ReplacerClassMap map) { if (type instanceof ObjectType) { return renameType((ObjectType)type, map); } else if (type instanceof BaseType) { return renameType((BaseType)type, map); } else { throw new Error("Don't know how to rename type " + type.getClass()); } } private static ObjectType renameType(ObjectType type, ReplacerClassMap map) { if (type instanceof ArrayType) { return renameType((ArrayType)type, map); } else if (type instanceof ClassType) { return renameType((ClassType)type, map); } else if (type instanceof TypeVariable) { return renameType((TypeVariable)type, map); } else { throw new Error("Don't know how to rename type " + type.getClass()); } } private static BaseType renameType(BaseType type, ReplacerClassMap map) { // don't have to rename primitives return null; } private static TypeVariable renameType(TypeVariable type, ReplacerClassMap map) { // don't have to rename template args return null; } private static ClassType renameType(ClassType type, ReplacerClassMap map) { // translate type args TypeArgument[] args = type.getTypeArguments(); if (args != null) { args = Arrays.copyOf(args, args.length); for (int i=0; i<args.length; i++) { TypeArgument newType = renameType(args[i], map); if (newType != null) { args[i] = newType; } } } if (type instanceof NestedClassType) { NestedClassType nestedType = (NestedClassType)type; // translate the name String name = getClassName(type); String newName = map.get(name); if (newName != null) { name = new ClassEntry(newName).getInnermostClassName(); } // translate the parent class too ClassType parent = renameType(nestedType.getDeclaringClass(), map); if (parent == null) { parent = nestedType.getDeclaringClass(); } return new NestedClassType(parent, name, args); } else { // translate the name String name = type.getName(); String newName = renameClassName(name, map); if (newName != null) { name = newName; } return new ClassType(name, args); } } private static String getClassName(ClassType type) { if (type instanceof NestedClassType) { NestedClassType nestedType = (NestedClassType)type; return getClassName(nestedType.getDeclaringClass()) + "$" + Descriptor.toJvmName(type.getName().replace('.', '$')); } else { return Descriptor.toJvmName(type.getName()); } } private static String renameClassName(String name, ReplacerClassMap map) { String newName = map.get(Descriptor.toJvmName(name)); if (newName != null) { return Descriptor.toJavaName(newName); } return null; } private static TypeArgument renameType(TypeArgument type, ReplacerClassMap map) { ObjectType subType = type.getType(); if (subType != null) { ObjectType newSubType = renameType(subType, map); if (newSubType != null) { switch (type.getKind()) { case ' ': return new TypeArgument(newSubType); case '+': return TypeArgument.subclassOf(newSubType); case '-': return TypeArgument.superOf(newSubType); default: throw new Error("Unknown type kind: " + type.getKind()); } } } return null; } private static ArrayType renameType(ArrayType type, ReplacerClassMap map) { Type newSubType = renameType(type.getComponentType(), map); if (newSubType != null) { return new ArrayType(type.getDimension(), newSubType); } return null; } private static TypeParameter renameType(TypeParameter type, ReplacerClassMap map) { ObjectType superclassType = type.getClassBound(); if (superclassType != null) { ObjectType newSuperclassType = renameType(superclassType, map); if (newSuperclassType != null) { superclassType = newSuperclassType; } } ObjectType[] interfaceTypes = type.getInterfaceBound(); if (interfaceTypes != null) { interfaceTypes = Arrays.copyOf(interfaceTypes, interfaceTypes.length); for (int i=0; i<interfaceTypes.length; i++) { ObjectType newInterfaceType = renameType(interfaceTypes[i], map); if (newInterfaceType != null) { interfaceTypes[i] = newInterfaceType; } } } return new TypeParameter(type.getName(), superclassType, interfaceTypes); } }
/* * ****************************************************************************** * Copyright 2014-2019 Spectra Logic Corporation. 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.ds3client.helpers.strategy.transferstrategy; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.spectralogic.ds3client.helpers.ChecksumListener; import com.spectralogic.ds3client.helpers.DataTransferredListener; import com.spectralogic.ds3client.helpers.FailureEventListener; import com.spectralogic.ds3client.helpers.MetadataReceivedListener; import com.spectralogic.ds3client.helpers.ObjectCompletedListener; import com.spectralogic.ds3client.helpers.WaitingForChunksListener; import com.spectralogic.ds3client.helpers.events.EventRunner; import com.spectralogic.ds3client.helpers.events.FailureEvent; import com.spectralogic.ds3client.helpers.events.MetadataEvent; import com.spectralogic.ds3client.models.BulkObject; import com.spectralogic.ds3client.models.ChecksumType; import com.spectralogic.ds3client.networking.Metadata; import java.util.Map; import java.util.Set; import java.util.UUID; public class EventDispatcherImpl implements EventDispatcher { private final EventRunner eventRunner; private final Set<DataTransferredObserver> dataTransferredObservers = Sets.newIdentityHashSet(); private final Set<ObjectCompletedObserver> objectCompletedObservers = Sets.newIdentityHashSet(); private final Set<ChecksumObserver> checksumObservers = Sets.newIdentityHashSet(); private final Set<WaitingForChunksObserver> waitingForChunksObservers = Sets.newIdentityHashSet(); private final Set<FailureEventObserver> failureEventObservers = Sets.newIdentityHashSet(); private final Set<MetaDataReceivedObserver> metaDataReceivedObservers = Sets.newConcurrentHashSet(); private final Set<BlobTransferredEventObserver> blobTransferredEventObservers = Sets.newIdentityHashSet(); private final Set<CanceledEventObserver> canceledEventObservers = Sets.newIdentityHashSet(); private final Map<DataTransferredListener, DataTransferredObserver> dataTransferredListeners = Maps.newConcurrentMap(); private final Map<ObjectCompletedListener, ObjectCompletedObserver> objectCompletedListeners = Maps.newIdentityHashMap(); private final Map<MetadataReceivedListener, MetaDataReceivedObserver> metadataReceivedListeners = Maps.newIdentityHashMap(); private final Map<ChecksumListener, ChecksumObserver> checksumListeners = Maps.newIdentityHashMap(); private final Map<WaitingForChunksListener, WaitingForChunksObserver> waitingForChunksListeners = Maps.newIdentityHashMap(); private final Map<FailureEventListener, FailureEventObserver> failureEventListeners = Maps.newIdentityHashMap(); public EventDispatcherImpl(final EventRunner eventRunner) { Preconditions.checkNotNull(eventRunner, "eventRunner must not be null."); this.eventRunner = eventRunner; } @Override public DataTransferredObserver attachDataTransferredObserver(final DataTransferredObserver dataTransferredObserver) { dataTransferredObservers.add(dataTransferredObserver); return dataTransferredObserver; } @Override public void removeDataTransferredObserver(final DataTransferredObserver dataTransferredObserver) { dataTransferredObservers.remove(dataTransferredObserver); } @Override public ObjectCompletedObserver attachObjectCompletedObserver(final ObjectCompletedObserver objectCompletedObserver) { objectCompletedObservers.add(objectCompletedObserver); return objectCompletedObserver; } @Override public void removeObjectCompletedObserver(final ObjectCompletedObserver objectCompletedObserver) { objectCompletedObservers.remove(objectCompletedObserver); } @Override public ChecksumObserver attachChecksumObserver(final ChecksumObserver checksumObserver) { checksumObservers.add(checksumObserver); return checksumObserver; } @Override public void removeChecksumObserver(final ChecksumObserver checksumObserver) { checksumObservers.remove(checksumObserver); } @Override public WaitingForChunksObserver attachWaitingForChunksObserver(final WaitingForChunksObserver waitingForChunksObserver) { waitingForChunksObservers.add(waitingForChunksObserver); return waitingForChunksObserver; } @Override public void removeWaitingForChunksObserver(final WaitingForChunksObserver waitingForChunksObserver) { waitingForChunksObservers.remove(waitingForChunksObserver); } @Override public FailureEventObserver attachFailureEventObserver(final FailureEventObserver failureEventObserver) { failureEventObservers.add(failureEventObserver); return failureEventObserver; } @Override public void removeFailureEventObserver(final FailureEventObserver failureEventObserver) { failureEventObservers.remove(failureEventObserver); } @Override public MetaDataReceivedObserver attachMetadataReceivedEventObserver(final MetaDataReceivedObserver metaDataReceivedObserver) { metaDataReceivedObservers.add(metaDataReceivedObserver); return metaDataReceivedObserver; } @Override public void removeMetadataReceivedEventObserver(final MetaDataReceivedObserver metaDataReceivedObserver) { metaDataReceivedObservers.remove(metaDataReceivedObserver); } @Override public BlobTransferredEventObserver attachBlobTransferredEventObserver(final BlobTransferredEventObserver blobTransferredEventObserver) { blobTransferredEventObservers.add(blobTransferredEventObserver); return blobTransferredEventObserver; } @Override public void removeBlobTransferredEventObserver(final BlobTransferredEventObserver blobTransferredEventObserver) { blobTransferredEventObservers.remove(blobTransferredEventObserver); } @Override public void attachDataTransferredListener(final DataTransferredListener listener) { DataTransferredObserver dataTransferredObserver = dataTransferredListeners.get(listener); if (dataTransferredObserver == null) { dataTransferredObserver = attachDataTransferredObserver(new DataTransferredObserver(listener)); dataTransferredListeners.put(listener, dataTransferredObserver); } } @Override public void removeDataTransferredListener(final DataTransferredListener listener) { final DataTransferredObserver dataTransferredObserver = dataTransferredListeners.get(listener); if (dataTransferredObserver != null) { removeDataTransferredObserver(dataTransferredObserver); dataTransferredListeners.remove(listener); } } @Override public void attachObjectCompletedListener(final ObjectCompletedListener listener) { ObjectCompletedObserver objectCompletedObserver = objectCompletedListeners.get(listener); if (objectCompletedObserver == null) { objectCompletedObserver = attachObjectCompletedObserver(new ObjectCompletedObserver(listener)); objectCompletedListeners.put(listener, objectCompletedObserver); } } @Override public void removeObjectCompletedListener(final ObjectCompletedListener listener) { final ObjectCompletedObserver objectCompletedObserver = objectCompletedListeners.get(listener); if (objectCompletedObserver != null) { removeObjectCompletedObserver(objectCompletedObserver); objectCompletedListeners.remove(listener); } } @Override public void attachMetadataReceivedListener(final MetadataReceivedListener listener) { MetaDataReceivedObserver metaDataReceivedObserver = metadataReceivedListeners.get(listener); if (metaDataReceivedObserver == null) { metaDataReceivedObserver = attachMetadataReceivedEventObserver(new MetaDataReceivedObserver(listener)); metadataReceivedListeners.put(listener, metaDataReceivedObserver); } } @Override public void removeMetadataReceivedListener(final MetadataReceivedListener listener) { final MetaDataReceivedObserver metaDataReceivedObserver = metadataReceivedListeners.get(listener); if (metaDataReceivedObserver != null) { removeMetadataReceivedEventObserver(metaDataReceivedObserver); metadataReceivedListeners.remove(listener); } } @Override public void attachChecksumListener(final ChecksumListener listener) { ChecksumObserver checksumObserver = checksumListeners.get(listener); if (checksumObserver == null) { checksumObserver = attachChecksumObserver(new ChecksumObserver(listener)); checksumListeners.put(listener, checksumObserver); } } @Override public void removeChecksumListener(final ChecksumListener listener) { final ChecksumObserver checksumObserver = checksumListeners.get(listener); if (checksumObserver != null) { removeChecksumObserver(checksumObserver); checksumListeners.remove(listener); } } @Override public void attachWaitingForChunksListener(final WaitingForChunksListener listener) { WaitingForChunksObserver waitingForChunksObserver = waitingForChunksListeners.get(listener); if (waitingForChunksObserver == null) { waitingForChunksObserver = attachWaitingForChunksObserver(new WaitingForChunksObserver(listener)); waitingForChunksListeners.put(listener, waitingForChunksObserver); } } @Override public void removeWaitingForChunksListener(final WaitingForChunksListener listener) { final WaitingForChunksObserver waitingForChunksObserver = waitingForChunksListeners.get(listener); if (waitingForChunksObserver != null) { removeWaitingForChunksObserver(waitingForChunksObserver); waitingForChunksListeners.remove(listener); } } @Override public void attachFailureEventListener(final FailureEventListener listener) { FailureEventObserver failureEventObserver = failureEventListeners.get(listener); if (failureEventObserver == null) { failureEventObserver = attachFailureEventObserver(new FailureEventObserver(listener)); failureEventListeners.put(listener, failureEventObserver); } } @Override public void removeFailureEventListener(final FailureEventListener listener) { final FailureEventObserver failureEventObserver = failureEventListeners.get(listener); if (failureEventObserver != null) { removeFailureEventObserver(failureEventObserver); failureEventListeners.remove(listener); } } @Override public CanceledEventObserver attachCanceledEventObserver(final CanceledEventObserver canceledEventObserver) { canceledEventObservers.add(canceledEventObserver); return canceledEventObserver; } @Override public void removeCanceledEventObserver(final CanceledEventObserver canceledEventObserver) { canceledEventObservers.remove(canceledEventObserver); } @Override public void emitFailureEvent(final FailureEvent failureEvent) { emitEvents(failureEventObservers, failureEvent); } @SuppressWarnings("unchecked") private <T> void emitEvents(final Set eventObservers, final T eventData) { for (final Object eventObserver : eventObservers) { eventRunner.emitEvent(() -> ((Observer<T>)eventObserver).update(eventData)); } } @Override public void emitWaitingForChunksEvents(final int secondsToDelay) { emitEvents(waitingForChunksObservers, secondsToDelay); } @Override public void emitChecksumEvent(final BulkObject blob, final ChecksumType.Type type, final String checksum) { emitEvents(checksumObservers, new ChecksumEvent(blob, type, checksum)); } @Override public void emitDataTransferredEvent(final BulkObject blob) { emitEvents(dataTransferredObservers, blob.getLength()); } @Override public void emitObjectCompletedEvent(final BulkObject blob) { emitObjectCompletedEvent(blob.getName()); } @Override public void emitObjectCompletedEvent(final String blobName) { emitEvents(objectCompletedObservers, blobName); } @Override public void emitMetaDataReceivedEvent(final String objectName, final Metadata metadata) { emitEvents(metaDataReceivedObservers, new MetadataEvent(objectName, metadata)); } @Override public void emitBlobTransferredEvent(final BulkObject blob) { emitEvents(blobTransferredEventObservers, blob); } @Override public void emitCanceledEvent(final UUID jobId) { emitEvents(canceledEventObservers, jobId); } @Override public void emitContentLengthMismatchFailureEvent(final BulkObject ds3Object, final String endpoint, final Throwable t) { final FailureEvent failureEvent = FailureEvent.builder() .doingWhat(FailureEvent.FailureActivity.GettingObject) .usingSystemWithEndpoint(endpoint) .withCausalException(t) .withObjectNamed(ds3Object.getName()) .build(); emitFailureEvent(failureEvent); } }
/******************************************************************************* * Copyright 2012 Apigee 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 org.usergrid.persistence; import static org.usergrid.persistence.Schema.PROPERTY_NAME; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import javax.xml.bind.annotation.XmlRootElement; import org.codehaus.jackson.annotate.JsonAnyGetter; import org.codehaus.jackson.annotate.JsonAnySetter; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import org.usergrid.persistence.annotations.EntityProperty; /** * The abstract superclass implementation of the Entity interface. * * @author edanuff * */ @XmlRootElement public abstract class AbstractEntity implements Entity { protected UUID uuid; protected Long created; protected Long modified; protected Map<String, Object> dynamic_properties = new TreeMap<String, Object>( String.CASE_INSENSITIVE_ORDER); protected Map<String, Set<Object>> dynamic_sets = new TreeMap<String, Set<Object>>( String.CASE_INSENSITIVE_ORDER); @Override @EntityProperty(required = true, mutable = false, basic = true) @JsonSerialize(include = Inclusion.NON_NULL) public UUID getUuid() { return uuid; } @Override public void setUuid(UUID uuid) { this.uuid = uuid; } @Override @EntityProperty(required = true, mutable = false, basic = true) public String getType() { return Schema.getDefaultSchema().getEntityType(this.getClass()); } @Override public void setType(String type) { } @Override @EntityProperty(indexed = true, required = true, mutable = false) @JsonSerialize(include = Inclusion.NON_NULL) public Long getCreated() { return created; } @Override public void setCreated(Long created) { if (created == null) { created = System.currentTimeMillis(); } this.created = created; } @Override @EntityProperty(indexed = true, required = true, mutable = true) @JsonSerialize(include = Inclusion.NON_NULL) public Long getModified() { return modified; } @Override public void setModified(Long modified) { if (modified == null) { modified = System.currentTimeMillis(); } this.modified = modified; } @Override @JsonIgnore public String getName() { return (String) getProperty(PROPERTY_NAME); } @Override @JsonIgnore public Map<String, Object> getProperties() { return Schema.getDefaultSchema().getEntityProperties(this); } @Override public final Object getProperty(String propertyName) { return Schema.getDefaultSchema().getEntityProperty(this, propertyName); } @Override public final void setProperty(String propertyName, Object propertyValue) { Schema.getDefaultSchema().setEntityProperty(this, propertyName, propertyValue); } @Override public void setProperties(Map<String, Object> properties) { dynamic_properties = new TreeMap<String, Object>( String.CASE_INSENSITIVE_ORDER); addProperties(properties); } @Override public void addProperties(Map<String, Object> properties) { if (properties == null) { return; } for (Entry<String, Object> entry : properties.entrySet()) { setProperty(entry.getKey(), entry.getValue()); } } @Override @JsonSerialize(include = Inclusion.NON_NULL) public Object getMetadata(String key) { return getDataset("metadata", key); } @Override public void setMetadata(String key, Object value) { setDataset("metadata", key, value); } @Override public void mergeMetadata(Map<String, Object> new_metadata) { mergeDataset("metadata", new_metadata); } @Override public void clearMetadata() { clearDataset("metadata"); } public <T> T getDataset(String property, String key) { Object md = dynamic_properties.get(property); if (md == null) { return null; } if (!(md instanceof Map<?, ?>)) { return null; } @SuppressWarnings("unchecked") Map<String, T> metadata = (Map<String, T>) md; return metadata.get(key); } public <T> void setDataset(String property, String key, T value) { if (key == null) { return; } Object md = dynamic_properties.get(property); if (!(md instanceof Map<?, ?>)) { md = new HashMap<String, T>(); dynamic_properties.put(property, md); } @SuppressWarnings("unchecked") Map<String, T> metadata = (Map<String, T>) md; metadata.put(key, value); } public <T> void mergeDataset(String property, Map<String, T> new_metadata) { Object md = dynamic_properties.get(property); if (!(md instanceof Map<?, ?>)) { md = new HashMap<String, T>(); dynamic_properties.put(property, md); } @SuppressWarnings("unchecked") Map<String, T> metadata = (Map<String, T>) md; metadata.putAll(new_metadata); } public void clearDataset(String property) { dynamic_properties.remove(property); } @Override public List<Entity> getCollections(String key) { return getDataset("collections", key); } @Override public void setCollections(String key, List<Entity> results) { setDataset("collections", key, results); } @Override public List<Entity> getConnections(String key) { return getDataset("connections", key); } @Override public void setConnections(String key, List<Entity> results) { setDataset("connections", key, results); } @Override public String toString() { return "Entity(" + getProperties() + ")"; } @Override @JsonAnySetter public void setDynamicProperty(String key, Object value) { dynamic_properties.put(key, value); } @Override @JsonAnyGetter public Map<String, Object> getDynamicProperties() { return dynamic_properties; } @Override public final int compareTo(Entity o) { if (o == null) { return 1; } try { long t1 = getUuid().timestamp(); long t2 = o.getUuid().timestamp(); return (t1 < t2) ? -1 : (t1 == t2) ? 0 : 1; } catch (UnsupportedOperationException e) { } return getUuid().compareTo(o.getUuid()); } @Override public Entity toTypedEntity() { Entity entity = EntityFactory.newEntity(getUuid(), getType()); entity.setProperties(getProperties()); return entity; } }
/* * Copyright (c) 2016 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * sisane-server: Helps you to develop easily AJAX web applications * by copying and modifying this Java Server. * * Sources at https://github.com/rafaelaznar/sisane-server * * sisane-server is distributed under the MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.daw.service.implementation; import com.google.gson.Gson; import java.sql.Connection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import net.daw.bean.implementation.UsuarioBean; import net.daw.bean.implementation.ReplyBean; import net.daw.bean.implementation.MedicoBean; import net.daw.dao.implementation.MedicoDao; import net.daw.connection.publicinterface.ConnectionInterface; import net.daw.helper.statics.AppConfigurationHelper; import static net.daw.helper.statics.AppConfigurationHelper.getSourceConnection; import net.daw.helper.statics.FilterBeanHelper; import net.daw.helper.statics.JsonMessage; import net.daw.helper.statics.Log4j; import net.daw.helper.statics.ParameterCook; import net.daw.service.publicinterface.TableServiceInterface; import net.daw.service.publicinterface.ViewServiceInterface; public class MedicoService implements TableServiceInterface, ViewServiceInterface { protected HttpServletRequest oRequest = null; public MedicoService(HttpServletRequest request) { oRequest = request; } private Boolean checkpermission(String strMethodName) throws Exception { UsuarioBean oPusuarioBean = (UsuarioBean) oRequest.getSession().getAttribute("userBean"); if (oPusuarioBean != null) { return true; } else { return false; } } @Override public ReplyBean getcount() throws Exception { if (this.checkpermission("getcount")) { String data = null; ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest)); Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); data = JsonMessage.getJsonExpression(200, Long.toString(oMedicoDao.getCount(alFilter))); } catch (Exception ex) { Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return new ReplyBean(200, data); } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } @Override public ReplyBean get() throws Exception { if (this.checkpermission("get")) { int id = ParameterCook.prepareId(oRequest); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); MedicoBean oMedicoBean = new MedicoBean(id); oMedicoBean = oMedicoDao.get(oMedicoBean, AppConfigurationHelper.getJsonMsgDepth()); Gson gson = AppConfigurationHelper.getGson(); data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(oMedicoBean)); } catch (Exception ex) { Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return new ReplyBean(200, data); } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } @Override public ReplyBean getall() throws Exception { if (this.checkpermission("getall")) { HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest)); ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest)); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); ArrayList<MedicoBean> arrBeans = oMedicoDao.getAll(alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth()); data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans)); } catch (Exception ex) { Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return new ReplyBean(200, data); } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } @Override public ReplyBean getpage() throws Exception { if (this.checkpermission("getpage")) { int intRegsPerPag = ParameterCook.prepareRpp(oRequest); int intPage = ParameterCook.preparePage(oRequest); HashMap<String, String> hmOrder = ParameterCook.getOrderParams(ParameterCook.prepareOrder(oRequest)); ArrayList<FilterBeanHelper> alFilter = ParameterCook.getFilterParams(ParameterCook.prepareFilter(oRequest)); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); List<MedicoBean> arrBeans = oMedicoDao.getPage(intRegsPerPag, intPage, alFilter, hmOrder, AppConfigurationHelper.getJsonMsgDepth()); data = JsonMessage.getJsonExpression(200, AppConfigurationHelper.getGson().toJson(arrBeans)); } catch (Exception ex) { Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return new ReplyBean(200, data); } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } @Override public ReplyBean remove() throws Exception { if (this.checkpermission("remove")) { Integer id = ParameterCook.prepareId(oRequest); String data = null; Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); oConnection.setAutoCommit(false); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); data = JsonMessage.getJsonExpression(200, (String) oMedicoDao.remove(id).toString()); oConnection.commit(); } catch (Exception ex) { if (oConnection != null) { oConnection.rollback(); } Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return new ReplyBean(200, data); } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } @Override public ReplyBean set() throws Exception { if (this.checkpermission("set")) { String jason = ParameterCook.prepareJson(oRequest); ReplyBean oReplyBean = new ReplyBean(); Connection oConnection = null; ConnectionInterface oDataConnectionSource = null; try { oDataConnectionSource = getSourceConnection(); oConnection = oDataConnectionSource.newConnection(); oConnection.setAutoCommit(false); MedicoDao oMedicoDao = new MedicoDao(oConnection, (UsuarioBean) oRequest.getSession().getAttribute("userBean"), null); MedicoBean oMedicoBean = new MedicoBean(); oMedicoBean = AppConfigurationHelper.getGson().fromJson(jason, oMedicoBean.getClass()); if (oMedicoBean != null) { Integer iResult = oMedicoDao.set(oMedicoBean); if (iResult >= 1) { oReplyBean.setCode(200); oReplyBean.setJson(JsonMessage.getJsonExpression(200, iResult.toString())); } else { oReplyBean.setCode(500); oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set")); } } else { oReplyBean.setCode(500); oReplyBean.setJson(JsonMessage.getJsonMsg(500, "Error during registry set")); } oConnection.commit(); } catch (Exception ex) { if (oConnection != null) { oConnection.rollback(); } Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex); throw new Exception(); } finally { if (oConnection != null) { oConnection.close(); } if (oDataConnectionSource != null) { oDataConnectionSource.disposeConnection(); } } return oReplyBean; } else { return new ReplyBean(401, JsonMessage.getJsonMsg(401, "Unauthorized")); } } }
/** * * Copyright 2017 Florian Erhard * * 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 gedi.remote; import gedi.app.extension.ExtensionContext; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.Workarounds; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.net.URI; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; public class RemoteConnections { private static final Logger log = Logger.getLogger( RemoteConnections.class.getName() ); private static RemoteConnections instance; public static RemoteConnections getInstance() { if (instance==null) instance = new RemoteConnections(); return instance; } private RemoteConnections(){ } /** * Connects to the given server; the mechanics is as follows: * <br/> * The initChannel consumer is supposed to register channel handlers (called upon channel.registered) * <br/> * Depending on the outcome of the Bootrap.connect method, either the errorHandler or the connectedHandler is called. * <br/> * If the connection is lost, the closedHandler is called. * <br/> * If you want to cancel the connection attempt, invoke cancel on the returned ChannelFuture. If you want to terminate the connection, use the * channel object from the connectedHandler. * <br /> * If the channel is unregistered, the added flag is reset for all handlers bound to the channel pipeline (important if you want to reuse * the handlers added by the initChannel consumer). * * @param uri * @param initChannel * @param errorHandler * @param connectedHandler * @param closedHandler * @return */ public ChannelFuture connect(URI uri, Consumer<SocketChannel> initChannel, Consumer<Throwable> errorHandler, Consumer<SocketChannel> connectedHandler, Runnable closedHandler) { final Protocol protocol = ProtocolExtensionPoint.getInstance().get(ExtensionContext.emptyContext(),uri.getScheme()); if (protocol==null) throw new RuntimeException("Protocol "+uri.getScheme()+" unknown!"); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); protocol.setCodecs(pipeline); initChannel.accept(ch); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { pipeline.addLast(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)); connectedHandler.accept(ch); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); closedHandler.run(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().iterator().forEachRemaining((e)->Workarounds.removeAdded(e.getValue())); super.channelUnregistered(ctx); } }); } }); // Make a new connection and wait until closed. ChannelFuture f = b.connect(uri.getHost(), uri.getPort()==-1?protocol.getDefaultPort():uri.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause!=null) { log.log(Level.INFO, "Connection failed to server "+uri+": "+cause.getMessage()); try { errorHandler.accept(cause); } finally { group.shutdownGracefully(); } } else { log.log(Level.INFO, "Client connected to server "+uri); future.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.log(Level.INFO, "Connection closed to server "+uri); group.shutdownGracefully(); } }); } } }); return f; } // /** // * Blocks! // * @param url // * @param handler // * @return // */ // public void connectSync(URI uri, final Consumer<SocketChannel> initChannel) { // // final Protocol protocol = ProtocolExtensionPoint.getInstance().getProtocol(uri.getScheme()); // if (protocol==null) throw new RuntimeException("Protocol "+uri.getScheme()+" unknown!"); // // // EventLoopGroup group = new NioEventLoopGroup(); // try { // Bootstrap b = new Bootstrap(); // b.group(group) // .channel(NioSocketChannel.class) // .handler(new ChannelInitializer<SocketChannel>() { // // @Override // protected void initChannel(SocketChannel ch) throws Exception { // ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast(new LoggingHandler(LogLevel.INFO)); // protocol.setCodecs(pipeline); // initChannel.accept(ch); // } // }); // // // // Make a new connection and wait until closed. // ChannelFuture f = b.connect(uri.getHost(), uri.getPort()==-1?protocol.getDefaultPort():uri.getPort()) // .addListener(new ChannelFutureListener() { // // @Override // public void operationComplete(ChannelFuture future) throws Exception { // System.out.println(future.cause()); // } // }) // .sync(); // // log.log(Level.INFO, "Client connected to server "+uri); // f.channel().closeFuture().sync(); //// } catch (ConnectException e) { // // } catch (InterruptedException e) { // log.log(Level.SEVERE, "Client thread interrupted", e); // } finally { // group.shutdownGracefully(); // } // } // // /** // * Returns without blocking! // * @param url // * @param handler // * @return // */ // public void connectAsync(final URI uri, final Consumer<SocketChannel> initChannel) { // new Thread() { // public void run() { // connectSync(uri, initChannel); // } // // }.start(); // } public RetryRemoteConnection connectRetry(URI uri, final Consumer<SocketChannel> initChannel, long retryMillisec, boolean killConnectionOnInterupt) { RetryRemoteConnection re = new RetryRemoteConnection(uri,initChannel,retryMillisec,killConnectionOnInterupt); new Thread(re).start(); return re; } /** * Returns without blocking! * @param url * @param handler * @return */ public void serveSync(Protocol protocol, final Consumer<SocketChannel> initChannel) { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)); protocol.setCodecs(pipeline); initChannel.accept(ch); } }); ChannelFuture f = b.bind(protocol.getDefaultPort()).sync(); log.log(Level.INFO, "Server thread started for protocol "+protocol+" on port "+protocol.getDefaultPort()); f.channel().closeFuture().sync(); } catch (InterruptedException e) { log.log(Level.SEVERE, "Server thread interrupted", e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } }
/** * 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.hive.jdbc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.File; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.Shell; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.conf.HiveConf.ConfVars; import org.apache.hive.jdbc.miniHS2.MiniHS2; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSSL { private static final Logger LOG = LoggerFactory.getLogger(TestSSL.class); private static final String KEY_STORE_NAME = "keystore.jks"; private static final String TRUST_STORE_NAME = "truststore.jks"; private static final String KEY_STORE_PASSWORD = "HiveJdbc"; private static final String JAVA_TRUST_STORE_PROP = "javax.net.ssl.trustStore"; private static final String JAVA_TRUST_STORE_PASS_PROP = "javax.net.ssl.trustStorePassword"; private static final String HS2_BINARY_MODE = "binary"; private static final String HS2_HTTP_MODE = "http"; private static final String HS2_HTTP_ENDPOINT = "cliservice"; private static final String HS2_BINARY_AUTH_MODE = "NONE"; private static final String HS2_HTTP_AUTH_MODE = "NOSASL"; private MiniHS2 miniHS2 = null; private static HiveConf conf = new HiveConf(); private Connection hs2Conn = null; private String dataFileDir = conf.get("test.data.files"); private Map<String, String> confOverlay; private final String SSL_CONN_PARAMS = ";ssl=true;sslTrustStore=" + URLEncoder.encode(dataFileDir + File.separator + TRUST_STORE_NAME) + ";trustStorePassword=" + KEY_STORE_PASSWORD; @BeforeClass public static void beforeTest() throws Exception { Class.forName(MiniHS2.getJdbcDriverName()); } @Before public void setUp() throws Exception { DriverManager.setLoginTimeout(0); if (!System.getProperty("test.data.files", "").isEmpty()) { dataFileDir = System.getProperty("test.data.files"); } dataFileDir = dataFileDir.replace('\\', '/').replace("c:", ""); miniHS2 = new MiniHS2(conf); confOverlay = new HashMap<String, String>(); } @After public void tearDown() throws Exception { if (hs2Conn != null) { hs2Conn.close(); } if (miniHS2 != null && miniHS2.isStarted()) { miniHS2.stop(); } System.clearProperty(JAVA_TRUST_STORE_PROP); System.clearProperty(JAVA_TRUST_STORE_PASS_PROP); } private int execCommand(String cmd) throws Exception { int exitCode; try { String output = Shell.execCommand("bash", "-c", cmd); LOG.info("Output from '" + cmd + "': " + output) ; exitCode = 0; } catch (Shell.ExitCodeException e) { exitCode = e.getExitCode(); LOG.info("Error executing '" + cmd + "', exitCode = " + exitCode, e); } return exitCode; } /*** * Tests to ensure SSLv2 and SSLv3 are disabled */ @Test public void testSSLVersion() throws Exception { Assume.assumeTrue(execCommand("which openssl") == 0); // we need openssl Assume.assumeTrue(System.getProperty("os.name").toLowerCase() .contains("linux")); // we depend on linux openssl exit codes setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); // Start HS2 with SSL miniHS2.start(confOverlay); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL() + ";ssl=true;sslTrustStore=" + dataFileDir + File.separator + TRUST_STORE_NAME + ";trustStorePassword=" + KEY_STORE_PASSWORD, System.getProperty("user.name"), "bar"); hs2Conn.close(); Assert.assertEquals("Expected exit code of 1", 1, execCommand("openssl s_client -connect " + miniHS2.getHost() + ":" + miniHS2.getBinaryPort() + " -ssl2 < /dev/null")); Assert.assertEquals("Expected exit code of 1", 1, execCommand("openssl s_client -connect " + miniHS2.getHost() + ":" + miniHS2.getBinaryPort() + " -ssl3 < /dev/null")); miniHS2.stop(); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); // make SSL connection try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL() + ";ssl=true;sslTrustStore=" + dataFileDir + File.separator + TRUST_STORE_NAME + ";trustStorePassword=" + KEY_STORE_PASSWORD + "?hive.server2.transport.mode=" + HS2_HTTP_MODE + ";hive.server2.thrift.http.path=" + HS2_HTTP_ENDPOINT, System.getProperty("user.name"), "bar"); Assert.fail("Expected SQLException during connect"); } catch (SQLException e) { LOG.info("Expected exception: " + e, e); Assert.assertEquals("08S01", e.getSQLState().trim()); Throwable cause = e.getCause(); Assert.assertNotNull(cause); while (cause.getCause() != null) { cause = cause.getCause(); } Assert.assertEquals("org.apache.http.NoHttpResponseException", cause.getClass().getName()); Assert.assertEquals("The target server failed to respond", cause.getMessage()); } miniHS2.stop(); } /*** * Test SSL client with non-SSL server fails * @throws Exception */ @Test public void testInvalidConfig() throws Exception { clearSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); miniHS2.start(confOverlay); DriverManager.setLoginTimeout(4); try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } System.setProperty(JAVA_TRUST_STORE_PROP, dataFileDir + File.separator + TRUST_STORE_NAME ); System.setProperty(JAVA_TRUST_STORE_PASS_PROP, KEY_STORE_PASSWORD); try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL() + ";ssl=true", System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } miniHS2.stop(); // Test in http mode with ssl properties specified in url System.clearProperty(JAVA_TRUST_STORE_PROP); System.clearProperty(JAVA_TRUST_STORE_PASS_PROP); setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); fail("SSL connection should fail with NON-SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } } /*** * Test non-SSL client with SSL server fails * @throws Exception */ @Test public void testConnectionMismatch() throws Exception { setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); miniHS2.start(confOverlay); // Start HS2 with SSL try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL(), System.getProperty("user.name"), "bar"); fail("NON SSL connection should fail with SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL()+ ";ssl=false", System.getProperty("user.name"), "bar"); fail("NON SSL connection should fail with SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } miniHS2.stop(); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); try { hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", ";ssl=false"), System.getProperty("user.name"), "bar"); fail("NON SSL connection should fail with SSL server"); } catch (SQLException e) { // expected error assertEquals("08S01", e.getSQLState().trim()); } } /*** * Test SSL client connection to SSL server * @throws Exception */ @Test public void testSSLConnectionWithURL() throws Exception { setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); // Start HS2 with SSL miniHS2.start(confOverlay); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); hs2Conn.close(); miniHS2.stop(); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); hs2Conn.close(); } /*** * Test SSL client connection to SSL server * @throws Exception */ @Test public void testSSLConnectionWithProperty() throws Exception { setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); // Start HS2 with SSL miniHS2.start(confOverlay); System.setProperty(JAVA_TRUST_STORE_PROP, dataFileDir + File.separator + TRUST_STORE_NAME ); System.setProperty(JAVA_TRUST_STORE_PASS_PROP, KEY_STORE_PASSWORD); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL() + ";ssl=true", System.getProperty("user.name"), "bar"); hs2Conn.close(); miniHS2.stop(); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); hs2Conn.close(); } /** * Start HS2 in SSL mode, open a SSL connection and fetch data * @throws Exception */ @Test public void testSSLFetch() throws Exception { setSslConfOverlay(confOverlay); // Test in binary mode setBinaryConfOverlay(confOverlay); // Start HS2 with SSL miniHS2.start(confOverlay); String tableName = "sslTab"; Path dataFilePath = new Path(dataFileDir, "kv1.txt"); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); // Set up test data setupTestTableWithData(tableName, dataFilePath, hs2Conn); Statement stmt = hs2Conn.createStatement(); ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName); int rowCount = 0; while (res.next()) { ++rowCount; assertEquals("val_" + res.getInt(1), res.getString(2)); } // read result over SSL assertEquals(500, rowCount); hs2Conn.close(); } /** * Start HS2 in Http mode with SSL enabled, open a SSL connection and fetch data * @throws Exception */ @Test public void testSSLFetchHttp() throws Exception { setSslConfOverlay(confOverlay); // Test in http mode setHttpConfOverlay(confOverlay); miniHS2.start(confOverlay); String tableName = "sslTab"; Path dataFilePath = new Path(dataFileDir, "kv1.txt"); // make SSL connection hs2Conn = DriverManager.getConnection(miniHS2.getJdbcURL("default", SSL_CONN_PARAMS), System.getProperty("user.name"), "bar"); // Set up test data setupTestTableWithData(tableName, dataFilePath, hs2Conn); Statement stmt = hs2Conn.createStatement(); ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName); int rowCount = 0; while (res.next()) { ++rowCount; assertEquals("val_" + res.getInt(1), res.getString(2)); } // read result over SSL assertEquals(500, rowCount); hs2Conn.close(); } private void setupTestTableWithData(String tableName, Path dataFilePath, Connection hs2Conn) throws Exception { Statement stmt = hs2Conn.createStatement(); stmt.execute("set hive.support.concurrency = false"); stmt.execute("drop table if exists " + tableName); stmt.execute("create table " + tableName + " (under_col int comment 'the under column', value string)"); // load data stmt.execute("load data local inpath '" + dataFilePath.toString() + "' into table " + tableName); stmt.close(); } private void setSslConfOverlay(Map<String, String> confOverlay) { confOverlay.put(ConfVars.HIVE_SERVER2_USE_SSL.varname, "true"); confOverlay.put(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PATH.varname, dataFileDir + File.separator + KEY_STORE_NAME); confOverlay.put(ConfVars.HIVE_SERVER2_SSL_KEYSTORE_PASSWORD.varname, KEY_STORE_PASSWORD); } private void clearSslConfOverlay(Map<String, String> confOverlay) { confOverlay.put(ConfVars.HIVE_SERVER2_USE_SSL.varname, "false"); } // Currently http mode works with server in NOSASL auth mode & doesn't support doAs private void setHttpConfOverlay(Map<String, String> confOverlay) { confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, HS2_HTTP_MODE); confOverlay.put(ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH.varname, HS2_HTTP_ENDPOINT); confOverlay.put(ConfVars.HIVE_SERVER2_AUTHENTICATION.varname, HS2_HTTP_AUTH_MODE); confOverlay.put(ConfVars.HIVE_SERVER2_ENABLE_DOAS.varname, "false"); } private void setBinaryConfOverlay(Map<String, String> confOverlay) { confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, HS2_BINARY_MODE); confOverlay.put(ConfVars.HIVE_SERVER2_AUTHENTICATION.varname, HS2_BINARY_AUTH_MODE); confOverlay.put(ConfVars.HIVE_SERVER2_ENABLE_DOAS.varname, "true"); } }
/* * Copyright (C) 2009 The Android Open Source Project * * 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 libcore.java.net; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Authenticator; import java.net.CacheRequest; import java.net.CacheResponse; import java.net.HttpRetryException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.ResponseCache; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import libcore.java.security.TestKeyStore; import libcore.javax.net.ssl.TestSSLContext; import tests.http.DefaultResponseCache; import tests.http.MockResponse; import tests.http.MockWebServer; import tests.http.RecordedRequest; public class URLConnectionTest extends junit.framework.TestCase { private static final Authenticator SIMPLE_AUTHENTICATOR = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } }; private MockWebServer server = new MockWebServer(); private String hostname; @Override protected void setUp() throws Exception { super.setUp(); hostname = InetAddress.getLocalHost().getHostName(); } @Override protected void tearDown() throws Exception { ResponseCache.setDefault(null); Authenticator.setDefault(null); System.clearProperty("proxyHost"); System.clearProperty("proxyPort"); System.clearProperty("http.proxyHost"); System.clearProperty("http.proxyPort"); System.clearProperty("https.proxyHost"); System.clearProperty("https.proxyPort"); server.shutdown(); super.tearDown(); } public void testRequestHeaders() throws IOException, InterruptedException { server.enqueue(new MockResponse()); server.play(); HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); urlConnection.addRequestProperty("D", "e"); urlConnection.addRequestProperty("D", "f"); Map<String, List<String>> requestHeaders = urlConnection.getRequestProperties(); assertEquals(newSet("e", "f"), new HashSet<String>(requestHeaders.get("D"))); try { requestHeaders.put("G", Arrays.asList("h")); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } try { requestHeaders.get("D").add("i"); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } try { urlConnection.setRequestProperty(null, "j"); fail(); } catch (NullPointerException expected) { } try { urlConnection.addRequestProperty(null, "k"); fail(); } catch (NullPointerException expected) { } urlConnection.setRequestProperty("NullValue", null); // should fail silently! urlConnection.addRequestProperty("AnotherNullValue", null); // should fail silently! urlConnection.getResponseCode(); RecordedRequest request = server.takeRequest(); assertContains(request.getHeaders(), "D: e"); assertContains(request.getHeaders(), "D: f"); assertContainsNoneMatching(request.getHeaders(), "NullValue.*"); assertContainsNoneMatching(request.getHeaders(), "AnotherNullValue.*"); assertContainsNoneMatching(request.getHeaders(), "G:.*"); assertContainsNoneMatching(request.getHeaders(), "null:.*"); try { urlConnection.addRequestProperty("N", "o"); fail("Set header after connect"); } catch (IllegalStateException expected) { } try { urlConnection.setRequestProperty("P", "q"); fail("Set header after connect"); } catch (IllegalStateException expected) { } } public void testResponseHeaders() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setStatus("HTTP/1.0 200 Fantastic") .addHeader("A: b") .addHeader("A: c") .setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8)); server.play(); HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, urlConnection.getResponseCode()); assertEquals("Fantastic", urlConnection.getResponseMessage()); Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields(); assertEquals(newSet("b", "c"), new HashSet<String>(responseHeaders.get("A"))); try { responseHeaders.put("N", Arrays.asList("o")); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } try { responseHeaders.get("A").add("d"); fail("Modified an unmodifiable view."); } catch (UnsupportedOperationException expected) { } } // Check that if we don't read to the end of a response, the next request on the // recycled connection doesn't get the unread tail of the first request's response. // http://code.google.com/p/android/issues/detail?id=2939 public void test_2939() throws Exception { MockResponse response = new MockResponse().setChunkedBody("ABCDE\nFGHIJ\nKLMNO\nPQR", 8); server.enqueue(response); server.enqueue(response); server.play(); assertContent("ABCDE", server.getUrl("/").openConnection(), 5); assertContent("ABCDE", server.getUrl("/").openConnection(), 5); } // Check that we recognize a few basic mime types by extension. // http://code.google.com/p/android/issues/detail?id=10100 public void test_10100() throws Exception { assertEquals("image/jpeg", URLConnection.guessContentTypeFromName("someFile.jpg")); assertEquals("application/pdf", URLConnection.guessContentTypeFromName("stuff.pdf")); } public void testConnectionsArePooled() throws Exception { MockResponse response = new MockResponse().setBody("ABCDEFGHIJKLMNOPQR"); server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection()); assertEquals(1, server.takeRequest().getSequenceNumber()); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection()); assertEquals(2, server.takeRequest().getSequenceNumber()); } public void testChunkedConnectionsArePooled() throws Exception { MockResponse response = new MockResponse().setChunkedBody("ABCDEFGHIJKLMNOPQR", 5); server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/foo").openConnection()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/bar?baz=quux").openConnection()); assertEquals(1, server.takeRequest().getSequenceNumber()); assertContent("ABCDEFGHIJKLMNOPQR", server.getUrl("/z").openConnection()); assertEquals(2, server.takeRequest().getSequenceNumber()); } enum WriteKind { BYTE_BY_BYTE, SMALL_BUFFERS, LARGE_BUFFERS } public void test_chunkedUpload_byteByByte() throws Exception { doUpload(TransferKind.CHUNKED, WriteKind.BYTE_BY_BYTE); } public void test_chunkedUpload_smallBuffers() throws Exception { doUpload(TransferKind.CHUNKED, WriteKind.SMALL_BUFFERS); } public void test_chunkedUpload_largeBuffers() throws Exception { doUpload(TransferKind.CHUNKED, WriteKind.LARGE_BUFFERS); } public void test_fixedLengthUpload_byteByByte() throws Exception { doUpload(TransferKind.FIXED_LENGTH, WriteKind.BYTE_BY_BYTE); } public void test_fixedLengthUpload_smallBuffers() throws Exception { doUpload(TransferKind.FIXED_LENGTH, WriteKind.SMALL_BUFFERS); } public void test_fixedLengthUpload_largeBuffers() throws Exception { doUpload(TransferKind.FIXED_LENGTH, WriteKind.LARGE_BUFFERS); } private void doUpload(TransferKind uploadKind, WriteKind writeKind) throws Exception { int n = 512*1024; server.setBodyLimit(0); server.enqueue(new MockResponse()); server.play(); HttpURLConnection conn = (HttpURLConnection) server.getUrl("/").openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); if (uploadKind == TransferKind.CHUNKED) { conn.setChunkedStreamingMode(-1); } else { conn.setFixedLengthStreamingMode(n); } OutputStream out = conn.getOutputStream(); if (writeKind == WriteKind.BYTE_BY_BYTE) { for (int i = 0; i < n; ++i) { out.write('x'); } } else { byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64*1024]; Arrays.fill(buf, (byte) 'x'); for (int i = 0; i < n; i += buf.length) { out.write(buf, 0, Math.min(buf.length, n - i)); } } out.close(); assertEquals(200, conn.getResponseCode()); RecordedRequest request = server.takeRequest(); assertEquals(n, request.getBodySize()); if (uploadKind == TransferKind.CHUNKED) { assertTrue(request.getChunkSizes().size() > 0); } else { assertTrue(request.getChunkSizes().isEmpty()); } } /** * Test that response caching is consistent with the RI and the spec. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4 */ public void test_responseCaching() throws Exception { // Test each documented HTTP/1.1 code, plus the first unused value in each range. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html // We can't test 100 because it's not really a response. // assertCached(false, 100); assertCached(false, 101); assertCached(false, 102); assertCached(true, 200); assertCached(false, 201); assertCached(false, 202); assertCached(true, 203); assertCached(false, 204); assertCached(false, 205); assertCached(true, 206); assertCached(false, 207); // (See test_responseCaching_300.) assertCached(true, 301); for (int i = 302; i <= 308; ++i) { assertCached(false, i); } for (int i = 400; i <= 406; ++i) { assertCached(false, i); } // (See test_responseCaching_407.) assertCached(false, 408); assertCached(false, 409); // (See test_responseCaching_410.) for (int i = 411; i <= 418; ++i) { assertCached(false, i); } for (int i = 500; i <= 506; ++i) { assertCached(false, i); } } public void test_responseCaching_300() throws Exception { // TODO: fix this for android assertCached(false, 300); } /** * Response code 407 should only come from proxy servers. Android's client * throws if it is sent by an origin server. */ public void testOriginServerSends407() throws Exception { server.enqueue(new MockResponse().setResponseCode(407)); server.play(); URL url = server.getUrl("/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try { conn.getResponseCode(); fail(); } catch (IOException expected) { } } public void test_responseCaching_410() throws Exception { // the HTTP spec permits caching 410s, but the RI doesn't. assertCached(false, 410); } private void assertCached(boolean shouldPut, int responseCode) throws Exception { server = new MockWebServer(); server.enqueue(new MockResponse() .setResponseCode(responseCode) .setBody("ABCDE") .addHeader("WWW-Authenticate: challenge")); server.play(); DefaultResponseCache responseCache = new DefaultResponseCache(); ResponseCache.setDefault(responseCache); URL url = server.getUrl("/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); assertEquals(responseCode, conn.getResponseCode()); // exhaust the content stream try { // TODO: remove special case once testUnauthorizedResponseHandling() is fixed if (responseCode != 401) { readAscii(conn.getInputStream(), Integer.MAX_VALUE); } } catch (IOException ignored) { } Set<URI> expectedCachedUris = shouldPut ? Collections.singleton(url.toURI()) : Collections.<URI>emptySet(); assertEquals(Integer.toString(responseCode), expectedCachedUris, responseCache.getContents().keySet()); server.shutdown(); // tearDown() isn't sufficient; this test starts multiple servers } public void testConnectViaHttps() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("this response comes via HTTPS", connection); RecordedRequest request = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); } public void testConnectViaHttpsReusingConnections() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS")); server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("this response comes via HTTPS", connection); connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("another response via HTTPS", connection); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); } public void testConnectViaHttpsReusingConnectionsDifferentFactories() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.enqueue(new MockResponse().setBody("another response via HTTPS")); server.play(); // install a custom SSL socket factory so the server can be authorized HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("this response comes via HTTPS", connection); connection = (HttpsURLConnection) server.getUrl("/").openConnection(); try { readAscii(connection.getInputStream(), Integer.MAX_VALUE); fail("without an SSL socket factory, the connection should fail"); } catch (SSLException expected) { } } public void testConnectViaHttpsWithSSLFallback() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setDisconnectAtStart(true)); server.enqueue(new MockResponse().setBody("this response comes via SSL")); server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("this response comes via SSL", connection); RecordedRequest request = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); } /** * Verify that we don't retry connections on certificate verification errors. * * http://code.google.com/p/android/issues/detail?id=13178 */ public void testConnectViaHttpsToUntrustedServer() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(TestKeyStore.getClientCA2(), TestKeyStore.getServer()); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse()); // unused server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/foo").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); try { connection.getInputStream(); fail(); } catch (SSLHandshakeException expected) { assertTrue(expected.getCause() instanceof CertificateException); } assertEquals(0, server.getRequestCount()); } public void testConnectViaProxyUsingProxyArg() throws Exception { testConnectViaProxy(ProxyConfig.CREATE_ARG); } public void testConnectViaProxyUsingProxySystemProperty() throws Exception { testConnectViaProxy(ProxyConfig.PROXY_SYSTEM_PROPERTY); } public void testConnectViaProxyUsingHttpProxySystemProperty() throws Exception { testConnectViaProxy(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY); } private void testConnectViaProxy(ProxyConfig proxyConfig) throws Exception { MockResponse mockResponse = new MockResponse().setBody("this response comes via a proxy"); server.enqueue(mockResponse); server.play(); URL url = new URL("http://android.com/foo"); HttpURLConnection connection = proxyConfig.connect(server, url); assertContent("this response comes via a proxy", connection); RecordedRequest request = server.takeRequest(); assertEquals("GET http://android.com/foo HTTP/1.1", request.getRequestLine()); assertContains(request.getHeaders(), "Host: android.com"); } public void testContentDisagreesWithContentLengthHeader() throws IOException { server.enqueue(new MockResponse() .setBody("abc\r\nYOU SHOULD NOT SEE THIS") .clearHeaders() .addHeader("Content-Length: 3")); server.play(); assertContent("abc", server.getUrl("/").openConnection()); } public void testContentDisagreesWithChunkedHeader() throws IOException { MockResponse mockResponse = new MockResponse(); mockResponse.setChunkedBody("abc", 3); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); bytesOut.write(mockResponse.getBody()); bytesOut.write("\r\nYOU SHOULD NOT SEE THIS".getBytes()); mockResponse.setBody(bytesOut.toByteArray()); mockResponse.clearHeaders(); mockResponse.addHeader("Transfer-encoding: chunked"); server.enqueue(mockResponse); server.play(); assertContent("abc", server.getUrl("/").openConnection()); } public void testConnectViaHttpProxyToHttpsUsingProxyArgWithNoProxy() throws Exception { testConnectViaDirectProxyToHttps(ProxyConfig.NO_PROXY); } public void testConnectViaHttpProxyToHttpsUsingHttpProxySystemProperty() throws Exception { // https should not use http proxy testConnectViaDirectProxyToHttps(ProxyConfig.HTTP_PROXY_SYSTEM_PROPERTY); } private void testConnectViaDirectProxyToHttps(ProxyConfig proxyConfig) throws Exception { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("this response comes via HTTPS")); server.play(); URL url = server.getUrl("/foo"); HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertContent("this response comes via HTTPS", connection); RecordedRequest request = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", request.getRequestLine()); } public void testConnectViaHttpProxyToHttpsUsingProxyArg() throws Exception { testConnectViaHttpProxyToHttps(ProxyConfig.CREATE_ARG); } public void testConnectViaHttpProxyToHttpsUsingHttpsProxySystemProperty() throws Exception { testConnectViaHttpProxyToHttps(ProxyConfig.HTTPS_PROXY_SYSTEM_PROPERTY); } /** * We were verifying the wrong hostname when connecting to an HTTPS site * through a proxy. http://b/3097277 */ private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception { TestSSLContext testSSLContext = TestSSLContext.create(); RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), true); server.enqueue(new MockResponse().clearHeaders()); // for CONNECT server.enqueue(new MockResponse().setBody("this response comes via a secure proxy")); server.play(); URL url = new URL("https://android.com/foo"); HttpsURLConnection connection = (HttpsURLConnection) proxyConfig.connect(server, url); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); connection.setHostnameVerifier(hostnameVerifier); assertContent("this response comes via a secure proxy", connection); RecordedRequest connect = server.takeRequest(); assertEquals("Connect line failure on proxy", "CONNECT android.com:443 HTTP/1.1", connect.getRequestLine()); assertContains(connect.getHeaders(), "Host: android.com"); RecordedRequest get = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", get.getRequestLine()); assertContains(get.getHeaders(), "Host: android.com"); assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls); } /** * Test which headers are sent unencrypted to the HTTP proxy. */ public void testProxyConnectIncludesProxyHeadersOnly() throws IOException, InterruptedException { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), true); server.enqueue(new MockResponse().clearHeaders()); // for CONNECT server.enqueue(new MockResponse().setBody("encrypted response from the origin server")); server.play(); URL url = new URL("https://android.com/foo"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection( server.toProxyAddress()); connection.addRequestProperty("Private", "Secret"); connection.addRequestProperty("Proxy-Authorization", "bar"); connection.addRequestProperty("User-Agent", "baz"); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); connection.setHostnameVerifier(hostnameVerifier); assertContent("encrypted response from the origin server", connection); RecordedRequest connect = server.takeRequest(); assertContainsNoneMatching(connect.getHeaders(), "Private.*"); assertContains(connect.getHeaders(), "Proxy-Authorization: bar"); assertContains(connect.getHeaders(), "User-Agent: baz"); assertContains(connect.getHeaders(), "Host: android.com"); assertContains(connect.getHeaders(), "Proxy-Connection: Keep-Alive"); RecordedRequest get = server.takeRequest(); assertContains(get.getHeaders(), "Private: Secret"); assertEquals(Arrays.asList("verify android.com"), hostnameVerifier.calls); } public void testDisconnectedConnection() throws IOException { server.enqueue(new MockResponse().setBody("ABCDEFGHIJKLMNOPQR")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); InputStream in = connection.getInputStream(); assertEquals('A', (char) in.read()); connection.disconnect(); try { in.read(); fail("Expected a connection closed exception"); } catch (IOException expected) { } } public void testResponseCachingAndInputStreamSkipWithFixedLength() throws IOException { testResponseCaching(TransferKind.FIXED_LENGTH); } public void testResponseCachingAndInputStreamSkipWithChunkedEncoding() throws IOException { testResponseCaching(TransferKind.CHUNKED); } public void testResponseCachingAndInputStreamSkipWithNoLengthHeaders() throws IOException { testResponseCaching(TransferKind.END_OF_STREAM); } /** * HttpURLConnection.getInputStream().skip(long) causes ResponseCache corruption * http://code.google.com/p/android/issues/detail?id=8175 */ private void testResponseCaching(TransferKind transferKind) throws IOException { MockResponse response = new MockResponse(); transferKind.setBody(response, "I love puppies but hate spiders", 1); server.enqueue(response); server.play(); DefaultResponseCache cache = new DefaultResponseCache(); ResponseCache.setDefault(cache); // Make sure that calling skip() doesn't omit bytes from the cache. URLConnection urlConnection = server.getUrl("/").openConnection(); InputStream in = urlConnection.getInputStream(); assertEquals("I love ", readAscii(in, "I love ".length())); reliableSkip(in, "puppies but hate ".length()); assertEquals("spiders", readAscii(in, "spiders".length())); assertEquals(-1, in.read()); in.close(); assertEquals(1, cache.getSuccessCount()); assertEquals(0, cache.getAbortCount()); urlConnection = server.getUrl("/").openConnection(); // this response is cached! in = urlConnection.getInputStream(); assertEquals("I love puppies but hate spiders", readAscii(in, "I love puppies but hate spiders".length())); assertEquals(-1, in.read()); assertEquals(1, cache.getMissCount()); assertEquals(1, cache.getHitCount()); assertEquals(1, cache.getSuccessCount()); assertEquals(0, cache.getAbortCount()); } public void testResponseCacheRequestHeaders() throws IOException, URISyntaxException { server.enqueue(new MockResponse().setBody("ABC")); server.play(); final AtomicReference<Map<String, List<String>>> requestHeadersRef = new AtomicReference<Map<String, List<String>>>(); ResponseCache.setDefault(new ResponseCache() { @Override public CacheResponse get(URI uri, String requestMethod, Map<String, List<String>> requestHeaders) throws IOException { requestHeadersRef.set(requestHeaders); return null; } @Override public CacheRequest put(URI uri, URLConnection conn) throws IOException { return null; } }); URL url = server.getUrl("/"); URLConnection urlConnection = url.openConnection(); urlConnection.addRequestProperty("A", "android"); readAscii(urlConnection.getInputStream(), Integer.MAX_VALUE); assertEquals(Arrays.asList("android"), requestHeadersRef.get().get("A")); } private void reliableSkip(InputStream in, int length) throws IOException { while (length > 0) { length -= in.skip(length); } } /** * Reads {@code count} characters from the stream. If the stream is * exhausted before {@code count} characters can be read, the remaining * characters are returned and the stream is closed. */ private String readAscii(InputStream in, int count) throws IOException { StringBuilder result = new StringBuilder(); for (int i = 0; i < count; i++) { int value = in.read(); if (value == -1) { in.close(); break; } result.append((char) value); } return result.toString(); } public void testServerDisconnectsPrematurelyWithContentLengthHeader() throws IOException { testServerPrematureDisconnect(TransferKind.FIXED_LENGTH); } public void testServerDisconnectsPrematurelyWithChunkedEncoding() throws IOException { testServerPrematureDisconnect(TransferKind.CHUNKED); } public void testServerDisconnectsPrematurelyWithNoLengthHeaders() throws IOException { /* * Intentionally empty. This case doesn't make sense because there's no * such thing as a premature disconnect when the disconnect itself * indicates the end of the data stream. */ } private void testServerPrematureDisconnect(TransferKind transferKind) throws IOException { MockResponse response = new MockResponse(); transferKind.setBody(response, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 16); server.enqueue(truncateViolently(response, 16)); server.enqueue(new MockResponse().setBody("Request #2")); server.play(); DefaultResponseCache cache = new DefaultResponseCache(); ResponseCache.setDefault(cache); BufferedReader reader = new BufferedReader(new InputStreamReader( server.getUrl("/").openConnection().getInputStream())); assertEquals("ABCDE", reader.readLine()); try { reader.readLine(); fail("This implementation silently ignored a truncated HTTP body."); } catch (IOException expected) { } assertEquals(1, cache.getAbortCount()); assertEquals(0, cache.getSuccessCount()); assertContent("Request #2", server.getUrl("/").openConnection()); assertEquals(1, cache.getAbortCount()); assertEquals(1, cache.getSuccessCount()); } public void testClientPrematureDisconnectWithContentLengthHeader() throws IOException { testClientPrematureDisconnect(TransferKind.FIXED_LENGTH); } public void testClientPrematureDisconnectWithChunkedEncoding() throws IOException { testClientPrematureDisconnect(TransferKind.CHUNKED); } public void testClientPrematureDisconnectWithNoLengthHeaders() throws IOException { testClientPrematureDisconnect(TransferKind.END_OF_STREAM); } private void testClientPrematureDisconnect(TransferKind transferKind) throws IOException { MockResponse response = new MockResponse(); transferKind.setBody(response, "ABCDE\nFGHIJKLMNOPQRSTUVWXYZ", 1024); server.enqueue(response); server.enqueue(new MockResponse().setBody("Request #2")); server.play(); DefaultResponseCache cache = new DefaultResponseCache(); ResponseCache.setDefault(cache); InputStream in = server.getUrl("/").openConnection().getInputStream(); assertEquals("ABCDE", readAscii(in, 5)); in.close(); try { in.read(); fail("Expected an IOException because the stream is closed."); } catch (IOException expected) { } assertEquals(1, cache.getAbortCount()); assertEquals(0, cache.getSuccessCount()); assertContent("Request #2", server.getUrl("/").openConnection()); assertEquals(1, cache.getAbortCount()); assertEquals(1, cache.getSuccessCount()); } /** * Shortens the body of {@code response} but not the corresponding headers. * Only useful to test how clients respond to the premature conclusion of * the HTTP body. */ private MockResponse truncateViolently(MockResponse response, int numBytesToKeep) { response.setDisconnectAtEnd(true); List<String> headers = new ArrayList<String>(response.getHeaders()); response.setBody(Arrays.copyOfRange(response.getBody(), 0, numBytesToKeep)); response.getHeaders().clear(); response.getHeaders().addAll(headers); return response; } public void testMarkAndResetWithContentLengthHeader() throws IOException { testMarkAndReset(TransferKind.FIXED_LENGTH); } public void testMarkAndResetWithChunkedEncoding() throws IOException { testMarkAndReset(TransferKind.CHUNKED); } public void testMarkAndResetWithNoLengthHeaders() throws IOException { testMarkAndReset(TransferKind.END_OF_STREAM); } public void testMarkAndReset(TransferKind transferKind) throws IOException { MockResponse response = new MockResponse(); transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024); server.enqueue(response); server.play(); DefaultResponseCache cache = new DefaultResponseCache(); ResponseCache.setDefault(cache); InputStream in = server.getUrl("/").openConnection().getInputStream(); assertFalse("This implementation claims to support mark().", in.markSupported()); in.mark(5); assertEquals("ABCDE", readAscii(in, 5)); try { in.reset(); fail(); } catch (IOException expected) { } assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE)); assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", server.getUrl("/").openConnection()); assertEquals(1, cache.getSuccessCount()); assertEquals(1, cache.getHitCount()); } /** * We've had a bug where we forget the HTTP response when we see response * code 401. This causes a new HTTP request to be issued for every call into * the URLConnection. */ public void testUnauthorizedResponseHandling() throws IOException { MockResponse response = new MockResponse() .addHeader("WWW-Authenticate: challenge") .setResponseCode(401) // UNAUTHORIZED .setBody("Unauthorized"); server.enqueue(response); server.enqueue(response); server.enqueue(response); server.play(); URL url = server.getUrl("/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); assertEquals(401, conn.getResponseCode()); assertEquals(401, conn.getResponseCode()); assertEquals(401, conn.getResponseCode()); assertEquals(1, server.getRequestCount()); } public void testNonHexChunkSize() throws IOException { server.enqueue(new MockResponse() .setBody("5\r\nABCDE\r\nG\r\nFGHIJKLMNOPQRSTU\r\n0\r\n\r\n") .clearHeaders() .addHeader("Transfer-encoding: chunked")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); try { readAscii(connection.getInputStream(), Integer.MAX_VALUE); fail(); } catch (IOException e) { } } public void testMissingChunkBody() throws IOException { server.enqueue(new MockResponse() .setBody("5") .clearHeaders() .addHeader("Transfer-encoding: chunked") .setDisconnectAtEnd(true)); server.play(); URLConnection connection = server.getUrl("/").openConnection(); try { readAscii(connection.getInputStream(), Integer.MAX_VALUE); fail(); } catch (IOException e) { } } /** * This test checks whether connections are gzipped by default. This * behavior in not required by the API, so a failure of this test does not * imply a bug in the implementation. */ public void testGzipEncodingEnabledByDefault() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setBody(gzip("ABCABCABC".getBytes("UTF-8"))) .addHeader("Content-Encoding: gzip")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("ABCABCABC", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertNull(connection.getContentEncoding()); RecordedRequest request = server.takeRequest(); assertContains(request.getHeaders(), "Accept-Encoding: gzip"); } public void testClientConfiguredGzipContentEncoding() throws Exception { server.enqueue(new MockResponse() .setBody(gzip("ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes("UTF-8"))) .addHeader("Content-Encoding: gzip")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); connection.addRequestProperty("Accept-Encoding", "gzip"); InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream()); assertEquals("ABCDEFGHIJKLMNOPQRSTUVWXYZ", readAscii(gunzippedIn, Integer.MAX_VALUE)); RecordedRequest request = server.takeRequest(); assertContains(request.getHeaders(), "Accept-Encoding: gzip"); } public void testGzipAndConnectionReuseWithFixedLength() throws Exception { testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.FIXED_LENGTH); } public void testGzipAndConnectionReuseWithChunkedEncoding() throws Exception { testClientConfiguredGzipContentEncodingAndConnectionReuse(TransferKind.CHUNKED); } public void testClientConfiguredCustomContentEncoding() throws Exception { server.enqueue(new MockResponse() .setBody("ABCDE") .addHeader("Content-Encoding: custom")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); connection.addRequestProperty("Accept-Encoding", "custom"); assertEquals("ABCDE", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest request = server.takeRequest(); assertContains(request.getHeaders(), "Accept-Encoding: custom"); } /** * Test a bug where gzip input streams weren't exhausting the input stream, * which corrupted the request that followed. * http://code.google.com/p/android/issues/detail?id=7059 */ private void testClientConfiguredGzipContentEncodingAndConnectionReuse( TransferKind transferKind) throws Exception { MockResponse responseOne = new MockResponse(); responseOne.addHeader("Content-Encoding: gzip"); transferKind.setBody(responseOne, gzip("one (gzipped)".getBytes("UTF-8")), 5); server.enqueue(responseOne); MockResponse responseTwo = new MockResponse(); transferKind.setBody(responseTwo, "two (identity)", 5); server.enqueue(responseTwo); server.play(); URLConnection connection = server.getUrl("/").openConnection(); connection.addRequestProperty("Accept-Encoding", "gzip"); InputStream gunzippedIn = new GZIPInputStream(connection.getInputStream()); assertEquals("one (gzipped)", readAscii(gunzippedIn, Integer.MAX_VALUE)); assertEquals(0, server.takeRequest().getSequenceNumber()); connection = server.getUrl("/").openConnection(); assertEquals("two (identity)", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(1, server.takeRequest().getSequenceNumber()); } /** * Obnoxiously test that the chunk sizes transmitted exactly equal the * requested data+chunk header size. Although setChunkedStreamingMode() * isn't specific about whether the size applies to the data or the * complete chunk, the RI interprets it as a complete chunk. */ public void testSetChunkedStreamingMode() throws IOException, InterruptedException { server.enqueue(new MockResponse()); server.play(); HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); urlConnection.setChunkedStreamingMode(8); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write("ABCDEFGHIJKLMNOPQ".getBytes("US-ASCII")); assertEquals(200, urlConnection.getResponseCode()); RecordedRequest request = server.takeRequest(); assertEquals("ABCDEFGHIJKLMNOPQ", new String(request.getBody(), "US-ASCII")); assertEquals(Arrays.asList(3, 3, 3, 3, 3, 2), request.getChunkSizes()); } public void testAuthenticateWithFixedLengthStreaming() throws Exception { testAuthenticateWithStreamingPost(StreamingMode.FIXED_LENGTH); } public void testAuthenticateWithChunkedStreaming() throws Exception { testAuthenticateWithStreamingPost(StreamingMode.CHUNKED); } private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception { MockResponse pleaseAuthenticate = new MockResponse() .setResponseCode(401) .addHeader("WWW-Authenticate: Basic realm=\"protected area\"") .setBody("Please authenticate."); server.enqueue(pleaseAuthenticate); server.play(); Authenticator.setDefault(SIMPLE_AUTHENTICATOR); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); connection.setDoOutput(true); byte[] requestBody = { 'A', 'B', 'C', 'D' }; if (streamingMode == StreamingMode.FIXED_LENGTH) { connection.setFixedLengthStreamingMode(requestBody.length); } else if (streamingMode == StreamingMode.CHUNKED) { connection.setChunkedStreamingMode(0); } OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody); outputStream.close(); try { connection.getInputStream(); fail(); } catch (HttpRetryException expected) { } // no authorization header for the request... RecordedRequest request = server.takeRequest(); assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*"); assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody())); } enum StreamingMode { FIXED_LENGTH, CHUNKED } public void testAuthenticateWithPost() throws Exception { MockResponse pleaseAuthenticate = new MockResponse() .setResponseCode(401) .addHeader("WWW-Authenticate: Basic realm=\"protected area\"") .setBody("Please authenticate."); // fail auth three times... server.enqueue(pleaseAuthenticate); server.enqueue(pleaseAuthenticate); server.enqueue(pleaseAuthenticate); // ...then succeed the fourth time server.enqueue(new MockResponse().setBody("Successful auth!")); server.play(); Authenticator.setDefault(SIMPLE_AUTHENTICATOR); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); connection.setDoOutput(true); byte[] requestBody = { 'A', 'B', 'C', 'D' }; OutputStream outputStream = connection.getOutputStream(); outputStream.write(requestBody); outputStream.close(); assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); // no authorization header for the first request... RecordedRequest request = server.takeRequest(); assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*"); // ...but the three requests that follow include an authorization header for (int i = 0; i < 3; i++) { request = server.takeRequest(); assertEquals("POST / HTTP/1.1", request.getRequestLine()); assertContains(request.getHeaders(), "Authorization: Basic " + "dXNlcm5hbWU6cGFzc3dvcmQ="); // "dXNl..." == base64("username:password") assertEquals(Arrays.toString(requestBody), Arrays.toString(request.getBody())); } } public void testAuthenticateWithGet() throws Exception { MockResponse pleaseAuthenticate = new MockResponse() .setResponseCode(401) .addHeader("WWW-Authenticate: Basic realm=\"protected area\"") .setBody("Please authenticate."); // fail auth three times... server.enqueue(pleaseAuthenticate); server.enqueue(pleaseAuthenticate); server.enqueue(pleaseAuthenticate); // ...then succeed the fourth time server.enqueue(new MockResponse().setBody("Successful auth!")); server.play(); Authenticator.setDefault(SIMPLE_AUTHENTICATOR); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); // no authorization header for the first request... RecordedRequest request = server.takeRequest(); assertContainsNoneMatching(request.getHeaders(), "Authorization: Basic .*"); // ...but the three requests that follow requests include an authorization header for (int i = 0; i < 3; i++) { request = server.takeRequest(); assertEquals("GET / HTTP/1.1", request.getRequestLine()); assertContains(request.getHeaders(), "Authorization: Basic " + "dXNlcm5hbWU6cGFzc3dvcmQ="); // "dXNl..." == base64("username:password") } } public void testRedirectedWithChunkedEncoding() throws Exception { testRedirected(TransferKind.CHUNKED, true); } public void testRedirectedWithContentLengthHeader() throws Exception { testRedirected(TransferKind.FIXED_LENGTH, true); } public void testRedirectedWithNoLengthHeaders() throws Exception { testRedirected(TransferKind.END_OF_STREAM, false); } private void testRedirected(TransferKind transferKind, boolean reuse) throws Exception { MockResponse response = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo"); transferKind.setBody(response, "This page has moved!", 10); server.enqueue(response); server.enqueue(new MockResponse().setBody("This is the new location!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest first = server.takeRequest(); assertEquals("GET / HTTP/1.1", first.getRequestLine()); RecordedRequest retry = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", retry.getRequestLine()); if (reuse) { assertEquals("Expected connection reuse", 1, retry.getSequenceNumber()); } } public void testRedirectedOnHttps() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo") .setBody("This page has moved!")); server.enqueue(new MockResponse().setBody("This is the new location!")); server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest first = server.takeRequest(); assertEquals("GET / HTTP/1.1", first.getRequestLine()); RecordedRequest retry = server.takeRequest(); assertEquals("GET /foo HTTP/1.1", retry.getRequestLine()); assertEquals("Expected connection reuse", 1, retry.getSequenceNumber()); } public void testNotRedirectedFromHttpsToHttp() throws IOException, InterruptedException { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: http://anyhost/foo") .setBody("This page has moved!")); server.play(); HttpsURLConnection connection = (HttpsURLConnection) server.getUrl("/").openConnection(); connection.setSSLSocketFactory(testSSLContext.clientContext.getSocketFactory()); assertEquals("This page has moved!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); } public void testNotRedirectedFromHttpToHttps() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: https://anyhost/foo") .setBody("This page has moved!")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals("This page has moved!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); } public void testRedirectToAnotherOriginServer() throws Exception { MockWebServer server2 = new MockWebServer(); server2.enqueue(new MockResponse().setBody("This is the 2nd server!")); server2.play(); server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: " + server2.getUrl("/").toString()) .setBody("This page has moved!")); server.enqueue(new MockResponse().setBody("This is the first server again!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the 2nd server!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(server2.getUrl("/"), connection.getURL()); // make sure the first server was careful to recycle the connection assertEquals("This is the first server again!", readAscii(server.getUrl("/").openStream(), Integer.MAX_VALUE)); RecordedRequest first = server.takeRequest(); assertContains(first.getHeaders(), "Host: " + hostname + ":" + server.getPort()); RecordedRequest second = server2.takeRequest(); assertContains(second.getHeaders(), "Host: " + hostname + ":" + server2.getPort()); RecordedRequest third = server.takeRequest(); assertEquals("Expected connection reuse", 1, third.getSequenceNumber()); server2.shutdown(); } public void testHttpsWithCustomTrustManager() throws Exception { RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier(); RecordingTrustManager trustManager = new RecordingTrustManager(); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { trustManager }, new java.security.SecureRandom()); HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); try { TestSSLContext testSSLContext = TestSSLContext.create(); server.useHttps(testSSLContext.serverContext.getSocketFactory(), false); server.enqueue(new MockResponse().setBody("ABC")); server.enqueue(new MockResponse().setBody("DEF")); server.enqueue(new MockResponse().setBody("GHI")); server.play(); URL url = server.getUrl("/"); assertEquals("ABC", readAscii(url.openStream(), Integer.MAX_VALUE)); assertEquals("DEF", readAscii(url.openStream(), Integer.MAX_VALUE)); assertEquals("GHI", readAscii(url.openStream(), Integer.MAX_VALUE)); assertEquals(Arrays.asList("verify " + hostname), hostnameVerifier.calls); assertEquals(Arrays.asList("checkServerTrusted [" + "CN=" + hostname + " 1, " + "CN=Test Intermediate Certificate Authority 1, " + "CN=Test Root Certificate Authority 1" + "] RSA"), trustManager.calls); } finally { HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory); } } public void testConnectTimeouts() throws IOException { // Set a backlog and use it up so that we can expect the // URLConnection to properly timeout. According to Steven's // 4.5 "listen function", linux adds 3 to the specified // backlog, so we need to connect 4 times before it will hang. ServerSocket serverSocket = new ServerSocket(0, 1); int serverPort = serverSocket.getLocalPort(); Socket[] sockets = new Socket[4]; for (int i = 0; i < sockets.length; i++) { sockets[i] = new Socket("localhost", serverPort); } URLConnection urlConnection = new URL("http://localhost:" + serverPort).openConnection(); urlConnection.setConnectTimeout(1000); try { urlConnection.getInputStream(); fail(); } catch (SocketTimeoutException expected) { } for (Socket s : sockets) { s.close(); } } public void testReadTimeouts() throws IOException { /* * This relies on the fact that MockWebServer doesn't close the * connection after a response has been sent. This causes the client to * try to read more bytes than are sent, which results in a timeout. */ MockResponse timeout = new MockResponse() .setBody("ABC") .clearHeaders() .addHeader("Content-Length: 4"); server.enqueue(timeout); server.play(); URLConnection urlConnection = server.getUrl("/").openConnection(); urlConnection.setReadTimeout(1000); InputStream in = urlConnection.getInputStream(); assertEquals('A', in.read()); assertEquals('B', in.read()); assertEquals('C', in.read()); try { in.read(); // if Content-Length was accurate, this would return -1 immediately fail(); } catch (SocketTimeoutException expected) { } } public void testSetChunkedEncodingAsRequestProperty() throws IOException, InterruptedException { server.enqueue(new MockResponse()); server.play(); HttpURLConnection urlConnection = (HttpURLConnection) server.getUrl("/").openConnection(); urlConnection.setRequestProperty("Transfer-encoding", "chunked"); urlConnection.setDoOutput(true); urlConnection.getOutputStream().write("ABC".getBytes("UTF-8")); assertEquals(200, urlConnection.getResponseCode()); RecordedRequest request = server.takeRequest(); assertEquals("ABC", new String(request.getBody(), "UTF-8")); } public void testConnectionCloseInRequest() throws IOException, InterruptedException { server.enqueue(new MockResponse()); // server doesn't honor the connection: close header! server.enqueue(new MockResponse()); server.play(); HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection(); a.setRequestProperty("Connection", "close"); assertEquals(200, a.getResponseCode()); HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, b.getResponseCode()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals("When connection: close is used, each request should get its own connection", 0, server.takeRequest().getSequenceNumber()); } public void testConnectionCloseInResponse() throws IOException, InterruptedException { server.enqueue(new MockResponse().addHeader("Connection: close")); server.enqueue(new MockResponse()); server.play(); HttpURLConnection a = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, a.getResponseCode()); HttpURLConnection b = (HttpURLConnection) server.getUrl("/").openConnection(); assertEquals(200, b.getResponseCode()); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals("When connection: close is used, each request should get its own connection", 0, server.takeRequest().getSequenceNumber()); } public void testConnectionCloseWithRedirect() throws IOException, InterruptedException { MockResponse response = new MockResponse() .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /foo") .addHeader("Connection: close"); server.enqueue(response); server.enqueue(new MockResponse().setBody("This is the new location!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This is the new location!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals("When connection: close is used, each request should get its own connection", 0, server.takeRequest().getSequenceNumber()); } public void testResponseCodeDisagreesWithHeaders() throws IOException, InterruptedException { server.enqueue(new MockResponse() .setResponseCode(HttpURLConnection.HTTP_NO_CONTENT) .setBody("This body is not allowed!")); server.play(); URLConnection connection = server.getUrl("/").openConnection(); assertEquals("This body is not allowed!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); } public void testSingleByteReadIsSigned() throws IOException { server.enqueue(new MockResponse().setBody(new byte[] { -2, -1 })); server.play(); URLConnection connection = server.getUrl("/").openConnection(); InputStream in = connection.getInputStream(); assertEquals(254, in.read()); assertEquals(255, in.read()); assertEquals(-1, in.read()); } public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException { testFlushAfterStreamTransmitted(TransferKind.CHUNKED); } public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException { testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH); } public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException { testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM); } /** * We explicitly permit apps to close the upload stream even after it has * been transmitted. We also permit flush so that buffered streams can * do a no-op flush when they are closed. http://b/3038470 */ private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException { server.enqueue(new MockResponse().setBody("abc")); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); connection.setDoOutput(true); byte[] upload = "def".getBytes("UTF-8"); if (transferKind == TransferKind.CHUNKED) { connection.setChunkedStreamingMode(0); } else if (transferKind == TransferKind.FIXED_LENGTH) { connection.setFixedLengthStreamingMode(upload.length); } OutputStream out = connection.getOutputStream(); out.write(upload); assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); out.flush(); // dubious but permitted try { out.write("ghi".getBytes("UTF-8")); fail(); } catch (IOException expected) { } } public void testGetHeadersThrows() throws IOException { server.enqueue(new MockResponse().setDisconnectAtStart(true)); server.play(); HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection(); try { connection.getInputStream(); fail(); } catch (IOException expected) { } try { connection.getInputStream(); fail(); } catch (IOException expected) { } } /** * Encodes the response body using GZIP and adds the corresponding header. */ public byte[] gzip(byte[] bytes) throws IOException { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); OutputStream gzippedOut = new GZIPOutputStream(bytesOut); gzippedOut.write(bytes); gzippedOut.close(); return bytesOut.toByteArray(); } /** * Reads at most {@code limit} characters from {@code in} and asserts that * content equals {@code expected}. */ private void assertContent(String expected, URLConnection connection, int limit) throws IOException { connection.connect(); assertEquals(expected, readAscii(connection.getInputStream(), limit)); ((HttpURLConnection) connection).disconnect(); } private void assertContent(String expected, URLConnection connection) throws IOException { assertContent(expected, connection, Integer.MAX_VALUE); } private void assertContains(List<String> headers, String header) { assertTrue(headers.toString(), headers.contains(header)); } private void assertContainsNoneMatching(List<String> headers, String pattern) { for (String header : headers) { if (header.matches(pattern)) { fail("Header " + header + " matches " + pattern); } } } private Set<String> newSet(String... elements) { return new HashSet<String>(Arrays.asList(elements)); } enum TransferKind { CHUNKED() { @Override void setBody(MockResponse response, byte[] content, int chunkSize) throws IOException { response.setChunkedBody(content, chunkSize); } }, FIXED_LENGTH() { @Override void setBody(MockResponse response, byte[] content, int chunkSize) { response.setBody(content); } }, END_OF_STREAM() { @Override void setBody(MockResponse response, byte[] content, int chunkSize) { response.setBody(content); response.setDisconnectAtEnd(true); for (Iterator<String> h = response.getHeaders().iterator(); h.hasNext(); ) { if (h.next().startsWith("Content-Length:")) { h.remove(); break; } } } }; abstract void setBody(MockResponse response, byte[] content, int chunkSize) throws IOException; void setBody(MockResponse response, String content, int chunkSize) throws IOException { setBody(response, content.getBytes("UTF-8"), chunkSize); } } enum ProxyConfig { NO_PROXY() { @Override public HttpURLConnection connect(MockWebServer server, URL url) throws IOException { return (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); } }, CREATE_ARG() { @Override public HttpURLConnection connect(MockWebServer server, URL url) throws IOException { return (HttpURLConnection) url.openConnection(server.toProxyAddress()); } }, PROXY_SYSTEM_PROPERTY() { @Override public HttpURLConnection connect(MockWebServer server, URL url) throws IOException { System.setProperty("proxyHost", "localhost"); System.setProperty("proxyPort", Integer.toString(server.getPort())); return (HttpURLConnection) url.openConnection(); } }, HTTP_PROXY_SYSTEM_PROPERTY() { @Override public HttpURLConnection connect(MockWebServer server, URL url) throws IOException { System.setProperty("http.proxyHost", "localhost"); System.setProperty("http.proxyPort", Integer.toString(server.getPort())); return (HttpURLConnection) url.openConnection(); } }, HTTPS_PROXY_SYSTEM_PROPERTY() { @Override public HttpURLConnection connect(MockWebServer server, URL url) throws IOException { System.setProperty("https.proxyHost", "localhost"); System.setProperty("https.proxyPort", Integer.toString(server.getPort())); return (HttpURLConnection) url.openConnection(); } }; public abstract HttpURLConnection connect(MockWebServer server, URL url) throws IOException; } private static class RecordingTrustManager implements X509TrustManager { private final List<String> calls = new ArrayList<String>(); public X509Certificate[] getAcceptedIssuers() { calls.add("getAcceptedIssuers"); return new X509Certificate[] {}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { calls.add("checkClientTrusted " + certificatesToString(chain) + " " + authType); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { calls.add("checkServerTrusted " + certificatesToString(chain) + " " + authType); } private String certificatesToString(X509Certificate[] certificates) { List<String> result = new ArrayList<String>(); for (X509Certificate certificate : certificates) { result.add(certificate.getSubjectDN() + " " + certificate.getSerialNumber()); } return result.toString(); } } private static class RecordingHostnameVerifier implements HostnameVerifier { private final List<String> calls = new ArrayList<String>(); public boolean verify(String hostname, SSLSession session) { calls.add("verify " + hostname); return true; } } }
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.lib.jdbc.multithread; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.RateLimiter; import com.streamsets.pipeline.api.BatchContext; import com.streamsets.pipeline.api.ErrorCode; import com.streamsets.pipeline.api.PushSource; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.api.ToErrorContext; import com.streamsets.pipeline.lib.jdbc.JdbcErrors; import com.streamsets.pipeline.lib.jdbc.JdbcUtil; import com.streamsets.pipeline.lib.jdbc.UtilsProvider; import com.streamsets.pipeline.lib.jdbc.multithread.cache.JdbcTableReadContextInvalidationListener; import com.streamsets.pipeline.lib.jdbc.multithread.cache.JdbcTableReadContextLoader; import com.streamsets.pipeline.lib.jdbc.multithread.util.OffsetQueryUtil; import com.streamsets.pipeline.lib.util.ThreadUtil; import com.streamsets.pipeline.stage.common.DefaultErrorRecordHandler; import com.streamsets.pipeline.stage.common.ErrorRecordHandler; import com.streamsets.pipeline.stage.origin.jdbc.CommonSourceConfigBean; import com.streamsets.pipeline.stage.origin.jdbc.table.TableJdbcConfigBean; import com.streamsets.pipeline.stage.origin.jdbc.table.TableJdbcELEvalContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.time.ZoneId; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TimeZone; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; public abstract class JdbcBaseRunnable implements Runnable, JdbcRunnable { private static final Logger LOG = LoggerFactory.getLogger(JdbcBaseRunnable.class); protected static final String JDBC_NAMESPACE_HEADER = "jdbc."; private static final long ACQUIRE_TABLE_SLEEP_INTERVAL = 5L; static final String THREAD_NAME = "Thread Name"; public static final String CURRENT_TABLE = "Current Table"; static final String TABLES_OWNED_COUNT = "Tables Owned"; static final String STATUS = "Status"; private static final String LAST_RATE_LIMIT_WAIT_TIME = "Last Rate Limit Wait (sec)"; public static final String TABLE_METRICS = "Table Metrics for Thread - "; public static final String TABLE_JDBC_THREAD_PREFIX = "Table Jdbc Runner - "; public static final String PARTITION_ATTRIBUTE = JDBC_NAMESPACE_HEADER + "partition"; public static final String THREAD_NUMBER_ATTRIBUTE = JDBC_NAMESPACE_HEADER + "threadNumber"; protected final PushSource.Context context; protected final Map<String, String> offsets; private final LoadingCache<TableRuntimeContext, TableReadContext> tableReadContextCache; private MultithreadedTableProvider tableProvider; protected final int threadNumber; private final int batchSize; protected final TableJdbcConfigBean tableJdbcConfigBean; protected final CommonSourceConfigBean commonSourceConfigBean; private final TableJdbcELEvalContext tableJdbcELEvalContext; private final ConnectionManager connectionManager; protected final ErrorRecordHandler errorRecordHandler; private final Map<String, Object> gaugeMap; protected TableRuntimeContext tableRuntimeContext; private long lastQueryIntervalTime; protected TableReadContext tableReadContext; private int numSQLErrors = 0; private SQLException firstSqlException = null; private final RateLimiter queryRateLimiter; private boolean isReconnect; protected final JdbcUtil jdbcUtil; private enum Status { WAITING_FOR_RATE_LIMIT_PERMIT, ACQUIRED_RATE_LIMIT_PERMIT, QUERYING_TABLE, GENERATING_BATCH, BATCH_GENERATED, ; } public JdbcBaseRunnable( PushSource.Context context, int threadNumber, int batchSize, Map<String, String> offsets, MultithreadedTableProvider tableProvider, ConnectionManager connectionManager, TableJdbcConfigBean tableJdbcConfigBean, CommonSourceConfigBean commonSourceConfigBean, CacheLoader<TableRuntimeContext, TableReadContext> tableCacheLoader, RateLimiter queryRateLimiter ) { this( context, threadNumber, batchSize, offsets, tableProvider, connectionManager, tableJdbcConfigBean, commonSourceConfigBean, tableCacheLoader, queryRateLimiter, false ); } public JdbcBaseRunnable( PushSource.Context context, int threadNumber, int batchSize, Map<String, String> offsets, MultithreadedTableProvider tableProvider, ConnectionManager connectionManager, TableJdbcConfigBean tableJdbcConfigBean, CommonSourceConfigBean commonSourceConfigBean, CacheLoader<TableRuntimeContext, TableReadContext> tableCacheLoader, RateLimiter queryRateLimiter, boolean isReconnect ) { this.jdbcUtil = UtilsProvider.getJdbcUtil(); this.context = context; this.threadNumber = threadNumber; this.lastQueryIntervalTime = -1; this.batchSize = batchSize; this.tableJdbcELEvalContext = new TableJdbcELEvalContext(context, context.createELVars()); this.offsets = offsets; this.tableProvider = tableProvider; this.tableJdbcConfigBean = tableJdbcConfigBean; this.commonSourceConfigBean = commonSourceConfigBean; this.connectionManager = connectionManager; this.tableReadContextCache = buildReadContextCache(tableCacheLoader); this.errorRecordHandler = new DefaultErrorRecordHandler(context, (ToErrorContext) context); this.numSQLErrors = 0; this.firstSqlException = null; this.isReconnect = isReconnect; // Metrics this.gaugeMap = context.createGauge(TABLE_METRICS + threadNumber).getValue(); this.queryRateLimiter = queryRateLimiter; } public LoadingCache<TableRuntimeContext, TableReadContext> getTableReadContextCache() { return tableReadContextCache; } @Override public void run() { Thread.currentThread().setName(TABLE_JDBC_THREAD_PREFIX + threadNumber); initGaugeIfNeeded(); while (!context.isStopped()) { generateBatchAndCommitOffset(context.startBatch()); } } /** * Builds the Read Context Cache {@link #tableReadContextCache} */ @SuppressWarnings("unchecked") private LoadingCache<TableRuntimeContext, TableReadContext> buildReadContextCache(CacheLoader<TableRuntimeContext, TableReadContext> tableCacheLoader) { CacheBuilder resultSetCacheBuilder = CacheBuilder.newBuilder() .removalListener(new JdbcTableReadContextInvalidationListener()); if (tableJdbcConfigBean.batchTableStrategy == BatchTableStrategy.SWITCH_TABLES) { if (tableJdbcConfigBean.resultCacheSize > 0) { resultSetCacheBuilder = resultSetCacheBuilder.maximumSize(tableJdbcConfigBean.resultCacheSize); } } else { resultSetCacheBuilder = resultSetCacheBuilder.maximumSize(1); } if (tableCacheLoader != null) { return resultSetCacheBuilder.build(tableCacheLoader); } else { return resultSetCacheBuilder.build(new JdbcTableReadContextLoader( connectionManager, offsets, tableJdbcConfigBean.fetchSize, tableJdbcConfigBean.quoteChar.getQuoteCharacter(), tableJdbcELEvalContext, isReconnect )); } } /** * Initialize the gauge with needed information */ private void initGaugeIfNeeded() { gaugeMap.put(THREAD_NAME, Thread.currentThread().getName()); gaugeMap.put(STATUS, ""); gaugeMap.put(TABLES_OWNED_COUNT, tableReadContextCache.size()); gaugeMap.put(CURRENT_TABLE, ""); } private void updateGauge(JdbcBaseRunnable.Status status) { gaugeMap.put(STATUS, status.name()); gaugeMap.put( CURRENT_TABLE, Optional.ofNullable(tableRuntimeContext).map(TableRuntimeContext::getQualifiedName).orElse("") ); gaugeMap.put( TABLES_OWNED_COUNT, tableProvider.getOwnedTablesQueue().size() ); } /** * Generate a batch (looping through as many tables as needed) until a batch can be generated * and then commit offset. */ private void generateBatchAndCommitOffset(BatchContext batchContext) { int recordCount = 0; int eventCount = 0; try { while (tableRuntimeContext == null) { tableRuntimeContext = tableProvider.nextTable(threadNumber); if (tableRuntimeContext == null) { // small sleep before trying to acquire a table again, to potentially allow a new partition to be // returned to shared queue or created final boolean uninterrupted = ThreadUtil.sleep(ACQUIRE_TABLE_SLEEP_INTERVAL); if (!uninterrupted) { LOG.trace("Interrupted which trying to acquire table"); } if (!uninterrupted || tableRuntimeContext == null) { return; } } } updateGauge(JdbcBaseRunnable.Status.QUERYING_TABLE); tableReadContext = getOrLoadTableReadContext(); ResultSet rs = tableReadContext.getResultSet(); boolean resultSetEndReached = false; try { updateGauge(JdbcBaseRunnable.Status.GENERATING_BATCH); while (recordCount < batchSize) { if (rs.isClosed() || !rs.next()) { if (rs.isClosed()) { LOG.trace("ResultSet is closed"); } resultSetEndReached = true; break; } createAndAddRecord(rs, tableRuntimeContext, batchContext); recordCount++; } LOG.trace("{} records generated", recordCount); if (commonSourceConfigBean.enableSchemaChanges) { generateSchemaChanges(batchContext); } tableRuntimeContext.setResultSetProduced(true); //Reset numSqlErrors if we are able to read result set and add records to the batch context. numSQLErrors = 0; firstSqlException = null; //If exception happened we do not report anything about no more data event //We report noMoreData if either evictTableReadContext is true (result set no more rows) / record count is 0. final AtomicBoolean tableFinished = new AtomicBoolean(false); final AtomicBoolean schemaFinished = new AtomicBoolean(false); final List<String> schemaFinishedTables = new LinkedList<>(); tableProvider.reportDataOrNoMoreData( tableRuntimeContext, recordCount, batchSize, resultSetEndReached, tableFinished, schemaFinished, schemaFinishedTables ); if (tableFinished.get()) { TableFinishedEvent.createTableFinishedEvent(context, batchContext, tableRuntimeContext); eventCount++; } if (schemaFinished.get()) { SchemaFinishedEvent.createSchemaFinishedEvent(context, batchContext, tableRuntimeContext, schemaFinishedTables); eventCount++; } } finally { if (resultSetEndReached) { tableReadContext.closeResultSet(); } handlePostBatchAsNeeded(resultSetEndReached, recordCount, eventCount, batchContext); } } catch (SQLException | ExecutionException | StageException | InterruptedException e) { LOG.error("Error happened", e); //invalidate if the connection is closed tableReadContextCache.invalidateAll(); connectionManager.closeConnection(); //If we have executed post batch that had errored out if (tableRuntimeContext != null) { final TableContext table = tableRuntimeContext.getSourceTableContext(); //if the currently acquired tableContext is no longer a valid candidate, try re-fetch the table from table provider if (commonSourceConfigBean.allowLateTable && !tableProvider.getActiveRuntimeContexts().containsKey(table)) { tableRuntimeContext = null; } } Throwable th = (e instanceof ExecutionException)? e.getCause() : e; if (th instanceof SQLException) { handleSqlException((SQLException)th); } else if (e instanceof InterruptedException) { LOG.error("Thread {} interrupted", gaugeMap.get(THREAD_NAME)); } else if (e instanceof StageException) { // Let the framework handle the StageException instead of handling it yourself. The default behavior for which is to stop pipeline throw (StageException) e; } else { handleStageError(JdbcErrors.JDBC_67, e); } } } private void handleSqlException(SQLException sqlE) { numSQLErrors++; if (numSQLErrors == 1) { firstSqlException = sqlE; } if (numSQLErrors < commonSourceConfigBean.numSQLErrorRetries) { LOG.error( "SQL Exception happened : {}, will retry. Retries Count : {}, Max Retries Count : {}", jdbcUtil.formatSqlException(sqlE), numSQLErrors, commonSourceConfigBean.numSQLErrorRetries ); } else { LOG.error("Maximum SQL Error Retries {} exhausted", commonSourceConfigBean.numSQLErrorRetries); handleStageError(JdbcErrors.JDBC_78, firstSqlException); } } private void calculateEvictTableFlag( AtomicBoolean evictTableReadContext, TableReadContext tableReadContext ) { if (tableReadContext.isNeverEvict()) { evictTableReadContext.set(false); return; } boolean shouldEvict = evictTableReadContext.get(); boolean isNumberOfBatchesReached = ( tableJdbcConfigBean.batchTableStrategy == BatchTableStrategy.SWITCH_TABLES && tableJdbcConfigBean.numberOfBatchesFromRs > 0 && tableReadContext.getNumberOfBatches() >= tableJdbcConfigBean.numberOfBatchesFromRs ); evictTableReadContext.set(shouldEvict || isNumberOfBatchesReached); } /** * After a batch is generate perform needed operations, generate and commit batch * Evict entries from {@link #tableReadContextCache}, reset {@link #tableRuntimeContext} */ protected void handlePostBatchAsNeeded( boolean resultSetEndReached, int recordCount, int eventCount, BatchContext batchContext ) { AtomicBoolean shouldEvict = new AtomicBoolean(resultSetEndReached); // If we read at least one record, it's safe to drop the starting offsets, otherwise they have to re-used if(recordCount > 0) { tableRuntimeContext.getSourceTableContext().clearStartOffset(); } //Only process batch if there are records or events if (recordCount > 0 || eventCount > 0) { TableReadContext tableReadContext = tableReadContextCache.getIfPresent(tableRuntimeContext); Optional.ofNullable(tableReadContext) .ifPresent(readContext -> { readContext.addProcessingMetrics(1, recordCount); LOG.debug( "Table {} read batches={} and records={}", tableRuntimeContext.getQualifiedName(), readContext.getNumberOfBatches(), readContext.getNumberOfRecords() ); calculateEvictTableFlag(shouldEvict, tableReadContext); }); updateGauge(JdbcBaseRunnable.Status.BATCH_GENERATED); //Process And Commit offsets if (tableRuntimeContext.isUsingNonIncrementalLoad()) { // process the batch now, will handle the offset commit outside this block context.processBatch(batchContext); } else { // for incremental (normal) mode, the offset was already stored in this map // by the specific subclass's createAndAddRecord method final String offsetValue = offsets.get(tableRuntimeContext.getOffsetKey()); context.processBatch(batchContext, tableRuntimeContext.getOffsetKey(), offsetValue); } } if (tableRuntimeContext.isUsingNonIncrementalLoad()) { // for non-incremental mode, the offset is simply a singleton map indicating whether it's finished final String offsetValue = createNonIncrementalLoadOffsetValue(resultSetEndReached); context.commitOffset(tableRuntimeContext.getOffsetKey(), offsetValue); } //Make sure we close the result set only when there are no more rows in the result set if (shouldEvict.get()) { //Invalidate so as to fetch a new result set //We close the result set/statement in Removal Listener tableReadContextCache.invalidate(tableRuntimeContext); tableProvider.releaseOwnedTable(tableRuntimeContext, threadNumber); tableRuntimeContext = null; } else if ( tableJdbcConfigBean.batchTableStrategy == BatchTableStrategy.SWITCH_TABLES && !tableRuntimeContext.isUsingNonIncrementalLoad()) { tableRuntimeContext = null; } final List<TableRuntimeContext> removedPartitions = tableProvider.getAndClearRemovedPartitions(); if (removedPartitions != null && removedPartitions.size() > 0) { for (TableRuntimeContext partition : removedPartitions) { LOG.debug( "Removing offset entry for partition {} since it has been removed from the table provider", partition.getDescription() ); context.commitOffset(partition.getOffsetKey(), null); } } } private static String createNonIncrementalLoadOffsetValue(boolean completed) { final Map<String, String> offsets = new HashMap<>(); offsets.put(TableRuntimeContext.NON_INCREMENTAL_LOAD_OFFSET_COMPLETED_KEY, String.valueOf(completed)); return OffsetQueryUtil.getSourceKeyOffsetsRepresentation(offsets); } /** * Initialize the {@link TableJdbcELEvalContext} before generating a batch */ private static void initTableEvalContextForProduce( TableJdbcELEvalContext tableJdbcELEvalContext, TableRuntimeContext tableContext, Calendar calendar ) { tableJdbcELEvalContext.setCalendar(calendar); tableJdbcELEvalContext.setTime(calendar.getTime()); tableJdbcELEvalContext.setTableContext(tableContext); } /** * Wait If needed before a new query is issued. (Does not wait if the result set is already cached) */ private void waitIfNeeded() throws InterruptedException { if (queryRateLimiter != null) { updateGauge(Status.WAITING_FOR_RATE_LIMIT_PERMIT); double waitTime = queryRateLimiter.acquire(); updateGauge(Status.ACQUIRED_RATE_LIMIT_PERMIT); gaugeMap.put(LAST_RATE_LIMIT_WAIT_TIME, waitTime); } else { LOG.debug("No query rate limiter in effect; not waiting"); } } /** * Get Or Load {@link TableReadContext} for {@link #tableRuntimeContext} */ private TableReadContext getOrLoadTableReadContext() throws ExecutionException, InterruptedException { initTableEvalContextForProduce( tableJdbcELEvalContext, tableRuntimeContext, Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(tableJdbcConfigBean.timeZoneID))) ); //Check and then if we want to wait for query being issued do that TableReadContext tableReadContext = tableReadContextCache.getIfPresent(tableRuntimeContext); LOG.trace("Selected table : '{}' for generating records", tableRuntimeContext.getDescription()); if (tableReadContext == null) { //Wait before issuing query (Optimization instead of waiting during each batch) waitIfNeeded(); //Set time before query initTableEvalContextForProduce( tableJdbcELEvalContext, tableRuntimeContext, Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of(tableJdbcConfigBean.timeZoneID))) ); tableReadContext = tableReadContextCache.get(tableRuntimeContext); //Record query time lastQueryIntervalTime = System.currentTimeMillis(); } return tableReadContext; } /** * Handle Exception */ private void handleStageError(ErrorCode errorCode, Exception e) { String errorMessage = (e instanceof SQLException)? jdbcUtil.formatSqlException((SQLException)e) : "Failure Happened"; LOG.error(errorMessage, e); try { errorRecordHandler.onError(errorCode, e); } catch (StageException se) { LOG.error("Error when routing to stage error", se); //Way to throw stage exception from runnable to main source thread Throwables.propagate(se); } } protected DatabaseVendor getVendor() { return connectionManager.getVendor(); } }
package org.yvka.Beleg2.console; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.StringTokenizer; /** * <p> * This class provides convenience methods for reading from the keyboard. <br> * <br> * It can be read several values from the keyboard,<br> * which must be separated by a space, a tab stop or a newline character.<br> * <br> * * </p> * @author Yves Kaufmann * */ public class IOTools { private static BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); private static StringTokenizer input; private static String string; /** * Read a integer number from the console and ensure that * the number is in the is between min and max. * * @param prompt the string which is display as prompt. * @param min the minimum value of the desired number. * @param max the maximum value of the desired number. * @return the entered number. */ public static int readNumberInRange(String prompt, int min, int max ) { int size = 0; boolean isVaidInput = false; while(!isVaidInput) { size = IOTools.readInteger( String.format("%s [%d-%d] : ",prompt, min, max) ); isVaidInput = size >= min && size <= max; if(!isVaidInput) { System.out.println("The specified size is out of the range [1-7]."); System.out.println("Please repeat the input ..."); } } return size; } /** * Deletes all in the current line. */ public static void flush() { input = null; } private static void init() { string = null; if ((input != null) && (input.hasMoreTokens())) return; while ((input == null) || (!input.hasMoreTokens())) { input = new StringTokenizer(readLine()); } } private static void error(Exception paramException, String paramString) { System.out.println("Input error " + paramException); System.out.println("Please repeat the input ..."); System.out.print(paramString); } /** * Reads a line from the keyboard. * * @param paramString the prompt for the user. * @return the readed line. */ public static String readLine(String paramString) { flush(); String str = ""; System.out.print(paramString); try { str = in.readLine(); } catch (IOException localIOException) { System.err.println(localIOException + "\n Program terminated...\n"); System.exit(1); } if (str == null) { System.err .println("Reached end of file.\nProgram terminated...\n"); System.exit(1); } return str; } /** * Read a integer value from the keyboard. * * @param paramString the prompt for the user. * @return the entered integer value. */ public static int readInteger(String paramString) { System.out.print(paramString); init(); for (;;) { try { return Integer.parseInt(input.nextToken()); } catch (NumberFormatException localNumberFormatException) { error(localNumberFormatException, paramString); } init(); } } /** * Reads a long value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered long value. */ public static long readLong(String paramString) { System.out.print(paramString); init(); for (;;) { try { return Long.parseLong(input.nextToken()); } catch (NumberFormatException localNumberFormatException) { error(localNumberFormatException, paramString); } init(); } } /** * Reads a double value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered double value. */ public static double readDouble(String paramString) { System.out.print(paramString); init(); for (;;) { try { return Double.valueOf(input.nextToken()).doubleValue(); } catch (NumberFormatException localNumberFormatException) { error(localNumberFormatException, paramString); } init(); } } /** * Reads a float value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered float value. */ public static float readFloat(String paramString) { System.out.print(paramString); init(); for (;;) { try { return Float.valueOf(input.nextToken()).floatValue(); } catch (NumberFormatException localNumberFormatException) { error(localNumberFormatException, paramString); } init(); } } /** * Reads a short value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered short value. */ public static short readShort(String paramString) { System.out.print(paramString); init(); for (;;) { try { return Short.valueOf(input.nextToken()).shortValue(); } catch (NumberFormatException localNumberFormatException) { error(localNumberFormatException, paramString); } init(); } } /** * Reads a boolean value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered boolean value. */ public static boolean readBoolean(String paramString) { String str = readString(paramString); while ((!str.equals("true")) && (!str.equals("false"))) str = readString(); return str.equals("true"); } /** * Reads a string value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered string value. */ public static String readString(String paramString) { System.out.print(paramString); init(); return input.nextToken(); } /** * Reads a char value from the keyboard. * * * @param paramString the prompt for the user. * @return the entered char value. */ public static char readChar(String paramString) { System.out.print(paramString); if ((string == null) || (string.length() == 0)) string = readString(""); char c = string.charAt(0); string = string.length() > 1 ? string.substring(1) : null; return c; } /** * Read a line value from the keyboard. * @return the entered line. */ public static String readLine() { return readLine(""); } /** * Read a integer value from the keyboard. * @return the entered integer. */ public static int readInteger() { return readInteger(""); } /** * Read a long value from the keyboard. * @return the entered long value. */ public static long readLong() { return readLong(""); } /** * Read a double value from the keyboard. * @return the entered double value. */ public static double readDouble() { return readDouble(""); } /** * Read a short value from the keyboard. * @return the entered short value. */ public static short readShort() { return readShort(""); } /** * Read a float value from the keyboard. * @return the entered float value. */ public static float readFloat() { return readFloat(""); } /** * Read a char value from the keyboard. * @return the entered char value. */ public static char readChar() { return readChar(""); } /** * Read a string value from the keyboard. * @return the entered string value. */ public static String readString() { return readString(""); } /** * Read a boolean value from the keyboard. * @return the entered boolean value. */ public static boolean readBoolean() { return readBoolean(""); } /** * Create the string representation of a specified double value. * * @param paramDouble the specified double value. * @return the string representation of 'paramDouble'. */ public static String toString(double paramDouble) { if ((Double.isInfinite(paramDouble)) || (Double.isNaN(paramDouble))) return String.valueOf(paramDouble); return new BigDecimal(paramDouble).toString(); } }
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.internal.util.xml; import java.io.*; import java.util.InvalidPropertiesFormatException; import java.util.Map.Entry; import java.util.Properties; import jdk.internal.org.xml.sax.Attributes; import jdk.internal.org.xml.sax.InputSource; import jdk.internal.org.xml.sax.SAXException; import jdk.internal.org.xml.sax.SAXParseException; import jdk.internal.org.xml.sax.helpers.DefaultHandler; import jdk.internal.util.xml.impl.SAXParserImpl; import jdk.internal.util.xml.impl.XMLStreamWriterImpl; /** * A class used to aid in Properties load and save in XML. This class is * re-implemented using a subset of SAX * * @author Joe Wang * @since 8 */ public class PropertiesDefaultHandler extends DefaultHandler { // Elements specified in the properties.dtd private static final String ELEMENT_ROOT = "properties"; private static final String ELEMENT_COMMENT = "comment"; private static final String ELEMENT_ENTRY = "entry"; private static final String ATTR_KEY = "key"; // The required DTD URI for exported properties private static final String PROPS_DTD_DECL = "<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">"; private static final String PROPS_DTD_URI = "http://java.sun.com/dtd/properties.dtd"; private static final String PROPS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!-- DTD for properties -->" + "<!ELEMENT properties ( comment?, entry* ) >" + "<!ATTLIST properties" + " version CDATA #FIXED \"1.0\">" + "<!ELEMENT comment (#PCDATA) >" + "<!ELEMENT entry (#PCDATA) >" + "<!ATTLIST entry " + " key CDATA #REQUIRED>"; /** * Version number for the format of exported properties files. */ private static final String EXTERNAL_XML_VERSION = "1.0"; private Properties properties; public void load(Properties props, InputStream in) throws IOException, InvalidPropertiesFormatException, UnsupportedEncodingException { this.properties = props; try { SAXParser parser = new SAXParserImpl(); parser.parse(in, this); } catch (SAXException saxe) { throw new InvalidPropertiesFormatException(saxe); } /** * String xmlVersion = propertiesElement.getAttribute("version"); if * (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0) throw new * InvalidPropertiesFormatException( "Exported Properties file format * version " + xmlVersion + " is not supported. This java installation * can read" + " versions " + EXTERNAL_XML_VERSION + " or older. You" + * " may need to install a newer version of JDK."); */ } public void store(Properties props, OutputStream os, String comment, String encoding) throws IOException { try { XMLStreamWriter writer = new XMLStreamWriterImpl(os, encoding); writer.writeStartDocument(); writer.writeDTD(PROPS_DTD_DECL); writer.writeStartElement(ELEMENT_ROOT); if (comment != null && comment.length() > 0) { writer.writeStartElement(ELEMENT_COMMENT); writer.writeCharacters(comment); writer.writeEndElement(); } synchronized(props) { for (Entry<Object, Object> e : props.entrySet()) { final Object k = e.getKey(); final Object v = e.getValue(); if (k instanceof String && v instanceof String) { writer.writeStartElement(ELEMENT_ENTRY); writer.writeAttribute(ATTR_KEY, (String)k); writer.writeCharacters((String)v); writer.writeEndElement(); } } } writer.writeEndElement(); writer.writeEndDocument(); writer.close(); } catch (XMLStreamException e) { if (e.getCause() instanceof UnsupportedEncodingException) { throw (UnsupportedEncodingException) e.getCause(); } throw new IOException(e); } } //////////////////////////////////////////////////////////////////// // Validate while parsing //////////////////////////////////////////////////////////////////// final static String ALLOWED_ELEMENTS = "properties, comment, entry"; final static String ALLOWED_COMMENT = "comment"; //////////////////////////////////////////////////////////////////// // Handler methods //////////////////////////////////////////////////////////////////// StringBuffer buf = new StringBuffer(); boolean sawComment = false; boolean validEntry = false; int rootElem = 0; String key; String rootElm; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (rootElem < 2) { rootElem++; } if (rootElm == null) { fatalError(new SAXParseException("An XML properties document must contain" + " the DOCTYPE declaration as defined by java.util.Properties.", null)); } if (rootElem == 1 && !rootElm.equals(qName)) { fatalError(new SAXParseException("Document root element \"" + qName + "\", must match DOCTYPE root \"" + rootElm + "\"", null)); } if (!ALLOWED_ELEMENTS.contains(qName)) { fatalError(new SAXParseException("Element type \"" + qName + "\" must be declared.", null)); } if (qName.equals(ELEMENT_ENTRY)) { validEntry = true; key = attributes.getValue(ATTR_KEY); if (key == null) { fatalError(new SAXParseException("Attribute \"key\" is required and must be specified for element type \"entry\"", null)); } } else if (qName.equals(ALLOWED_COMMENT)) { if (sawComment) { fatalError(new SAXParseException("Only one comment element may be allowed. " + "The content of element type \"properties\" must match \"(comment?,entry*)\"", null)); } sawComment = true; } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (validEntry) { buf.append(ch, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (!ALLOWED_ELEMENTS.contains(qName)) { fatalError(new SAXParseException("Element: " + qName + " is invalid, must match \"(comment?,entry*)\".", null)); } if (validEntry) { properties.setProperty(key, buf.toString()); buf.delete(0, buf.length()); validEntry = false; } } @Override public void notationDecl(String name, String publicId, String systemId) throws SAXException { rootElm = name; } @Override public InputSource resolveEntity(String pubid, String sysid) throws SAXException, IOException { { if (sysid.equals(PROPS_DTD_URI)) { InputSource is; is = new InputSource(new StringReader(PROPS_DTD)); is.setSystemId(PROPS_DTD_URI); return is; } throw new SAXException("Invalid system identifier: " + sysid); } } @Override public void error(SAXParseException x) throws SAXException { throw x; } @Override public void fatalError(SAXParseException x) throws SAXException { throw x; } @Override public void warning(SAXParseException x) throws SAXException { throw x; } }
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright The OWASP ZAP Development Team * * 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.zaproxy.zap.db.sql; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.parosproxy.paros.db.DatabaseException; import org.parosproxy.paros.db.DbUtils; import org.parosproxy.paros.db.RecordContext; import org.parosproxy.paros.db.TableContext; public class SqlTableContext extends SqlAbstractTable implements TableContext { private static final String TABLE_NAME = DbSQL.getSQL("context.table_name"); private static final String DATAID = DbSQL.getSQL("context.field.dataid"); private static final String CONTEXTID = DbSQL.getSQL("context.field.contextid"); private static final String TYPE = DbSQL.getSQL("context.field.type"); private static final String DATA = DbSQL.getSQL("context.field.data"); public SqlTableContext() { } @Override protected void reconnect(Connection conn) throws DatabaseException { try { if (!DbUtils.hasTable(conn, TABLE_NAME)) { // Need to create the table DbUtils.executeAndClose(conn.prepareStatement(DbSQL.getSQL("context.ps.createtable"))); } } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#read(long) */ @Override public synchronized RecordContext read(long dataId) throws DatabaseException { SqlPreparedStatementWrapper psRead = null; try { psRead = DbSQL.getSingleton().getPreparedStatement("context.ps.read"); psRead.getPs().setLong(1, dataId); try (ResultSet rs = psRead.getPs().executeQuery()) { RecordContext result = build(rs); return result; } } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psRead); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#insert(int, int, java.lang.String) */ @Override public synchronized RecordContext insert(int contextId, int type, String url) throws DatabaseException { SqlPreparedStatementWrapper psInsert = null; try { psInsert = DbSQL.getSingleton().getPreparedStatement("context.ps.insert"); psInsert.getPs().setInt(1, contextId); psInsert.getPs().setInt(2, type); psInsert.getPs().setString(3, url); psInsert.getPs().executeUpdate(); long id; try (ResultSet rs = psInsert.getLastInsertedId()) { rs.next(); id = rs.getLong(1); } return read(id); } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psInsert); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#delete(int, int, java.lang.String) */ @Override public synchronized void delete(int contextId, int type, String data) throws DatabaseException { SqlPreparedStatementWrapper psDeleteData = null; try { psDeleteData = DbSQL.getSingleton().getPreparedStatement("context.ps.delete"); psDeleteData.getPs().setInt(1, contextId); psDeleteData.getPs().setInt(2, type); psDeleteData.getPs().setString(3, data); psDeleteData.getPs().executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psDeleteData); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#deleteAllDataForContextAndType(int, int) */ @Override public synchronized void deleteAllDataForContextAndType(int contextId, int type) throws DatabaseException { SqlPreparedStatementWrapper psDeleteAllDataForContextAndType = null; try { psDeleteAllDataForContextAndType = DbSQL.getSingleton().getPreparedStatement("context.ps.alldataforcontexttype"); psDeleteAllDataForContextAndType.getPs().setInt(1, contextId); psDeleteAllDataForContextAndType.getPs().setInt(2, type); psDeleteAllDataForContextAndType.getPs().executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psDeleteAllDataForContextAndType); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#deleteAllDataForContext(int) */ @Override public synchronized void deleteAllDataForContext(int contextId) throws DatabaseException { SqlPreparedStatementWrapper psDeleteAllDataForContext = null; try { psDeleteAllDataForContext = DbSQL.getSingleton().getPreparedStatement("context.ps.alldataforcontext"); psDeleteAllDataForContext.getPs().setInt(1, contextId); psDeleteAllDataForContext.getPs().executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psDeleteAllDataForContext); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#getAllData() */ @Override public List<RecordContext> getAllData () throws DatabaseException { SqlPreparedStatementWrapper psGetAllData = null; try { psGetAllData = DbSQL.getSingleton().getPreparedStatement("context.ps.alldata"); List<RecordContext> result = new ArrayList<>(); try (ResultSet rs = psGetAllData.getPs().executeQuery()) { while (rs.next()) { result.add(new RecordContext(rs.getLong(DATAID), rs.getInt(CONTEXTID), rs.getInt(TYPE), rs.getString(DATA))); } } return result; } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psGetAllData); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#getDataForContext(int) */ @Override public List<RecordContext> getDataForContext (int contextId) throws DatabaseException { SqlPreparedStatementWrapper psGetAllDataForContext = null; try { psGetAllDataForContext = DbSQL.getSingleton().getPreparedStatement("context.ps.alldataforcontext"); List<RecordContext> result = new ArrayList<>(); psGetAllDataForContext.getPs().setInt(1, contextId); try (ResultSet rs = psGetAllDataForContext.getPs().executeQuery()) { while (rs.next()) { result.add(new RecordContext(rs.getLong(DATAID), rs.getInt(CONTEXTID), rs.getInt(TYPE), rs.getString(DATA))); } } return result; } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psGetAllDataForContext); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#getDataForContextAndType(int, int) */ @Override public List<RecordContext> getDataForContextAndType (int contextId, int type) throws DatabaseException { SqlPreparedStatementWrapper psGetAllDataForContextAndType = null; try { psGetAllDataForContextAndType = DbSQL.getSingleton().getPreparedStatement("context.ps.alldataforcontexttype"); List<RecordContext> result = new ArrayList<>(); psGetAllDataForContextAndType.getPs().setInt(1, contextId); psGetAllDataForContextAndType.getPs().setInt(2, type); try (ResultSet rs = psGetAllDataForContextAndType.getPs().executeQuery()) { while (rs.next()) { result.add(new RecordContext(rs.getLong(DATAID), rs.getInt(CONTEXTID), rs.getInt(TYPE), rs.getString(DATA))); } } return result; } catch (SQLException e) { throw new DatabaseException(e); } finally { DbSQL.getSingleton().releasePreparedStatement(psGetAllDataForContextAndType); } } private RecordContext build(ResultSet rs) throws DatabaseException { try { RecordContext rt = null; if (rs.next()) { rt = new RecordContext(rs.getLong(DATAID), rs.getInt(CONTEXTID), rs.getInt(TYPE), rs.getString(DATA)); } return rt; } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableContext#setData(int, int, java.util.List) */ @Override public void setData(int contextId, int type, List<String> dataList) throws DatabaseException { this.deleteAllDataForContextAndType(contextId, type); for (String data : dataList) { this.insert(contextId, type, data); } } }
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package microsoft.exchange.webservices.data.property.complex.recurrence.pattern; import microsoft.exchange.webservices.data.attribute.EditorBrowsable; import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.EwsUtilities; import microsoft.exchange.webservices.data.core.ExchangeService; import microsoft.exchange.webservices.data.core.XmlElementNames; import microsoft.exchange.webservices.data.core.enumeration.property.time.DayOfTheWeek; import microsoft.exchange.webservices.data.core.enumeration.property.time.DayOfTheWeekIndex; import microsoft.exchange.webservices.data.core.enumeration.attribute.EditorBrowsableState; import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; import microsoft.exchange.webservices.data.core.enumeration.property.time.Month; import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace; import microsoft.exchange.webservices.data.core.exception.misc.ArgumentException; import microsoft.exchange.webservices.data.core.exception.misc.ArgumentOutOfRangeException; import microsoft.exchange.webservices.data.core.exception.service.local.ServiceValidationException; import microsoft.exchange.webservices.data.property.complex.ComplexProperty; import microsoft.exchange.webservices.data.property.complex.IComplexPropertyChangedDelegate; import microsoft.exchange.webservices.data.property.complex.recurrence.DayOfTheWeekCollection; import microsoft.exchange.webservices.data.property.complex.recurrence.range.EndDateRecurrenceRange; import microsoft.exchange.webservices.data.property.complex.recurrence.range.NoEndRecurrenceRange; import microsoft.exchange.webservices.data.property.complex.recurrence.range.NumberedRecurrenceRange; import microsoft.exchange.webservices.data.property.complex.recurrence.range.RecurrenceRange; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** * Represents a recurrence pattern, as used by Appointment and Task item. */ public abstract class Recurrence extends ComplexProperty { /** * The start date. */ private Date startDate; /** * The number of occurrences. */ private Integer numberOfOccurrences; /** * The end date. */ private Date endDate; /** * Initializes a new instance. */ public Recurrence() { super(); } /** * Initializes a new instance. * * @param startDate the start date */ public Recurrence(Date startDate) { this(); this.startDate = startDate; } /** * Gets the name of the XML element. * * @return the xml element name */ public abstract String getXmlElementName(); /** * Gets a value indicating whether this instance is regeneration pattern. * * @return true, if is regeneration pattern */ public boolean isRegenerationPattern() { return false; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { } /** * Writes elements to XML. * * @param writer the writer * @throws Exception the exception */ @Override public final void writeElementsToXml(EwsServiceXmlWriter writer) throws Exception { writer.writeStartElement(XmlNamespace.Types, this.getXmlElementName()); this.internalWritePropertiesToXml(writer); writer.writeEndElement(); RecurrenceRange range = null; if (!this.hasEnd()) { range = new NoEndRecurrenceRange(this.getStartDate()); } else if (this.getNumberOfOccurrences() != null) { range = new NumberedRecurrenceRange(this.startDate, this.numberOfOccurrences); } else { if (this.getEndDate() != null) { range = new EndDateRecurrenceRange(this.getStartDate(), this .getEndDate()); } } if (range != null) { range.writeToXml(writer, range.getXmlElementName()); } } /** * Gets a property value or throw if null. * * * @param <T> the generic type * @param cls the cls * @param value the value * @param name the name * @return Property value * @throws ServiceValidationException the service validation exception */ public <T> T getFieldValueOrThrowIfNull(Class<T> cls, Object value, String name) throws ServiceValidationException { if (value != null) { return (T) value; } else { throw new ServiceValidationException(String.format( "The recurrence pattern's %s property must be specified.", name)); } } /** * Gets the date and time when the recurrence start. * * @return Date * @throws ServiceValidationException the service validation exception */ public Date getStartDate() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Date.class, this.startDate, "StartDate"); } /** * sets the date and time when the recurrence start. * * @param value the new start date */ public void setStartDate(Date value) { this.startDate = value; } /** * Gets a value indicating whether the pattern has a fixed number of * occurrences or an end date. * * @return boolean */ public boolean hasEnd() { return ((this.numberOfOccurrences != null) || (this.endDate != null)); } /** * Sets up this recurrence so that it never ends. Calling NeverEnds is * equivalent to setting both NumberOfOccurrences and EndDate to null. */ public void neverEnds() { this.numberOfOccurrences = null; this.endDate = null; this.changed(); } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.startDate == null) { throw new ServiceValidationException("The recurrence pattern's StartDate property must be specified."); } } /** * Gets the number of occurrences after which the recurrence ends. * Setting NumberOfOccurrences resets EndDate. * * @return the number of occurrences */ public Integer getNumberOfOccurrences() { return this.numberOfOccurrences; } /** * Gets the number of occurrences after which the recurrence ends. * Setting NumberOfOccurrences resets EndDate. * * @param value the new number of occurrences * @throws ArgumentException the argument exception */ public void setNumberOfOccurrences(Integer value) throws ArgumentException { if (value < 1) { throw new ArgumentException("NumberOfOccurrences must be greater than 0."); } if (this.canSetFieldValue(this.numberOfOccurrences, value)) { numberOfOccurrences = value; this.changed(); } this.endDate = null; } /** * Gets the date after which the recurrence ends. Setting EndDate resets * NumberOfOccurrences. * * @return the end date */ public Date getEndDate() { return this.endDate; } /** * sets the date after which the recurrence ends. Setting EndDate resets * NumberOfOccurrences. * * @param value the new end date */ public void setEndDate(Date value) { if (this.canSetFieldValue(this.endDate, value)) { this.endDate = value; this.changed(); } this.numberOfOccurrences = null; } /** * Represents a recurrence pattern where each occurrence happens a specific * number of days after the previous one. */ public final static class DailyPattern extends IntervalPattern { /** * Gets the name of the XML element. * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.DailyRecurrence; } /** * Initializes a new instance of the DailyPattern class. */ public DailyPattern() { super(); } /** * Initializes a new instance of the DailyPattern class. * * @param startDate The date and time when the recurrence starts. * @param interval The number of days between each occurrence. * @throws ArgumentOutOfRangeException the argument out of range exception */ public DailyPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate, interval); } } /** * Represents a regeneration pattern, as used with recurring tasks, where * each occurrence happens a specified number of days after the previous one * is completed. */ public final static class DailyRegenerationPattern extends IntervalPattern { /** * Initializes a new instance of the DailyRegenerationPattern class. */ public DailyRegenerationPattern() { super(); } /** * Initializes a new instance of the DailyRegenerationPattern class. * * @param startDate The date and time when the recurrence starts. * @param interval The number of days between each occurrence. * @throws ArgumentOutOfRangeException the argument out of range exception */ public DailyRegenerationPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate, interval); } /** * Gets the name of the XML element. * * @return the xml element name */ public String getXmlElementName() { return XmlElementNames.DailyRegeneration; } /** * Gets a value indicating whether this instance is a regeneration * pattern. * * @return true, if is regeneration pattern */ public boolean isRegenerationPattern() { return true; } } /** * Represents a recurrence pattern where each occurrence happens at a * specific interval after the previous one. * [EditorBrowsable(EditorBrowsableState.Never)] */ @EditorBrowsable(state = EditorBrowsableState.Never) public abstract static class IntervalPattern extends Recurrence { /** * The interval. */ private int interval = 1; /** * Initializes a new instance of the IntervalPattern class. */ public IntervalPattern() { super(); } /** * Initializes a new instance of the IntervalPattern class. * * @param startDate The date and time when the recurrence starts. * @param interval The number of days between each occurrence. * @throws ArgumentOutOfRangeException the argument out of range exception */ public IntervalPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate); if (interval < 1) { throw new ArgumentOutOfRangeException("interval", "The interval must be greater than or equal to 1."); } this.setInterval(interval); } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.Interval, this.getInterval()); } /** * Tries to read element from XML. * * @param reader the reader * @return true, if successful * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.Interval)) { this.interval = reader.readElementValue(Integer.class); return true; } else { return false; } } } /** * Gets the interval between occurrences. * * @return the interval */ public int getInterval() { return this.interval; } /** * Sets the interval. * * @param value the new interval * @throws ArgumentOutOfRangeException the argument out of range exception */ public void setInterval(int value) throws ArgumentOutOfRangeException { if (value < 1) { throw new ArgumentOutOfRangeException("value", "The interval must be greater than or equal to 1."); } if (this.canSetFieldValue(this.interval, value)) { this.interval = value; this.changed(); } } } /** * Represents a recurrence pattern where each occurrence happens on a * specific day a specific number of months after the previous one. */ public final static class MonthlyPattern extends IntervalPattern { /** * The day of month. */ private Integer dayOfMonth; /** * Initializes a new instance of the MonthlyPattern class. */ public MonthlyPattern() { super(); } /** * Initializes a new instance of the MonthlyPattern class. * * @param startDate the start date * @param interval the interval * @param dayOfMonth the day of month * @throws ArgumentOutOfRangeException the argument out of range exception */ public MonthlyPattern(Date startDate, int interval, int dayOfMonth) throws ArgumentOutOfRangeException { super(startDate, interval); this.setDayOfMonth(dayOfMonth); } // / Gets the name of the XML element. /* * (non-Javadoc) * * @see microsoft.exchange.webservices.Recurrence#getXmlElementName() */ @Override public String getXmlElementName() { return XmlElementNames.AbsoluteMonthlyRecurrence; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.DayOfMonth, this.getDayOfMonth()); } /** * Tries to read element from XML. * * @param reader the reader * @return True if appropriate element was read. * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.DayOfMonth)) { this.dayOfMonth = reader.readElementValue(Integer.class); return true; } else { return false; } } } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.dayOfMonth == null) { throw new ServiceValidationException("DayOfMonth must be between 1 and 31."); } } /** * Gets the day of month. * * @return the day of month * @throws ServiceValidationException the service validation exception */ public int getDayOfMonth() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Integer.class, this.dayOfMonth, "DayOfMonth"); } /** * Sets the day of month. * * @param value the new day of month * @throws ArgumentOutOfRangeException the argument out of range exception */ public void setDayOfMonth(int value) throws ArgumentOutOfRangeException { if (value < 1 || value > 31) { throw new ArgumentOutOfRangeException("DayOfMonth", "DayOfMonth must be between 1 and 31."); } if (this.canSetFieldValue(this.dayOfMonth, value)) { this.dayOfMonth = value; this.changed(); } } } /** * Represents a regeneration pattern, as used with recurring tasks, where * each occurrence happens a specified number of months after the previous * one is completed. */ public final static class MonthlyRegenerationPattern extends IntervalPattern { /** * Instantiates a new monthly regeneration pattern. */ public MonthlyRegenerationPattern() { super(); } /** * Instantiates a new monthly regeneration pattern. * * @param startDate the start date * @param interval the interval * @throws ArgumentOutOfRangeException the argument out of range exception */ public MonthlyRegenerationPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate, interval); } /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.MonthlyRegeneration; } /** * Gets a value indicating whether this instance is regeneration * pattern. <value> <c>true</c> if this instance is regeneration * pattern; otherwise, <c>false</c>. </value> * * @return true, if is regeneration pattern */ public boolean isRegenerationPattern() { return true; } } /** * Represents a recurrence pattern where each occurrence happens on a * relative day a specific number of months after the previous one. */ public final static class RelativeMonthlyPattern extends IntervalPattern { /** * The day of the week. */ private DayOfTheWeek dayOfTheWeek; /** * The day of the week index. */ private DayOfTheWeekIndex dayOfTheWeekIndex; // / Initializes a new instance of the <see // cref="RelativeMonthlyPattern"/> class. /** * Instantiates a new relative monthly pattern. */ public RelativeMonthlyPattern() { super(); } /** * Instantiates a new relative monthly pattern. * * @param startDate the start date * @param interval the interval * @param dayOfTheWeek the day of the week * @param dayOfTheWeekIndex the day of the week index * @throws ArgumentOutOfRangeException the argument out of range exception */ public RelativeMonthlyPattern(Date startDate, int interval, DayOfTheWeek dayOfTheWeek, DayOfTheWeekIndex dayOfTheWeekIndex) throws ArgumentOutOfRangeException { super(startDate, interval); this.setDayOfTheWeek(dayOfTheWeek); this.setDayOfTheWeekIndex(dayOfTheWeekIndex); } /** * Gets the name of the XML element. * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.RelativeMonthlyRecurrence; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.DaysOfWeek, this.getDayOfTheWeek()); writer .writeElementValue(XmlNamespace.Types, XmlElementNames.DayOfWeekIndex, this .getDayOfTheWeekIndex()); } /** * Tries to read element from XML. * * @param reader the reader * @return True if appropriate element was read. * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.DaysOfWeek)) { this.dayOfTheWeek = reader .readElementValue(DayOfTheWeek.class); return true; } else if (reader.getLocalName().equals( XmlElementNames.DayOfWeekIndex)) { this.dayOfTheWeekIndex = reader .readElementValue(DayOfTheWeekIndex.class); return true; } else { return false; } } } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.dayOfTheWeek == null) { throw new ServiceValidationException( "The recurrence pattern's property DayOfTheWeek must be specified."); } if (this.dayOfTheWeekIndex == null) { throw new ServiceValidationException( "The recurrence pattern's DayOfWeekIndex property must be specified."); } } /** * Day of the week index. * * @return the day of the week index * @throws ServiceValidationException the service validation exception */ public DayOfTheWeekIndex getDayOfTheWeekIndex() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(DayOfTheWeekIndex.class, this.dayOfTheWeekIndex, "DayOfTheWeekIndex"); } /** * Day of the week index. * * @param value the value */ public void setDayOfTheWeekIndex(DayOfTheWeekIndex value) { if (this.canSetFieldValue(this.dayOfTheWeekIndex, value)) { this.dayOfTheWeekIndex = value; this.changed(); } } /** * Gets the day of the week. * * @return the day of the week * @throws ServiceValidationException the service validation exception */ public DayOfTheWeek getDayOfTheWeek() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(DayOfTheWeek.class, this.dayOfTheWeek, "DayOfTheWeek"); } /** * Sets the day of the week. * * @param value the new day of the week */ public void setDayOfTheWeek(DayOfTheWeek value) { if (this.canSetFieldValue(this.dayOfTheWeek, value)) { this.dayOfTheWeek = value; this.changed(); } } } /** * The Class RelativeYearlyPattern. */ public final static class RelativeYearlyPattern extends Recurrence { /** * The day of the week. */ private DayOfTheWeek dayOfTheWeek; /** * The day of the week index. */ private DayOfTheWeekIndex dayOfTheWeekIndex; /** * The month. */ private Month month; /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.RelativeYearlyRecurrence; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.DaysOfWeek, this.dayOfTheWeek); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.DayOfWeekIndex, this.dayOfTheWeekIndex); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.Month, this.month); } /** * Tries to read element from XML. * * @param reader the reader * @return True if element was read. * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.DaysOfWeek)) { this.dayOfTheWeek = reader .readElementValue(DayOfTheWeek.class); return true; } else if (reader.getLocalName().equals( XmlElementNames.DayOfWeekIndex)) { this.dayOfTheWeekIndex = reader .readElementValue(DayOfTheWeekIndex.class); return true; } else if (reader.getLocalName().equals(XmlElementNames.Month)) { this.month = reader.readElementValue(Month.class); return true; } else { return false; } } } /** * Instantiates a new relative yearly pattern. */ public RelativeYearlyPattern() { super(); } /** * Instantiates a new relative yearly pattern. * * @param startDate the start date * @param month the month * @param dayOfTheWeek the day of the week * @param dayOfTheWeekIndex the day of the week index */ public RelativeYearlyPattern(Date startDate, Month month, DayOfTheWeek dayOfTheWeek, DayOfTheWeekIndex dayOfTheWeekIndex) { super(startDate); this.month = month; this.dayOfTheWeek = dayOfTheWeek; this.dayOfTheWeekIndex = dayOfTheWeekIndex; } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.dayOfTheWeekIndex == null) { throw new ServiceValidationException( "The recurrence pattern's DayOfWeekIndex property must be specified."); } if (this.dayOfTheWeek == null) { throw new ServiceValidationException( "The recurrence pattern's property DayOfTheWeek must be specified."); } if (this.month == null) { throw new ServiceValidationException("The recurrence pattern's Month property must be specified."); } } /** * Gets the relative position of the day specified in DayOfTheWeek * within the month. * * @return the day of the week index * @throws ServiceValidationException the service validation exception */ public DayOfTheWeekIndex getDayOfTheWeekIndex() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(DayOfTheWeekIndex.class, this.dayOfTheWeekIndex, "DayOfTheWeekIndex"); } /** * Sets the relative position of the day specified in DayOfTheWeek * within the month. * * @param value the new day of the week index */ public void setDayOfTheWeekIndex(DayOfTheWeekIndex value) { if (this.canSetFieldValue(this.dayOfTheWeekIndex, value)) { this.dayOfTheWeekIndex = value; this.changed(); } } /** * Gets the day of the week. * * @return the day of the week * @throws ServiceValidationException the service validation exception */ public DayOfTheWeek getDayOfTheWeek() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(DayOfTheWeek.class, this.dayOfTheWeek, "DayOfTheWeek"); } /** * Sets the day of the week. * * @param value the new day of the week */ public void setDayOfTheWeek(DayOfTheWeek value) { if (this.canSetFieldValue(this.dayOfTheWeek, value)) { this.dayOfTheWeek = value; this.changed(); } } /** * Gets the month. * * @return the month * @throws ServiceValidationException the service validation exception */ public Month getMonth() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Month.class, this.month, "Month"); } /** * Sets the month. * * @param value the new month */ public void setMonth(Month value) { if (this.canSetFieldValue(this.month, value)) { this.month = value; this.changed(); } } } /** * Represents a recurrence pattern where each occurrence happens on specific * days a specific number of weeks after the previous one. */ public final static class WeeklyPattern extends IntervalPattern implements IComplexPropertyChangedDelegate { /** * The days of the week. */ private DayOfTheWeekCollection daysOfTheWeek = new DayOfTheWeekCollection(); private Calendar firstDayOfWeek; /** * Initializes a new instance of the WeeklyPattern class. specific days * a specific number of weeks after the previous one. */ public WeeklyPattern() { super(); this.daysOfTheWeek.addOnChangeEvent(this); } /** * Initializes a new instance of the WeeklyPattern class. * * @param startDate the start date * @param interval the interval * @param daysOfTheWeek the days of the week * @throws ArgumentOutOfRangeException the argument out of range exception */ public WeeklyPattern(Date startDate, int interval, DayOfTheWeek... daysOfTheWeek) throws ArgumentOutOfRangeException { super(startDate, interval); ArrayList<DayOfTheWeek> toProcess = new ArrayList<DayOfTheWeek>( Arrays.asList(daysOfTheWeek)); Iterator<DayOfTheWeek> idaysOfTheWeek = toProcess.iterator(); this.daysOfTheWeek.addRange(idaysOfTheWeek); } /** * Change event handler. * * @param complexProperty the complex property */ private void daysOfTheWeekChanged(ComplexProperty complexProperty) { this.changed(); } /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.WeeklyRecurrence; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); this.getDaysOfTheWeek().writeToXml(writer, XmlElementNames.DaysOfWeek); if (this.firstDayOfWeek != null) { EwsUtilities .validatePropertyVersion((ExchangeService) writer.getService(), ExchangeVersion.Exchange2010_SP1, "FirstDayOfWeek"); writer.writeElementValue( XmlNamespace.Types, XmlElementNames.FirstDayOfWeek, this.firstDayOfWeek); } } /** * Tries to read element from XML. * * @param reader the reader * @return True if appropriate element was read. * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.DaysOfWeek)) { this.getDaysOfTheWeek().loadFromXml(reader, reader.getLocalName()); return true; } else if (reader.getLocalName().equals(XmlElementNames.FirstDayOfWeek)) { this.firstDayOfWeek = reader. readElementValue(Calendar.class, XmlNamespace.Types, XmlElementNames.FirstDayOfWeek); return true; } else { return false; } } } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.getDaysOfTheWeek().getCount() == 0) { throw new ServiceValidationException( "The recurrence pattern's property DaysOfTheWeek must contain at least one day of the week."); } } /** * Gets the list of the days of the week when occurrences happen. * * @return the days of the week */ public DayOfTheWeekCollection getDaysOfTheWeek() { return this.daysOfTheWeek; } public Calendar getFirstDayOfWeek() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Calendar.class, this.firstDayOfWeek, "FirstDayOfWeek"); } public void setFirstDayOfWeek(Calendar value) { if (this.canSetFieldValue(this.firstDayOfWeek, value)) { this.firstDayOfWeek = value; this.changed(); } } /* * (non-Javadoc) * * @see * microsoft.exchange.webservices. * ComplexPropertyChangedDelegateInterface# * complexPropertyChanged(microsoft.exchange.webservices.ComplexProperty * ) */ @Override public void complexPropertyChanged(ComplexProperty complexProperty) { this.daysOfTheWeekChanged(complexProperty); } } /** * Represents a regeneration pattern, as used with recurring tasks, where * each occurrence happens a specified number of weeks after the previous * one is completed. */ public final static class WeeklyRegenerationPattern extends IntervalPattern { /** * Initializes a new instance of the WeeklyRegenerationPattern class. */ public WeeklyRegenerationPattern() { super(); } /** * Initializes a new instance of the WeeklyRegenerationPattern class. * * @param startDate the start date * @param interval the interval * @throws ArgumentOutOfRangeException the argument out of range exception */ public WeeklyRegenerationPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate, interval); } /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.WeeklyRegeneration; } /** * Gets a value indicating whether this instance is regeneration * pattern. <value> <c>true</c> if this instance is regeneration * pattern; otherwise, <c>false</c>. </value> * * @return true, if is regeneration pattern */ public boolean isRegenerationPattern() { return true; } } /** * Represents a recurrence pattern where each occurrence happens on a * specific day every year. */ public final static class YearlyPattern extends Recurrence { /** * The month. */ private Month month; /** * The day of month. */ private Integer dayOfMonth; /** * Initializes a new instance of the YearlyPattern class. */ public YearlyPattern() { super(); } /** * Initializes a new instance of the YearlyPattern class. * * @param startDate the start date * @param month the month * @param dayOfMonth the day of month */ public YearlyPattern(Date startDate, Month month, int dayOfMonth) { super(startDate); this.month = month; this.dayOfMonth = dayOfMonth; } /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.AbsoluteYearlyRecurrence; } /** * Write property to XML. * * @param writer the writer * @throws Exception the exception */ @Override public void internalWritePropertiesToXml(EwsServiceXmlWriter writer) throws Exception { super.internalWritePropertiesToXml(writer); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.DayOfMonth, this.getDayOfMonth()); writer.writeElementValue(XmlNamespace.Types, XmlElementNames.Month, this.getMonth()); } /** * Tries to read element from XML. * * @param reader the reader * @return True if element was read * @throws Exception the exception */ @Override public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception { if (super.tryReadElementFromXml(reader)) { return true; } else { if (reader.getLocalName().equals(XmlElementNames.DayOfMonth)) { this.dayOfMonth = reader.readElementValue(Integer.class); return true; } else if (reader.getLocalName().equals(XmlElementNames.Month)) { this.month = reader.readElementValue(Month.class); return true; } else { return false; } } } /** * Validates this instance. * * @throws Exception */ @Override public void internalValidate() throws Exception { super.internalValidate(); if (this.month == null) { throw new ServiceValidationException("The recurrence pattern's Month property must be specified."); } if (this.dayOfMonth == null) { throw new ServiceValidationException( "The recurrence pattern's DayOfMonth property must be specified."); } } /** * Gets the month of the year when each occurrence happens. * * @return the month * @throws ServiceValidationException the service validation exception */ public Month getMonth() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Month.class, this.month, "Month"); } /** * Sets the month. * * @param value the new month */ public void setMonth(Month value) { if (this.canSetFieldValue(this.month, value)) { this.month = value; this.changed(); } } /** * Gets the day of the month when each occurrence happens. DayOfMonth * must be between 1 and 31. * * @return the day of month * @throws ServiceValidationException the service validation exception */ public int getDayOfMonth() throws ServiceValidationException { return this.getFieldValueOrThrowIfNull(Integer.class, this.dayOfMonth, "DayOfMonth"); } /** * Sets the day of the month when each occurrence happens. DayOfMonth * must be between 1 and 31. * * @param value the new day of month * @throws ArgumentOutOfRangeException the argument out of range exception */ public void setDayOfMonth(int value) throws ArgumentOutOfRangeException { if (value < 1 || value > 31) { throw new ArgumentOutOfRangeException("DayOfMonth", "DayOfMonth must be between 1 and 31."); } if (this.canSetFieldValue(this.dayOfMonth, value)) { this.dayOfMonth = value; this.changed(); } } } /** * Represents a regeneration pattern, as used with recurring tasks, where * each occurrence happens a specified number of years after the previous * one is completed. */ public final static class YearlyRegenerationPattern extends IntervalPattern { /** * Gets the name of the XML element. <value>The name of the XML * element.</value> * * @return the xml element name */ @Override public String getXmlElementName() { return XmlElementNames.YearlyRegeneration; } /** * Gets a value indicating whether this instance is regeneration * pattern. * * @return true, if is regeneration pattern */ public boolean isRegenerationPattern() { return true; } /** * Initializes a new instance of the YearlyRegenerationPattern class. */ public YearlyRegenerationPattern() { super(); } /** * Initializes a new instance of the YearlyRegenerationPattern class. * * @param startDate the start date * @param interval the interval * @throws ArgumentOutOfRangeException the argument out of range exception */ public YearlyRegenerationPattern(Date startDate, int interval) throws ArgumentOutOfRangeException { super(startDate, interval); } } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.cluster; import org.elasticsearch.Version; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.routing.RecoverySource; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodesHelper; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.cluster.routing.allocation.FailedShard; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator; import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocator; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDecider; import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders; import org.elasticsearch.cluster.routing.allocation.decider.Decision; import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationDecider; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.gateway.GatewayAllocator; import org.elasticsearch.snapshots.SnapshotShardSizeInfo; import org.elasticsearch.snapshots.SnapshotsInfoService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.gateway.TestGatewayAllocator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import static java.util.Collections.emptyMap; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; public abstract class ESAllocationTestCase extends ESTestCase { private static final ClusterSettings EMPTY_CLUSTER_SETTINGS = new ClusterSettings( Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS ); public static final SnapshotsInfoService SNAPSHOT_INFO_SERVICE_WITH_NO_SHARD_SIZES = () -> new SnapshotShardSizeInfo( ImmutableOpenMap.of() ) { @Override public Long getShardSize(ShardRouting shardRouting) { assert shardRouting.recoverySource().getType() == RecoverySource.Type.SNAPSHOT : "Expecting a recovery source of type [SNAPSHOT] but got [" + shardRouting.recoverySource().getType() + ']'; throw new UnsupportedOperationException(); } }; public static MockAllocationService createAllocationService() { return createAllocationService(Settings.EMPTY); } public static MockAllocationService createAllocationService(Settings settings) { return createAllocationService(settings, random()); } public static MockAllocationService createAllocationService(Settings settings, Random random) { return createAllocationService(settings, EMPTY_CLUSTER_SETTINGS, random); } public static MockAllocationService createAllocationService(Settings settings, ClusterSettings clusterSettings, Random random) { return new MockAllocationService( randomAllocationDeciders(settings, clusterSettings, random), new TestGatewayAllocator(), new BalancedShardsAllocator(settings), EmptyClusterInfoService.INSTANCE, SNAPSHOT_INFO_SERVICE_WITH_NO_SHARD_SIZES ); } public static MockAllocationService createAllocationService(Settings settings, ClusterInfoService clusterInfoService) { return new MockAllocationService( randomAllocationDeciders(settings, EMPTY_CLUSTER_SETTINGS, random()), new TestGatewayAllocator(), new BalancedShardsAllocator(settings), clusterInfoService, SNAPSHOT_INFO_SERVICE_WITH_NO_SHARD_SIZES ); } public static MockAllocationService createAllocationService(Settings settings, GatewayAllocator gatewayAllocator) { return createAllocationService(settings, gatewayAllocator, SNAPSHOT_INFO_SERVICE_WITH_NO_SHARD_SIZES); } public static MockAllocationService createAllocationService(Settings settings, SnapshotsInfoService snapshotsInfoService) { return createAllocationService(settings, new TestGatewayAllocator(), snapshotsInfoService); } public static MockAllocationService createAllocationService( Settings settings, GatewayAllocator gatewayAllocator, SnapshotsInfoService snapshotsInfoService ) { return new MockAllocationService( randomAllocationDeciders(settings, EMPTY_CLUSTER_SETTINGS, random()), gatewayAllocator, new BalancedShardsAllocator(settings), EmptyClusterInfoService.INSTANCE, snapshotsInfoService ); } public static AllocationDeciders randomAllocationDeciders(Settings settings, ClusterSettings clusterSettings, Random random) { List<AllocationDecider> deciders = new ArrayList<>( ClusterModule.createAllocationDeciders(settings, clusterSettings, Collections.emptyList()) ); Collections.shuffle(deciders, random); return new AllocationDeciders(deciders); } protected static Set<DiscoveryNodeRole> MASTER_DATA_ROLES = Collections.unmodifiableSet( Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE) ); protected static DiscoveryNode newNode(String nodeId) { return newNode(nodeId, Version.CURRENT); } protected static DiscoveryNode newNode(String nodeName, String nodeId, Map<String, String> attributes) { return new DiscoveryNode(nodeName, nodeId, buildNewFakeTransportAddress(), attributes, MASTER_DATA_ROLES, Version.CURRENT); } protected static DiscoveryNode newNode(String nodeId, Map<String, String> attributes) { return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), attributes, MASTER_DATA_ROLES, Version.CURRENT); } protected static DiscoveryNode newNode(String nodeId, Set<DiscoveryNodeRole> roles) { return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT); } protected static DiscoveryNode newNode(String nodeName, String nodeId, Set<DiscoveryNodeRole> roles) { return new DiscoveryNode(nodeName, nodeId, buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT); } protected static DiscoveryNode newNode(String nodeId, Version version) { return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, version); } protected static ClusterState startRandomInitializingShard(ClusterState clusterState, AllocationService strategy) { List<ShardRouting> initializingShards = RoutingNodesHelper.shardsWithState(clusterState.getRoutingNodes(), INITIALIZING); if (initializingShards.isEmpty()) { return clusterState; } return startShardsAndReroute(strategy, clusterState, randomFrom(initializingShards)); } protected static AllocationDeciders yesAllocationDeciders() { return new AllocationDeciders( Arrays.asList( new TestAllocateDecision(Decision.YES), new SameShardAllocationDecider( Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS) ) ) ); } protected static AllocationDeciders noAllocationDeciders() { return new AllocationDeciders(Collections.singleton(new TestAllocateDecision(Decision.NO))); } protected static AllocationDeciders throttleAllocationDeciders() { return new AllocationDeciders( Arrays.asList( new TestAllocateDecision(Decision.THROTTLE), new SameShardAllocationDecider( Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS) ) ) ); } protected ClusterState applyStartedShardsUntilNoChange(ClusterState clusterState, AllocationService service) { ClusterState lastClusterState; do { lastClusterState = clusterState; logger.debug("ClusterState: {}", clusterState.getRoutingNodes()); clusterState = startInitializingShardsAndReroute(service, clusterState); } while (lastClusterState.equals(clusterState) == false); return clusterState; } /** * Mark all initializing shards as started, then perform a reroute (which may start some other shards initializing). * * @return the cluster state after completing the reroute. */ public static ClusterState startInitializingShardsAndReroute(AllocationService allocationService, ClusterState state) { return startShardsAndReroute(allocationService, state, RoutingNodesHelper.shardsWithState(state.getRoutingNodes(), INITIALIZING)); } /** * Mark all initializing shards on the given node as started, then perform a reroute (which may start some other shards initializing). * * @return the cluster state after completing the reroute. */ public static ClusterState startInitializingShardsAndReroute( AllocationService allocationService, ClusterState clusterState, RoutingNode routingNode ) { return startShardsAndReroute(allocationService, clusterState, routingNode.shardsWithState(INITIALIZING)); } /** * Mark all initializing shards for the given index as started, then perform a reroute (which may start some other shards initializing). * * @return the cluster state after completing the reroute. */ public static ClusterState startInitializingShardsAndReroute( AllocationService allocationService, ClusterState clusterState, String index ) { return startShardsAndReroute( allocationService, clusterState, clusterState.routingTable().index(index).shardsWithState(INITIALIZING) ); } /** * Mark the given shards as started, then perform a reroute (which may start some other shards initializing). * * @return the cluster state after completing the reroute. */ public static ClusterState startShardsAndReroute( AllocationService allocationService, ClusterState clusterState, ShardRouting... initializingShards ) { return startShardsAndReroute(allocationService, clusterState, Arrays.asList(initializingShards)); } /** * Mark the given shards as started, then perform a reroute (which may start some other shards initializing). * * @return the cluster state after completing the reroute. */ public static ClusterState startShardsAndReroute( AllocationService allocationService, ClusterState clusterState, List<ShardRouting> initializingShards ) { return allocationService.reroute(allocationService.applyStartedShards(clusterState, initializingShards), "reroute after starting"); } public static class TestAllocateDecision extends AllocationDecider { private final Decision decision; public TestAllocateDecision(Decision decision) { this.decision = decision; } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return decision; } @Override public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) { return decision; } } /** A lock {@link AllocationService} allowing tests to override time */ protected static class MockAllocationService extends AllocationService { private volatile long nanoTimeOverride = -1L; public MockAllocationService( AllocationDeciders allocationDeciders, GatewayAllocator gatewayAllocator, ShardsAllocator shardsAllocator, ClusterInfoService clusterInfoService, SnapshotsInfoService snapshotsInfoService ) { super(allocationDeciders, gatewayAllocator, shardsAllocator, clusterInfoService, snapshotsInfoService); } public void setNanoTimeOverride(long nanoTime) { this.nanoTimeOverride = nanoTime; } @Override protected long currentNanoTime() { return nanoTimeOverride == -1L ? super.currentNanoTime() : nanoTimeOverride; } } /** * Mocks behavior in ReplicaShardAllocator to remove delayed shards from list of unassigned shards so they don't get reassigned yet. */ protected static class DelayedShardsMockGatewayAllocator extends GatewayAllocator { public DelayedShardsMockGatewayAllocator() {} @Override public void applyStartedShards(List<ShardRouting> startedShards, RoutingAllocation allocation) { // no-op } @Override public void applyFailedShards(List<FailedShard> failedShards, RoutingAllocation allocation) { // no-op } @Override public void beforeAllocation(RoutingAllocation allocation) { // no-op } @Override public void afterPrimariesBeforeReplicas(RoutingAllocation allocation) { // no-op } @Override public void allocateUnassigned( ShardRouting shardRouting, RoutingAllocation allocation, UnassignedAllocationHandler unassignedAllocationHandler ) { if (shardRouting.primary() || shardRouting.unassignedInfo().getReason() == UnassignedInfo.Reason.INDEX_CREATED) { return; } if (shardRouting.unassignedInfo().isDelayed()) { unassignedAllocationHandler.removeAndIgnore(UnassignedInfo.AllocationStatus.DELAYED_ALLOCATION, allocation.changes()); } } } }
package org.apereo.cas.configuration.model.core.authentication; import org.apereo.cas.configuration.model.support.digest.DigestProperties; import org.apereo.cas.configuration.model.support.generic.AcceptAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.FileAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.RejectAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.RemoteAddressAuthenticationProperties; import org.apereo.cas.configuration.model.support.generic.ShiroAuthenticationProperties; import org.apereo.cas.configuration.model.support.jaas.JaasAuthenticationProperties; import org.apereo.cas.configuration.model.support.jdbc.JdbcAuthenticationProperties; import org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties; import org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties; import org.apereo.cas.configuration.model.support.mongo.MongoAuthenticationProperties; import org.apereo.cas.configuration.model.support.ntlm.NtlmProperties; import org.apereo.cas.configuration.model.support.oauth.OAuthProperties; import org.apereo.cas.configuration.model.support.oidc.OidcProperties; import org.apereo.cas.configuration.model.support.openid.OpenIdProperties; import org.apereo.cas.configuration.model.support.pac4j.Pac4jProperties; import org.apereo.cas.configuration.model.support.pm.PasswordManagementProperties; import org.apereo.cas.configuration.model.support.radius.RadiusProperties; import org.apereo.cas.configuration.model.support.rest.RestAuthenticationProperties; import org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties; import org.apereo.cas.configuration.model.support.spnego.SpnegoProperties; import org.apereo.cas.configuration.model.support.stormpath.StormpathProperties; import org.apereo.cas.configuration.model.support.throttle.ThrottleProperties; import org.apereo.cas.configuration.model.support.token.TokenAuthenticationProperties; import org.apereo.cas.configuration.model.support.trusted.TrustedAuthenticationProperties; import org.apereo.cas.configuration.model.support.wsfed.WsFederationProperties; import org.apereo.cas.configuration.model.support.x509.X509Properties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import java.util.ArrayList; import java.util.List; /** * This is {@link AuthenticationProperties}. * * @author Misagh Moayyed * @since 5.0.0 */ public class AuthenticationProperties { @NestedConfigurationProperty private PasswordManagementProperties pm = new PasswordManagementProperties(); @NestedConfigurationProperty private AdaptiveAuthenticationProperties adaptive = new AdaptiveAuthenticationProperties(); @NestedConfigurationProperty private PrincipalAttributesProperties attributeRepository = new PrincipalAttributesProperties(); @NestedConfigurationProperty private DigestProperties digest = new DigestProperties(); @NestedConfigurationProperty private RestAuthenticationProperties rest = new RestAuthenticationProperties(); @NestedConfigurationProperty private List<LdapAuthenticationProperties> ldap = new ArrayList<>(); @NestedConfigurationProperty private ThrottleProperties throttle = new ThrottleProperties(); @NestedConfigurationProperty private SamlIdPProperties samlIdp = new SamlIdPProperties(); @NestedConfigurationProperty private AuthenticationExceptionsProperties exceptions = new AuthenticationExceptionsProperties(); @NestedConfigurationProperty private AuthenticationPolicyProperties policy = new AuthenticationPolicyProperties(); @NestedConfigurationProperty private AcceptAuthenticationProperties accept = new AcceptAuthenticationProperties(); @NestedConfigurationProperty private FileAuthenticationProperties file = new FileAuthenticationProperties(); @NestedConfigurationProperty private RejectAuthenticationProperties reject = new RejectAuthenticationProperties(); @NestedConfigurationProperty private RemoteAddressAuthenticationProperties remoteAddress = new RemoteAddressAuthenticationProperties(); @NestedConfigurationProperty private ShiroAuthenticationProperties shiro = new ShiroAuthenticationProperties(); @NestedConfigurationProperty private TrustedAuthenticationProperties trusted = new TrustedAuthenticationProperties(); @NestedConfigurationProperty private JaasAuthenticationProperties jaas = new JaasAuthenticationProperties(); @NestedConfigurationProperty private JdbcAuthenticationProperties jdbc = new JdbcAuthenticationProperties(); @NestedConfigurationProperty private MultifactorAuthenticationProperties mfa = new MultifactorAuthenticationProperties(); @NestedConfigurationProperty private MongoAuthenticationProperties mongo = new MongoAuthenticationProperties(); @NestedConfigurationProperty private NtlmProperties ntlm = new NtlmProperties(); @NestedConfigurationProperty private OAuthProperties oauth = new OAuthProperties(); @NestedConfigurationProperty private OidcProperties oidc = new OidcProperties(); @NestedConfigurationProperty private OpenIdProperties openid = new OpenIdProperties(); @NestedConfigurationProperty private Pac4jProperties pac4j = new Pac4jProperties(); @NestedConfigurationProperty private RadiusProperties radius = new RadiusProperties(); @NestedConfigurationProperty private SpnegoProperties spnego = new SpnegoProperties(); @NestedConfigurationProperty private StormpathProperties stormpath = new StormpathProperties(); @NestedConfigurationProperty private WsFederationProperties wsfed = new WsFederationProperties(); @NestedConfigurationProperty private X509Properties x509 = new X509Properties(); @NestedConfigurationProperty private TokenAuthenticationProperties token = new TokenAuthenticationProperties(); public TokenAuthenticationProperties getToken() { return token; } public void setToken(final TokenAuthenticationProperties token) { this.token = token; } public AuthenticationExceptionsProperties getExceptions() { return exceptions; } public void setExceptions(final AuthenticationExceptionsProperties exceptions) { this.exceptions = exceptions; } public AuthenticationPolicyProperties getPolicy() { return policy; } public AcceptAuthenticationProperties getAccept() { return accept; } public void setAccept(final AcceptAuthenticationProperties accept) { this.accept = accept; } public FileAuthenticationProperties getFile() { return file; } public void setFile(final FileAuthenticationProperties file) { this.file = file; } public RejectAuthenticationProperties getReject() { return reject; } public void setReject(final RejectAuthenticationProperties reject) { this.reject = reject; } public RemoteAddressAuthenticationProperties getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(final RemoteAddressAuthenticationProperties remoteAddress) { this.remoteAddress = remoteAddress; } public ShiroAuthenticationProperties getShiro() { return shiro; } public void setShiro(final ShiroAuthenticationProperties shiro) { this.shiro = shiro; } public JaasAuthenticationProperties getJaas() { return jaas; } public void setJaas(final JaasAuthenticationProperties jaas) { this.jaas = jaas; } public JdbcAuthenticationProperties getJdbc() { return jdbc; } public void setJdbc(final JdbcAuthenticationProperties jdbc) { this.jdbc = jdbc; } public MultifactorAuthenticationProperties getMfa() { return mfa; } public void setMfa(final MultifactorAuthenticationProperties mfa) { this.mfa = mfa; } public MongoAuthenticationProperties getMongo() { return mongo; } public void setMongo(final MongoAuthenticationProperties mongo) { this.mongo = mongo; } public NtlmProperties getNtlm() { return ntlm; } public void setNtlm(final NtlmProperties ntlm) { this.ntlm = ntlm; } public OAuthProperties getOauth() { return oauth; } public void setOauth(final OAuthProperties oauth) { this.oauth = oauth; } public OidcProperties getOidc() { return oidc; } public void setOidc(final OidcProperties oidc) { this.oidc = oidc; } public OpenIdProperties getOpenid() { return openid; } public void setOpenid(final OpenIdProperties openid) { this.openid = openid; } public Pac4jProperties getPac4j() { return pac4j; } public void setPac4j(final Pac4jProperties pac4j) { this.pac4j = pac4j; } public RadiusProperties getRadius() { return radius; } public void setRadius(final RadiusProperties radius) { this.radius = radius; } public SpnegoProperties getSpnego() { return spnego; } public void setSpnego(final SpnegoProperties spnego) { this.spnego = spnego; } public StormpathProperties getStormpath() { return stormpath; } public void setStormpath(final StormpathProperties stormpath) { this.stormpath = stormpath; } public WsFederationProperties getWsfed() { return wsfed; } public void setWsfed(final WsFederationProperties wsfed) { this.wsfed = wsfed; } public X509Properties getX509() { return x509; } public void setX509(final X509Properties x509) { this.x509 = x509; } public SamlIdPProperties getSamlIdp() { return samlIdp; } public void setSamlIdp(final SamlIdPProperties samlIdp) { this.samlIdp = samlIdp; } public ThrottleProperties getThrottle() { return throttle; } public void setThrottle(final ThrottleProperties throttle) { this.throttle = throttle; } public TrustedAuthenticationProperties getTrusted() { return trusted; } public void setTrusted(final TrustedAuthenticationProperties trusted) { this.trusted = trusted; } public List<LdapAuthenticationProperties> getLdap() { return ldap; } public void setLdap(final List<LdapAuthenticationProperties> ldap) { this.ldap = ldap; } public RestAuthenticationProperties getRest() { return rest; } public void setRest(final RestAuthenticationProperties rest) { this.rest = rest; } public DigestProperties getDigest() { return digest; } public void setDigest(final DigestProperties digest) { this.digest = digest; } public PrincipalAttributesProperties getAttributeRepository() { return attributeRepository; } public void setAttributeRepository(final PrincipalAttributesProperties attributeRepository) { this.attributeRepository = attributeRepository; } public AdaptiveAuthenticationProperties getAdaptive() { return adaptive; } public void setAdaptive(final AdaptiveAuthenticationProperties adaptive) { this.adaptive = adaptive; } public void setPolicy(final AuthenticationPolicyProperties policy) { this.policy = policy; } public PasswordManagementProperties getPm() { return pm; } public void setPm(final PasswordManagementProperties pm) { this.pm = pm; } }
/* Copyright 2016 Samsung Electronics Co., LTD * * 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.gearvrf; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.WeakHashMap; import org.gearvrf.script.IScriptManager; import org.gearvrf.script.IScriptFile; import org.gearvrf.script.IScriptable; /** * This class provides API for event-related operations in the * framework. In the framework, events are categorized into * groups, each of which is represented by an interface extending * the tag interface {@link IEvents}. For example, * the event group {@link IScriptEvents} contain life-cycle events * {@link IScriptEvents#onInit(GVRContext)}, and per-frame callbacks * {@link IScriptEvents#onStep()}.<p> * * Other event groups can be defined in similar ways. As seen above, * we don't necessarily use classes to represent events themselves, * but we may create event classes (such as {@code MouseEvent}) to * represent details of an event, and pass it to an event handler.<p> * * An event handler can take one of the two forms. 1) It can be a * class implementing an event interface in Java. 2) It can be a * script in a scripting language, such as Lua and Javascript. In * the scripting case, the prototype of the function mirrors their * Java counterpart. For example, a handler function in Lua for * {@link IScriptEvents#onInit(GVRContext)} is<p> * * <pre> * {@code * function onInit(gvrf) * ... * end * } * </pre> */ public class GVREventManager { private static final String TAG = GVREventManager.class.getSimpleName(); private GVRContext mGvrContext; // Cache for Java handler methods; keys *must* be weakly referenced private final WeakHashMap<Object, Map<String, Method>> mHandlerMethodCache; public static final int SEND_MASK_OBJECT = 0x1; protected static final int SEND_MASK_LISTENERS = 0x2; protected static final int SEND_MASK_SCRIPTS = 0x4; public static final int SEND_MASK_ALL = SEND_MASK_OBJECT | SEND_MASK_LISTENERS | SEND_MASK_SCRIPTS; GVREventManager(GVRContext gvrContext) { mGvrContext = gvrContext; mHandlerMethodCache = new WeakHashMap<Object, Map<String, Method>>(); } /** * Delivers an event to a handler object. An event is sent in the following * way: <p> * * <ol> * <li> If the {@code target} defines the interface of the class object * {@code eventsClass}, the event is delivered to it first, by invoking * the corresponding method in the {@code target}. </li> * <li> If the {@code target} implements interface {@link IEventReceiver}, the * event is delivered to listeners added to the {@link GVREventReceiver} object. * See {@link GVREventReceiver} for more information. * </li> * <li> If the target is bound with scripts, the event is delivered to the scripts. * A script can be attached to the target using {@link org.gearvrf.script.GVRScriptManager#attachScriptFile(IScriptable, GVRScriptFile)}.</li> * </ol> * * @param target * The object which handles the event. * @param eventsClass * The interface class object representing an event group, such * as {@link IScriptEvents}.class. * @param eventName * The name of the event, such as "onInit". * @param params * Parameters of the event. It should match the parameter list * of the corresponding method in the interface, specified by {@code * event class} * @return * {@code true} if the event is handled successfully, {@code false} if not handled * or any error occurred. */ public boolean sendEvent(Object target, Class<? extends IEvents> eventsClass, String eventName, Object... params) { return sendEventWithMask(SEND_MASK_ALL, target, eventsClass, eventName, params); } public boolean sendEventWithMask(int sendMask, Object target, Class<? extends IEvents> eventsClass, String eventName, Object... params) { return sendEventWithMaskParamArray(sendMask, target, eventsClass, eventName, params); } protected boolean sendEventWithMaskParamArray(int sendMask, Object target, Class<? extends IEvents> eventsClass, String eventName, Object[] params) { // Set to true if an event is handled. boolean handledSuccessful = false; // Verify the event name and parameters (cached) Method method = findHandlerMethod(target, eventsClass, eventName, params); if ((sendMask & SEND_MASK_OBJECT) != 0) { // Invoke the method if the target implements the interface if (eventsClass.isInstance(target)) { invokeMethod(target, method, params); handledSuccessful = true; } } if ((sendMask & SEND_MASK_LISTENERS) != 0) { // Try to deliver to the event receiver (if any) if (target instanceof IEventReceiver) { IEventReceiver receivingTarget = (IEventReceiver) target; GVREventReceiver receiver = receivingTarget.getEventReceiver(); List<IEvents> listeners = receiver.getListeners(); for (IEvents listener : listeners) { // Skip the listener due to different type, or has been removed if (!eventsClass.isInstance(listener) || receiver.getOwner() != target) continue; Method listenerMethod = findHandlerMethod(listener, eventsClass, eventName, params); if (listenerMethod != null) { // This may throw RuntimeException if the handler does so. invokeMethod(listener, listenerMethod, params); handledSuccessful = true; } } } } if ((sendMask & SEND_MASK_SCRIPTS) != 0) { // Try invoking the handler in the script if (target instanceof IScriptable) { handledSuccessful |= tryInvokeScript((IScriptable)target, eventName, params); } } return handledSuccessful; } /* * Return the method in eventsClass by checking the signature. * RuntimeException is thrown if the event is not found in the eventsClass interface, * or the parameter types don't match. */ private Method findHandlerMethod(Object target, Class<? extends IEvents> eventsClass, String eventName, Object[] params) { // Use cached method if available. Note: no further type checking is done if the // method has been cached. It will be checked by JRE when the method is invoked. Method cachedMethod = getCachedMethod(target, eventName); if (cachedMethod != null) { return cachedMethod; } // Check the event and params against the eventsClass interface object. Method nameMatch = null; Method signatureMatch = null; for (Method method : eventsClass.getMethods()) { // Match method name and event name if (method.getName().equals(eventName)) { nameMatch = method; // Check number of parameters Class<?>[] types = method.getParameterTypes(); if (types.length != params.length) continue; // Check parameter types int i = 0; boolean foundMatchedMethod = true; for (Class<?> type : types) { Object param = params[i++]; if (!isInstanceWithAutoboxing(type, param)) { foundMatchedMethod = false; break; } } if (foundMatchedMethod) { signatureMatch = method; break; } } } // Error if (nameMatch == null) { throw new RuntimeException(String.format("The interface contains no method %s", eventName)); } else if (signatureMatch == null ){ throw new RuntimeException(String.format("The interface contains a method %s but " + "parameters don't match", eventName)); } // Cache the method for the target, even if it doesn't implement the interface. This is // to avoid always verifying the event. addCachedMethod(target, eventName, signatureMatch); return signatureMatch; } private boolean isInstanceWithAutoboxing(Class<?> type, Object value) { if (type.isInstance(value)) { return true; } // Allow null value for subtypes of Object but not int, float, etc. if (value == null) { return Object.class.isAssignableFrom(type); } // Return false if auto-boxing is not possible if (!(value instanceof Number || value instanceof Boolean)) { return false; } // Check auto-boxing of numeric and boolean values if (type.equals(boolean.class) && Boolean.class.isInstance(value)) { return true; } if (type.equals(int.class) && Integer.class.isInstance(value)) { return true; } if (type.equals(long.class) && Long.class.isInstance(value)) { return true; } if (type.equals(short.class) && Short.class.isInstance(value)) { return true; } if (type.equals(byte.class) && Byte.class.isInstance(value)) { return true; } if (type.equals(float.class) && Float.class.isInstance(value)) { return true; } if (type.equals(double.class) && Double.class.isInstance(value)) { return true; } return false; } private Method getCachedMethod(Object target, String eventName) { // Lock the whole cache for both first- and second-level lookup synchronized (mHandlerMethodCache) { Map<String, Method> targetCache = mHandlerMethodCache.get(target); if (targetCache == null) { return null; } return targetCache.get(eventName); } } private void addCachedMethod(Object target, String eventName, Method method) { // Lock the whole cache for both first- and second-level lookup synchronized (mHandlerMethodCache) { Map<String, Method> targetCache = mHandlerMethodCache.get(target); if (targetCache == null) { targetCache = new TreeMap<String, Method>(); mHandlerMethodCache.put(target, targetCache); } targetCache.put(eventName, method); } } private boolean tryInvokeScript(IScriptable target, String eventName, Object[] params) { IScriptManager sm = mGvrContext.getScriptManager(); if (sm == null) { return false; } IScriptFile script = sm.getScriptFile(target); if (script == null) return false; return script.invokeFunction(eventName, params); } private void invokeMethod(Object target, Method method, Object[] params) { try { method.invoke(target, params); } catch (IllegalAccessException e) { e.printStackTrace(); mGvrContext.logError(e.getMessage(), target); } catch (IllegalArgumentException e) { e.printStackTrace(); mGvrContext.logError(e.getMessage(), target); } catch (InvocationTargetException e) { Throwable throwable = e.getCause(); // rethrow the RuntimeException back to the application if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } else { e.printStackTrace(); mGvrContext.logError(e.getMessage(), target); } } } }
package imageshare.servlets; import imageshare.model.Image; import imageshare.oraclehandler.OracleHandler; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.SingleThreadModel; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This class displays the results of the indexed search by querying the * database which is including keyword and/or date search. */ public class SearchServlet extends HttpServlet implements SingleThreadModel { private static final long serialVersionUID = 1L; private static final String SEARCH_JSP = "/webapp/jsp/search.jsp"; String user = ""; private OracleHandler database; private String keywords; private String fromDate; private String toDate; private String fromdatesql; private String todatesql; private List<Image> results = new ArrayList<Image>(); private String sortby; private String thumbs; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); user = (String) request.getSession(true).getAttribute("user"); /* if no user logged in, redirect to login page */ if (user == null) { response.sendRedirect("index"); return; }; thumbs = ""; request.getSession(true).setAttribute("galHTML", thumbs); RequestDispatcher requestDispatcher = request.getRequestDispatcher(SEARCH_JSP); requestDispatcher.forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] keywordsList; user = (String) request.getSession(true).getAttribute("user"); /* if no user logged in, redirect to login page */ if (user == null) { response.sendRedirect("index"); return; }; String orderStr = ""; thumbs = ""; database = OracleHandler.getInstance(); keywords = request.getParameter("query"); fromDate = request.getParameter("fromdate"); toDate = request.getParameter("todate"); sortby = request.getParameter("sortby"); /* * Changing format from yyyy-MM-dd to dd-MMM-yy for sql */ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yy"); try { Date date = sdf.parse(fromDate); Date date1 = sdf.parse(toDate); fromdatesql = sdf1.format(date); todatesql = sdf1.format(date1); } catch (Exception e) { e.getMessage(); } /* * Get how query will be sorted */ String order = null; // time descending if (sortby.equals("1")) { orderStr = "Most Recent Time First"; order = "order by timing DESC"; } // time ascending else if (sortby.equals("2")) { orderStr = "Most Recent Time Last"; order = "order by timing"; } // rank else { orderStr = "Rank"; order = "order by score DESC"; } /* * The user has to input from and to dates otherwise * only keyword search to get resultset of query */ if (!(keywords.equals(""))) { keywordsList = keywords.split("\\s+"); if((fromDate.equals("")) || (toDate.equals(""))) { try { results = database.getImagesByKeywords(user, keywordsList, order); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } thumbs = thumbs + "<h3>Your results for: <strong class='text-primary'>" + keywords + "</strong>" + " ordered by <strong class='text-success'>" + orderStr + "</strong></h3>"; writeThumbnails(request, response); } else { try { results = database.getImagesByDateAndKeywords(user, fromdatesql, todatesql, keywordsList, order); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } thumbs = thumbs + "<h3>Your results for <strong class='text-primary'>" + keywords + "</strong>" + " between <strong class='text-warning'>" + fromDate + "</strong> and <strong class='text-warning'>" + toDate + "</strong>" + " ordered by <strong class='text-success'> " + orderStr + "</strong></h3>"; writeThumbnails(request, response); } } else if (!((fromDate.equals("")) || (toDate.equals("")))) { if (!(order.equals("order by 1 DESC"))) { try { results = database.getImagesByDate(user, fromdatesql, todatesql, order); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } thumbs = thumbs + "<h3>Your results for images between <strong class='text-warning'>" + fromDate + "</strong> and <strong class='text-warning'>" + toDate + "</strong>" + " ordered by <strong class='text-success'>" + orderStr + "</strong></h3>"; writeThumbnails(request, response); } else { thumbs = thumbs + "<h3><p class='text-danger'>Cannot sort by rank with just time, please" + " sort differently or add keywords </p></h3>"; } } else { thumbs = thumbs + "<h3><p class='text-danger'>Please enter a valid search query</p></h3>"; } request.getSession(true).setAttribute("galHTML", thumbs); RequestDispatcher requestDispatcher = request.getRequestDispatcher(SEARCH_JSP); requestDispatcher.forward(request, response); } private void writeThumbnails(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Generate and append all user visible thumbnails to the page. thumbs = thumbs + "<hgroup class='mb20'><h3 class='lead'>" + "<strong class='text-danger'>" + Integer.toString(results.size()) + "</strong> images were found: </h3></hgroup><div id='gal' class='list-group gallery'>"; for (int i = 0; i < results.size(); ++i) { String getURL = "thumbnail?" + results.get(i).getPhotoId(); String editURL = "updateimage?" + results.get(i).getPhotoId(); String displayURL = "display?" + results.get(i).getPhotoId(); thumbs = thumbs + "<div class=\'col-sm-3 col-xs-5 col-md-2 col-lg-2\'>"+ "<small class=\'text-muted\'>"+ Integer.toString(i+1) + "<br></small>"; //display ranking is that is the option if(!sortby.equals("1") && !sortby.equals("2")) { thumbs = thumbs + "<small class=\'text-muted\'>"+"Ranking: " + Integer.toString(results.get(i).getScore()) + "<br></small>"; } thumbs = thumbs + "<small class=\'text-muted\'>"+"Date Created: " + results.get(i).getDate().toString() + "<br></small>"; if (results.get(i).getOwnerName().equals(user)) { thumbs = thumbs + "<a href='" + editURL + "'><strong class=\'text-muted\'>Edit</strong></a>"; } thumbs = thumbs + "<div id='" + Integer.toString(results.get(i).getPhotoId()) + "'><a class='thumbnail fancybox' href='" + displayURL + "'><img class='img-responsive' alt='' src='" + getURL + "'/></a></div></div>"; } } }
package SolarPrizm.mcStats; import net.minecraft.src.*; import java.io.Serializable; import java.util.ArrayList; public final class BlockCoord implements Serializable {//TODO make BigInteger or long private int x, y, z; private static ArrayList<BlockCoord> coordinates = new ArrayList<BlockCoord>(); public BlockCoord(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public int getX() { return x; } public int getY() { return y; } public int getZ() { return z; } public int getBlockID(World world) { return world.getBlockId(x, y, z); } public int getBlockMeta(World world) { return world.getBlockMetadata(x, y, z); } public int getBlockID() { return mod_mcStats.mc.theWorld.getBlockId(x, y, z); } public int getBlockMeta() { return mod_mcStats.mc.theWorld.getBlockMetadata(x, y, z); } public BlockCoord(int x, int y, int z, int side) { if(side == 0) y--; else if(side == 1) y++; else if(side == 2) z--; else if(side == 3) z++; else if(side == 4) x--; else if(side == 5) x++; this.x = x; this.y = y; this.z = z; } public static ArrayList<BlockCoord> getCoord() { return coordinates; } public static void setCoord(ArrayList<BlockCoord> array) { coordinates = array; } public static void setCoord(String string) { coordinates = new ArrayList<BlockCoord>(); string = string.substring(1, string.length()-1); while(string != null && string.length() > 2) { if(string.substring(0,1).equals("(")) { String coord = string.substring(0, string.indexOf(")")+1); if(coord != null && !coord.equals("")) BlockCoord.addCoordinatesWithoutNotify(BlockCoord.parseBlockCoord(coord)); string = string.substring(1); string = string.contains("(") ? string.substring(string.indexOf("(")) : ""; } } } /** * Adds Block Coordinates according to the block it was placed on. * @param x The X coordinate of the block right clicked * @param y The Y coordinate * @param z The Z coordinate * @param side The side right clicked */ public static void addCoordinates(int x, int y, int z, int side) { if(side == 0) y--; else if(side == 1) y++; else if(side == 2) z--; else if(side == 3) z++; else if(side == 4) x--; else if(side == 5) x++; addCoordinates(x, y, z); // System.out.println("BlockCoord: "+coordinates); } public static void addCoordinates(int x, int y, int z) { coordinates.add(new BlockCoord(x, y, z)); mod_mcStats.updateProperties(); } public static void addCoordinates(BlockCoord blockcoord) { coordinates.add(blockcoord); mod_mcStats.updateProperties(); } public static void addCoordinatesWithoutNotify(int x, int y, int z) { coordinates.add(new BlockCoord(x, y, z)); } public static void addCoordinatesWithoutNotify(BlockCoord blockcoord) { coordinates.add(blockcoord); } public static BlockCoord getCoordinates(int x, int y, int z) { for(BlockCoord coord : coordinates) { if(coord.x == x && coord.y == y && coord.z == z) return coord; } return null; } public static boolean isPlaced(int x, int y, int z) { for(BlockCoord coord : coordinates) { if(coord.x == x && coord.y == y && coord.z == z) return true; } return false; } public static void removeDuplicates(int x, int y, int z) { for(BlockCoord coord : coordinates) if(coord.x == x && coord.y == y && coord.z == z) coord.removeSelf(); } public static void addCoordinatesIfNotDuplicate(int x, int y, int z) { BlockCoord coord = new BlockCoord(x, y, z); if(!isPlaced(x, y, z)) { coordinates.add(coord); mod_mcStats.updateProperties(); // System.out.println("BlockCoord: "+coordinates); } } public static void addCoordinatesIfNotDuplicate(int x, int y, int z, int side) { if(side == 0) y--; else if(side == 1) y++; else if(side == 2) z--; else if(side == 3) z++; else if(side == 4) x--; else if(side == 5) x++; addCoordinatesIfNotDuplicate(x, y, z); } public void removeSelf() { coordinates.remove(this); mod_mcStats.updateProperties(); } public String toString() { return "("+x+","+y+","+z+")"; } public static BlockCoord parseBlockCoord(String string) { string = string.substring(1,string.length()-1); int x = Integer.parseInt(string.substring(0, string.indexOf(","))); string = string.substring(string.indexOf(",")+1); int y = Integer.parseInt(string.substring(0, string.indexOf(","))); string = string.substring(string.indexOf(",")+1); int z = Integer.parseInt(string); return new BlockCoord(x, y, z); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.repositories.s3; import com.amazonaws.AmazonClientException; import com.amazonaws.services.s3.model.AbortMultipartUploadRequest; import com.amazonaws.services.s3.model.CompleteMultipartUploadRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.InitiateMultipartUploadRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.MultiObjectDeleteException; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PartETag; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.UploadPartRequest; import com.amazonaws.services.s3.model.UploadPartResult; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.lucene.util.SetOnce; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.core.CheckedConsumer; import org.elasticsearch.core.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.blobstore.BlobContainer; import org.elasticsearch.common.blobstore.BlobMetadata; import org.elasticsearch.common.blobstore.BlobPath; import org.elasticsearch.common.blobstore.BlobStoreException; import org.elasticsearch.common.blobstore.DeleteResult; import org.elasticsearch.common.blobstore.support.AbstractBlobContainer; import org.elasticsearch.common.blobstore.support.PlainBlobMetadata; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Iterators; import org.elasticsearch.core.Tuple; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.repositories.blobstore.ChunkedBlobOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import static org.elasticsearch.repositories.s3.S3Repository.MAX_FILE_SIZE; import static org.elasticsearch.repositories.s3.S3Repository.MAX_FILE_SIZE_USING_MULTIPART; import static org.elasticsearch.repositories.s3.S3Repository.MIN_PART_SIZE_USING_MULTIPART; class S3BlobContainer extends AbstractBlobContainer { private static final Logger logger = LogManager.getLogger(S3BlobContainer.class); /** * Maximum number of deletes in a {@link DeleteObjectsRequest}. * @see <a href="https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html">S3 Documentation</a>. */ private static final int MAX_BULK_DELETES = 1000; private final S3BlobStore blobStore; private final String keyPath; S3BlobContainer(BlobPath path, S3BlobStore blobStore) { super(path); this.blobStore = blobStore; this.keyPath = path.buildAsString(); } @Override public boolean blobExists(String blobName) { try (AmazonS3Reference clientReference = blobStore.clientReference()) { return SocketAccess.doPrivileged(() -> clientReference.client().doesObjectExist(blobStore.bucket(), buildKey(blobName))); } catch (final Exception e) { throw new BlobStoreException("Failed to check if blob [" + blobName +"] exists", e); } } @Override public InputStream readBlob(String blobName) throws IOException { return new S3RetryingInputStream(blobStore, buildKey(blobName)); } @Override public InputStream readBlob(String blobName, long position, long length) throws IOException { if (position < 0L) { throw new IllegalArgumentException("position must be non-negative"); } if (length < 0) { throw new IllegalArgumentException("length must be non-negative"); } if (length == 0) { return new ByteArrayInputStream(new byte[0]); } else { return new S3RetryingInputStream(blobStore, buildKey(blobName), position, Math.addExact(position, length - 1)); } } @Override public long readBlobPreferredLength() { // This container returns streams that must be fully consumed, so we tell consumers to make bounded requests. return new ByteSizeValue(32, ByteSizeUnit.MB).getBytes(); } /** * This implementation ignores the failIfAlreadyExists flag as the S3 API has no way to enforce this due to its weak consistency model. */ @Override public void writeBlob(String blobName, InputStream inputStream, long blobSize, boolean failIfAlreadyExists) throws IOException { assert inputStream.markSupported() : "No mark support on inputStream breaks the S3 SDK's ability to retry requests"; SocketAccess.doPrivilegedIOException(() -> { if (blobSize <= getLargeBlobThresholdInBytes()) { executeSingleUpload(blobStore, buildKey(blobName), inputStream, blobSize); } else { executeMultipartUpload(blobStore, buildKey(blobName), inputStream, blobSize); } return null; }); } @Override public void writeBlob(String blobName, boolean failIfAlreadyExists, boolean atomic, CheckedConsumer<OutputStream, IOException> writer) throws IOException { final String absoluteBlobKey = buildKey(blobName); try (AmazonS3Reference clientReference = blobStore.clientReference(); ChunkedBlobOutputStream<PartETag> out = new ChunkedBlobOutputStream<>(blobStore.bigArrays(), blobStore.bufferSizeInBytes()) { private final SetOnce<String> uploadId = new SetOnce<>(); @Override protected void flushBuffer() throws IOException { flushBuffer(false); } private void flushBuffer(boolean lastPart) throws IOException { if (buffer.size() == 0) { return; } if (flushedBytes == 0L) { assert lastPart == false : "use single part upload if there's only a single part"; uploadId.set(SocketAccess.doPrivileged(() -> clientReference.client().initiateMultipartUpload(initiateMultiPartUpload(absoluteBlobKey)).getUploadId())); if (Strings.isEmpty(uploadId.get())) { throw new IOException("Failed to initialize multipart upload " + absoluteBlobKey); } } assert lastPart == false || successful : "must only write last part if successful"; final UploadPartRequest uploadRequest = createPartUploadRequest( buffer.bytes().streamInput(), uploadId.get(), parts.size() + 1, absoluteBlobKey, buffer.size(), lastPart); final UploadPartResult uploadResponse = SocketAccess.doPrivileged(() -> clientReference.client().uploadPart(uploadRequest)); finishPart(uploadResponse.getPartETag()); } @Override protected void onCompletion() throws IOException { if (flushedBytes == 0L) { writeBlob(blobName, buffer.bytes(), failIfAlreadyExists); } else { flushBuffer(true); final CompleteMultipartUploadRequest complRequest = new CompleteMultipartUploadRequest(blobStore.bucket(), absoluteBlobKey, uploadId.get(), parts); complRequest.setRequestMetricCollector(blobStore.multiPartUploadMetricCollector); SocketAccess.doPrivilegedVoid(() -> clientReference.client().completeMultipartUpload(complRequest)); } } @Override protected void onFailure() { if (Strings.hasText(uploadId.get())) { abortMultiPartUpload(uploadId.get(), absoluteBlobKey); } } }) { writer.accept(out); out.markSuccess(); } } private UploadPartRequest createPartUploadRequest(InputStream stream, String uploadId, int number, String blobName, long size, boolean lastPart) { final UploadPartRequest uploadRequest = new UploadPartRequest(); uploadRequest.setBucketName(blobStore.bucket()); uploadRequest.setKey(blobName); uploadRequest.setUploadId(uploadId); uploadRequest.setPartNumber(number); uploadRequest.setInputStream(stream); uploadRequest.setRequestMetricCollector(blobStore.multiPartUploadMetricCollector); uploadRequest.setPartSize(size); uploadRequest.setLastPart(lastPart); return uploadRequest; } private void abortMultiPartUpload(String uploadId, String blobName) { final AbortMultipartUploadRequest abortRequest = new AbortMultipartUploadRequest(blobStore.bucket(), blobName, uploadId); try (AmazonS3Reference clientReference = blobStore.clientReference()) { SocketAccess.doPrivilegedVoid(() -> clientReference.client().abortMultipartUpload(abortRequest)); } } private InitiateMultipartUploadRequest initiateMultiPartUpload(String blobName) { final InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(blobStore.bucket(), blobName); initRequest.setStorageClass(blobStore.getStorageClass()); initRequest.setCannedACL(blobStore.getCannedACL()); initRequest.setRequestMetricCollector(blobStore.multiPartUploadMetricCollector); if (blobStore.serverSideEncryption()) { final ObjectMetadata md = new ObjectMetadata(); md.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); initRequest.setObjectMetadata(md); } return initRequest; } // package private for testing long getLargeBlobThresholdInBytes() { return blobStore.bufferSizeInBytes(); } @Override public void writeBlobAtomic(String blobName, BytesReference bytes, boolean failIfAlreadyExists) throws IOException { writeBlob(blobName, bytes, failIfAlreadyExists); } @Override @SuppressWarnings("unchecked") public DeleteResult delete() throws IOException { final AtomicLong deletedBlobs = new AtomicLong(); final AtomicLong deletedBytes = new AtomicLong(); try (AmazonS3Reference clientReference = blobStore.clientReference()) { ObjectListing prevListing = null; while (true) { ObjectListing list; if (prevListing != null) { final ObjectListing finalPrevListing = prevListing; list = SocketAccess.doPrivileged(() -> clientReference.client().listNextBatchOfObjects(finalPrevListing)); } else { final ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); listObjectsRequest.setBucketName(blobStore.bucket()); listObjectsRequest.setPrefix(keyPath); listObjectsRequest.setRequestMetricCollector(blobStore.listMetricCollector); list = SocketAccess.doPrivileged(() -> clientReference.client().listObjects(listObjectsRequest)); } final Iterator<S3ObjectSummary> objectSummaryIterator = list.getObjectSummaries().iterator(); final Iterator<String> blobNameIterator = new Iterator<>() { @Override public boolean hasNext() { return objectSummaryIterator.hasNext(); } @Override public String next() { final S3ObjectSummary summary = objectSummaryIterator.next(); deletedBlobs.incrementAndGet(); deletedBytes.addAndGet(summary.getSize()); return summary.getKey(); } }; if (list.isTruncated()) { doDeleteBlobs(blobNameIterator, false); prevListing = list; } else { doDeleteBlobs(Iterators.concat(blobNameIterator, Collections.singletonList(keyPath).iterator()), false); break; } } } catch (final AmazonClientException e) { throw new IOException("Exception when deleting blob container [" + keyPath + "]", e); } return new DeleteResult(deletedBlobs.get(), deletedBytes.get()); } @Override public void deleteBlobsIgnoringIfNotExists(Iterator<String> blobNames) throws IOException { doDeleteBlobs(blobNames, true); } private void doDeleteBlobs(Iterator<String> blobNames, boolean relative) throws IOException { if (blobNames.hasNext() == false) { return; } final Iterator<String> outstanding; if (relative) { outstanding = new Iterator<>() { @Override public boolean hasNext() { return blobNames.hasNext(); } @Override public String next() { return buildKey(blobNames.next()); } }; } else { outstanding = blobNames; } final List<String> partition = new ArrayList<>(); try (AmazonS3Reference clientReference = blobStore.clientReference()) { // S3 API only allows 1k blobs per delete so we split up the given blobs into requests of max. 1k deletes final AtomicReference<Exception> aex = new AtomicReference<>(); SocketAccess.doPrivilegedVoid(() -> { outstanding.forEachRemaining(key -> { partition.add(key); if (partition.size() == MAX_BULK_DELETES) { deletePartition(clientReference, partition, aex); partition.clear(); } }); if (partition.isEmpty() == false) { deletePartition(clientReference, partition, aex); } }); if (aex.get() != null) { throw aex.get(); } } catch (Exception e) { throw new IOException("Failed to delete blobs " + partition.stream().limit(10).collect(Collectors.toList()), e); } } private void deletePartition(AmazonS3Reference clientReference, List<String> partition, AtomicReference<Exception> aex) { try { clientReference.client().deleteObjects(bulkDelete(blobStore.bucket(), partition)); } catch (MultiObjectDeleteException e) { // We are sending quiet mode requests so we can't use the deleted keys entry on the exception and instead // first remove all keys that were sent in the request and then add back those that ran into an exception. logger.warn( () -> new ParameterizedMessage("Failed to delete some blobs {}", e.getErrors() .stream().map(err -> "[" + err.getKey() + "][" + err.getCode() + "][" + err.getMessage() + "]") .collect(Collectors.toList())), e); aex.set(ExceptionsHelper.useOrSuppress(aex.get(), e)); } catch (AmazonClientException e) { // The AWS client threw any unexpected exception and did not execute the request at all so we do not // remove any keys from the outstanding deletes set. aex.set(ExceptionsHelper.useOrSuppress(aex.get(), e)); } } private static DeleteObjectsRequest bulkDelete(String bucket, List<String> blobs) { return new DeleteObjectsRequest(bucket).withKeys(blobs.toArray(Strings.EMPTY_ARRAY)).withQuiet(true); } @Override public Map<String, BlobMetadata> listBlobsByPrefix(@Nullable String blobNamePrefix) throws IOException { try (AmazonS3Reference clientReference = blobStore.clientReference()) { return executeListing(clientReference, listObjectsRequest(blobNamePrefix == null ? keyPath : buildKey(blobNamePrefix))) .stream() .flatMap(listing -> listing.getObjectSummaries().stream()) .map(summary -> new PlainBlobMetadata(summary.getKey().substring(keyPath.length()), summary.getSize())) .collect(Collectors.toMap(PlainBlobMetadata::name, Function.identity())); } catch (final AmazonClientException e) { throw new IOException("Exception when listing blobs by prefix [" + blobNamePrefix + "]", e); } } @Override public Map<String, BlobMetadata> listBlobs() throws IOException { return listBlobsByPrefix(null); } @Override public Map<String, BlobContainer> children() throws IOException { try (AmazonS3Reference clientReference = blobStore.clientReference()) { return executeListing(clientReference, listObjectsRequest(keyPath)).stream().flatMap(listing -> { assert listing.getObjectSummaries().stream().noneMatch(s -> { for (String commonPrefix : listing.getCommonPrefixes()) { if (s.getKey().substring(keyPath.length()).startsWith(commonPrefix)) { return true; } } return false; }) : "Response contained children for listed common prefixes."; return listing.getCommonPrefixes().stream(); }) .map(prefix -> prefix.substring(keyPath.length())) .filter(name -> name.isEmpty() == false) // Stripping the trailing slash off of the common prefix .map(name -> name.substring(0, name.length() - 1)) .collect(Collectors.toMap(Function.identity(), name -> blobStore.blobContainer(path().add(name)))); } catch (final AmazonClientException e) { throw new IOException("Exception when listing children of [" + path().buildAsString() + ']', e); } } private static List<ObjectListing> executeListing(AmazonS3Reference clientReference, ListObjectsRequest listObjectsRequest) { final List<ObjectListing> results = new ArrayList<>(); ObjectListing prevListing = null; while (true) { ObjectListing list; if (prevListing != null) { final ObjectListing finalPrevListing = prevListing; list = SocketAccess.doPrivileged(() -> clientReference.client().listNextBatchOfObjects(finalPrevListing)); } else { list = SocketAccess.doPrivileged(() -> clientReference.client().listObjects(listObjectsRequest)); } results.add(list); if (list.isTruncated()) { prevListing = list; } else { break; } } return results; } private ListObjectsRequest listObjectsRequest(String keyPath) { return new ListObjectsRequest().withBucketName(blobStore.bucket()).withPrefix(keyPath).withDelimiter("/") .withRequestMetricCollector(blobStore.listMetricCollector); } private String buildKey(String blobName) { return keyPath + blobName; } /** * Uploads a blob using a single upload request */ void executeSingleUpload(final S3BlobStore blobStore, final String blobName, final InputStream input, final long blobSize) throws IOException { // Extra safety checks if (blobSize > MAX_FILE_SIZE.getBytes()) { throw new IllegalArgumentException("Upload request size [" + blobSize + "] can't be larger than " + MAX_FILE_SIZE); } if (blobSize > blobStore.bufferSizeInBytes()) { throw new IllegalArgumentException("Upload request size [" + blobSize + "] can't be larger than buffer size"); } final ObjectMetadata md = new ObjectMetadata(); md.setContentLength(blobSize); if (blobStore.serverSideEncryption()) { md.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); } final PutObjectRequest putRequest = new PutObjectRequest(blobStore.bucket(), blobName, input, md); putRequest.setStorageClass(blobStore.getStorageClass()); putRequest.setCannedAcl(blobStore.getCannedACL()); putRequest.setRequestMetricCollector(blobStore.putMetricCollector); try (AmazonS3Reference clientReference = blobStore.clientReference()) { SocketAccess.doPrivilegedVoid(() -> { clientReference.client().putObject(putRequest); }); } catch (final AmazonClientException e) { throw new IOException("Unable to upload object [" + blobName + "] using a single upload", e); } } /** * Uploads a blob using multipart upload requests. */ void executeMultipartUpload(final S3BlobStore blobStore, final String blobName, final InputStream input, final long blobSize) throws IOException { ensureMultiPartUploadSize(blobSize); final long partSize = blobStore.bufferSizeInBytes(); final Tuple<Long, Long> multiparts = numberOfMultiparts(blobSize, partSize); if (multiparts.v1() > Integer.MAX_VALUE) { throw new IllegalArgumentException("Too many multipart upload requests, maybe try a larger buffer size?"); } final int nbParts = multiparts.v1().intValue(); final long lastPartSize = multiparts.v2(); assert blobSize == (((nbParts - 1) * partSize) + lastPartSize) : "blobSize does not match multipart sizes"; final SetOnce<String> uploadId = new SetOnce<>(); final String bucketName = blobStore.bucket(); boolean success = false; try (AmazonS3Reference clientReference = blobStore.clientReference()) { uploadId.set(SocketAccess.doPrivileged(() -> clientReference.client().initiateMultipartUpload(initiateMultiPartUpload(blobName)).getUploadId())); if (Strings.isEmpty(uploadId.get())) { throw new IOException("Failed to initialize multipart upload " + blobName); } final List<PartETag> parts = new ArrayList<>(); long bytesCount = 0; for (int i = 1; i <= nbParts; i++) { final boolean lastPart = i == nbParts; final UploadPartRequest uploadRequest = createPartUploadRequest(input, uploadId.get(), i, blobName, lastPart ? lastPartSize : partSize, lastPart); bytesCount += uploadRequest.getPartSize(); final UploadPartResult uploadResponse = SocketAccess.doPrivileged(() -> clientReference.client().uploadPart(uploadRequest)); parts.add(uploadResponse.getPartETag()); } if (bytesCount != blobSize) { throw new IOException("Failed to execute multipart upload for [" + blobName + "], expected " + blobSize + "bytes sent but got " + bytesCount); } final CompleteMultipartUploadRequest complRequest = new CompleteMultipartUploadRequest(bucketName, blobName, uploadId.get(), parts); complRequest.setRequestMetricCollector(blobStore.multiPartUploadMetricCollector); SocketAccess.doPrivilegedVoid(() -> clientReference.client().completeMultipartUpload(complRequest)); success = true; } catch (final AmazonClientException e) { throw new IOException("Unable to upload object [" + blobName + "] using multipart upload", e); } finally { if ((success == false) && Strings.hasLength(uploadId.get())) { abortMultiPartUpload(uploadId.get(), blobName); } } } // non-static, package private for testing void ensureMultiPartUploadSize(final long blobSize) { if (blobSize > MAX_FILE_SIZE_USING_MULTIPART.getBytes()) { throw new IllegalArgumentException("Multipart upload request size [" + blobSize + "] can't be larger than " + MAX_FILE_SIZE_USING_MULTIPART); } if (blobSize < MIN_PART_SIZE_USING_MULTIPART.getBytes()) { throw new IllegalArgumentException("Multipart upload request size [" + blobSize + "] can't be smaller than " + MIN_PART_SIZE_USING_MULTIPART); } } /** * Returns the number parts of size of {@code partSize} needed to reach {@code totalSize}, * along with the size of the last (or unique) part. * * @param totalSize the total size * @param partSize the part size * @return a {@link Tuple} containing the number of parts to fill {@code totalSize} and * the size of the last part */ static Tuple<Long, Long> numberOfMultiparts(final long totalSize, final long partSize) { if (partSize <= 0) { throw new IllegalArgumentException("Part size must be greater than zero"); } if ((totalSize == 0L) || (totalSize <= partSize)) { return Tuple.tuple(1L, totalSize); } final long parts = totalSize / partSize; final long remaining = totalSize % partSize; if (remaining == 0) { return Tuple.tuple(parts, partSize); } else { return Tuple.tuple(parts + 1, remaining); } } }
/* * Copyright 2015 Adaptris Ltd. * * 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.adaptris.core.mail; import static org.apache.commons.lang.StringUtils.isEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import com.adaptris.annotation.AdapterComponent; import com.adaptris.annotation.AdvancedConfig; import com.adaptris.annotation.AutoPopulated; import com.adaptris.annotation.ComponentProfile; import com.adaptris.annotation.DisplayOrder; import com.adaptris.annotation.InputFieldDefault; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.CoreConstants; import com.adaptris.core.NullConnection; import com.adaptris.core.ProduceDestination; import com.adaptris.core.ProduceException; import com.adaptris.mail.SmtpClient; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * Email implementation of the AdaptrisMessageProducer interface. * <p> * Because email is implicitly asynchronous, Request-Reply is invalid, and as such if the request method is used, an * <code>UnsupportedOperationException</code> is thrown. * <p> * Available Content-Encoding schemes that are supported are the same as those specified in RFC2045. They include "base64", * "quoted-printable", "7bit", "8bit" and "binary * </p> * <p> * The Content-Type may be any arbitary string such as application/edi-x12, however if no appropriate * <code>DataContentHandler</code> is installed, then the results can be undefined * </p> * <p> * The following metadata elements will change behaviour. * <ul> * <li>emailsubject - Override the configured subject with the value stored against this key. * <li>emailtemplatebody - If the producer is configured to send the payload as an attachment, the value stored against this key * will be used as the message body.</li> * <li>emailattachmentfilename - If this is set, and the message is to be sent as an attachment, then this will be used as the * filename, otherwise the messages unique id will be used.</li> * <li>emailattachmentcontenttype - If this is set, and the message is to be sent as an attachment, then this will be used as the * attachment content-type, otherwise the default setting (or configured setting) will be used.</li> * <li>emailcc - If this is set, this this comma separated list will override any configured CC list.</li> * </ul> * <p> * It is possible to control the underlying behaviour of this producer through the use of various properties that will be passed to * the <code>javax.mail.Session</code> instance. You need to refer to the javamail documentation to see a list of the available * properties and meanings. * </p> * * @config default-smtp-producer * * @see MailProducer * @see CoreConstants#EMAIL_SUBJECT * @see CoreConstants#EMAIL_ATTACH_FILENAME * @see CoreConstants#EMAIL_ATTACH_CONTENT_TYPE * @see CoreConstants#EMAIL_TEMPLATE_BODY * @see CoreConstants#EMAIL_CC_LIST */ @XStreamAlias("default-smtp-producer") @AdapterComponent @ComponentProfile(summary = "Send an email", tag = "producer,email", recommended = {NullConnection.class}) @DisplayOrder(order = {"smtpUrl", "username", "password", "subject", "from", "ccList", "bccList"}) public class DefaultSmtpProducer extends MailProducer { @AdvancedConfig @InputFieldDefault(value = "false") private Boolean isAttachment; @NotNull @AutoPopulated @AdvancedConfig private String contentType = "text/plain"; @NotNull @AutoPopulated @Pattern(regexp = "base64|quoted-printable|uuencode|x-uuencode|x-uue|binary|7bit|8bit") @AdvancedConfig private String contentEncoding = "base64"; @NotNull @AutoPopulated @AdvancedConfig private String attachmentContentType = "application/octet-stream"; @AdvancedConfig private String contentTypeKey = null; /** * @see Object#Object() * * */ public DefaultSmtpProducer() { super(); } /** * @see com.adaptris.core.AdaptrisMessageProducer #produce(AdaptrisMessage, * ProduceDestination) */ @Override public void produce(AdaptrisMessage msg, ProduceDestination destination) throws ProduceException { try { SmtpClient smtp = getClient(msg); smtp.setEncoding(contentEncoding); byte[] encodedPayload = encode(msg); smtp.addTo(destination.getDestination(msg)); if (isAttachment()) { String template = msg .getMetadataValue(CoreConstants.EMAIL_TEMPLATE_BODY); if (template != null) { if (msg.getContentEncoding() != null) { smtp.setMessage(template.getBytes(msg.getContentEncoding()), contentType); } else { smtp.setMessage(template.getBytes(), contentType); } } String fname = msg.headersContainsKey(CoreConstants.EMAIL_ATTACH_FILENAME) ? msg.getMetadataValue(CoreConstants.EMAIL_ATTACH_FILENAME) : msg.getUniqueId(); String type = msg.headersContainsKey(CoreConstants.EMAIL_ATTACH_CONTENT_TYPE) ? msg.getMetadataValue(CoreConstants.EMAIL_ATTACH_CONTENT_TYPE) : getAttachmentContentType(); smtp.addAttachment(encodedPayload, fname, type); } else { String payloadContent = contentType; if (contentTypeKey != null) { if (msg.headersContainsKey(contentTypeKey)) { String s = msg.getMetadataValue(contentTypeKey); if (!isEmpty(s)) { log.debug(contentTypeKey + " overrides configured content type"); payloadContent = s; } } } smtp.setMessage(encodedPayload, payloadContent); } smtp.send(); } catch (Exception e) { log.error("Could not produce message because of " + e.getMessage()); throw new ProduceException(e); } } /** * Specify if this message should be sent as an attachment. * * @param b true or false. */ public void setIsAttachment(Boolean b) { isAttachment = b; } /** * Get the attachment flag. * * @return true or false. */ public Boolean getIsAttachment() { return isAttachment; } boolean isAttachment() { return getIsAttachment() != null ? getIsAttachment().booleanValue() : false; } /** * Set the content type of the email. * * @param s the content type */ public void setContentType(String s) { contentType = s; } /** * Get the content type of the email. * * @return the content type. */ public String getContentType() { return contentType; } /** * Set the Content encoding of the email. * * @param s the content encoding. */ public void setContentEncoding(String s) { contentEncoding = s; } /** * Get the encoding of the email. * * @return the content encoding. */ public String getContentEncoding() { return contentEncoding; } /** * Set the content type associated with the attachement. * <p> * The default content-type for attachments is * <code>application/octet-stream</code> * </p> * * @param s the content type * * @see #setContentType(String) * @see #setIsAttachment(Boolean) * @see SmtpClient#addAttachment(byte[], java.lang.String, java.lang.String) */ public void setAttachmentContentType(String s) { attachmentContentType = s; } /** * Get the content type associated with the attachement. * * @see SmtpClient#addAttachment(byte[], java.lang.String, java.lang.String) * @return the attachment content type. */ public String getAttachmentContentType() { return attachmentContentType; } /** * Get the metadata key from which to extract the metadata. * * @return the contentTypeKey */ public String getContentTypeKey() { return contentTypeKey; } /** * Set the content type metadata key that will be used to extract the Content * Type. * <p> * In the event that this metadata key exists, it will be used in preference * to the configured content-type. * </p> * * @param s the contentTypeKey to set */ public void setContentTypeKey(String s) { contentTypeKey = s; } }
package com.github.kostyasha.github.integration.generic; import antlr.ANTLRException; import com.cloudbees.jenkins.GitHubRepositoryName; import com.coravy.hudson.plugins.github.GithubProjectProperty; import com.github.kostyasha.github.integration.generic.errors.GitHubErrorsAction; import com.github.kostyasha.github.integration.generic.errors.impl.GitHubRepoProviderError; import com.github.kostyasha.github.integration.generic.repoprovider.GitHubPluginRepoProvider; import com.google.common.annotations.Beta; import hudson.model.Action; import hudson.model.Job; import hudson.triggers.Trigger; import org.jenkinsci.plugins.github.pullrequest.GitHubPRTriggerMode; import org.kohsuke.github.GHRepository; import org.kohsuke.stapler.DataBoundSetter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; import static org.codehaus.groovy.runtime.InvokerHelper.asList; import static org.jenkinsci.plugins.github.pullrequest.GitHubPRTriggerMode.CRON; /** * @author Kanstantsin Shautsou */ public abstract class GitHubTrigger<T extends GitHubTrigger<T>> extends Trigger<Job<?, ?>> { private static final Logger LOG = LoggerFactory.getLogger(GitHubTrigger.class); @CheckForNull private GitHubPRTriggerMode triggerMode = CRON; /** * Cancel queued runs for specific kind (i.e. PR by number, branch by name). */ protected boolean cancelQueued = false; private boolean abortRunning = false; protected boolean skipFirstRun = false; @Beta private List<GitHubRepoProvider> repoProviders = asList(new GitHubPluginRepoProvider()); // default private transient GitHubRepoProvider repoProvider = null; @CheckForNull private GitHubErrorsAction errorsAction; // for performance private transient GitHubRepositoryName repoName; protected GitHubTrigger(String cronTabSpec) throws ANTLRException { super(cronTabSpec); } public GitHubTrigger(String spec, GitHubPRTriggerMode triggerMode) throws ANTLRException { super(spec); this.triggerMode = triggerMode; } @Nonnull public GitHubPRTriggerMode getTriggerMode() { return isNull(triggerMode) ? CRON : triggerMode; } public void setTriggerMode(GitHubPRTriggerMode triggerMode) { this.triggerMode = triggerMode; } public boolean isCancelQueued() { return cancelQueued; } @DataBoundSetter public void setCancelQueued(boolean cancelQueued) { this.cancelQueued = cancelQueued; } public boolean isAbortRunning() { return abortRunning; } @DataBoundSetter public void setAbortRunning(boolean abortRunning) { this.abortRunning = abortRunning; } public boolean isSkipFirstRun() { return skipFirstRun; } @DataBoundSetter public void setSkipFirstRun(boolean skipFirstRun) { this.skipFirstRun = skipFirstRun; } public GitHubRepositoryName getRepoName() { return repoName; } public void setRepoName(GitHubRepositoryName repoName) { this.repoName = repoName; } @Override public void start(Job<?, ?> project, boolean newInstance) { repoName = null; // reset cache getRepoProviders().forEach(GitHubRepoProvider::onTriggerStart); super.start(project, newInstance); } @Beta @Nonnull public List<GitHubRepoProvider> getRepoProviders() { if (isNull(repoProviders)) { repoProviders = asList(new GitHubPluginRepoProvider()); // old default behaviour } return repoProviders; } @Beta @DataBoundSetter public void setRepoProviders(List<GitHubRepoProvider> repoProviders) { this.repoProviders = repoProviders; } @Beta public void setRepoProvider(@Nonnull GitHubRepoProvider prov) { repoProviders = asList(prov); } @Beta public GitHubRepoProvider getRepoProvider() { final ArrayList<Throwable> throwables = new ArrayList<>(); if (isNull(repoProvider)) { boolean failed = false; for (GitHubRepoProvider prov : getRepoProviders()) { try { prov.getGHRepository(this); repoProvider = prov; } catch (Exception ex) { LOG.debug("Provider failed:", ex); throwables.add(ex); failed = true; } } if (failed) { LOG.error("Can't find repo provider for GitHubBranchTrigger job: {}. All repo providers failed: {}", getJob().getFullName(), throwables ); } } if (isNull(repoProvider)) { getErrorsAction().addOrReplaceError(new GitHubRepoProviderError( String.format("Can't find repo provider for %s.<br/> All providers failed: %s", job.getFullName(), throwables) )); } checkState(nonNull(repoProvider), "Can't find repo provider for %s", job.getFullName()); getErrorsAction().removeErrors(GitHubRepoProviderError.class); return repoProvider; } @Nonnull public GHRepository getRemoteRepository() throws IOException { GHRepository remoteRepository = getRepoProvider().getGHRepository(this); checkState(nonNull(remoteRepository), "Can't get remote GH repo for %s", job.getFullName()); return remoteRepository; } @Nonnull public GitHubErrorsAction getErrorsAction() { if (isNull(errorsAction)) { errorsAction = new GitHubErrorsAction(getDescriptor().getDisplayName() + " Trigger Errors"); } return errorsAction; } @Override public void stop() { repoName = null; getRepoProviders().forEach(GitHubRepoProvider::onTriggerStop); //TODO clean hooks? if (nonNull(job)) { LOG.info("Stopping '{}' for project '{}'", getDescriptor().getDisplayName(), job.getFullName()); } super.stop(); } public abstract String getFinishMsg(); public abstract GitHubPollingLogAction getPollingLogAction(); /** * Run full scan. */ public abstract void doRun(); @Nonnull @Override public Collection<? extends Action> getProjectActions() { final ArrayList<Action> actions = new ArrayList<>(); if (nonNull(getPollingLogAction())) { actions.add(getPollingLogAction()); } actions.add(getErrorsAction()); return actions; } @CheckForNull public Job getJob() { return job; } public GitHubRepositoryName getRepoFullName() { return getRepoFullName(getJob()); } public GitHubRepositoryName getRepoFullName(Job item) { Job<?, ?> job = (Job) item; if (isNull(repoName)) { checkNotNull(job, "job object is null, race condition?"); GithubProjectProperty ghpp = job.getProperty(GithubProjectProperty.class); checkNotNull(ghpp, "GitHub project property is not defined. Can't setup GitHub trigger for job %s", job.getName()); checkNotNull(ghpp.getProjectUrl(), "A GitHub project url is required"); GitHubRepositoryName repo = GitHubRepositoryName.create(ghpp.getProjectUrl().baseUrl()); checkNotNull(repo, "Invalid GitHub project url: %s", ghpp.getProjectUrl().baseUrl()); setRepoName(repo); } return repoName; } public void trySave() { try { job.save(); } catch (IOException e) { LOG.error("Error while saving job to file", e); } } protected void saveIfSkipFirstRun() { if (skipFirstRun) { LOG.info("Skipping first run for {}", job.getFullName()); skipFirstRun = false; trySave(); } } }
/* 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.activiti.standalone.jpa; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.activiti.engine.impl.test.AbstractFlowableTestCase; import org.activiti.engine.impl.variable.EntityManagerSession; import org.activiti.engine.impl.variable.EntityManagerSessionFactory; import org.flowable.engine.ProcessEngine; import org.flowable.engine.ProcessEngineConfiguration; import org.flowable.engine.common.api.FlowableException; import org.flowable.engine.common.api.FlowableIllegalArgumentException; import org.flowable.engine.common.impl.history.HistoryLevel; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.flowable.variable.api.history.HistoricVariableInstance; /** * @author Frederik Heremans */ public class JPAVariableTest extends AbstractFlowableTestCase { protected static ProcessEngine cachedProcessEngine; private static FieldAccessJPAEntity simpleEntityFieldAccess; private static PropertyAccessJPAEntity simpleEntityPropertyAccess; private static SubclassFieldAccessJPAEntity subclassFieldAccess; private static SubclassPropertyAccessJPAEntity subclassPropertyAccess; private static ByteIdJPAEntity byteIdJPAEntity; private static ShortIdJPAEntity shortIdJPAEntity; private static IntegerIdJPAEntity integerIdJPAEntity; private static LongIdJPAEntity longIdJPAEntity; private static FloatIdJPAEntity floatIdJPAEntity; private static DoubleIdJPAEntity doubleIdJPAEntity; private static CharIdJPAEntity charIdJPAEntity; private static StringIdJPAEntity stringIdJPAEntity; private static DateIdJPAEntity dateIdJPAEntity; private static SQLDateIdJPAEntity sqlDateIdJPAEntity; private static BigDecimalIdJPAEntity bigDecimalIdJPAEntity; private static BigIntegerIdJPAEntity bigIntegerIdJPAEntity; private static CompoundIdJPAEntity compoundIdJPAEntity; private static FieldAccessJPAEntity entityToQuery; private static FieldAccessJPAEntity entityToUpdate; private static boolean entitiesInitialized; private static EntityManagerFactory entityManagerFactory; protected void initializeProcessEngine() { if (cachedProcessEngine == null) { ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) ProcessEngineConfiguration .createProcessEngineConfigurationFromResource("org/activiti/standalone/jpa/flowable.cfg.xml"); cachedProcessEngine = processEngineConfiguration.buildProcessEngine(); org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) ((ProcessEngineConfigurationImpl) cachedProcessEngine .getProcessEngineConfiguration()).getFlowable5CompatibilityHandler().getRawProcessConfiguration(); EntityManagerSessionFactory entityManagerSessionFactory = (EntityManagerSessionFactory) activiti5ProcessEngineConfig .getSessionFactories() .get(EntityManagerSession.class); entityManagerFactory = entityManagerSessionFactory.getEntityManagerFactory(); } processEngine = cachedProcessEngine; } public void setupJPAEntities() { if (!entitiesInitialized) { EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); // Simple test data simpleEntityFieldAccess = new FieldAccessJPAEntity(); simpleEntityFieldAccess.setId(1L); simpleEntityFieldAccess.setValue("value1"); manager.persist(simpleEntityFieldAccess); simpleEntityPropertyAccess = new PropertyAccessJPAEntity(); simpleEntityPropertyAccess.setId(1L); simpleEntityPropertyAccess.setValue("value2"); manager.persist(simpleEntityPropertyAccess); subclassFieldAccess = new SubclassFieldAccessJPAEntity(); subclassFieldAccess.setId(1L); subclassFieldAccess.setValue("value3"); manager.persist(subclassFieldAccess); subclassPropertyAccess = new SubclassPropertyAccessJPAEntity(); subclassPropertyAccess.setId(1L); subclassPropertyAccess.setValue("value4"); manager.persist(subclassPropertyAccess); // Test entities with all possible ID types byteIdJPAEntity = new ByteIdJPAEntity(); byteIdJPAEntity.setByteId((byte) 1); manager.persist(byteIdJPAEntity); shortIdJPAEntity = new ShortIdJPAEntity(); shortIdJPAEntity.setShortId((short) 123); manager.persist(shortIdJPAEntity); integerIdJPAEntity = new IntegerIdJPAEntity(); integerIdJPAEntity.setIntId(123); manager.persist(integerIdJPAEntity); longIdJPAEntity = new LongIdJPAEntity(); longIdJPAEntity.setLongId(123456789L); manager.persist(longIdJPAEntity); floatIdJPAEntity = new FloatIdJPAEntity(); floatIdJPAEntity.setFloatId((float) 123.45678); manager.persist(floatIdJPAEntity); doubleIdJPAEntity = new DoubleIdJPAEntity(); doubleIdJPAEntity.setDoubleId(12345678.987654); manager.persist(doubleIdJPAEntity); charIdJPAEntity = new CharIdJPAEntity(); charIdJPAEntity.setCharId('g'); manager.persist(charIdJPAEntity); dateIdJPAEntity = new DateIdJPAEntity(); dateIdJPAEntity.setDateId(new java.util.Date()); manager.persist(dateIdJPAEntity); sqlDateIdJPAEntity = new SQLDateIdJPAEntity(); sqlDateIdJPAEntity.setDateId(new java.sql.Date(Calendar.getInstance().getTimeInMillis())); manager.persist(sqlDateIdJPAEntity); stringIdJPAEntity = new StringIdJPAEntity(); stringIdJPAEntity.setStringId("azertyuiop"); manager.persist(stringIdJPAEntity); bigDecimalIdJPAEntity = new BigDecimalIdJPAEntity(); bigDecimalIdJPAEntity.setBigDecimalId(new BigDecimal("12345678912345678900000.123456789123456789")); manager.persist(bigDecimalIdJPAEntity); bigIntegerIdJPAEntity = new BigIntegerIdJPAEntity(); bigIntegerIdJPAEntity.setBigIntegerId(new BigInteger("12345678912345678912345678900000")); manager.persist(bigIntegerIdJPAEntity); manager.flush(); manager.getTransaction().commit(); manager.close(); entitiesInitialized = true; } } public void setupIllegalJPAEntities() { EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); compoundIdJPAEntity = new CompoundIdJPAEntity(); EmbeddableCompoundId id = new EmbeddableCompoundId(); id.setIdPart1(123L); id.setIdPart2("part2"); compoundIdJPAEntity.setId(id); manager.persist(compoundIdJPAEntity); manager.flush(); manager.getTransaction().commit(); manager.close(); } public void setupQueryJPAEntity() { EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); entityToQuery = new FieldAccessJPAEntity(); entityToQuery.setId(2L); manager.persist(entityToQuery); manager.flush(); manager.getTransaction().commit(); manager.close(); } public void setupJPAEntityToUpdate() { EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); entityToUpdate = new FieldAccessJPAEntity(); entityToUpdate.setId(3L); manager.persist(entityToUpdate); manager.flush(); manager.getTransaction().commit(); manager.close(); } @Deployment public void testStoreJPAEntityAsVariable() { setupJPAEntities(); // ----------------------------------------------------------------------------- // Simple test, Start process with JPA entities as variables // ----------------------------------------------------------------------------- Map<String, Object> variables = new HashMap<String, Object>(); variables.put("simpleEntityFieldAccess", simpleEntityFieldAccess); variables.put("simpleEntityPropertyAccess", simpleEntityPropertyAccess); variables.put("subclassFieldAccess", subclassFieldAccess); variables.put("subclassPropertyAccess", subclassPropertyAccess); // Start the process with the JPA-entities as variables. They will be stored in the DB. ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) { HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().variableName("simpleEntityFieldAccess").singleResult(); FieldAccessJPAEntity entity = (FieldAccessJPAEntity) historicVariableInstance.getValue(); assertNotNull(entity); assertEquals("value1", entity.getValue()); } // Read entity with @Id on field Object fieldAccessResult = runtimeService.getVariable(processInstance.getId(), "simpleEntityFieldAccess"); assertTrue(fieldAccessResult instanceof FieldAccessJPAEntity); assertEquals(1L, ((FieldAccessJPAEntity) fieldAccessResult).getId().longValue()); assertEquals("value1", ((FieldAccessJPAEntity) fieldAccessResult).getValue()); // Read entity with @Id on property Object propertyAccessResult = runtimeService.getVariable(processInstance.getId(), "simpleEntityPropertyAccess"); assertTrue(propertyAccessResult instanceof PropertyAccessJPAEntity); assertEquals(1L, ((PropertyAccessJPAEntity) propertyAccessResult).getId().longValue()); assertEquals("value2", ((PropertyAccessJPAEntity) propertyAccessResult).getValue()); // Read entity with @Id on field of mapped superclass Object subclassFieldResult = runtimeService.getVariable(processInstance.getId(), "subclassFieldAccess"); assertTrue(subclassFieldResult instanceof SubclassFieldAccessJPAEntity); assertEquals(1L, ((SubclassFieldAccessJPAEntity) subclassFieldResult).getId().longValue()); assertEquals("value3", ((SubclassFieldAccessJPAEntity) subclassFieldResult).getValue()); // Read entity with @Id on property of mapped superclass Object subclassPropertyResult = runtimeService.getVariable(processInstance.getId(), "subclassPropertyAccess"); assertTrue(subclassPropertyResult instanceof SubclassPropertyAccessJPAEntity); assertEquals(1L, ((SubclassPropertyAccessJPAEntity) subclassPropertyResult).getId().longValue()); assertEquals("value4", ((SubclassPropertyAccessJPAEntity) subclassPropertyResult).getValue()); // ----------------------------------------------------------------------------- // Test updating JPA-entity to null-value and back again // ----------------------------------------------------------------------------- Object currentValue = runtimeService.getVariable(processInstance.getId(), "simpleEntityFieldAccess"); assertNotNull(currentValue); // Set to null runtimeService.setVariable(processInstance.getId(), "simpleEntityFieldAccess", null); currentValue = runtimeService.getVariable(processInstance.getId(), "simpleEntityFieldAccess"); assertNull(currentValue); // Set to JPA-entity again runtimeService.setVariable(processInstance.getId(), "simpleEntityFieldAccess", simpleEntityFieldAccess); currentValue = runtimeService.getVariable(processInstance.getId(), "simpleEntityFieldAccess"); assertNotNull(currentValue); assertTrue(currentValue instanceof FieldAccessJPAEntity); assertEquals(1L, ((FieldAccessJPAEntity) currentValue).getId().longValue()); // ----------------------------------------------------------------------------- // Test all allowed types of ID values // ----------------------------------------------------------------------------- variables = new HashMap<String, Object>(); variables.put("byteIdJPAEntity", byteIdJPAEntity); variables.put("shortIdJPAEntity", shortIdJPAEntity); variables.put("integerIdJPAEntity", integerIdJPAEntity); variables.put("longIdJPAEntity", longIdJPAEntity); variables.put("floatIdJPAEntity", floatIdJPAEntity); variables.put("doubleIdJPAEntity", doubleIdJPAEntity); variables.put("charIdJPAEntity", charIdJPAEntity); variables.put("stringIdJPAEntity", stringIdJPAEntity); variables.put("dateIdJPAEntity", dateIdJPAEntity); variables.put("sqlDateIdJPAEntity", sqlDateIdJPAEntity); variables.put("bigDecimalIdJPAEntity", bigDecimalIdJPAEntity); variables.put("bigIntegerIdJPAEntity", bigIntegerIdJPAEntity); // Start the process with the JPA-entities as variables. They will be stored in the DB. ProcessInstance processInstanceAllTypes = runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); Object byteIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "byteIdJPAEntity"); assertTrue(byteIdResult instanceof ByteIdJPAEntity); assertEquals(byteIdJPAEntity.getByteId(), ((ByteIdJPAEntity) byteIdResult).getByteId()); Object shortIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "shortIdJPAEntity"); assertTrue(shortIdResult instanceof ShortIdJPAEntity); assertEquals(shortIdJPAEntity.getShortId(), ((ShortIdJPAEntity) shortIdResult).getShortId()); Object integerIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "integerIdJPAEntity"); assertTrue(integerIdResult instanceof IntegerIdJPAEntity); assertEquals(integerIdJPAEntity.getIntId(), ((IntegerIdJPAEntity) integerIdResult).getIntId()); Object longIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "longIdJPAEntity"); assertTrue(longIdResult instanceof LongIdJPAEntity); assertEquals(longIdJPAEntity.getLongId(), ((LongIdJPAEntity) longIdResult).getLongId()); Object floatIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "floatIdJPAEntity"); assertTrue(floatIdResult instanceof FloatIdJPAEntity); assertEquals(floatIdJPAEntity.getFloatId(), ((FloatIdJPAEntity) floatIdResult).getFloatId()); Object doubleIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "doubleIdJPAEntity"); assertTrue(doubleIdResult instanceof DoubleIdJPAEntity); assertEquals(doubleIdJPAEntity.getDoubleId(), ((DoubleIdJPAEntity) doubleIdResult).getDoubleId()); Object charIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "charIdJPAEntity"); assertTrue(charIdResult instanceof CharIdJPAEntity); assertEquals(charIdJPAEntity.getCharId(), ((CharIdJPAEntity) charIdResult).getCharId()); Object stringIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "stringIdJPAEntity"); assertTrue(stringIdResult instanceof StringIdJPAEntity); assertEquals(stringIdJPAEntity.getStringId(), ((StringIdJPAEntity) stringIdResult).getStringId()); Object dateIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "dateIdJPAEntity"); assertTrue(dateIdResult instanceof DateIdJPAEntity); assertEquals(dateIdJPAEntity.getDateId(), ((DateIdJPAEntity) dateIdResult).getDateId()); Object sqlDateIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "sqlDateIdJPAEntity"); assertTrue(sqlDateIdResult instanceof SQLDateIdJPAEntity); assertEquals(sqlDateIdJPAEntity.getDateId(), ((SQLDateIdJPAEntity) sqlDateIdResult).getDateId()); Object bigDecimalIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "bigDecimalIdJPAEntity"); assertTrue(bigDecimalIdResult instanceof BigDecimalIdJPAEntity); assertEquals(bigDecimalIdJPAEntity.getBigDecimalId(), ((BigDecimalIdJPAEntity) bigDecimalIdResult).getBigDecimalId()); Object bigIntegerIdResult = runtimeService.getVariable(processInstanceAllTypes.getId(), "bigIntegerIdJPAEntity"); assertTrue(bigIntegerIdResult instanceof BigIntegerIdJPAEntity); assertEquals(bigIntegerIdJPAEntity.getBigIntegerId(), ((BigIntegerIdJPAEntity) bigIntegerIdResult).getBigIntegerId()); } @Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testStoreJPAEntityAsVariable.bpmn20.xml" }) public void testStoreJPAEntityListAsVariable() { setupJPAEntities(); // ----------------------------------------------------------------------------- // Simple test, Start process with lists of JPA entities as variables // ----------------------------------------------------------------------------- Map<String, Object> variables = new HashMap<String, Object>(); variables.put("simpleEntityFieldAccess", Arrays.asList(simpleEntityFieldAccess, simpleEntityFieldAccess, simpleEntityFieldAccess)); variables.put("simpleEntityPropertyAccess", Arrays.asList(simpleEntityPropertyAccess, simpleEntityPropertyAccess, simpleEntityPropertyAccess)); variables.put("subclassFieldAccess", Arrays.asList(subclassFieldAccess, subclassFieldAccess, subclassFieldAccess)); variables.put("subclassPropertyAccess", Arrays.asList(subclassPropertyAccess, subclassPropertyAccess, subclassPropertyAccess)); // Start the process with the JPA-entities as variables. They will be stored in the DB. ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); // Read entity with @Id on field Object fieldAccessResult = runtimeService.getVariable(processInstance.getId(), "simpleEntityFieldAccess"); assertTrue(fieldAccessResult instanceof List<?>); List<?> list = (List<?>) fieldAccessResult; assertEquals(3L, list.size()); assertTrue(list.get(0) instanceof FieldAccessJPAEntity); assertEquals(((FieldAccessJPAEntity) list.get(0)).getId(), simpleEntityFieldAccess.getId()); // Read entity with @Id on property Object propertyAccessResult = runtimeService.getVariable(processInstance.getId(), "simpleEntityPropertyAccess"); assertTrue(propertyAccessResult instanceof List<?>); list = (List<?>) propertyAccessResult; assertEquals(3L, list.size()); assertTrue(list.get(0) instanceof PropertyAccessJPAEntity); assertEquals(((PropertyAccessJPAEntity) list.get(0)).getId(), simpleEntityPropertyAccess.getId()); // Read entity with @Id on field of mapped superclass Object subclassFieldResult = runtimeService.getVariable(processInstance.getId(), "subclassFieldAccess"); assertTrue(subclassFieldResult instanceof List<?>); list = (List<?>) subclassFieldResult; assertEquals(3L, list.size()); assertTrue(list.get(0) instanceof SubclassFieldAccessJPAEntity); assertEquals(((SubclassFieldAccessJPAEntity) list.get(0)).getId(), simpleEntityPropertyAccess.getId()); // Read entity with @Id on property of mapped superclass Object subclassPropertyResult = runtimeService.getVariable(processInstance.getId(), "subclassPropertyAccess"); assertTrue(subclassPropertyResult instanceof List<?>); list = (List<?>) subclassPropertyResult; assertEquals(3L, list.size()); assertTrue(list.get(0) instanceof SubclassPropertyAccessJPAEntity); assertEquals(((SubclassPropertyAccessJPAEntity) list.get(0)).getId(), simpleEntityPropertyAccess.getId()); } @Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testStoreJPAEntityAsVariable.bpmn20.xml" }) public void testStoreJPAEntityListAsVariableEdgeCases() { setupJPAEntities(); // Test using mixed JPA-entities which are not serializable, should not be picked up by JPA list type en therefor fail // due to serialization error Map<String, Object> variables = new HashMap<String, Object>(); variables.put("simpleEntityFieldAccess", Arrays.asList(simpleEntityFieldAccess, simpleEntityPropertyAccess)); try { runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); fail("Exception expected"); } catch (FlowableException ae) { // Expected } // Test updating value to an empty list and back variables = new HashMap<String, Object>(); variables.put("list", Arrays.asList(simpleEntityFieldAccess, simpleEntityFieldAccess)); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); runtimeService.setVariable(processInstance.getId(), "list", new ArrayList<String>()); assertEquals(0L, ((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).size()); runtimeService.setVariable(processInstance.getId(), "list", Arrays.asList(simpleEntityFieldAccess, simpleEntityFieldAccess)); assertEquals(2L, ((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).size()); assertTrue(((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).get(0) instanceof FieldAccessJPAEntity); // Test updating to list of Strings runtimeService.setVariable(processInstance.getId(), "list", Arrays.asList("TEST", "TESTING")); assertEquals(2L, ((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).size()); assertTrue(((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).get(0) instanceof String); runtimeService.setVariable(processInstance.getId(), "list", Arrays.asList(simpleEntityFieldAccess, simpleEntityFieldAccess)); assertEquals(2L, ((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).size()); assertTrue(((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).get(0) instanceof FieldAccessJPAEntity); // Test updating to null runtimeService.setVariable(processInstance.getId(), "list", null); assertNull(runtimeService.getVariable(processInstance.getId(), "list")); runtimeService.setVariable(processInstance.getId(), "list", Arrays.asList(simpleEntityFieldAccess, simpleEntityFieldAccess)); assertEquals(2L, ((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).size()); assertTrue(((List<?>) runtimeService.getVariable(processInstance.getId(), "list")).get(0) instanceof FieldAccessJPAEntity); } // https://activiti.atlassian.net/browse/ACT-995 @Deployment(resources = "org/activiti/standalone/jpa/JPAVariableTest.testQueryJPAVariable.bpmn20.xml") public void testReplaceExistingJPAEntityWithAnotherOfSameType() { EntityManager manager = entityManagerFactory.createEntityManager(); manager.getTransaction().begin(); // Old variable that gets replaced FieldAccessJPAEntity oldVariable = new FieldAccessJPAEntity(); oldVariable.setId(11L); oldVariable.setValue("value1"); manager.persist(oldVariable); // New variable FieldAccessJPAEntity newVariable = new FieldAccessJPAEntity(); newVariable.setId(12L); newVariable.setValue("value2"); manager.persist(newVariable); manager.flush(); manager.getTransaction().commit(); manager.close(); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcess"); String executionId = processInstance.getId(); String variableName = "testVariable"; runtimeService.setVariable(executionId, variableName, oldVariable); runtimeService.setVariable(executionId, variableName, newVariable); Object variable = runtimeService.getVariable(executionId, variableName); assertEquals(newVariable.getId(), ((FieldAccessJPAEntity) variable).getId()); } @Deployment public void testIllegalEntities() { setupIllegalJPAEntities(); // Starting process instance with a variable that has a compound primary key, which is not supported. Map<String, Object> variables = new HashMap<String, Object>(); variables.put("compoundIdJPAEntity", compoundIdJPAEntity); try { runtimeService.startProcessInstanceByKey("JPAVariableProcessExceptions", variables); fail("Exception expected"); } catch (FlowableException ae) { assertTextPresent("Cannot find field or method with annotation @Id on class", ae.getMessage()); assertTextPresent("only single-valued primary keys are supported on JPA-entities", ae.getMessage()); } // Starting process instance with a variable that has null as ID-value variables = new HashMap<String, Object>(); variables.put("nullValueEntity", new FieldAccessJPAEntity()); try { runtimeService.startProcessInstanceByKey("JPAVariableProcessExceptions", variables); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("Value of primary key for JPA-Entity cannot be null", ae.getMessage()); } // Starting process instance with an invalid type of ID // Under normal circumstances, JPA will throw an exception for this of the class is // present in the PU when creating EntityManagerFactory, but we test it *just in case* variables = new HashMap<String, Object>(); IllegalIdClassJPAEntity illegalIdTypeEntity = new IllegalIdClassJPAEntity(); illegalIdTypeEntity.setId(Calendar.getInstance()); variables.put("illegalTypeId", illegalIdTypeEntity); try { runtimeService.startProcessInstanceByKey("JPAVariableProcessExceptions", variables); fail("Exception expected"); } catch (FlowableException ae) { assertTextPresent("Unsupported Primary key type for JPA-Entity", ae.getMessage()); } // Start process instance with JPA-entity which has an ID but isn't persisted. When reading // the variable we should get an exception. variables = new HashMap<String, Object>(); FieldAccessJPAEntity nonPersistentEntity = new FieldAccessJPAEntity(); nonPersistentEntity.setId(9999L); variables.put("nonPersistentEntity", nonPersistentEntity); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcessExceptions", variables); try { runtimeService.getVariable(processInstance.getId(), "nonPersistentEntity"); fail("Exception expected"); } catch (FlowableException ae) { assertTextPresent("Entity does not exist: " + FieldAccessJPAEntity.class.getName() + " - 9999", ae.getMessage()); } } @Deployment public void testQueryJPAVariable() { setupQueryJPAEntity(); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("entityToQuery", entityToQuery); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("JPAVariableProcess", variables); // Query the processInstance ProcessInstance result = runtimeService.createProcessInstanceQuery().variableValueEquals("entityToQuery", entityToQuery).singleResult(); assertNotNull(result); assertEquals(result.getId(), processInstance.getId()); // Query with the same entity-type but with different ID should have no result FieldAccessJPAEntity unexistingEntity = new FieldAccessJPAEntity(); unexistingEntity.setId(8888L); result = runtimeService.createProcessInstanceQuery().variableValueEquals("entityToQuery", unexistingEntity).singleResult(); assertNull(result); // All other operators are unsupported try { runtimeService.createProcessInstanceQuery().variableValueNotEquals("entityToQuery", entityToQuery).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("JPA entity variables can only be used in 'variableValueEquals'", ae.getMessage()); } try { runtimeService.createProcessInstanceQuery().variableValueGreaterThan("entityToQuery", entityToQuery).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("JPA entity variables can only be used in 'variableValueEquals'", ae.getMessage()); } try { runtimeService.createProcessInstanceQuery().variableValueGreaterThanOrEqual("entityToQuery", entityToQuery).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("JPA entity variables can only be used in 'variableValueEquals'", ae.getMessage()); } try { runtimeService.createProcessInstanceQuery().variableValueLessThan("entityToQuery", entityToQuery).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("JPA entity variables can only be used in 'variableValueEquals'", ae.getMessage()); } try { runtimeService.createProcessInstanceQuery().variableValueLessThanOrEqual("entityToQuery", entityToQuery).singleResult(); fail("Exception expected"); } catch (FlowableIllegalArgumentException ae) { assertTextPresent("JPA entity variables can only be used in 'variableValueEquals'", ae.getMessage()); } } @Deployment public void testUpdateJPAEntityValues() { setupJPAEntityToUpdate(); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("entityToUpdate", entityToUpdate); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateJPAValuesProcess", variables); // Servicetask in process 'UpdateJPAValuesProcess' should have set value on entityToUpdate. Object updatedEntity = runtimeService.getVariable(processInstance.getId(), "entityToUpdate"); assertTrue(updatedEntity instanceof FieldAccessJPAEntity); assertEquals("updatedValue", ((FieldAccessJPAEntity) updatedEntity).getValue()); } }
package owltools.gaf.inference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.geneontology.reasoner.ExpressionMaterializingReasoner; import org.geneontology.reasoner.ExpressionMaterializingReasonerFactory; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.AddImport; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLImportsDeclaration; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import org.semanticweb.owlapi.util.OWLClassExpressionVisitorAdapter; import owltools.gaf.Bioentity; import owltools.gaf.ExtensionExpression; import owltools.gaf.GafDocument; import owltools.gaf.GeneAnnotation; import owltools.graph.OWLGraphWrapper; import owltools.vocab.OBOUpperVocabulary; /** * Use a reasoner to find more specific named classes for annotations with extension expressions. * * see http://code.google.com/p/owltools/wiki/AnnotationExtensionFolding * @author cjm */ public class FoldBasedPredictor extends AbstractAnnotationPredictor implements AnnotationPredictor { private static final Logger LOG = Logger.getLogger(FoldBasedPredictor.class); private OWLReasoner reasoner = null; private Set<OWLClass> relevantClasses; private OWLObjectProperty partOf; private OWLObjectProperty occursIn; private Set<OWLObjectProperty> defaultProperties; private boolean isInitialized = false; private final boolean throwExceptions; public FoldBasedPredictor(GafDocument gafDocument, OWLGraphWrapper graph, boolean throwExceptions) { super(gafDocument, graph); this.throwExceptions = throwExceptions; isInitialized = init(); Logger.getLogger("org.semanticweb.elk").setLevel(Level.ERROR); } @Override public boolean isInitialized() { return isInitialized; } public boolean init() { OWLReasonerFactory reasonerFactory = new ElkReasonerFactory(); reasoner = reasonerFactory.createReasoner(getGraph().getSourceOntology()); boolean consistent = reasoner.isConsistent(); if (!consistent) { LOG.error("The ontology is not consistent. Impossible to make proper predictions."); if (throwExceptions) { throw new RuntimeException("The ontology is not consistent. Impossible to make proper predictions."); } return false; } relevantClasses = new HashSet<OWLClass>(); // add GO // biological process OWLClass bp = getGraph().getOWLClassByIdentifier("GO:0008150"); addRelevant(bp, reasoner, getGraph(), relevantClasses); // molecular function OWLClass mf = getGraph().getOWLClassByIdentifier("GO:0003674"); addRelevant(mf, reasoner, getGraph(), relevantClasses); // cellular component OWLClass cc = getGraph().getOWLClassByIdentifier("GO:0005575"); addRelevant(cc, reasoner, getGraph(), relevantClasses); // properties partOf = OBOUpperVocabulary.BFO_part_of.getObjectProperty(getGraph().getDataFactory()); occursIn = OBOUpperVocabulary.BFO_occurs_in.getObjectProperty(getGraph().getDataFactory()); defaultProperties = Collections.unmodifiableSet(new HashSet<OWLObjectProperty>(Arrays.asList(partOf, occursIn))); if (relevantClasses.isEmpty()) { LOG.error("No valid classes found for fold based prediction folding."); if (throwExceptions) { throw new RuntimeException("No valid classes found for fold based prediction folding."); } return false; } return true; } private static void addRelevant(OWLClass root, OWLReasoner r, OWLGraphWrapper g, Set<OWLClass> relevant) { if (root != null) { Set<OWLClass> candidates = r.getSubClasses(root, false).getFlattened(); for (OWLClass candidate : candidates) { // hack to restric to GO ids! String identifier = g.getIdentifier(candidate.getIRI()); if (identifier.startsWith("GO:")) { relevant.add(candidate); } } } } @Override public List<Prediction> predictForBioEntities(Map<Bioentity, ? extends Collection<GeneAnnotation>> annMap) { final List<Prediction> predictions = new ArrayList<Prediction>(); final OWLGraphWrapper g = getGraph(); final OWLDataFactory f = g.getDataFactory(); final OWLOntologyManager m = g.getManager(); // step 0: generate a throw away ontology which imports the source ontology final OWLOntology generatedContainer; try { generatedContainer = g.getManager().createOntology(IRI.generateDocumentIRI()); // import source OWLOntology source = g.getSourceOntology(); OWLOntologyID sourceId = source.getOntologyID(); OWLImportsDeclaration sourceImportDeclaration = f.getOWLImportsDeclaration(sourceId.getOntologyIRI()); m.applyChange(new AddImport(generatedContainer, sourceImportDeclaration)); } catch(Exception e) { String msg = "Could not setup container ontology"; LOG.error(msg, e); if (throwExceptions) { throw new RuntimeException(msg, e); } return predictions; } ExpressionMaterializingReasoner reasoner = null; try { // step 1: prepare ontology final Map<OWLClass, PredicationDataContainer> sourceData = new HashMap<OWLClass, PredicationDataContainer>(); final Map<Bioentity, Set<OWLClass>> allExistingAnnotations = new HashMap<Bioentity, Set<OWLClass>>(); final Map<Bioentity, Set<OWLClass>> allGeneratedClasses = generateAxioms(generatedContainer, annMap, allExistingAnnotations, sourceData); // step 2: reasoner reasoner = new ExpressionMaterializingReasonerFactory(new ElkReasonerFactory()).createReasoner(generatedContainer); reasoner.setIncludeImports(true); reasoner.materializeExpressions(defaultProperties); // step 3: find folded classes BioentityLoop: for(Entry<Bioentity, Set<OWLClass>> entry : allGeneratedClasses.entrySet()) { final Set<OWLClass> used = new HashSet<OWLClass>(); final Bioentity e = entry.getKey(); final Set<OWLClass> existing = allExistingAnnotations.get(e); final Set<OWLClass> generatedClasses = entry.getValue(); // step 3.1: check for direct equivalent classes final Set<OWLClass> checkForDirectSuper = new HashSet<OWLClass>(generatedClasses); for(OWLClass generated : generatedClasses) { Set<OWLClass> equivalents = reasoner.getEquivalentClasses(generated).getEntitiesMinus(generated); final PredicationDataContainer source = sourceData.get(generated); for (OWLClass equivalentCls : equivalents) { if (equivalentCls.isBottomEntity()) { // if the class is unsatisfiable skip the bioentity, no safe prediction possible LOG.warn("skipping folding prediction for '"+e.getId()+"' due unsatisfiable expression."); break BioentityLoop; } if (generatedClasses.contains(equivalentCls)) { continue; } if (relevantClasses.contains(equivalentCls) == false) { continue; } checkForDirectSuper.remove(generated); if (existing != null && existing.contains(equivalentCls)) { continue; } if (used.add(equivalentCls) && source != null) { Prediction prediction = getPrediction(source.ann, equivalentCls, e.getId(), source.ann.getCls()); prediction.setReason(generateReason(equivalentCls, source.cls, source.extensionExpression, source.expressions, source.evidence, g)); predictions.add(prediction); } } } // step 3.2: check for direct super classes (including default properties such as part_of and occurs_in), // but only for classes which did not have a named relevant equivalent class for(final OWLClass generated : checkForDirectSuper) { Set<OWLClass> parents = reasoner.getSuperClasses(generated, true).getFlattened(); final PredicationDataContainer source = sourceData.get(generated); for (final OWLClass parent : parents) { if (parent.isBuiltIn()) { continue; } if (generatedClasses.contains(parent)) { continue; } if (relevantClasses.contains(parent) == false) { continue; } if (existing != null && existing.contains(parent)) { continue; } if (used.add(parent) && source != null) { Prediction prediction = getPrediction(source.ann, parent, e.getId(), source.ann.getCls()); prediction.setReason(generateReason(parent, source.cls, source.extensionExpression, source.expressions, source.evidence, g)); predictions.add(prediction); } } // check also for occurs_in and part_of Set<OWLClassExpression> superClassesExpressions = reasoner.getSuperClassExpressions(generated, true); for (final OWLClassExpression ce : superClassesExpressions) { ce.accept(new OWLClassExpressionVisitorAdapter(){ @Override public void visit(OWLObjectSomeValuesFrom svf) { OWLClassExpression superClsExpr = svf.getFiller(); OWLObjectPropertyExpression p = svf.getProperty(); if(defaultProperties.contains(p) && superClsExpr.isAnonymous() == false) { final OWLClass cls = superClsExpr.asOWLClass(); if (cls.isBuiltIn()) { return; } if (relevantClasses.contains(cls) == false) { return; } if (existing != null && existing.contains(cls)) { return; } if (used.add(cls) && source != null) { Prediction prediction = getPrediction(source.ann, cls, e.getId(), source.ann.getCls()); prediction.setReason(generateReason(cls, source.cls, source.extensionExpression, source.expressions, source.evidence, g)); predictions.add(prediction); } } } }); } } } return predictions; } finally { if (reasoner != null) { reasoner.dispose(); } if (generatedContainer != null) { m.removeOntology(generatedContainer); } } } private static class PredicationDataContainer { final GeneAnnotation ann; final OWLClass cls; final List<ExtensionExpression> expressions; final OWLClassExpression extensionExpression; final String evidence; PredicationDataContainer(GeneAnnotation source, OWLClass annotatedCls, String evidence, OWLClassExpression extensionExpression, List<ExtensionExpression> expressions) { super(); this.ann = source; this.cls = annotatedCls; this.extensionExpression = extensionExpression; this.expressions = expressions; this.evidence = evidence; } } private Map<Bioentity, Set<OWLClass>> generateAxioms(OWLOntology generatedContainer, Map<Bioentity, ? extends Collection<GeneAnnotation>> annMap, Map<Bioentity, Set<OWLClass>> allExistingAnnotations, Map<OWLClass, PredicationDataContainer> sourceData) { final OWLGraphWrapper g = getGraph(); final OWLDataFactory f = g.getDataFactory(); final OWLOntologyManager m = g.getManager(); Map<Bioentity, Set<OWLClass>> allGeneratedClasses = new HashMap<Bioentity, Set<OWLClass>>(); for(Entry<Bioentity, ? extends Collection<GeneAnnotation>> entry : annMap.entrySet()) { Set<OWLClass> generatedClasses = new HashSet<OWLClass>(); Set<OWLClass> existingAnnotations = new HashSet<OWLClass>(); Bioentity e = entry.getKey(); for (GeneAnnotation ann : entry.getValue()) { // skip ND evidence annotations String evidenceString = ann.getShortEvidence(); if ("ND".equals(evidenceString)) { continue; } // parse annotation cls String annotatedToClassString = ann.getCls(); OWLClass annotatedToClass = g.getOWLClassByIdentifier(annotatedToClassString); if (annotatedToClass == null) { LOG.warn("Skipping annotation for prediction. Could not find cls for id: "+annotatedToClassString); continue; } // add annotation class (and its super classes as known annotation) existingAnnotations.add(annotatedToClass); existingAnnotations.addAll(reasoner.getSuperClasses(annotatedToClass, false).getFlattened()); // parse c16 expressions List<List<ExtensionExpression>> extensionExpressionGroups = ann.getExtensionExpressions(); if (extensionExpressionGroups != null && !extensionExpressionGroups.isEmpty()) { for (List<ExtensionExpression> group : extensionExpressionGroups) { Set<OWLClassExpression> units = new HashSet<OWLClassExpression>(); for (ExtensionExpression ext : group) { String extClsString = ext.getCls(); String extRelString = ext.getRelation(); OWLClass extCls = f.getOWLClass(g.getIRIByIdentifier(extClsString)); OWLObjectProperty extRel = g.getOWLObjectPropertyByIdentifier(extRelString); if (extRel == null) { continue; } units.add(f.getOWLObjectSomeValuesFrom(extRel, extCls)); } if (units.isEmpty()) { continue; } units.add(annotatedToClass); final OWLClassExpression groupExpression = f.getOWLObjectIntersectionOf(units); OWLClass generatedClass = f.getOWLClass(IRI.generateDocumentIRI()); OWLAxiom axiom = f.getOWLEquivalentClassesAxiom(generatedClass, groupExpression); m.addAxiom(generatedContainer, axiom); generatedClasses.add(generatedClass); sourceData.put(generatedClass, new PredicationDataContainer(ann, annotatedToClass, evidenceString, groupExpression, group)); } } } if (generatedClasses.isEmpty() == false) { allGeneratedClasses.put(e, generatedClasses); allExistingAnnotations.put(e, existingAnnotations); } } return allGeneratedClasses; } private String generateReason(OWLClass foldedClass, OWLClass annotatedToClass, OWLClassExpression groupExpression, List<ExtensionExpression> expressions, String evidence, OWLGraphWrapper g) { StringBuilder sb = new StringBuilder(); sb.append(g.getIdentifier(foldedClass)); sb.append('\t'); String foldedClassLabel = g.getLabel(foldedClass); if (foldedClassLabel != null) { sb.append(foldedClassLabel); } sb.append('\t'); sb.append(FoldBasedPredictor.class.getSimpleName()); sb.append('\t'); sb.append(g.getIdentifier(annotatedToClass)); sb.append('\t'); String annotatedToClassLabel = g.getLabel(annotatedToClass); if (annotatedToClassLabel != null) { sb.append(annotatedToClassLabel); } for(ExtensionExpression ext : expressions) { sb.append('\t'); sb.append(ext.getRelation()); sb.append('\t'); sb.append(ext.getCls()); sb.append('\t'); OWLClass extCls = g.getOWLClassByIdentifier(ext.getCls()); if (extCls != null) { String extClsLabel = g.getLabel(extCls); if (extClsLabel != null) { sb.append(extClsLabel); } } } sb.append('\t'); sb.append(evidence); return sb.toString(); } protected Prediction getPrediction(GeneAnnotation ann, OWLClass c, String bioentity, String with) { GeneAnnotation annP = new GeneAnnotation(ann); annP.setBioentity(bioentity); annP.setCls(getGraph().getIdentifier(c)); annP.setEvidence("IC", null); annP.setWithInfos(Collections.singleton(with)); Prediction prediction = new Prediction(annP); return prediction; } @Override public void dispose() { if (reasoner != null) { reasoner.dispose(); } } }
/* Copyright 1995-2015 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.core.geometry; import com.esri.core.geometry.VertexDescription.Semantics; import java.io.Serializable; /** * A Point is a zero-dimensional object that represents a specific (X,Y) * location in a two-dimensional XY-Plane. In case of Geographic Coordinate * Systems, the X coordinate is the longitude and the Y is the latitude. */ public final class Point extends Geometry implements Serializable { private static final long serialVersionUID = 2L;// TODO:remove as we use // writeReplace and // GeometrySerializer double[] m_attributes; // use doubles to store everything (long are bitcast) /** * Creates an empty 2D point. */ public Point() { m_description = VertexDescriptionDesignerImpl.getDefaultDescriptor2D(); } Point(VertexDescription vd) { if (vd == null) throw new IllegalArgumentException(); m_description = vd; } /** * Creates a 2D Point with specified X and Y coordinates. In case of * Geographic Coordinate Systems, the X coordinate is the longitude and the * Y is the latitude. * * @param x * The X coordinate of the new 2D point. * @param y * The Y coordinate of the new 2D point. */ public Point(double x, double y) { m_description = VertexDescriptionDesignerImpl.getDefaultDescriptor2D(); setXY(x, y); } public Point(Point2D pt) { m_description = VertexDescriptionDesignerImpl.getDefaultDescriptor2D(); setXY(pt); } /** * Creates a 3D point with specified X, Y and Z coordinates. In case of * Geographic Coordinate Systems, the X coordinate is the longitude and the * Y is the latitude. * * @param x * The X coordinate of the new 3D point. * @param y * The Y coordinate of the new 3D point. * @param z * The Z coordinate of the new 3D point. * */ public Point(double x, double y, double z) { m_description = VertexDescriptionDesignerImpl.getDefaultDescriptor2D(); Point3D pt = new Point3D(); pt.setCoords(x, y, z); setXYZ(pt); } /** * Returns XY coordinates of this point. */ public final Point2D getXY() { if (isEmptyImpl()) throw new GeometryException( "This operation should not be performed on an empty geometry."); Point2D pt = new Point2D(); pt.setCoords(m_attributes[0], m_attributes[1]); return pt; } /** * Returns XY coordinates of this point. */ public final void getXY(Point2D pt) { if (isEmptyImpl()) throw new GeometryException( "This operation should not be performed on an empty geometry."); pt.setCoords(m_attributes[0], m_attributes[1]); } /** * Sets the XY coordinates of this point. param pt The point to create the X * and Y coordinate from. */ public final void setXY(Point2D pt) { _touch(); setXY(pt.x, pt.y); } /** * Returns XYZ coordinates of the point. Z will be set to 0 if Z is missing. */ Point3D getXYZ() { if (isEmptyImpl()) throw new GeometryException( "This operation should not be performed on an empty geometry."); Point3D pt = new Point3D(); pt.x = m_attributes[0]; pt.y = m_attributes[1]; if (m_description.hasZ()) pt.z = m_attributes[2]; else pt.z = VertexDescription.getDefaultValue(Semantics.Z); return pt; } /** * Sets the XYZ coordinates of this point. * * @param pt * The point to create the XYZ coordinate from. */ void setXYZ(Point3D pt) { _touch(); boolean bHasZ = hasAttribute(Semantics.Z); if (!bHasZ && !VertexDescription.isDefaultValue(Semantics.Z, pt.z)) {// add // Z // only // if // pt.z // is // not // a // default // value. addAttribute(Semantics.Z); bHasZ = true; } if (m_attributes == null) _setToDefault(); m_attributes[0] = pt.x; m_attributes[1] = pt.y; if (bHasZ) m_attributes[2] = pt.z; } /** * Returns the X coordinate of the point. */ public final double getX() { if (isEmptyImpl()) throw new GeometryException( "This operation should not be performed on an empty geometry."); return m_attributes[0]; } /** * Sets the X coordinate of the point. * * @param x * The X coordinate to be set for this point. */ public void setX(double x) { setAttribute(Semantics.POSITION, 0, x); } /** * Returns the Y coordinate of this point. */ public final double getY() { if (isEmptyImpl()) throw new GeometryException( "This operation should not be performed on an empty geometry."); return m_attributes[1]; } /** * Sets the Y coordinate of this point. * * @param y * The Y coordinate to be set for this point. */ public void setY(double y) { setAttribute(Semantics.POSITION, 1, y); } /** * Returns the Z coordinate of this point. */ public double getZ() { return getAttributeAsDbl(Semantics.Z, 0); } /** * Sets the Z coordinate of this point. * * @param z * The Z coordinate to be set for this point. */ public void setZ(double z) { setAttribute(Semantics.Z, 0, z); } /** * Returns the attribute M of this point. */ public double getM() { return getAttributeAsDbl(Semantics.M, 0); } /** * Sets the M coordinate of this point. * * @param m * The M coordinate to be set for this point. */ public void setM(double m) { setAttribute(Semantics.M, 0, m); } /** * Returns the ID of this point. */ public int getID() { return getAttributeAsInt(Semantics.ID, 0); } /** * Sets the ID of this point. * * @param id * The ID of this point. */ public void setID(int id) { setAttribute(Semantics.ID, 0, id); } /** * Returns value of the given vertex attribute's ordinate. * * @param semantics * The attribute semantics. * @param ordinate * The attribute's ordinate. For example, the Y coordinate of the * NORMAL has ordinate of 1. * @return The ordinate as double value. */ public double getAttributeAsDbl(int semantics, int ordinate) { if (isEmptyImpl()) throw new GeometryException( "This operation was performed on an Empty Geometry."); int ncomps = VertexDescription.getComponentCount(semantics); if (ordinate >= ncomps) throw new IndexOutOfBoundsException(); int attributeIndex = m_description.getAttributeIndex(semantics); if (attributeIndex >= 0) return m_attributes[m_description ._getPointAttributeOffset(attributeIndex) + ordinate]; else return VertexDescription.getDefaultValue(semantics); } /** * Returns value of the given vertex attribute's ordinate. The ordinate is * always 0 because integer attributes always have one component. * * @param semantics * The attribute semantics. * @param ordinate * The attribute's ordinate. For example, the y coordinate of the * NORMAL has ordinate of 1. * @return The ordinate value truncated to a 32 bit integer value. */ public int getAttributeAsInt(int semantics, int ordinate) { if (isEmptyImpl()) throw new GeometryException( "This operation was performed on an Empty Geometry."); int ncomps = VertexDescription.getComponentCount(semantics); if (ordinate >= ncomps) throw new IndexOutOfBoundsException(); int attributeIndex = m_description.getAttributeIndex(semantics); if (attributeIndex >= 0) return (int) m_attributes[m_description ._getPointAttributeOffset(attributeIndex) + ordinate]; else return (int) VertexDescription.getDefaultValue(semantics); } /** * Sets the value of the attribute. * * @param semantics * The attribute semantics. * @param ordinate * The ordinate of the attribute. * @param value * Is the array to write values to. The attribute type and the * number of elements must match the persistence type, as well as * the number of components of the attribute. */ public void setAttribute(int semantics, int ordinate, double value) { _touch(); int ncomps = VertexDescription.getComponentCount(semantics); if (ncomps < ordinate) throw new IndexOutOfBoundsException(); int attributeIndex = m_description.getAttributeIndex(semantics); if (attributeIndex < 0) { addAttribute(semantics); attributeIndex = m_description.getAttributeIndex(semantics); } if (m_attributes == null) _setToDefault(); m_attributes[m_description._getPointAttributeOffset(attributeIndex) + ordinate] = value; } public void setAttribute(int semantics, int ordinate, int value) { setAttribute(semantics, ordinate, (double) value); } @Override public Geometry.Type getType() { return Type.Point; } @Override public int getDimension() { return 0; } @Override public void setEmpty() { _touch(); if (m_attributes != null) { m_attributes[0] = NumberUtils.NaN(); m_attributes[1] = NumberUtils.NaN(); } } @Override protected void _assignVertexDescriptionImpl(VertexDescription newDescription) { if (m_attributes == null) { m_description = newDescription; return; } int[] mapping = VertexDescriptionDesignerImpl.mapAttributes(newDescription, m_description); double[] newAttributes = new double[newDescription._getTotalComponents()]; int j = 0; for (int i = 0, n = newDescription.getAttributeCount(); i < n; i++) { int semantics = newDescription.getSemantics(i); int nords = VertexDescription.getComponentCount(semantics); if (mapping[i] == -1) { double d = VertexDescription.getDefaultValue(semantics); for (int ord = 0; ord < nords; ord++) { newAttributes[j] = d; j++; } } else { int m = mapping[i]; int offset = m_description._getPointAttributeOffset(m); for (int ord = 0; ord < nords; ord++) { newAttributes[j] = m_attributes[offset]; j++; offset++; } } } m_attributes = newAttributes; m_description = newDescription; } /** * Sets the Point to a default, non-empty state. */ void _setToDefault() { resizeAttributes(m_description._getTotalComponents()); Point.attributeCopy(m_description._getDefaultPointAttributes(), m_attributes, m_description._getTotalComponents()); m_attributes[0] = NumberUtils.NaN(); m_attributes[1] = NumberUtils.NaN(); } @Override public void applyTransformation(Transformation2D transform) { if (isEmptyImpl()) return; Point2D pt = getXY(); transform.transform(pt, pt); setXY(pt); } @Override void applyTransformation(Transformation3D transform) { if (isEmptyImpl()) return; addAttribute(Semantics.Z); Point3D pt = getXYZ(); setXYZ(transform.transform(pt)); } @Override public void copyTo(Geometry dst) { if (dst.getType() != Type.Point) throw new IllegalArgumentException(); Point pointDst = (Point) dst; dst._touch(); if (m_attributes == null) { pointDst.setEmpty(); pointDst.m_attributes = null; pointDst.assignVertexDescription(m_description); } else { pointDst.assignVertexDescription(m_description); pointDst.resizeAttributes(m_description._getTotalComponents()); attributeCopy(m_attributes, pointDst.m_attributes, m_description._getTotalComponents()); } } @Override public Geometry createInstance() { Point point = new Point(m_description); return point; } @Override public boolean isEmpty() { return isEmptyImpl(); } final boolean isEmptyImpl() { return ((m_attributes == null) || NumberUtils.isNaN(m_attributes[0]) || NumberUtils .isNaN(m_attributes[1])); } @Override public void queryEnvelope(Envelope env) { env.setEmpty(); if (m_description != env.m_description) env.assignVertexDescription(m_description); env.merge(this); } @Override public void queryEnvelope2D(Envelope2D env) { if (isEmptyImpl()) { env.setEmpty(); return; } env.xmin = m_attributes[0]; env.ymin = m_attributes[1]; env.xmax = m_attributes[0]; env.ymax = m_attributes[1]; } @Override void queryEnvelope3D(Envelope3D env) { if (isEmptyImpl()) { env.setEmpty(); return; } Point3D pt = getXYZ(); env.xmin = pt.x; env.ymin = pt.y; env.zmin = pt.z; env.xmax = pt.x; env.ymax = pt.y; env.zmax = pt.z; } @Override public Envelope1D queryInterval(int semantics, int ordinate) { Envelope1D env = new Envelope1D(); if (isEmptyImpl()) { env.setEmpty(); return env; } double s = getAttributeAsDbl(semantics, ordinate); env.vmin = s; env.vmax = s; return env; } private void resizeAttributes(int newSize) { if (m_attributes == null) { m_attributes = new double[newSize]; } else if (m_attributes.length < newSize) { double[] newbuffer = new double[newSize]; System.arraycopy(m_attributes, 0, newbuffer, 0, m_attributes.length); m_attributes = newbuffer; } } static void attributeCopy(double[] src, double[] dst, int count) { if (count > 0) System.arraycopy(src, 0, dst, 0, count); } /** * Set the X and Y coordinate of the point. * * @param x * X coordinate of the point. * @param y * Y coordinate of the point. */ public void setXY(double x, double y) { _touch(); if (m_attributes == null) _setToDefault(); m_attributes[0] = x; m_attributes[1] = y; } /** * Returns TRUE when this geometry has exactly same type, properties, and * coordinates as the other geometry. */ @Override public boolean equals(Object _other) { if (_other == this) return true; if (!(_other instanceof Point)) return false; Point otherPt = (Point) _other; if (m_description != otherPt.m_description) return false; if (isEmptyImpl()) if (otherPt.isEmptyImpl()) return true; else return false; for (int i = 0, n = m_description._getTotalComponents(); i < n; i++) if (m_attributes[i] != otherPt.m_attributes[i]) return false; return true; } /** * Returns the hash code for the point. */ @Override public int hashCode() { int hashCode = m_description.hashCode(); if (!isEmptyImpl()) { for (int i = 0, n = m_description._getTotalComponents(); i < n; i++) { long bits = Double.doubleToLongBits(m_attributes[i]); int hc = (int) (bits ^ (bits >>> 32)); hashCode = NumberUtils.hash(hashCode, hc); } } return hashCode; } @Override public Geometry getBoundary() { return null; } @Override public void replaceNaNs(int semantics, double value) { addAttribute(semantics); if (isEmpty()) return; int ncomps = VertexDescription.getComponentCount(semantics); for (int i = 0; i < ncomps; i++) { double v = getAttributeAsDbl(semantics, i); if (Double.isNaN(v)) setAttribute(semantics, i, value); } } }
/* * 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 java.nio; /** A buffer of doubles. * <p> * A double buffer can be created in either one of the following ways: * </p> * <ul> * <li>{@link #allocate(int) Allocate} a new double array and create a buffer based on it;</li> * <li>{@link #wrap(double[]) Wrap} an existing double array to create a new buffer;</li> * <li>Use {@link java.nio.ByteBuffer#asDoubleBuffer() ByteBuffer.asDoubleBuffer} to create a double buffer based on a byte buffer. * </li> * </ul> * * @since Android 1.0 */ public abstract class DoubleBuffer extends Buffer implements Comparable<DoubleBuffer> { /** Creates a double buffer based on a newly allocated double array. * * @param capacity the capacity of the new buffer. * @return the created double buffer. * @throws IllegalArgumentException if {@code capacity} is less than zero. * @since Android 1.0 */ public static DoubleBuffer allocate (int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } return BufferFactory.newDoubleBuffer(capacity); } /** Creates a new double buffer by wrapping the given double array. * <p> * Calling this method has the same effect as {@code wrap(array, 0, array.length)}. * </p> * * @param array the double array which the new buffer will be based on. * @return the created double buffer. * @since Android 1.0 */ public static DoubleBuffer wrap (double[] array) { return wrap(array, 0, array.length); } /** Creates a new double buffer by wrapping the given double array. * <p> * The new buffer's position will be {@code start}, limit will be {@code start + len}, capacity will be the length of the array. * </p> * * @param array the double array which the new buffer will be based on. * @param start the start index, must not be negative and not greater than {@code array.length}. * @param len the length, must not be negative and not greater than {@code array.length - start}. * @return the created double buffer. * @exception IndexOutOfBoundsException if either {@code start} or {@code len} is invalid. * @since Android 1.0 */ public static DoubleBuffer wrap (double[] array, int start, int len) { int length = array.length; if (start < 0 || len < 0 || (long)start + (long)len > length) { throw new IndexOutOfBoundsException(); } DoubleBuffer buf = BufferFactory.newDoubleBuffer(array); buf.position = start; buf.limit = start + len; return buf; } /** Constructs a {@code DoubleBuffer} with given capacity. * * @param capacity the capacity of the buffer. */ DoubleBuffer (int capacity) { super(capacity); } /** Returns the double array which this buffer is based on, if there is one. * * @return the double array which this buffer is based on. * @exception ReadOnlyBufferException if this buffer is based on an array but it is read-only. * @exception UnsupportedOperationException if this buffer is not based on an array. * @since Android 1.0 */ public final double[] array () { return protectedArray(); } /** Returns the offset of the double array which this buffer is based on, if there is one. * <p> * The offset is the index of the array corresponding to the zero position of the buffer. * </p> * * @return the offset of the double array which this buffer is based on. * @exception ReadOnlyBufferException if this buffer is based on an array, but it is read-only. * @exception UnsupportedOperationException if this buffer is not based on an array. * @since Android 1.0 */ public final int arrayOffset () { return protectedArrayOffset(); } /** Returns a read-only buffer that shares its content with this buffer. * <p> * The returned buffer is guaranteed to be a new instance, even if this buffer is read-only itself. The new buffer's position, * limit, capacity and mark are the same as this buffer's. * </p> * <p> * The new buffer shares its content with this buffer, which means that this buffer's change of content will be visible to the * new buffer. The two buffer's position, limit and mark are independent. * </p> * * @return a read-only version of this buffer. * @since Android 1.0 */ public abstract DoubleBuffer asReadOnlyBuffer (); /** Compacts this double buffer. * <p> * The remaining doubles will be moved to the head of the buffer, staring from position zero. Then the position is set to * {@code remaining()}; the limit is set to capacity; the mark is cleared. * </p> * * @return this buffer. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public abstract DoubleBuffer compact (); /** Compare the remaining doubles of this buffer to another double buffer's remaining doubles. * * @param otherBuffer another double buffer. * @return a negative value if this is less than {@code other}; 0 if this equals to {@code other}; a positive value if this is * greater than {@code other}. * @exception ClassCastException if {@code other} is not a double buffer. * @since Android 1.0 */ public int compareTo (DoubleBuffer otherBuffer) { int compareRemaining = (remaining() < otherBuffer.remaining()) ? remaining() : otherBuffer.remaining(); int thisPos = position; int otherPos = otherBuffer.position; // BEGIN android-changed double thisDouble, otherDouble; while (compareRemaining > 0) { thisDouble = get(thisPos); otherDouble = otherBuffer.get(otherPos); // checks for double and NaN inequality if ((thisDouble != otherDouble) && ((thisDouble == thisDouble) || (otherDouble == otherDouble))) { return thisDouble < otherDouble ? -1 : 1; } thisPos++; otherPos++; compareRemaining--; } // END android-changed return remaining() - otherBuffer.remaining(); } /** Returns a duplicated buffer that shares its content with this buffer. * <p> * The duplicated buffer's position, limit, capacity and mark are the same as this buffer's. The duplicated buffer's read-only * property and byte order are the same as this buffer's, too. * </p> * <p> * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the * other. The two buffer's position, limit and mark are independent. * </p> * * @return a duplicated buffer that shares its content with this buffer. * @since Android 1.0 */ public abstract DoubleBuffer duplicate (); /** Checks whether this double buffer is equal to another object. * <p> * If {@code other} is not a double buffer then {@code false} is returned. Two double buffers are equal if and only if their * remaining doubles are exactly the same. Position, limit, capacity and mark are not considered. * </p> * * @param other the object to compare with this double buffer. * @return {@code true} if this double buffer is equal to {@code other}, {@code false} otherwise. * @since Android 1.0 */ public boolean equals (Object other) { if (!(other instanceof DoubleBuffer)) { return false; } DoubleBuffer otherBuffer = (DoubleBuffer)other; if (remaining() != otherBuffer.remaining()) { return false; } int myPosition = position; int otherPosition = otherBuffer.position; boolean equalSoFar = true; while (equalSoFar && (myPosition < limit)) { equalSoFar = get(myPosition++) == otherBuffer.get(otherPosition++); } return equalSoFar; } /** Returns the double at the current position and increases the position by 1. * * @return the double at the current position. * @exception BufferUnderflowException if the position is equal or greater than limit. * @since Android 1.0 */ public abstract double get (); /** Reads doubles from the current position into the specified double array and increases the position by the number of doubles * read. * <p> * Calling this method has the same effect as {@code get(dest, 0, dest.length)}. * </p> * * @param dest the destination double array. * @return this buffer. * @exception BufferUnderflowException if {@code dest.length} is greater than {@code remaining()}. * @since Android 1.0 */ public DoubleBuffer get (double[] dest) { return get(dest, 0, dest.length); } /** Reads doubles from the current position into the specified double array, starting from the specified offset, and increases * the position by the number of doubles read. * * @param dest the target double array. * @param off the offset of the double array, must not be negative and not greater than {@code dest.length}. * @param len the number of doubles to read, must be no less than zero and not greater than {@code dest.length - off}. * @return this buffer. * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. * @exception BufferUnderflowException if {@code len} is greater than {@code remaining()}. * @since Android 1.0 */ public DoubleBuffer get (double[] dest, int off, int len) { int length = dest.length; if (off < 0 || len < 0 || (long)off + (long)len > length) { throw new IndexOutOfBoundsException(); } if (len > remaining()) { throw new BufferUnderflowException(); } for (int i = off; i < off + len; i++) { dest[i] = get(); } return this; } /** Returns a double at the specified index; the position is not changed. * * @param index the index, must not be negative and less than limit. * @return a double at the specified index. * @exception IndexOutOfBoundsException if index is invalid. * @since Android 1.0 */ public abstract double get (int index); /** Indicates whether this buffer is based on a double array and is read/write. * * @return {@code true} if this buffer is based on a double array and provides read/write access, {@code false} otherwise. * @since Android 1.0 */ public final boolean hasArray () { return protectedHasArray(); } // /** // * Calculates this buffer's hash code from the remaining chars. The // * position, limit, capacity and mark don't affect the hash code. // * // * @return the hash code calculated from the remaining chars. // * @since Android 1.0 // */ // public int hashCode() { // int myPosition = position; // int hash = 0; // long l; // while (myPosition < limit) { // l = Double.doubleToLongBits(get(myPosition++)); // hash = hash + ((int) l) ^ ((int) (l >> 32)); // } // return hash; // } /** Indicates whether this buffer is direct. A direct buffer will try its best to take advantage of native memory APIs and it * may not stay in the Java heap, so it is not affected by garbage collection. * <p> * A double buffer is direct if it is based on a byte buffer and the byte buffer is direct. * </p> * * @return {@code true} if this buffer is direct, {@code false} otherwise. * @since Android 1.0 */ public abstract boolean isDirect (); /** Returns the byte order used by this buffer when converting doubles from/to bytes. * <p> * If this buffer is not based on a byte buffer, then this always returns the platform's native byte order. * </p> * * @return the byte order used by this buffer when converting doubles from/to bytes. * @since Android 1.0 */ public abstract ByteOrder order (); /** Child class implements this method to realize {@code array()}. * * @see #array() */ abstract double[] protectedArray (); /** Child class implements this method to realize {@code arrayOffset()}. * * @see #arrayOffset() */ abstract int protectedArrayOffset (); /** Child class implements this method to realize {@code hasArray()}. * * @see #hasArray() */ abstract boolean protectedHasArray (); /** Writes the given double to the current position and increases the position by 1. * * @param d the double to write. * @return this buffer. * @exception BufferOverflowException if position is equal or greater than limit. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public abstract DoubleBuffer put (double d); /** Writes doubles from the given double array to the current position and increases the position by the number of doubles * written. * <p> * Calling this method has the same effect as {@code put(src, 0, src.length)}. * </p> * * @param src the source double array. * @return this buffer. * @exception BufferOverflowException if {@code remaining()} is less than {@code src.length}. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public final DoubleBuffer put (double[] src) { return put(src, 0, src.length); } /** Writes doubles from the given double array, starting from the specified offset, to the current position and increases the * position by the number of doubles written. * * @param src the source double array. * @param off the offset of double array, must not be negative and not greater than {@code src.length}. * @param len the number of doubles to write, must be no less than zero and not greater than {@code src.length - off}. * @return this buffer. * @exception BufferOverflowException if {@code remaining()} is less than {@code len}. * @exception IndexOutOfBoundsException if either {@code off} or {@code len} is invalid. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public DoubleBuffer put (double[] src, int off, int len) { int length = src.length; if (off < 0 || len < 0 || (long)off + (long)len > length) { throw new IndexOutOfBoundsException(); } if (len > remaining()) { throw new BufferOverflowException(); } for (int i = off; i < off + len; i++) { put(src[i]); } return this; } /** Writes all the remaining doubles of the {@code src} double buffer to this buffer's current position, and increases both * buffers' position by the number of doubles copied. * * @param src the source double buffer. * @return this buffer. * @exception BufferOverflowException if {@code src.remaining()} is greater than this buffer's {@code remaining()}. * @exception IllegalArgumentException if {@code src} is this buffer. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public DoubleBuffer put (DoubleBuffer src) { if (src == this) { throw new IllegalArgumentException(); } if (src.remaining() > remaining()) { throw new BufferOverflowException(); } double[] doubles = new double[src.remaining()]; src.get(doubles); put(doubles); return this; } /** Write a double to the specified index of this buffer and the position is not changed. * * @param index the index, must not be negative and less than the limit. * @param d the double to write. * @return this buffer. * @exception IndexOutOfBoundsException if index is invalid. * @exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. * @since Android 1.0 */ public abstract DoubleBuffer put (int index, double d); /** Returns a sliced buffer that shares its content with this buffer. * <p> * The sliced buffer's capacity will be this buffer's {@code remaining()}, and its zero position will correspond to this * buffer's current position. The new buffer's position will be 0, limit will be its capacity, and its mark is cleared. The new * buffer's read-only property and byte order are the same as this buffer's. * </p> * <p> * The new buffer shares its content with this buffer, which means either buffer's change of content will be visible to the * other. The two buffer's position, limit and mark are independent. * </p> * * @return a sliced buffer that shares its content with this buffer. * @since Android 1.0 */ public abstract DoubleBuffer slice (); /** Returns a string representing the state of this double buffer. * * @return A string representing the state of this double buffer. * @since Android 1.0 */ public String toString () { StringBuffer buf = new StringBuffer(); buf.append(getClass().getName()); buf.append(", status: capacity="); //$NON-NLS-1$ buf.append(capacity()); buf.append(" position="); //$NON-NLS-1$ buf.append(position()); buf.append(" limit="); //$NON-NLS-1$ buf.append(limit()); return buf.toString(); } }
package com.redhat.ceylon.ide.netbeans; import org.eclipse.ceylon.cmr.api.ArtifactContext; import org.eclipse.ceylon.cmr.api.RepositoryManager; import org.eclipse.ceylon.cmr.api.RepositoryManagerBuilder; import org.eclipse.ceylon.cmr.impl.CMRJULLogger; import org.eclipse.ceylon.cmr.impl.DefaultRepository; import org.eclipse.ceylon.cmr.impl.FileContentStore; import org.eclipse.ceylon.cmr.impl.FlatRepository; import org.eclipse.ceylon.common.Constants; import org.eclipse.ceylon.compiler.java.runtime.metamodel.Metamodel; import org.eclipse.ceylon.model.cmr.ArtifactResult; import org.eclipse.ceylon.model.cmr.ArtifactResultType; import org.eclipse.ceylon.model.cmr.Exclusion; import org.eclipse.ceylon.model.cmr.ModuleScope; import org.eclipse.ceylon.model.cmr.PathFilter; import org.eclipse.ceylon.model.cmr.Repository; import org.eclipse.ceylon.model.cmr.VisibilityType; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.math.BigInteger; import java.net.Proxy; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import java.util.regex.Pattern; import org.openide.modules.Dependency; import org.openide.modules.InstalledFileLocator; import org.openide.modules.ModuleInfo; import org.openide.modules.Modules; import org.openide.modules.OnStart; import org.openide.util.Exceptions; import org.openide.util.Lookup; @OnStart public class PluginStartup implements Runnable { private static final Pattern moduleArchivePatternCar = Pattern.compile("([^\\-]+)-(.+)\\.(c|C)ar"); private static final Pattern moduleArchivePatternJar = Pattern.compile("(.+)-([^\\-]+)\\.(j|J)ar"); private static final Map<String, String> registeredModules = new HashMap<>(); private static final String MODULE_NAME = "com.redhat.ceylon.ide.netbeans"; private final FilenameFilter archivesFilter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".car") || name.endsWith(".jar"); } }; private final FileFilter directoryFilter = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }; @Override public void run() { registerCeylonModules(); registerNetbeansModules(); } private void registerNetbeansModules() { final Modules modules = Lookup.getDefault().lookup(Modules.class); ModuleInfo mod = modules.findCodeNameBase(MODULE_NAME); final Set<Dependency> deps = mod.getDependencies(); for (Dependency dep : deps) { String depName = dep.getName(); int slash = depName.indexOf('/'); if (slash > 0) { depName = depName.substring(0, slash); } ModuleInfo depInfo = modules.findCodeNameBase(depName); if (depInfo == null) { Logger.getLogger(getClass().getName()).warning( "Can't find dependency info for module " + depName); } else { try { Method meth = depInfo.getClass().getDeclaredMethod("getJarFile"); meth.setAccessible(true); File jarFile = (File) meth.invoke(depInfo); registerNetbeansModule(jarFile, depName.replaceAll("-", ".")); } catch (ReflectiveOperationException ex) { // TODO look for JARs in platform/core and platform/lib Logger.getLogger(getClass().getName()).warning( "Can't get JAR file for module " + depName); } } } } private void registerNetbeansModule(final File jar, final String moduleName) { ArtifactResult artifactResult = new ArtifactResult() { @Override public String name() { return moduleName; } @Override public String version() { return "current"; } @Override public ArtifactResultType type() { return ArtifactResultType.CEYLON; } @Override public VisibilityType visibilityType() { return VisibilityType.STRICT; } @Override public File artifact() { return jar; } @Override public PathFilter filter() { return null; } @Override public List<ArtifactResult> dependencies() { return Collections.emptyList(); } @Override public String repositoryDisplayString() { return null; } @Override public Repository repository() { return null; } @Override public String namespace() { return null; } @Override public boolean optional() { return false; } @Override public boolean exported() { return false; } @Override public ModuleScope moduleScope() { return null; } @Override public List<Exclusion> getExclusions() { return Collections.emptyList(); } @Override public String groupId() { return null; } @Override public String artifactId() { return moduleName; } @Override public String classifier() { return null; } }; registerModule(artifactResult, getClass().getClassLoader()); } private void registerCeylonModules() throws RuntimeException { File archiveDirectory = getDirectory("ceylon/embeddedRepo"); File embeddedDist = getDirectory("ceylon/embeddedDist/repo"); Logger.getLogger("PluginStartup").info("Scanning archives in " + archiveDirectory + " and " + embeddedDist); RepositoryManagerBuilder builder = new RepositoryManagerBuilder( archiveDirectory, new CMRJULLogger(), true, Constants.DEFAULT_TIMEOUT, Proxy.NO_PROXY); FileContentStore structureBuilder = new FileContentStore(archiveDirectory); builder.addRepository(new FlatRepository(structureBuilder.createRoot())); structureBuilder = new FileContentStore(embeddedDist); builder.addRepository(new DefaultRepository(structureBuilder.createRoot())); RepositoryManager repoManager = builder.buildRepository(); for (File file : getArchives(archiveDirectory, embeddedDist)) { File dir = file.getParentFile(); String name = file.getName(); String moduleName; String moduleVersion; String moduleType; if (name.endsWith(".car") || name.endsWith(".jar")){ // Use the repo layout to determine name and version moduleVersion = dir.getName(); int versionPos = name.indexOf(moduleVersion); moduleName = name.substring(0, versionPos - 1); moduleType = name.endsWith(".car") ? ArtifactContext.CAR : ArtifactContext.JAR; } else { continue; } ArtifactContext ctx = new ArtifactContext( null, moduleName, moduleVersion, moduleType ); ArtifactResult result = repoManager.getArtifactResult(ctx); if (result == null) { throw new RuntimeException("Ceylon Metamodel Registering failed : module '" + ctx.getName() + "' could not be registered."); } else { registerModule(result, getClass().getClassLoader()); } } } private List<File> getArchives(File archiveDirectory, File embeddedDist) { List<File> archives = new ArrayList<>(); visitDirectory(archiveDirectory, archives); visitDirectory(embeddedDist, archives); return archives; } private void visitDirectory(File directory, List<File> archives) { archives.addAll(Arrays.asList(directory.listFiles(archivesFilter))); for (File subdir : directory.listFiles(directoryFilter)) { visitDirectory(subdir, archives); } } private void registerModule(ArtifactResult moduleArtifact, ClassLoader classLoader) { String artifactFileName = moduleArtifact.artifact().getName(); String artifactMD5 = ""; try { artifactMD5 = generateBufferedHash(moduleArtifact.artifact()); } catch (NoSuchAlgorithmException | IOException e) { Exceptions.printStackTrace(e); } String alreadyRegisteredModuleMD5 = registeredModules.get(artifactFileName); if (alreadyRegisteredModuleMD5 == null) { Metamodel.loadModule(moduleArtifact.name(), moduleArtifact.version(), moduleArtifact, classLoader); registeredModules.put(artifactFileName, artifactMD5); } else if (alreadyRegisteredModuleMD5.isEmpty() || !alreadyRegisteredModuleMD5.equals(artifactMD5)) { throw new RuntimeException("Ceylon Metamodel Registering failed : the module '" + moduleArtifact.name() + "/" + moduleArtifact.version() + "' cannot be registered since it has already been registered " + "by another plugin with a different binary archive"); } // In other cases, we don't need to register again } private String generateBufferedHash(File file) throws NoSuchAlgorithmException, IOException { MessageDigest md = MessageDigest.getInstance("MD5"); InputStream is = new FileInputStream(file); byte[] buffer = new byte[8192]; int read; while ((read = is.read(buffer)) > 0) md.update(buffer, 0, read); byte[] md5 = md.digest(); BigInteger bi = new BigInteger(1, md5); return bi.toString(16); } private File getDirectory(String name) { File dir = InstalledFileLocator.getDefault().locate( name, MODULE_NAME, false); if (dir == null || !dir.exists() || !dir.isDirectory()) { throw new RuntimeException("Could not find installed directory " + name); } return dir; } }
// Copyright 2014 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.analysis; import static com.google.devtools.build.lib.analysis.ExtraActionUtils.createExtraActionProvider; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.constraints.ConstraintSemantics; import com.google.devtools.build.lib.analysis.constraints.EnvironmentCollection; import com.google.devtools.build.lib.analysis.constraints.SupportedEnvironments; import com.google.devtools.build.lib.analysis.constraints.SupportedEnvironmentsProvider; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.packages.ClassObjectConstructor; import com.google.devtools.build.lib.packages.NativeClassObjectConstructor; import com.google.devtools.build.lib.packages.SkylarkClassObject; import com.google.devtools.build.lib.packages.Target; import com.google.devtools.build.lib.packages.TargetUtils; import com.google.devtools.build.lib.rules.test.ExecutionInfoProvider; import com.google.devtools.build.lib.rules.test.InstrumentedFilesProvider; import com.google.devtools.build.lib.rules.test.TestActionBuilder; import com.google.devtools.build.lib.rules.test.TestEnvironmentProvider; import com.google.devtools.build.lib.rules.test.TestProvider; import com.google.devtools.build.lib.rules.test.TestProvider.TestParams; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.Type; import com.google.devtools.build.lib.util.Preconditions; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; /** * Builder class for analyzed rule instances. * * <p>This is used to tell Bazel which {@link TransitiveInfoProvider}s are produced by the analysis * of a configured target. For more information about analysis, see * {@link com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory}. * * @see com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory */ public final class RuleConfiguredTargetBuilder { private final RuleContext ruleContext; private final TransitiveInfoProviderMapBuilder providersBuilder = new TransitiveInfoProviderMapBuilder(); private final Map<String, NestedSetBuilder<Artifact>> outputGroupBuilders = new TreeMap<>(); /** These are supported by all configured targets and need to be specially handled. */ private NestedSet<Artifact> filesToBuild = NestedSetBuilder.emptySet(Order.STABLE_ORDER); private RunfilesSupport runfilesSupport; private Artifact executable; private ImmutableSet<ActionAnalysisMetadata> actionsWithoutExtraAction = ImmutableSet.of(); public RuleConfiguredTargetBuilder(RuleContext ruleContext) { this.ruleContext = ruleContext; add(LicensesProvider.class, LicensesProviderImpl.of(ruleContext)); add(VisibilityProvider.class, new VisibilityProviderImpl(ruleContext.getVisibility())); } /** * Constructs the RuleConfiguredTarget instance based on the values set for this Builder. */ public ConfiguredTarget build() { if (ruleContext.getConfiguration().enforceConstraints()) { checkConstraints(); } if (ruleContext.hasErrors()) { return null; } FilesToRunProvider filesToRunProvider = new FilesToRunProvider( getFilesToRun(runfilesSupport, filesToBuild), runfilesSupport, executable); addProvider(new FileProvider(filesToBuild)); addProvider(filesToRunProvider); if (runfilesSupport != null) { // If a binary is built, build its runfiles, too addOutputGroup( OutputGroupProvider.HIDDEN_TOP_LEVEL, runfilesSupport.getRunfilesMiddleman()); } else if (providersBuilder.contains(RunfilesProvider.class)) { // If we don't have a RunfilesSupport (probably because this is not a binary rule), we still // want to build the files this rule contributes to runfiles of dependent rules so that we // report an error if one of these is broken. // // Note that this is a best-effort thing: there is .getDataRunfiles() and all the language- // specific *RunfilesProvider classes, which we don't add here for reasons that are lost in // the mists of time. addOutputGroup( OutputGroupProvider.HIDDEN_TOP_LEVEL, providersBuilder .getProvider(RunfilesProvider.class) .getDefaultRunfiles() .getAllArtifacts()); } // Create test action and artifacts if target was successfully initialized // and is a test. if (TargetUtils.isTestRule(ruleContext.getTarget())) { Preconditions.checkState(runfilesSupport != null); add(TestProvider.class, initializeTestProvider(filesToRunProvider)); } ExtraActionArtifactsProvider extraActionsProvider = createExtraActionProvider(actionsWithoutExtraAction, ruleContext); add(ExtraActionArtifactsProvider.class, extraActionsProvider); if (!outputGroupBuilders.isEmpty()) { ImmutableMap.Builder<String, NestedSet<Artifact>> outputGroups = ImmutableMap.builder(); for (Map.Entry<String, NestedSetBuilder<Artifact>> entry : outputGroupBuilders.entrySet()) { outputGroups.put(entry.getKey(), entry.getValue().build()); } OutputGroupProvider outputGroupProvider = new OutputGroupProvider(outputGroups.build()); addNativeDeclaredProvider(outputGroupProvider); } TransitiveInfoProviderMap providers = providersBuilder.build(); return new RuleConfiguredTarget(ruleContext, providers); } /** * Like getFilesToBuild(), except that it also includes the runfiles middleman, if any. Middlemen * are expanded in the SpawnStrategy or by the Distributor. */ private NestedSet<Artifact> getFilesToRun( RunfilesSupport runfilesSupport, NestedSet<Artifact> filesToBuild) { if (runfilesSupport == null) { return filesToBuild; } else { NestedSetBuilder<Artifact> allFilesToBuild = NestedSetBuilder.stableOrder(); allFilesToBuild.addTransitive(filesToBuild); allFilesToBuild.add(runfilesSupport.getRunfilesMiddleman()); return allFilesToBuild.build(); } } /** * Invokes Blaze's constraint enforcement system: checks that this rule's dependencies * support its environments and reports appropriate errors if violations are found. Also * publishes this rule's supported environments for the rules that depend on it. */ private void checkConstraints() { if (!ruleContext.getRule().getRuleClassObject().supportsConstraintChecking()) { return; } EnvironmentCollection supportedEnvironments = ConstraintSemantics.getSupportedEnvironments(ruleContext); if (supportedEnvironments != null) { EnvironmentCollection.Builder refinedEnvironments = new EnvironmentCollection.Builder(); Map<Label, Target> removedEnvironmentCulprits = new LinkedHashMap<>(); ConstraintSemantics.checkConstraints(ruleContext, supportedEnvironments, refinedEnvironments, removedEnvironmentCulprits); add(SupportedEnvironmentsProvider.class, new SupportedEnvironments(supportedEnvironments, refinedEnvironments.build(), removedEnvironmentCulprits)); } } private TestProvider initializeTestProvider(FilesToRunProvider filesToRunProvider) { int explicitShardCount = ruleContext.attributes().get("shard_count", Type.INTEGER); if (explicitShardCount < 0 && ruleContext.getRule().isAttributeValueExplicitlySpecified("shard_count")) { ruleContext.attributeError("shard_count", "Must not be negative."); } if (explicitShardCount > 50) { ruleContext.attributeError("shard_count", "Having more than 50 shards is indicative of poor test organization. " + "Please reduce the number of shards."); } TestActionBuilder testActionBuilder = new TestActionBuilder(ruleContext) .setInstrumentedFiles(providersBuilder.getProvider(InstrumentedFilesProvider.class)); TestEnvironmentProvider environmentProvider = (TestEnvironmentProvider) providersBuilder.getProvider(TestEnvironmentProvider.SKYLARK_CONSTRUCTOR.getKey()); if (environmentProvider != null) { testActionBuilder.addExtraEnv(environmentProvider.getEnvironment()); } TestParams testParams = testActionBuilder .setFilesToRunProvider(filesToRunProvider) .setExecutionRequirements( (ExecutionInfoProvider) providersBuilder .getProvider(ExecutionInfoProvider.SKYLARK_CONSTRUCTOR.getKey())) .setShardCount(explicitShardCount) .build(); ImmutableList<String> testTags = ImmutableList.copyOf(ruleContext.getRule().getRuleTags()); return new TestProvider(testParams, testTags); } /** Add a specific provider. */ public <T extends TransitiveInfoProvider> RuleConfiguredTargetBuilder addProvider( TransitiveInfoProvider provider) { providersBuilder.add(provider); return this; } /** Add a collection of specific providers. */ public <T extends TransitiveInfoProvider> RuleConfiguredTargetBuilder addProviders( Iterable<TransitiveInfoProvider> providers) { providersBuilder.addAll(providers); return this; } /** Add a collection of specific providers. */ public <T extends TransitiveInfoProvider> RuleConfiguredTargetBuilder addProviders( TransitiveInfoProviderMap providers) { providersBuilder.addAll(providers); return this; } /** * Add a specific provider with a given value. * * @deprecated use {@link #addProvider} */ @Deprecated public <T extends TransitiveInfoProvider> RuleConfiguredTargetBuilder add(Class<T> key, T value) { return addProvider(key, value); } /** Add a specific provider with a given value. */ public <T extends TransitiveInfoProvider> RuleConfiguredTargetBuilder addProvider( Class<? extends T> key, T value) { Preconditions.checkNotNull(key); Preconditions.checkNotNull(value); providersBuilder.put(key, value); return this; } private <T extends TransitiveInfoProvider> void maybeAddSkylarkLegacyProvider( SkylarkClassObject value) { if (value.getConstructor() instanceof NativeClassObjectConstructor.WithLegacySkylarkName) { addSkylarkTransitiveInfo( ((NativeClassObjectConstructor.WithLegacySkylarkName) value.getConstructor()) .getSkylarkName(), value); } } /** * Add a Skylark transitive info. The provider value must be safe (i.e. a String, a Boolean, * an Integer, an Artifact, a Label, None, a Java TransitiveInfoProvider or something composed * from these in Skylark using lists, sets, structs or dicts). Otherwise an EvalException is * thrown. */ public RuleConfiguredTargetBuilder addSkylarkTransitiveInfo( String name, Object value, Location loc) throws EvalException { providersBuilder.put(name, value); return this; } /** * Adds a "declared provider" defined in Skylark to the rule. * Use this method for declared providers defined in Skyark. * * Has special handling for {@link OutputGroupProvider}: that provider is not added * from Skylark directly, instead its outpuyt groups are added. * * Use {@link #addNativeDeclaredProvider(SkylarkClassObject)} in definitions of * native rules. */ public RuleConfiguredTargetBuilder addSkylarkDeclaredProvider( SkylarkClassObject provider, Location loc) throws EvalException { ClassObjectConstructor constructor = provider.getConstructor(); if (!constructor.isExported()) { throw new EvalException(constructor.getLocation(), "All providers must be top level values"); } if (OutputGroupProvider.SKYLARK_CONSTRUCTOR.getKey().equals(constructor.getKey())) { OutputGroupProvider outputGroupProvider = (OutputGroupProvider) provider; for (String outputGroup : outputGroupProvider) { addOutputGroup(outputGroup, outputGroupProvider.getOutputGroup(outputGroup)); } } else { providersBuilder.put(provider); } return this; } /** * Adds "declared providers" defined in native code to the rule. Use this method for declared * providers in definitions of native rules. * * <p>Use {@link #addSkylarkDeclaredProvider(SkylarkClassObject, Location)} for Skylark rule * implementations. */ public RuleConfiguredTargetBuilder addNativeDeclaredProviders( Iterable<SkylarkClassObject> providers) { for (SkylarkClassObject provider : providers) { addNativeDeclaredProvider(provider); } return this; } /** * Adds a "declared provider" defined in native code to the rule. * Use this method for declared providers in definitions of native rules. * * Use {@link #addSkylarkDeclaredProvider(SkylarkClassObject, Location)} * for Skylark rule implementations. */ public RuleConfiguredTargetBuilder addNativeDeclaredProvider(SkylarkClassObject provider) { ClassObjectConstructor constructor = provider.getConstructor(); Preconditions.checkState(constructor.isExported()); providersBuilder.put(provider); maybeAddSkylarkLegacyProvider(provider); return this; } /** * Add a Skylark transitive info. The provider value must be safe. */ public RuleConfiguredTargetBuilder addSkylarkTransitiveInfo( String name, Object value) { providersBuilder.put(name, value); return this; } /** * Set the runfiles support for executable targets. */ public RuleConfiguredTargetBuilder setRunfilesSupport( RunfilesSupport runfilesSupport, Artifact executable) { this.runfilesSupport = runfilesSupport; this.executable = executable; return this; } /** * Set the files to build. */ public RuleConfiguredTargetBuilder setFilesToBuild(NestedSet<Artifact> filesToBuild) { this.filesToBuild = filesToBuild; return this; } private NestedSetBuilder<Artifact> getOutputGroupBuilder(String name) { NestedSetBuilder<Artifact> result = outputGroupBuilders.get(name); if (result != null) { return result; } result = NestedSetBuilder.stableOrder(); outputGroupBuilders.put(name, result); return result; } /** * Adds a set of files to an output group. */ public RuleConfiguredTargetBuilder addOutputGroup(String name, NestedSet<Artifact> artifacts) { getOutputGroupBuilder(name).addTransitive(artifacts); return this; } /** * Adds a file to an output group. */ public RuleConfiguredTargetBuilder addOutputGroup(String name, Artifact artifact) { getOutputGroupBuilder(name).add(artifact); return this; } /** * Adds multiple output groups. */ public RuleConfiguredTargetBuilder addOutputGroups(Map<String, NestedSet<Artifact>> groups) { for (Map.Entry<String, NestedSet<Artifact>> group : groups.entrySet()) { getOutputGroupBuilder(group.getKey()).addTransitive(group.getValue()); } return this; } /** * Set the extra action pseudo actions. */ public RuleConfiguredTargetBuilder setActionsWithoutExtraAction( ImmutableSet<ActionAnalysisMetadata> actions) { this.actionsWithoutExtraAction = actions; return this; } }
/* * Copyright 2015-2016 DevCon5 GmbH, info@devcon5.ch * * 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.tourniquet.junit.http.rules; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.Deque; import java.util.Map; import io.undertow.UndertowOptions; import io.undertow.server.BlockingHttpExchange; import io.undertow.server.HttpServerExchange; import io.undertow.server.ServerConnection; import io.undertow.server.handlers.Cookie; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.xnio.OptionMap; /** * */ @RunWith(MockitoJUnitRunner.class) public class HttpExchangeTest { @Mock private BlockingHttpExchange blockingHttpExchange; @Rule public HttpServerExchangeMock xchg = new HttpServerExchangeMock(); /** * The class under test */ private HttpExchange subject; private HttpServerExchange exchange; @Before public void setUp() throws Exception { exchange = xchg.getExchange(); subject = new HttpExchange(xchg.getExchange()); } @Test public void testGetRequestMethod() throws Exception { //prepare exchange.setRequestMethod(HttpString.tryFromString("POST")); //act String method = subject.getRequestMethod(); //assert assertEquals("POST", method); } @Test public void testGetHost() throws Exception { //prepare exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act String host = subject.getHost(); //assert assertEquals("somehost", host); } @Test public void testGetPort() throws Exception { //prepare exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act int port = subject.getPort(); //assert assertEquals(12345, port); } @Test public void testGetHostAndPort() throws Exception { //prepare exchange.setRequestScheme("http"); exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act String hostAndPort = subject.getHostAndPort(); //assert assertEquals("somehost:12345", hostAndPort); } @Test public void testGetInputStream() throws Exception { //prepare when(blockingHttpExchange.getInputStream()).thenReturn(new ByteArrayInputStream("content".getBytes())); exchange.startBlocking(blockingHttpExchange); //act InputStream is = subject.getInputStream(); //assert assertNotNull(is); assertEquals("content", IOUtils.toString(is)); } @Test public void testGetInputStream_reRead() throws Exception { //prepare when(blockingHttpExchange.getInputStream()).thenReturn(new ByteArrayInputStream("content".getBytes())); exchange.startBlocking(blockingHttpExchange); //act //first read assertEquals("content", IOUtils.toString(subject.getInputStream())); //second read assertEquals("content", IOUtils.toString(subject.getInputStream())); } @Test public void testGetPayload() throws Exception { //prepare byte[] data = "content".getBytes(); when(blockingHttpExchange.getInputStream()).thenReturn(new ByteArrayInputStream(data)); exchange.startBlocking(blockingHttpExchange); //act byte[] payload = subject.getPayload(); //assert assertArrayEquals(data, payload); } @Test public void testGetOutputStream() throws Exception { //prepare exchange.startBlocking(); //act OutputStream os = subject.getOutputStream(); os.write("test".getBytes()); //assert assertNotNull(os); xchg.getBuffer().rewind(); byte[] data = new byte[4]; xchg.getBuffer().get(data); assertEquals("test", new String(data)); } @Test public void testGetRequestScheme() throws Exception { //prepare exchange.setRequestScheme("http"); //act String scheme = subject.getRequestScheme(); //assert assertEquals("http", scheme); } @Test public void testGetRequestPath() throws Exception { //prepare exchange.setRequestPath("testpath"); //act String path = subject.getRequestPath(); //assert assertEquals("testpath", path); } @Test public void testGetRelativePath() throws Exception { //prepare exchange.setRelativePath("testpath"); //act String path = subject.getRelativePath(); //assert assertEquals("testpath", path); } @Test public void testGetResolvedPath() throws Exception { //prepare exchange.setResolvedPath("testpath"); //act String path = subject.getResolvedPath(); //assert assertEquals("testpath", path); } @Test public void testGetQueryString() throws Exception { //prepare exchange.setQueryString("querystring"); //act String query = subject.getQueryString(); //assert assertEquals("querystring", query); } @Test public void testGetRequestURI() throws Exception { //prepare exchange.setRequestURI("requestUri"); //act String uri = subject.getRequestURI(); //assert assertEquals("requestUri", uri); } @Test public void testGetRequestURL() throws Exception { //prepare exchange.setRequestScheme("http"); exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); exchange.setRequestURI("/requestUri"); //act String uri = subject.getRequestURL(); //assert assertEquals("http://somehost:12345/requestUri", uri); } @Test public void testGetPathParameters() throws Exception { //prepare exchange.addPathParam("param", "value"); //act Map<String, Deque<String>> params = subject.getPathParameters(); //assert assertNotNull(params); assertTrue(params.containsKey("param")); assertTrue(params.get("param").contains("value")); } @Test public void testGetQueryParameters() throws Exception { //prepare exchange.addQueryParam("param", "value"); //act Map<String, Deque<String>> params = subject.getQueryParameters(); //assert assertNotNull(params); assertTrue(params.containsKey("param")); assertTrue(params.get("param").contains("value")); } @Test public void testGetRequestHeaders() throws Exception { //prepare HeaderMap headerMap = exchange.getRequestHeaders(); headerMap.add(Headers.ACCEPT, "text/plain"); //act Map<String, Deque<String>> headers = subject.getRequestHeaders(); //assert assertNotNull(headers); assertEquals(1, headers.size()); assertTrue(headers.get("Accept").contains("text/plain")); } @Test public void testGetRequestCookies() throws Exception { //prepare ServerConnection scon = xchg.getServerConnection(); OptionMap map = OptionMap.builder() .set(UndertowOptions.MAX_COOKIES, 100) .set(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, false) .getMap(); when(scon.getUndertowOptions()).thenReturn(map); HeaderMap headerMap = exchange.getRequestHeaders(); headerMap.add(Headers.COOKIE, "cookie=name"); //act Map<String, String> cookies = subject.getRequestCookies(); //assert assertNotNull(cookies); assertTrue(cookies.containsKey("cookie")); assertEquals("name", cookies.get("cookie")); } @Test public void testAddResponseCookie() throws Exception { //prepare //act subject.addResponseCookie("cookie", "name"); //assert Map<String, Cookie> cookies = exchange.getResponseCookies(); assertTrue(cookies.containsKey("cookie")); assertEquals("cookie", cookies.get("cookie").getName()); assertEquals("name", cookies.get("cookie").getValue()); } @Test public void testGetContentLength() throws Exception { //prepare HeaderMap headerMap = exchange.getRequestHeaders(); headerMap.add(Headers.CONTENT_LENGTH, 123456L); //act long length = subject.getContentLength(); //assert assertEquals(123456L, length); } @Test public void testGetSourceAddress() throws Exception { //prepare exchange.setSourceAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act InetSocketAddress source = subject.getSourceAddress(); //assert assertNotNull(source); assertEquals("somehost", source.getHostName()); assertEquals(12345, source.getPort()); } @Test public void testGetDestinationAddress() throws Exception { //prepare exchange.setDestinationAddress(InetSocketAddress.createUnresolved("somehost", 12345)); //act InetSocketAddress dest = subject.getDestinationAddress(); //assert assertNotNull(dest); assertEquals("somehost", dest.getHostName()); assertEquals(12345, dest.getPort()); } @Test public void testSetResponseContentLength() throws Exception { //prepare //act subject.setResponseContentLength(123456L); //assert long contentLength = exchange.getResponseContentLength(); assertEquals(123456L, contentLength); } @Test public void testSetStatusCode() throws Exception { //prepare //act subject.setStatusCode(404); //assert assertEquals(404, exchange.getStatusCode()); } @Test public void testAddResponseHeader() throws Exception { //prepare //act subject.addResponseHeader("Content-Type", "text/plain"); //assert HeaderMap responseHeaders = exchange.getResponseHeaders(); assertTrue(responseHeaders.contains("Content-Type")); assertEquals("text/plain", responseHeaders.get("Content-Type").element()); } }
/** * 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.camel.commands; import java.util.List; import java.util.Map; import java.util.Set; /** * CamelController interface defines the expected behaviors to manipulate Camel resources (context, route, etc). */ public interface CamelController { /** * Gets information about a given Camel context by the given name. * * @param name the Camel context name. * @return a list of key/value pairs with CamelContext information * @throws java.lang.Exception can be thrown */ Map<String, Object> getCamelContextInformation(String name) throws Exception; /** * Get the list of Camel context. * * @return a list of key/value pairs with CamelContext information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getCamelContexts() throws Exception; /** * Get the list of Camel context filter by reg ex. * * @param filter the filter which supports * and ? as wildcards * @return a list of key/value pairs with CamelContext information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getCamelContexts(String filter) throws Exception; /** * Returns detailed CamelContext and route statistics as XML identified by a ID and a Camel context. * * @param camelContextName the Camel context. * @param fullStats whether to include verbose stats * @param includeProcessors whether to embed per processor stats from the route * @return the CamelContext statistics as XML * @throws java.lang.Exception can be thrown */ String getCamelContextStatsAsXml(String camelContextName, boolean fullStats, boolean includeProcessors) throws Exception; /** * Browses the inflight exchanges * * @param camelContextName the Camel context. * @param limit maximum number of exchanges to return * @param sortByLongestDuration <tt>true</tt> to sort by longest duration, <tt>false</tt> to sort by exchange id * @return a list of key/value pairs with inflight exchange information * @throws java.lang.Exception can be thrown */ List<Map<String, Object>> browseInflightExchanges(String camelContextName, int limit, boolean sortByLongestDuration) throws Exception; /** * Starts the given Camel context. * * @param camelContextName the Camel context. * @throws java.lang.Exception can be thrown */ void startContext(String camelContextName) throws Exception; /** * Stops the given Camel context. * * @param camelContextName the Camel context. * @throws java.lang.Exception can be thrown */ void stopContext(String camelContextName) throws Exception; /** * Suspends the given Camel context. * * @param camelContextName the Camel context. * @throws java.lang.Exception can be thrown */ void suspendContext(String camelContextName) throws Exception; /** * Resumes the given Camel context. * * @param camelContextName the Camel context. * @throws java.lang.Exception can be thrown */ void resumeContext(String camelContextName) throws Exception; /** * Get all routes. If Camel context name is null, all routes from all contexts are listed. * * @param camelContextName the Camel context name. If null, all contexts are considered. * @return a list of key/value pairs with routes information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getRoutes(String camelContextName) throws Exception; /** * Get all routes filtered by the regex. * * @param camelContextName the Camel context name. If null, all contexts are considered. * @param filter the filter which supports * and ? as wildcards * @return a list of key/value pairs with routes information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getRoutes(String camelContextName, String filter) throws Exception; /** * Reset all the route stats for the given Camel context * * @param camelContextName the Camel context. * @throws java.lang.Exception can be thrown */ void resetRouteStats(String camelContextName) throws Exception; /** * Starts the given route * * @param camelContextName the Camel context. * @param routeId the route ID. * @throws java.lang.Exception can be thrown */ void startRoute(String camelContextName, String routeId) throws Exception; /** * Stops the given route * * @param camelContextName the Camel context. * @param routeId the route ID. * @throws java.lang.Exception can be thrown */ void stopRoute(String camelContextName, String routeId) throws Exception; /** * Suspends the given route * * @param camelContextName the Camel context. * @param routeId the route ID. * @throws java.lang.Exception can be thrown */ void suspendRoute(String camelContextName, String routeId) throws Exception; /** * Resumes the given route * * @param camelContextName the Camel context. * @param routeId the route ID. * @throws java.lang.Exception can be thrown */ void resumeRoute(String camelContextName, String routeId) throws Exception; /** * Return the definition of a route as XML identified by a ID and a Camel context. * * @param routeId the route ID. * @param camelContextName the Camel context. * @return the route model as XML * @throws java.lang.Exception can be thrown */ String getRouteModelAsXml(String routeId, String camelContextName) throws Exception; /** * Returns detailed route statistics as XML identified by a ID and a Camel context. * * @param routeId the route ID. * @param camelContextName the Camel context. * @param fullStats whether to include verbose stats * @param includeProcessors whether to embed per processor stats from the route * @return the route statistics as XML * @throws java.lang.Exception can be thrown */ String getRouteStatsAsXml(String routeId, String camelContextName, boolean fullStats, boolean includeProcessors) throws Exception; /** * Return the endpoints * * @param camelContextName the Camel context. * @return a list of key/value pairs with endpoint information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getEndpoints(String camelContextName) throws Exception; /** * Return endpoint runtime statistics * * @param camelContextName the Camel context * @return a list of key/value pairs with endpoint runtime statistics * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getEndpointRuntimeStatistics(String camelContextName) throws Exception; /** * Return the definition of the REST services as XML for the given Camel context. * * @param camelContextName the Camel context. * @return the REST model as xml * @throws java.lang.Exception can be thrown */ String getRestModelAsXml(String camelContextName) throws Exception; /** * Return the REST services API documentation as JSon (requires camel-swagger-java on classpath) * * @param camelContextName the Camel context. * @return the REST API documentation as JSon * @throws java.lang.Exception can be thrown */ String getRestApiDocAsJson(String camelContextName) throws Exception; /** * Return the REST services for the given Camel context. * * @param camelContextName the Camel context. * @return a list of key/value pairs with REST information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> getRestServices(String camelContextName) throws Exception; /** * Explains an endpoint uri * * @param camelContextName the Camel context. * @param uri the endpoint uri * @param allOptions whether to explain all options, or only the explicit configured options from the uri * @return a JSON schema with explanation of the options * @throws java.lang.Exception can be thrown */ String explainEndpointAsJSon(String camelContextName, String uri, boolean allOptions) throws Exception; /** * Explains an EIP * * @param camelContextName the Camel context. * @param nameOrId the name of the EIP ({@link org.apache.camel.NamedNode#getShortName()} or a node id to refer to a specific node from the routes. * @param allOptions whether to explain all options, or only the explicit configured options from the uri * @return a JSON schema with explanation of the options * @throws java.lang.Exception can be thrown */ String explainEipAsJSon(String camelContextName, String nameOrId, boolean allOptions) throws Exception; /** * Lists Components which are in use or available on the classpath and include information * * @param camelContextName the Camel context. * @return a list of key/value pairs with component information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> listComponents(String camelContextName) throws Exception; /** * Lists all EIPs from the Camel EIP catalog * * @param filter optional filter to filter by labels * @return a list of key/value pairs with model information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> listEipsCatalog(String filter) throws Exception; /** * Lists all the labels from the Camel EIP catalog * * @return a map which key is the label, and the set is the models names that has the given label * @throws java.lang.Exception can be thrown */ Map<String, Set<String>> listEipsLabelCatalog() throws Exception; /** * Collects information about a Camel component from catalog * * @param name the component name * @return a map of key/value pairs with component information * @throws java.lang.Exception can be thrown */ Map<String, Object> componentInfo(String name) throws Exception; /** * Lists all components from the Camel components catalog * * @param filter optional filter to filter by labels * @return a list of key/value pairs with component information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> listComponentsCatalog(String filter) throws Exception; /** * Lists all the labels from the Camel components catalog * * @return a map which key is the label, and the set is the component names that has the given label * @throws java.lang.Exception can be thrown */ Map<String, Set<String>> listComponentsLabelCatalog() throws Exception; /** * Lists all data formats from the Camel components catalog * * @param filter optional filter to filter by labels * @return a list of key/value pairs with data format information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> listDataFormatsCatalog(String filter) throws Exception; /** * Lists all the labels from the Camel data formats catalog * * @return a map which key is the label, and the set is the data format names that has the given label * @throws java.lang.Exception can be thrown */ Map<String, Set<String>> listDataFormatsLabelCatalog() throws Exception; /** * Lists all languages from the Camel components catalog * * @param filter optional filter to filter by labels * @return a list of key/value pairs with language information * @throws java.lang.Exception can be thrown */ List<Map<String, String>> listLanguagesCatalog(String filter) throws Exception; /** * Lists all the labels from the Camel languages catalog * * @return a map which key is the label, and the set is the language names that has the given label * @throws java.lang.Exception can be thrown */ Map<String, Set<String>> listLanguagesLabelCatalog() throws Exception; }
/* * 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.activemq.artemis.tests.extras.jms.bridge; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.api.jms.JMSFactoryType; import org.apache.activemq.artemis.jms.bridge.ConnectionFactoryFactory; import org.apache.activemq.artemis.jms.bridge.QualityOfServiceMode; import org.apache.activemq.artemis.jms.bridge.impl.JMSBridgeImpl; import org.apache.activemq.artemis.jms.client.ActiveMQXAConnectionFactory; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.integration.ra.DummyTransactionManager; import org.junit.Assert; import org.junit.Test; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.Synchronization; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.xa.XAResource; public class JMSBridgeReconnectionTest extends BridgeTestBase { /** * */ private static final int TIME_WAIT = 5000; private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; // Crash and reconnect // Once and only once @Test public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, false); } @Test public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_P_LargeMessage() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, true, true); } @Test public void testCrashAndReconnectDestBasic_OnceAndOnlyOnce_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.ONCE_AND_ONLY_ONCE, false, false); } // dups ok @Test public void testCrashAndReconnectDestBasic_DuplicatesOk_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.DUPLICATES_OK, true, false); } @Test public void testCrashAndReconnectDestBasic_DuplicatesOk_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.DUPLICATES_OK, false, false); } // At most once @Test public void testCrashAndReconnectDestBasic_AtMostOnce_P() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.AT_MOST_ONCE, true, false); } @Test public void testCrashAndReconnectDestBasic_AtMostOnce_NP() throws Exception { performCrashAndReconnectDestBasic(QualityOfServiceMode.AT_MOST_ONCE, false, false); } // Crash tests specific to XA transactions @Test public void testCrashAndReconnectDestCrashBeforePrepare_P() throws Exception { performCrashAndReconnectDestCrashBeforePrepare(true); } @Test public void testCrashAndReconnectDestCrashBeforePrepare_NP() throws Exception { performCrashAndReconnectDestCrashBeforePrepare(false); } // Crash before bridge is started @Test public void testRetryConnectionOnStartup() throws Exception { jmsServer1.stop(); JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); bridge.setTransactionManager(newTransactionManager()); addActiveMQComponent(bridge); bridge.start(); Assert.assertFalse(bridge.isStarted()); Assert.assertTrue(bridge.isFailed()); // Restart the server jmsServer1.start(); createQueue("targetQueue", 1); setUpAdministeredObjects(); Thread.sleep(3000); Assert.assertTrue(bridge.isStarted()); Assert.assertFalse(bridge.isFailed()); } /** * https://jira.jboss.org/jira/browse/HORNETQ-287 */ @Test public void testStopBridgeWithFailureWhenStarted() throws Exception { jmsServer1.stop(); JMSBridgeImpl bridge = new JMSBridgeImpl(cff0, cff1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 500, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); bridge.setTransactionManager(newTransactionManager()); bridge.start(); Assert.assertFalse(bridge.isStarted()); Assert.assertTrue(bridge.isFailed()); bridge.stop(); Assert.assertFalse(bridge.isStarted()); // we restart and setup the server for the test's tearDown checks jmsServer1.start(); createQueue("targetQueue", 1); setUpAdministeredObjects(); } /* * Send some messages * Crash the destination server * Bring the destination server back up * Send some more messages * Verify all messages are received */ private void performCrashAndReconnectDestBasic(final QualityOfServiceMode qosMode, final boolean persistent, final boolean largeMessage) throws Exception { JMSBridgeImpl bridge = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; } bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, qosMode, 10, -1, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); final int NUM_MESSAGES = 10; // Send some messages sendMessages(cf0, sourceQueue, 0, NUM_MESSAGES / 2, persistent, largeMessage); // Verify none are received checkEmpty(targetQueue, 1); // Now crash the dest server JMSBridgeReconnectionTest.log.info("About to crash server"); jmsServer1.stop(); // Wait a while before starting up to simulate the dest being down for a while JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up"); Thread.sleep(TIME_WAIT); JMSBridgeReconnectionTest.log.info("Done wait"); // Restart the server JMSBridgeReconnectionTest.log.info("Restarting server"); jmsServer1.start(); // jmsServer1.createQueue(false, "targetQueue", null, true, "queue/targetQueue"); createQueue("targetQueue", 1); setUpAdministeredObjects(); // Send some more messages JMSBridgeReconnectionTest.log.info("Sending more messages"); sendMessages(cf0, sourceQueue, NUM_MESSAGES / 2, NUM_MESSAGES / 2, persistent, largeMessage); JMSBridgeReconnectionTest.log.info("Sent messages"); jmsServer1.stop(); bridge.stop(); System.out.println("JMSBridgeReconnectionTest.performCrashAndReconnectDestBasic"); } @Test public void performCrashDestinationStopBridge() throws Exception { ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; final JMSBridgeImpl bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.DUPLICATES_OK, 10, -1, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); Thread clientThread = new Thread(new Runnable() { @Override public void run() { while (bridge.isStarted()) { try { sendMessages(cf0, sourceQueue, 0, 1, false, false); } catch (Exception e) { e.printStackTrace(); } } } }); clientThread.start(); checkAllMessageReceivedInOrder(cf1, targetQueue, 0, 1, false); JMSBridgeReconnectionTest.log.info("About to crash server"); jmsServer1.stop(); // Wait a while before starting up to simulate the dest being down for a while JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up"); Thread.sleep(TIME_WAIT); JMSBridgeReconnectionTest.log.info("Done wait"); bridge.stop(); clientThread.join(5000); assertTrue(!clientThread.isAlive()); } @Test public void performCrashAndReconnect() throws Exception { performCrashAndReconnect(true); } @Test public void performCrashAndNoReconnect() throws Exception { performCrashAndReconnect(false); } private void performCrashAndReconnect(boolean restart) throws Exception { cff1xa = new ConnectionFactoryFactory() { public Object createConnectionFactory() throws Exception { ActiveMQXAConnectionFactory cf = (ActiveMQXAConnectionFactory) ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.XA_CF, new TransportConfiguration( INVM_CONNECTOR_FACTORY, params1)); // Note! We disable automatic reconnection on the session factory. The bridge needs to do the reconnection cf.setReconnectAttempts(-1); cf.setBlockOnNonDurableSend(true); cf.setBlockOnDurableSend(true); cf.setCacheLargeMessagesClient(true); return cf; } }; DummyTransactionManager tm = new DummyTransactionManager(); DummyTransaction tx = new DummyTransaction(); tm.tx = tx; JMSBridgeImpl bridge = new JMSBridgeImpl(cff0xa, cff1xa, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 10, 5000, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(tm); bridge.start(); // Now crash the dest server JMSBridgeReconnectionTest.log.info("About to crash server"); jmsServer1.stop(); if (restart) { jmsServer1.start(); } // Wait a while before starting up to simulate the dest being down for a while JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up"); Thread.sleep(TIME_WAIT); JMSBridgeReconnectionTest.log.info("Done wait"); bridge.stop(); if (restart) { assertTrue(tx.rolledback); assertTrue(tx.targetConnected); } else { assertTrue(tx.rolledback); assertFalse(tx.targetConnected); } } private class DummyTransaction implements Transaction { boolean rolledback = false; ClientSession targetSession; boolean targetConnected = false; @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException { } @Override public void rollback() throws IllegalStateException, SystemException { rolledback = true; targetConnected = !targetSession.isClosed(); } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { } @Override public int getStatus() throws SystemException { return 0; } @Override public boolean enlistResource(XAResource xaResource) throws RollbackException, IllegalStateException, SystemException { targetSession = (ClientSession) xaResource; return false; } @Override public boolean delistResource(XAResource xaResource, int i) throws IllegalStateException, SystemException { return false; } @Override public void registerSynchronization(Synchronization synchronization) throws RollbackException, IllegalStateException, SystemException { } } /* * Send some messages * Crash the destination server * Set the max batch time such that it will attempt to send the batch while the dest server is down * Bring up the destination server * Send some more messages * Verify all messages are received */ private void performCrashAndReconnectDestCrashBeforePrepare(final boolean persistent) throws Exception { JMSBridgeImpl bridge = new JMSBridgeImpl(cff0xa, cff1xa, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 1000, -1, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, 10, 5000, null, null, false); addActiveMQComponent(bridge); bridge.setTransactionManager(newTransactionManager()); bridge.start(); final int NUM_MESSAGES = 10; // Send some messages sendMessages(cf0, sourceQueue, 0, NUM_MESSAGES / 2, persistent, false); // verify none are received checkEmpty(targetQueue, 1); // Now crash the dest server JMSBridgeReconnectionTest.log.info("About to crash server"); jmsServer1.stop(); // Wait a while before starting up to simulate the dest being down for a while JMSBridgeReconnectionTest.log.info("Waiting 5 secs before bringing server back up"); Thread.sleep(TIME_WAIT); JMSBridgeReconnectionTest.log.info("Done wait"); // Restart the server jmsServer1.start(); createQueue("targetQueue", 1); setUpAdministeredObjects(); sendMessages(cf0, sourceQueue, NUM_MESSAGES / 2, NUM_MESSAGES / 2, persistent, false); checkMessagesReceived(cf1, targetQueue, QualityOfServiceMode.ONCE_AND_ONLY_ONCE, NUM_MESSAGES, false, false); } }
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.historicaltimeseries; import java.util.Map; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.core.config.ConfigSource; import com.opengamma.id.UniqueId; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesInfoDocument; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesLoader; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesMaster; import com.opengamma.master.historicaltimeseries.ManageableHistoricalTimeSeries; import com.opengamma.web.WebPerRequestData; /** * Data class for web-based historical time-series. */ @BeanDefinition public class WebHistoricalTimeSeriesData extends WebPerRequestData { /** * The historical time-series master. */ @PropertyDefinition private HistoricalTimeSeriesMaster _historicalTimeSeriesMaster; /** * The historical time-series loader. */ @PropertyDefinition private HistoricalTimeSeriesLoader _historicalTimeSeriesLoader; /** * The config source */ @PropertyDefinition private ConfigSource _configSource; /** * The historical time-series id from the input URI. */ @PropertyDefinition private String _uriHistoricalTimeSeriesId; /** * The loaded historical time-series info. */ @PropertyDefinition private HistoricalTimeSeriesInfoDocument _info; /** * The loaded historical time-series data points. */ @PropertyDefinition private ManageableHistoricalTimeSeries _timeSeries; /** * Gets the best available id. * @param overrideId the override id, null derives the result from the data * @return the id, may be null */ public String getBestHistoricalTimeSeriesUriId(final UniqueId overrideId) { if (overrideId != null) { return overrideId.toLatest().toString(); } return getInfo() != null ? getInfo().getUniqueId().toLatest().toString() : getUriHistoricalTimeSeriesId(); } //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code WebHistoricalTimeSeriesData}. * @return the meta-bean, not null */ public static WebHistoricalTimeSeriesData.Meta meta() { return WebHistoricalTimeSeriesData.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(WebHistoricalTimeSeriesData.Meta.INSTANCE); } @Override public WebHistoricalTimeSeriesData.Meta metaBean() { return WebHistoricalTimeSeriesData.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the historical time-series master. * @return the value of the property */ public HistoricalTimeSeriesMaster getHistoricalTimeSeriesMaster() { return _historicalTimeSeriesMaster; } /** * Sets the historical time-series master. * @param historicalTimeSeriesMaster the new value of the property */ public void setHistoricalTimeSeriesMaster(HistoricalTimeSeriesMaster historicalTimeSeriesMaster) { this._historicalTimeSeriesMaster = historicalTimeSeriesMaster; } /** * Gets the the {@code historicalTimeSeriesMaster} property. * @return the property, not null */ public final Property<HistoricalTimeSeriesMaster> historicalTimeSeriesMaster() { return metaBean().historicalTimeSeriesMaster().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the historical time-series loader. * @return the value of the property */ public HistoricalTimeSeriesLoader getHistoricalTimeSeriesLoader() { return _historicalTimeSeriesLoader; } /** * Sets the historical time-series loader. * @param historicalTimeSeriesLoader the new value of the property */ public void setHistoricalTimeSeriesLoader(HistoricalTimeSeriesLoader historicalTimeSeriesLoader) { this._historicalTimeSeriesLoader = historicalTimeSeriesLoader; } /** * Gets the the {@code historicalTimeSeriesLoader} property. * @return the property, not null */ public final Property<HistoricalTimeSeriesLoader> historicalTimeSeriesLoader() { return metaBean().historicalTimeSeriesLoader().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the config source * @return the value of the property */ public ConfigSource getConfigSource() { return _configSource; } /** * Sets the config source * @param configSource the new value of the property */ public void setConfigSource(ConfigSource configSource) { this._configSource = configSource; } /** * Gets the the {@code configSource} property. * @return the property, not null */ public final Property<ConfigSource> configSource() { return metaBean().configSource().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the historical time-series id from the input URI. * @return the value of the property */ public String getUriHistoricalTimeSeriesId() { return _uriHistoricalTimeSeriesId; } /** * Sets the historical time-series id from the input URI. * @param uriHistoricalTimeSeriesId the new value of the property */ public void setUriHistoricalTimeSeriesId(String uriHistoricalTimeSeriesId) { this._uriHistoricalTimeSeriesId = uriHistoricalTimeSeriesId; } /** * Gets the the {@code uriHistoricalTimeSeriesId} property. * @return the property, not null */ public final Property<String> uriHistoricalTimeSeriesId() { return metaBean().uriHistoricalTimeSeriesId().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the loaded historical time-series info. * @return the value of the property */ public HistoricalTimeSeriesInfoDocument getInfo() { return _info; } /** * Sets the loaded historical time-series info. * @param info the new value of the property */ public void setInfo(HistoricalTimeSeriesInfoDocument info) { this._info = info; } /** * Gets the the {@code info} property. * @return the property, not null */ public final Property<HistoricalTimeSeriesInfoDocument> info() { return metaBean().info().createProperty(this); } //----------------------------------------------------------------------- /** * Gets the loaded historical time-series data points. * @return the value of the property */ public ManageableHistoricalTimeSeries getTimeSeries() { return _timeSeries; } /** * Sets the loaded historical time-series data points. * @param timeSeries the new value of the property */ public void setTimeSeries(ManageableHistoricalTimeSeries timeSeries) { this._timeSeries = timeSeries; } /** * Gets the the {@code timeSeries} property. * @return the property, not null */ public final Property<ManageableHistoricalTimeSeries> timeSeries() { return metaBean().timeSeries().createProperty(this); } //----------------------------------------------------------------------- @Override public WebHistoricalTimeSeriesData clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { WebHistoricalTimeSeriesData other = (WebHistoricalTimeSeriesData) obj; return JodaBeanUtils.equal(getHistoricalTimeSeriesMaster(), other.getHistoricalTimeSeriesMaster()) && JodaBeanUtils.equal(getHistoricalTimeSeriesLoader(), other.getHistoricalTimeSeriesLoader()) && JodaBeanUtils.equal(getConfigSource(), other.getConfigSource()) && JodaBeanUtils.equal(getUriHistoricalTimeSeriesId(), other.getUriHistoricalTimeSeriesId()) && JodaBeanUtils.equal(getInfo(), other.getInfo()) && JodaBeanUtils.equal(getTimeSeries(), other.getTimeSeries()) && super.equals(obj); } return false; } @Override public int hashCode() { int hash = 7; hash = hash * 31 + JodaBeanUtils.hashCode(getHistoricalTimeSeriesMaster()); hash = hash * 31 + JodaBeanUtils.hashCode(getHistoricalTimeSeriesLoader()); hash = hash * 31 + JodaBeanUtils.hashCode(getConfigSource()); hash = hash * 31 + JodaBeanUtils.hashCode(getUriHistoricalTimeSeriesId()); hash = hash * 31 + JodaBeanUtils.hashCode(getInfo()); hash = hash * 31 + JodaBeanUtils.hashCode(getTimeSeries()); return hash ^ super.hashCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(224); buf.append("WebHistoricalTimeSeriesData{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } @Override protected void toString(StringBuilder buf) { super.toString(buf); buf.append("historicalTimeSeriesMaster").append('=').append(JodaBeanUtils.toString(getHistoricalTimeSeriesMaster())).append(',').append(' '); buf.append("historicalTimeSeriesLoader").append('=').append(JodaBeanUtils.toString(getHistoricalTimeSeriesLoader())).append(',').append(' '); buf.append("configSource").append('=').append(JodaBeanUtils.toString(getConfigSource())).append(',').append(' '); buf.append("uriHistoricalTimeSeriesId").append('=').append(JodaBeanUtils.toString(getUriHistoricalTimeSeriesId())).append(',').append(' '); buf.append("info").append('=').append(JodaBeanUtils.toString(getInfo())).append(',').append(' '); buf.append("timeSeries").append('=').append(JodaBeanUtils.toString(getTimeSeries())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code WebHistoricalTimeSeriesData}. */ public static class Meta extends WebPerRequestData.Meta { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code historicalTimeSeriesMaster} property. */ private final MetaProperty<HistoricalTimeSeriesMaster> _historicalTimeSeriesMaster = DirectMetaProperty.ofReadWrite( this, "historicalTimeSeriesMaster", WebHistoricalTimeSeriesData.class, HistoricalTimeSeriesMaster.class); /** * The meta-property for the {@code historicalTimeSeriesLoader} property. */ private final MetaProperty<HistoricalTimeSeriesLoader> _historicalTimeSeriesLoader = DirectMetaProperty.ofReadWrite( this, "historicalTimeSeriesLoader", WebHistoricalTimeSeriesData.class, HistoricalTimeSeriesLoader.class); /** * The meta-property for the {@code configSource} property. */ private final MetaProperty<ConfigSource> _configSource = DirectMetaProperty.ofReadWrite( this, "configSource", WebHistoricalTimeSeriesData.class, ConfigSource.class); /** * The meta-property for the {@code uriHistoricalTimeSeriesId} property. */ private final MetaProperty<String> _uriHistoricalTimeSeriesId = DirectMetaProperty.ofReadWrite( this, "uriHistoricalTimeSeriesId", WebHistoricalTimeSeriesData.class, String.class); /** * The meta-property for the {@code info} property. */ private final MetaProperty<HistoricalTimeSeriesInfoDocument> _info = DirectMetaProperty.ofReadWrite( this, "info", WebHistoricalTimeSeriesData.class, HistoricalTimeSeriesInfoDocument.class); /** * The meta-property for the {@code timeSeries} property. */ private final MetaProperty<ManageableHistoricalTimeSeries> _timeSeries = DirectMetaProperty.ofReadWrite( this, "timeSeries", WebHistoricalTimeSeriesData.class, ManageableHistoricalTimeSeries.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap( this, (DirectMetaPropertyMap) super.metaPropertyMap(), "historicalTimeSeriesMaster", "historicalTimeSeriesLoader", "configSource", "uriHistoricalTimeSeriesId", "info", "timeSeries"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 173967376: // historicalTimeSeriesMaster return _historicalTimeSeriesMaster; case 157715905: // historicalTimeSeriesLoader return _historicalTimeSeriesLoader; case 195157501: // configSource return _configSource; case 1609878101: // uriHistoricalTimeSeriesId return _uriHistoricalTimeSeriesId; case 3237038: // info return _info; case 779431844: // timeSeries return _timeSeries; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends WebHistoricalTimeSeriesData> builder() { return new DirectBeanBuilder<WebHistoricalTimeSeriesData>(new WebHistoricalTimeSeriesData()); } @Override public Class<? extends WebHistoricalTimeSeriesData> beanType() { return WebHistoricalTimeSeriesData.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code historicalTimeSeriesMaster} property. * @return the meta-property, not null */ public final MetaProperty<HistoricalTimeSeriesMaster> historicalTimeSeriesMaster() { return _historicalTimeSeriesMaster; } /** * The meta-property for the {@code historicalTimeSeriesLoader} property. * @return the meta-property, not null */ public final MetaProperty<HistoricalTimeSeriesLoader> historicalTimeSeriesLoader() { return _historicalTimeSeriesLoader; } /** * The meta-property for the {@code configSource} property. * @return the meta-property, not null */ public final MetaProperty<ConfigSource> configSource() { return _configSource; } /** * The meta-property for the {@code uriHistoricalTimeSeriesId} property. * @return the meta-property, not null */ public final MetaProperty<String> uriHistoricalTimeSeriesId() { return _uriHistoricalTimeSeriesId; } /** * The meta-property for the {@code info} property. * @return the meta-property, not null */ public final MetaProperty<HistoricalTimeSeriesInfoDocument> info() { return _info; } /** * The meta-property for the {@code timeSeries} property. * @return the meta-property, not null */ public final MetaProperty<ManageableHistoricalTimeSeries> timeSeries() { return _timeSeries; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 173967376: // historicalTimeSeriesMaster return ((WebHistoricalTimeSeriesData) bean).getHistoricalTimeSeriesMaster(); case 157715905: // historicalTimeSeriesLoader return ((WebHistoricalTimeSeriesData) bean).getHistoricalTimeSeriesLoader(); case 195157501: // configSource return ((WebHistoricalTimeSeriesData) bean).getConfigSource(); case 1609878101: // uriHistoricalTimeSeriesId return ((WebHistoricalTimeSeriesData) bean).getUriHistoricalTimeSeriesId(); case 3237038: // info return ((WebHistoricalTimeSeriesData) bean).getInfo(); case 779431844: // timeSeries return ((WebHistoricalTimeSeriesData) bean).getTimeSeries(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case 173967376: // historicalTimeSeriesMaster ((WebHistoricalTimeSeriesData) bean).setHistoricalTimeSeriesMaster((HistoricalTimeSeriesMaster) newValue); return; case 157715905: // historicalTimeSeriesLoader ((WebHistoricalTimeSeriesData) bean).setHistoricalTimeSeriesLoader((HistoricalTimeSeriesLoader) newValue); return; case 195157501: // configSource ((WebHistoricalTimeSeriesData) bean).setConfigSource((ConfigSource) newValue); return; case 1609878101: // uriHistoricalTimeSeriesId ((WebHistoricalTimeSeriesData) bean).setUriHistoricalTimeSeriesId((String) newValue); return; case 3237038: // info ((WebHistoricalTimeSeriesData) bean).setInfo((HistoricalTimeSeriesInfoDocument) newValue); return; case 779431844: // timeSeries ((WebHistoricalTimeSeriesData) bean).setTimeSeries((ManageableHistoricalTimeSeries) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- }
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.math; /** Takes a linear value in the range of 0-1 and outputs a (usually) non-linear, interpolated value. * @author Nathan Sweet */ public abstract class Interpolation { /** @param a Alpha value between 0 and 1. */ abstract public float apply (float a); /** @param a Alpha value between 0 and 1. */ public float apply (float start, float end, float a) { return start + (end - start) * apply(a); } // static public final Interpolation linear = new Interpolation() { public float apply (float a) { return a; } }; // /** Aka "smoothstep". */ static public final Interpolation smooth = new Interpolation() { public float apply (float a) { return a * a * (3 - 2 * a); } }; static public final Interpolation smooth2 = new Interpolation() { public float apply (float a) { a = a * a * (3 - 2 * a); return a * a * (3 - 2 * a); } }; /** By Ken Perlin. */ static public final Interpolation smoother = new Interpolation() { public float apply (float a) { return a * a * a * (a * (a * 6 - 15) + 10); } }; static public final Interpolation fade = smoother; // static public final Pow pow2 = new Pow(2); /** Slow, then fast. */ static public final PowIn pow2In = new PowIn(2); static public final PowIn slowFast = pow2In; /** Fast, then slow. */ static public final PowOut pow2Out = new PowOut(2); static public final PowOut fastSlow = pow2Out; static public final Interpolation pow2InInverse = new Interpolation() { public float apply (float a) { return (float)Math.sqrt(a); } }; static public final Interpolation pow2OutInverse = new Interpolation() { public float apply (float a) { return 1 - (float)Math.sqrt(-(a - 1)); } }; static public final Pow pow3 = new Pow(3); static public final PowIn pow3In = new PowIn(3); static public final PowOut pow3Out = new PowOut(3); static public final Interpolation pow3InInverse = new Interpolation() { public float apply (float a) { return (float)Math.cbrt(a); } }; static public final Interpolation pow3OutInverse = new Interpolation() { public float apply (float a) { return 1 - (float)Math.cbrt(-(a - 1)); } }; static public final Pow pow4 = new Pow(4); static public final PowIn pow4In = new PowIn(4); static public final PowOut pow4Out = new PowOut(4); static public final Pow pow5 = new Pow(5); static public final PowIn pow5In = new PowIn(5); static public final PowOut pow5Out = new PowOut(5); static public final Interpolation sine = new Interpolation() { public float apply (float a) { return (1 - MathUtils.cos(a * MathUtils.PI)) / 2; } }; static public final Interpolation sineIn = new Interpolation() { public float apply (float a) { return 1 - MathUtils.cos(a * MathUtils.PI / 2); } }; static public final Interpolation sineOut = new Interpolation() { public float apply (float a) { return MathUtils.sin(a * MathUtils.PI / 2); } }; static public final Exp exp10 = new Exp(2, 10); static public final ExpIn exp10In = new ExpIn(2, 10); static public final ExpOut exp10Out = new ExpOut(2, 10); static public final Exp exp5 = new Exp(2, 5); static public final ExpIn exp5In = new ExpIn(2, 5); static public final ExpOut exp5Out = new ExpOut(2, 5); static public final Interpolation circle = new Interpolation() { public float apply (float a) { if (a <= 0.5f) { a *= 2; return (1 - (float)Math.sqrt(1 - a * a)) / 2; } a--; a *= 2; return ((float)Math.sqrt(1 - a * a) + 1) / 2; } }; static public final Interpolation circleIn = new Interpolation() { public float apply (float a) { return 1 - (float)Math.sqrt(1 - a * a); } }; static public final Interpolation circleOut = new Interpolation() { public float apply (float a) { a--; return (float)Math.sqrt(1 - a * a); } }; static public final Elastic elastic = new Elastic(2, 10, 7, 1); static public final ElasticIn elasticIn = new ElasticIn(2, 10, 6, 1); static public final ElasticOut elasticOut = new ElasticOut(2, 10, 7, 1); static public final Swing swing = new Swing(1.5f); static public final SwingIn swingIn = new SwingIn(2f); static public final SwingOut swingOut = new SwingOut(2f); static public final Bounce bounce = new Bounce(4); static public final BounceIn bounceIn = new BounceIn(4); static public final BounceOut bounceOut = new BounceOut(4); // static public class Pow extends Interpolation { final int power; public Pow (int power) { this.power = power; } public float apply (float a) { if (a <= 0.5f) return (float)Math.pow(a * 2, power) / 2; return (float)Math.pow((a - 1) * 2, power) / (power % 2 == 0 ? -2 : 2) + 1; } } static public class PowIn extends Pow { public PowIn (int power) { super(power); } public float apply (float a) { return (float)Math.pow(a, power); } } static public class PowOut extends Pow { public PowOut (int power) { super(power); } public float apply (float a) { return (float)Math.pow(a - 1, power) * (power % 2 == 0 ? -1 : 1) + 1; } } // static public class Exp extends Interpolation { final float value, power, min, scale; public Exp (float value, float power) { this.value = value; this.power = power; min = (float)Math.pow(value, -power); scale = 1 / (1 - min); } public float apply (float a) { if (a <= 0.5f) return ((float)Math.pow(value, power * (a * 2 - 1)) - min) * scale / 2; return (2 - ((float)Math.pow(value, -power * (a * 2 - 1)) - min) * scale) / 2; } }; static public class ExpIn extends Exp { public ExpIn (float value, float power) { super(value, power); } public float apply (float a) { return ((float)Math.pow(value, power * (a - 1)) - min) * scale; } } static public class ExpOut extends Exp { public ExpOut (float value, float power) { super(value, power); } public float apply (float a) { return 1 - ((float)Math.pow(value, -power * a) - min) * scale; } } // static public class Elastic extends Interpolation { final float value, power, scale, bounces; public Elastic (float value, float power, int bounces, float scale) { this.value = value; this.power = power; this.scale = scale; this.bounces = bounces * MathUtils.PI * (bounces % 2 == 0 ? 1 : -1); } public float apply (float a) { if (a <= 0.5f) { a *= 2; return (float)Math.pow(value, power * (a - 1)) * MathUtils.sin(a * bounces) * scale / 2; } a = 1 - a; a *= 2; return 1 - (float)Math.pow(value, power * (a - 1)) * MathUtils.sin((a) * bounces) * scale / 2; } } static public class ElasticIn extends Elastic { public ElasticIn (float value, float power, int bounces, float scale) { super(value, power, bounces, scale); } public float apply (float a) { if (a >= 0.99) return 1; return (float)Math.pow(value, power * (a - 1)) * MathUtils.sin(a * bounces) * scale; } } static public class ElasticOut extends Elastic { public ElasticOut (float value, float power, int bounces, float scale) { super(value, power, bounces, scale); } public float apply (float a) { if (a == 0) return 0; a = 1 - a; return (1 - (float)Math.pow(value, power * (a - 1)) * MathUtils.sin(a * bounces) * scale); } } // static public class Bounce extends BounceOut { public Bounce (float[] widths, float[] heights) { super(widths, heights); } public Bounce (int bounces) { super(bounces); } private float out (float a) { float test = a + widths[0] / 2; if (test < widths[0]) return test / (widths[0] / 2) - 1; return super.apply(a); } public float apply (float a) { if (a <= 0.5f) return (1 - out(1 - a * 2)) / 2; return out(a * 2 - 1) / 2 + 0.5f; } } static public class BounceOut extends Interpolation { final float[] widths, heights; public BounceOut (float[] widths, float[] heights) { if (widths.length != heights.length) throw new IllegalArgumentException("Must be the same number of widths and heights."); this.widths = widths; this.heights = heights; } public BounceOut (int bounces) { if (bounces < 2 || bounces > 5) throw new IllegalArgumentException("bounces cannot be < 2 or > 5: " + bounces); widths = new float[bounces]; heights = new float[bounces]; heights[0] = 1; switch (bounces) { case 2: widths[0] = 0.6f; widths[1] = 0.4f; heights[1] = 0.33f; break; case 3: widths[0] = 0.4f; widths[1] = 0.4f; widths[2] = 0.2f; heights[1] = 0.33f; heights[2] = 0.1f; break; case 4: widths[0] = 0.34f; widths[1] = 0.34f; widths[2] = 0.2f; widths[3] = 0.15f; heights[1] = 0.26f; heights[2] = 0.11f; heights[3] = 0.03f; break; case 5: widths[0] = 0.3f; widths[1] = 0.3f; widths[2] = 0.2f; widths[3] = 0.1f; widths[4] = 0.1f; heights[1] = 0.45f; heights[2] = 0.3f; heights[3] = 0.15f; heights[4] = 0.06f; break; } widths[0] *= 2; } public float apply (float a) { if (a == 1) return 1; a += widths[0] / 2; float width = 0, height = 0; for (int i = 0, n = widths.length; i < n; i++) { width = widths[i]; if (a <= width) { height = heights[i]; break; } a -= width; } a /= width; float z = 4 / width * height * a; return 1 - (z - z * a) * width; } } static public class BounceIn extends BounceOut { public BounceIn (float[] widths, float[] heights) { super(widths, heights); } public BounceIn (int bounces) { super(bounces); } public float apply (float a) { return 1 - super.apply(1 - a); } } // static public class Swing extends Interpolation { private final float scale; public Swing (float scale) { this.scale = scale * 2; } public float apply (float a) { if (a <= 0.5f) { a *= 2; return a * a * ((scale + 1) * a - scale) / 2; } a--; a *= 2; return a * a * ((scale + 1) * a + scale) / 2 + 1; } } static public class SwingOut extends Interpolation { private final float scale; public SwingOut (float scale) { this.scale = scale; } public float apply (float a) { a--; return a * a * ((scale + 1) * a + scale) + 1; } } static public class SwingIn extends Interpolation { private final float scale; public SwingIn (float scale) { this.scale = scale; } public float apply (float a) { return a * a * ((scale + 1) * a - scale); } } }
/******************************************************************************* * Copyright 2002-2015, OpenNebula Project (OpenNebula.org), C12G Labs * * 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.opennebula.client; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; public class OneSystem { protected Client client; private static final String USER_QUOTA_INFO = "userquota.info"; private static final String USER_QUOTA_UPDATE = "userquota.update"; private static final String GROUP_QUOTA_INFO = "groupquota.info"; private static final String GROUP_QUOTA_UPDATE = "groupquota.update"; public static final String VERSION = "4.13.80"; public OneSystem(Client client) { this.client = client; } /** * Calls OpenNebula and retrieves the oned version * * @return The server's xml-rpc response encapsulated */ public OneResponse getOnedVersion() { return client.call("system.version"); } /** * Returns whether of not the oned version is the same as the OCA version * * @return true if oned is the same version */ public boolean compatibleVersion() { OneResponse r = getOnedVersion(); if (r.isError()) { return false; } String[] ocaVersion = VERSION.split("\\.", 3); String[] onedVersion = r.getMessage().split("\\.", 3); return ocaVersion.length == onedVersion.length && ocaVersion[0].equals(onedVersion[0]) && ocaVersion[1].equals(onedVersion[1]); } /** * Calls OpenNebula and retrieves oned configuration * * @return The server's xml-rpc response encapsulated */ public OneResponse getConfiguration() { return client.call("system.config"); } /** * Calls OpenNebula and retrieves oned configuration * * @return The xml root node in case of success, null otherwise */ public Node getConfigurationXML() { OneResponse r = getConfiguration(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Gets the default user quota limits * * @return the default user quota in case of success, Error otherwise */ public OneResponse getUserQuotas() { return client.call(USER_QUOTA_INFO); } /** * Gets the default user quota limits * * @return The xml root node in case of success, null otherwise */ public Node getUserQuotasXML() { OneResponse r = getUserQuotas(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Sets the default user quota limits * * @param quota a template (XML or txt) with the new quota limits * @return If an error occurs the error message contains the reason. */ public OneResponse setUserQuotas(String quota) { return client.call(USER_QUOTA_UPDATE, quota); } /** * Gets the default group quota limits * * @return the default group quota in case of success, Error otherwise */ public OneResponse getGroupQuotas() { return client.call(GROUP_QUOTA_INFO); } /** * Gets the default group quota limits * * @return The xml root node in case of success, null otherwise */ public Node getGroupQuotasXML() { OneResponse r = getGroupQuotas(); Node xml = null; if (r.isError()) { return null; } try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse( new ByteArrayInputStream(r.getMessage().getBytes())); xml = doc.getDocumentElement(); } catch (Exception e) {} return xml; } /** * Sets the default group quota limits * * @param quota a template (XML or txt) with the new quota limits * @return If an error occurs the error message contains the reason. */ public OneResponse setGroupQuotas(String quota) { return client.call(GROUP_QUOTA_UPDATE, quota); } }
/* * Copyright 2008-present MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mongodb.internal.session; import com.mongodb.MongoException; import com.mongodb.ReadPreference; import com.mongodb.ServerApi; import com.mongodb.connection.ClusterDescription; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.connection.Cluster; import com.mongodb.internal.connection.ConcurrentPool; import com.mongodb.internal.connection.ConcurrentPool.Prune; import com.mongodb.internal.connection.Connection; import com.mongodb.internal.connection.NoOpSessionContext; import com.mongodb.internal.selector.ReadPreferenceServerSelector; import com.mongodb.internal.validator.NoOpFieldNameValidator; import com.mongodb.lang.Nullable; import com.mongodb.selector.ServerSelector; import com.mongodb.session.ServerSession; import org.bson.BsonArray; import org.bson.BsonBinary; import org.bson.BsonDocument; import org.bson.BsonDocumentWriter; import org.bson.UuidRepresentation; import org.bson.codecs.BsonDocumentCodec; import org.bson.codecs.EncoderContext; import org.bson.codecs.UuidCodec; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import static com.mongodb.assertions.Assertions.isTrue; import static com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE; import static java.util.concurrent.TimeUnit.MINUTES; public class ServerSessionPool { private static final int END_SESSIONS_BATCH_SIZE = 10000; private final ConcurrentPool<ServerSessionImpl> serverSessionPool = new ConcurrentPool<>(INFINITE_SIZE, new ServerSessionItemFactory()); private final Cluster cluster; private final ServerSessionPool.Clock clock; private volatile boolean closing; private volatile boolean closed; private final List<BsonDocument> closedSessionIdentifiers = new ArrayList<BsonDocument>(); private final @Nullable ServerApi serverApi; interface Clock { long millis(); } public ServerSessionPool(final Cluster cluster, final @Nullable ServerApi serverApi) { this(cluster, serverApi, new Clock() { @Override public long millis() { return System.currentTimeMillis(); } }); } public ServerSessionPool(final Cluster cluster, final @Nullable ServerApi serverApi, final Clock clock) { this.cluster = cluster; this.serverApi = serverApi; this.clock = clock; } public ServerSession get() { isTrue("server session pool is open", !closed); ServerSessionImpl serverSession = serverSessionPool.get(); while (shouldPrune(serverSession)) { serverSessionPool.release(serverSession, true); serverSession = serverSessionPool.get(); } return serverSession; } public void release(final ServerSession serverSession) { serverSessionPool.release((ServerSessionImpl) serverSession); serverSessionPool.prune(); } public void close() { try { closing = true; serverSessionPool.close(); List<BsonDocument> identifiers; synchronized (this) { identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers); closedSessionIdentifiers.clear(); } endClosedSessions(identifiers); } finally { closed = true; } } public int getInUseCount() { return serverSessionPool.getInUseCount(); } private void closeSession(final ServerSessionImpl serverSession) { serverSession.close(); // only track closed sessions when pool is in the process of closing if (!closing) { return; } List<BsonDocument> identifiers = null; synchronized (this) { closedSessionIdentifiers.add(serverSession.getIdentifier()); if (closedSessionIdentifiers.size() == END_SESSIONS_BATCH_SIZE) { identifiers = new ArrayList<BsonDocument>(closedSessionIdentifiers); closedSessionIdentifiers.clear(); } } if (identifiers != null) { endClosedSessions(identifiers); } } private void endClosedSessions(final List<BsonDocument> identifiers) { if (identifiers.isEmpty()) { return; } final List<ServerDescription> primaryPreferred = new ReadPreferenceServerSelector(ReadPreference.primaryPreferred()) .select(cluster.getCurrentDescription()); if (primaryPreferred.isEmpty()) { return; } Connection connection = null; try { connection = cluster.selectServer(new ServerSelector() { @Override public List<ServerDescription> select(final ClusterDescription clusterDescription) { for (ServerDescription cur : clusterDescription.getServerDescriptions()) { if (cur.getAddress().equals(primaryPreferred.get(0).getAddress())) { return Collections.singletonList(cur); } } return Collections.emptyList(); } }).getServer().getConnection(); connection.command("admin", new BsonDocument("endSessions", new BsonArray(identifiers)), new NoOpFieldNameValidator(), ReadPreference.primaryPreferred(), new BsonDocumentCodec(), NoOpSessionContext.INSTANCE, serverApi, IgnorableRequestContext.INSTANCE); } catch (MongoException e) { // ignore exceptions } finally { if (connection != null) { connection.release(); } } } private boolean shouldPrune(final ServerSessionImpl serverSession) { Integer logicalSessionTimeoutMinutes = cluster.getCurrentDescription().getLogicalSessionTimeoutMinutes(); // if the server no longer supports sessions, prune the session if (logicalSessionTimeoutMinutes == null) { return false; } if (serverSession.isMarkedDirty()) { return true; } long currentTimeMillis = clock.millis(); final long timeSinceLastUse = currentTimeMillis - serverSession.getLastUsedAtMillis(); final long oneMinuteFromTimeout = MINUTES.toMillis(logicalSessionTimeoutMinutes - 1); return timeSinceLastUse > oneMinuteFromTimeout; } final class ServerSessionImpl implements ServerSession { private final BsonDocument identifier; private long transactionNumber = 0; private volatile long lastUsedAtMillis = clock.millis(); private volatile boolean closed; private volatile boolean dirty = false; ServerSessionImpl(final BsonBinary identifier) { this.identifier = new BsonDocument("id", identifier); } void close() { closed = true; } long getLastUsedAtMillis() { return lastUsedAtMillis; } @Override public long getTransactionNumber() { return transactionNumber; } @Override public BsonDocument getIdentifier() { lastUsedAtMillis = clock.millis(); return identifier; } @Override public long advanceTransactionNumber() { transactionNumber++; return transactionNumber; } @Override public boolean isClosed() { return closed; } @Override public void markDirty() { dirty = true; } @Override public boolean isMarkedDirty() { return dirty; } } private final class ServerSessionItemFactory implements ConcurrentPool.ItemFactory<ServerSessionImpl> { @Override public ServerSessionImpl create() { return new ServerSessionImpl(createNewServerSessionIdentifier()); } @Override public void close(final ServerSessionImpl serverSession) { closeSession(serverSession); } @Override public Prune shouldPrune(final ServerSessionImpl serverSession) { return ServerSessionPool.this.shouldPrune(serverSession) ? Prune.YES : Prune.STOP; } private BsonBinary createNewServerSessionIdentifier() { UuidCodec uuidCodec = new UuidCodec(UuidRepresentation.STANDARD); BsonDocument holder = new BsonDocument(); BsonDocumentWriter bsonDocumentWriter = new BsonDocumentWriter(holder); bsonDocumentWriter.writeStartDocument(); bsonDocumentWriter.writeName("id"); uuidCodec.encode(bsonDocumentWriter, UUID.randomUUID(), EncoderContext.builder().build()); bsonDocumentWriter.writeEndDocument(); return holder.getBinary("id"); } } }
package com.eeeeeric.mpc.hc.api; /** * These are commands that MPC-HC recognizes. */ public enum WMCommand { SET_VOLUME("Set Volume", -2), SEEK("Seek", -1), QUICK_OPEN_FILE("Quick Open File", 969), OPEN_FILE("Open File", 800), OPEN_DVD_BD("Open DVD/BD", 801), OPEN_DEVICE("Open Device", 802), REOPEN_FILE("Reopen File", 976), MOVE_TO_RECYCLE_BIN("Move to Recycle Bin", 24044), SAVE_A_COPY("Save a Copy", 805), SAVE_IMAGE("Save Image", 806), SAVE_IMAGE_AUTO("Save Image (auto)", 807), SAVE_THUMBNAILS("Save thumbnails", 808), LOAD_SUBTITLE("Load Subtitle", 809), SAVE_SUBTITLE("Save Subtitle", 810), CLOSE("Close", 804), PROPERTIES("Properties", 814), EXIT("Exit", 816), PLAY_PAUSE("Play/Pause", 889), PLAY("Play", 887), PAUSE("Pause", 888), STOP("Stop", 890), FRAMESTEP("Framestep", 891), FRAMESTEP_BACK("Framestep back", 892), GO_TO("Go To", 893), INCREASE_RATE("Increase Rate", 895), DECREASE_RATE("Decrease Rate", 894), RESET_RATE("Reset Rate", 896), AUDIO_DELAY_PLUS_10_MS("Audio Delay +10 ms", 905), AUDIO_DELAY_MINUS_10_MS("Audio Delay -10 ms", 906), JUMP_FORWARD_SMALL("Jump Forward (small)", 900), JUMP_BACKWARD_SMALL("Jump Backward (small)", 899), JUMP_FORWARD_MEDIUM("Jump Forward (medium)", 902), JUMP_BACKWARD_MEDIUM("Jump Backward (medium)", 901), JUMP_FORWARD_LARGE("Jump Forward (large)", 904), JUMP_BACKWARD_LARGE("Jump Backward (large)", 903), JUMP_FORWARD_KEYFRAME("Jump Forward (keyframe)", 898), JUMP_BACKWARD_KEYFRAME("Jump Backward (keyframe)", 897), JUMP_TO_BEGINNING("Jump to Beginning", 996), NEXT("Next", 922), PREVIOUS("Previous", 921), NEXT_FILE("Next File", 920), PREVIOUS_FILE("Previous File", 919), TUNER_SCAN("Tuner scan", 974), QUICK_ADD_FAVORITE("Quick add favorite", 975), TOGGLE_CAPTION_AND_MENU("Toggle Caption&Menu", 817), TOGGLE_SEEKER("Toggle Seeker", 818), TOGGLE_CONTROLS("Toggle Controls", 819), TOGGLE_INFORMATION("Toggle Information", 820), TOGGLE_STATISTICS("Toggle Statistics", 821), TOGGLE_STATUS("Toggle Status", 822), TOGGLE_SUBRESYNC_BAR("Toggle Subresync Bar", 823), TOGGLE_PLAYLIST_BAR("Toggle Playlist Bar", 824), TOGGLE_CAPTURE_BAR("Toggle Capture Bar", 825), TOGGLE_NAVIGATION_BAR("Toggle Navigation Bar", 33415), TOGGLE_DEBUG_SHADERS("Toggle Debug Shaders", 826), VIEW_MINIMAL("View Minimal", 827), VIEW_COMPACT("View Compact", 828), VIEW_NORMAL("View Normal", 829), FULLSCREEN("Fullscreen", 830), FULLSCREEN_WITHOUT_RES_CHANGE("Fullscreen (w/o res.change)", 831), ZOOM_50("Zoom 50%", 832), ZOOM_100("Zoom 100%", 833), ZOOM_200("Zoom 200%", 834), ZOOM_AUTO_FIT("Zoom Auto Fit", 968), ZOOM_AUTO_FIT_LARGER_ONLY("Zoom Auto Fit (Larger Only)", 4900), NEXT_AR_PRESET("Next AR Preset", 859), VIDFRM_HALF("VidFrm Half", 835), VIDFRM_NORMAL("VidFrm Normal", 836), VIDFRM_DOUBLE("VidFrm Double", 837), VIDFRM_STRETCH("VidFrm Stretch", 838), VIDFRM_INSIDE("VidFrm Inside", 839), VIDFRM_ZOOM_1("VidFrm Zoom 1", 841), VIDFRM_ZOOM_2("VidFrm Zoom 2", 842), VIDFRM_OUTSIDE("VidFrm Outside", 840), VIDFRM_SWITCH_ZOOM("VidFrm Switch Zoom", 843), ALWAYS_ON_TOP("Always On Top", 884), PNS_RESET("PnS Reset", 861), PNS_INC_SIZE("PnS Inc Size", 862), PNS_INC_WIDTH("PnS Inc Width", 864), PNS_INC_HEIGHT("PnS Inc Height", 866), PNS_DEC_SIZE("PnS Dec Size", 863), PNS_DEC_WIDTH("PnS Dec Width", 865), PNS_DEC_HEIGHT("PnS Dec Height", 867), PNS_CENTER("PnS Center", 876), PNS_LEFT("PnS Left", 868), PNS_RIGHT("PnS Right", 869), PNS_UP("PnS Up", 870), PNS_DOWN("PnS Down", 871), PNS_UP_LEFT("PnS Up/Left", 872), PNS_UP_RIGHT("PnS Up/Right", 873), PNS_DOWN_LEFT("PnS Down/Left", 874), PNS_DOWN_RIGHT("PnS Down/Right", 875), PNS_ROTATE_X_PLUS("PnS Rotate X+", 877), PNS_ROTATE_X_MINUS("PnS Rotate X-", 878), PNS_ROTATE_Y_PLUS("PnS Rotate Y+", 879), PNS_ROTATE_Y_MINUS("PnS Rotate Y-", 880), PNS_ROTATE_Z_PLUS("PnS Rotate Z+", 881), PNS_ROTATE_Z_MINUS("PnS Rotate Z-", 882), VOLUME_UP("Volume Up", 907), VOLUME_DOWN("Volume Down", 908), VOLUME_MUTE("Volume Mute", 909), VOLUME_BOOST_INCREASE("Volume boost increase", 970), VOLUME_BOOST_DECREASE("Volume boost decrease", 971), VOLUME_BOOST_MIN("Volume boost Min", 972), VOLUME_BOOST_MAX("Volume boost Max", 973), TOGGLE_CUSTOM_CHANNEL_MAPPING("Toggle custom channel mapping", 993), TOGGLE_NORMALIZATION("Toggle normalization", 994), TOGGLE_REGAIN_VOLUME("Toggle regain volume", 995), BRIGHTNESS_INCREASE("Brightness increase", 984), BRIGHTNESS_DECREASE("Brightness decrease", 985), CONTRAST_INCREASE("Contrast increase", 986), CONTRAST_DECREASE("Contrast decrease", 987), HUE_INCREASE("Hue increase", 988), HUE_DECREASE("Hue decrease", 989), SATURATION_INCREASE("Saturation increase", 990), SATURATION_DECREASE("Saturation decrease", 991), RESET_COLOR_SETTINGS("Reset color settings", 992), DVD_TITLE_MENU("DVD Title Menu", 923), DVD_ROOT_MENU("DVD Root Menu", 924), DVD_SUBTITLE_MENU("DVD Subtitle Menu", 925), DVD_AUDIO_MENU("DVD Audio Menu", 926), DVD_ANGLE_MENU("DVD Angle Menu", 927), DVD_CHAPTER_MENU("DVD Chapter Menu", 928), DVD_MENU_LEFT("DVD Menu Left", 929), DVD_MENU_RIGHT("DVD Menu Right", 930), DVD_MENU_UP("DVD Menu Up", 931), DVD_MENU_DOWN("DVD Menu Down", 932), DVD_MENU_ACTIVATE("DVD Menu Activate", 933), DVD_MENU_BACK("DVD Menu Back", 934), DVD_MENU_LEAVE("DVD Menu Leave", 935), BOSS_KEY("Boss key", 944), PLAYER_MENU_SHORT("Player Menu (short)", 949), PLAYER_MENU_LONG("Player Menu (long)", 950), FILTERS_MENU("Filters Menu", 951), OPTIONS("Options", 815), NEXT_AUDIO("Next Audio", 952), PREV_AUDIO("Prev Audio", 953), NEXT_SUBTITLE("Next Subtitle", 954), PREV_SUBTITLE("Prev Subtitle", 955), ON_OFF_SUBTITLE("On/Off Subtitle", 956), RELOAD_SUBTITLES("Reload Subtitles", 2302), DOWNLOAD_SUBTITLES("Download subtitles", 812), NEXT_AUDIO_OGM("Next Audio (OGM)", 957), PREV_AUDIO_OGM("Prev Audio (OGM)", 958), NEXT_SUBTITLE_OGM("Next Subtitle (OGM)", 959), PREV_SUBTITLE_OGM("Prev Subtitle (OGM)", 960), NEXT_ANGLE_DVD("Next Angle (DVD)", 961), PREV_ANGLE_DVD("Prev Angle (DVD)", 962), NEXT_AUDIO_DVD("Next Audio (DVD)", 963), PREV_AUDIO_DVD("Prev Audio (DVD)", 964), NEXT_SUBTITLE_DVD("Next Subtitle (DVD)", 965), PREV_SUBTITLE_DVD("Prev Subtitle (DVD)", 966), ON_OFF_SUBTITLE_DVD("On/Off Subtitle (DVD)", 967), TEARING_TEST("Tearing Test", 32769), REMAINING_TIME("Remaining Time", 32778), NEXT_SHADER_PRESET("Next Shader Preset", 57382), PREV_SHADER_PRESET("Prev Shader Preset", 57384), TOGGLE_DIRECT3D_FULLSCREEN("Toggle Direct3D fullscreen", 32779), GOTO_PREV_SUBTITLE("Goto Prev Subtitle", 32780), GOTO_NEXT_SUBTITLE("Goto Next Subtitle", 32781), SHIFT_SUBTITLE_LEFT("Shift Subtitle Left", 32782), SHIFT_SUBTITLE_RIGHT("Shift Subtitle Right", 32783), DISPLAY_STATS("Display Stats", 32784), RESET_DISPLAY_STATS("Reset Display Stats", 33405), VSYNC("VSync", 33243), ENABLE_FRAME_TIME_CORRECTION("Enable Frame Time Correction", 33265), ACCURATE_VSYNC("Accurate VSync", 33260), DECREASE_VSYNC_OFFSET("Decrease VSync Offset", 33246), INCREASE_VSYNC_OFFSET("Increase VSync Offset", 33247), SUBTITLE_DELAY_MINUS("Subtitle Delay -", 24000), SUBTITLE_DELAY_PLUS("Subtitle Delay +", 24001), AFTER_PLAYBACK_EXIT("After Playback: Exit", 912), AFTER_PLAYBACK_STAND_BY("After Playback: Stand By", 913), AFTER_PLAYBACK_HIBERNATE("After Playback: Hibernate", 914), AFTER_PLAYBACK_SHUTDOWN("After Playback: Shutdown", 915), AFTER_PLAYBACK_LOG_OFF("After Playback: Log Off", 916), AFTER_PLAYBACK_LOCK("After Playback: Lock", 917), AFTER_PLAYBACK_TURN_OFF_THE_MONITOR("After Playback: Turn off the monitor", 918), AFTER_PLAYBACK_PLAY_NEXT_FILE_IN_THE_FOLDER("After Playback: Play next file in the folder", 947), TOGGLE_EDL_WINDOW("Toggle EDL window", 846), EDL_SET_IN("EDL set In", 847), EDL_SET_OUT("EDL set Out", 848), EDL_NEW_CLIP("EDL new clip", 849), EDL_SAVE("EDL save", 860); private String commandName; private int value; /** * Create a new instance. * * @param commandName * A human friendly string of what the command does * @param value * The integer command code */ WMCommand(String commandName, int value) { this.commandName = commandName; this.value = value; } /** * Returns a human friendly string of what the command does * * @return a human friendly string of what the command does */ public String getCommandName() { return commandName; } /** * Returns the integer command code. * * @return the integer command code. */ public int getValue() { return value; } }
/* * RED5 Open Source Media Server - https://github.com/Red5/ * * Copyright 2006-2016 by respective authors (see below). 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 org.red5.server.net.rtmp.event; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import org.apache.mina.core.buffer.IoBuffer; import org.red5.codec.VideoCodec; import org.red5.io.ITag; import org.red5.io.IoConstants; import org.red5.server.api.stream.IStreamPacket; import org.red5.server.stream.IStreamData; /** * Video data event */ public class VideoData extends BaseEvent implements IoConstants, IStreamData<VideoData>, IStreamPacket { private static final long serialVersionUID = 5538859593815804830L; /** * Videoframe type */ public static enum FrameType { UNKNOWN, KEYFRAME, INTERFRAME, DISPOSABLE_INTERFRAME, } /** * Video data */ protected IoBuffer data; /** * Data type */ private byte dataType = TYPE_VIDEO_DATA; /** * Frame type, unknown by default */ protected FrameType frameType = FrameType.UNKNOWN; /** * The codec id */ protected int codecId = -1; /** * True if this is configuration data and false otherwise */ protected boolean config; /** Constructs a new VideoData. */ public VideoData() { this(IoBuffer.allocate(0).flip()); } /** * Create video data event with given data buffer * * @param data * Video data */ public VideoData(IoBuffer data) { super(Type.STREAM_DATA); setData(data); } /** * Create video data event with given data buffer * * @param data * Video data * @param copy * true to use a copy of the data or false to use reference */ public VideoData(IoBuffer data, boolean copy) { super(Type.STREAM_DATA); if (copy) { byte[] array = new byte[data.limit()]; data.mark(); data.get(array); data.reset(); setData(array); } else { setData(data); } } /** {@inheritDoc} */ @Override public byte getDataType() { return dataType; } public void setDataType(byte dataType) { this.dataType = dataType; } /** {@inheritDoc} */ public IoBuffer getData() { return data; } public void setData(IoBuffer data) { this.data = data; if (data != null && data.limit() > 0) { data.mark(); int firstByte = data.get(0) & 0xff; codecId = firstByte & ITag.MASK_VIDEO_CODEC; if (codecId == VideoCodec.AVC.getId()) { config = (data.get() == 0); } data.reset(); int frameType = (firstByte & MASK_VIDEO_FRAMETYPE) >> 4; if (frameType == FLAG_FRAMETYPE_KEYFRAME) { this.frameType = FrameType.KEYFRAME; } else if (frameType == FLAG_FRAMETYPE_INTERFRAME) { this.frameType = FrameType.INTERFRAME; } else if (frameType == FLAG_FRAMETYPE_DISPOSABLE) { this.frameType = FrameType.DISPOSABLE_INTERFRAME; } else { this.frameType = FrameType.UNKNOWN; } } } public void setData(byte[] data) { this.data = IoBuffer.allocate(data.length); this.data.put(data).flip(); } /** * Getter for frame type * * @return Type of video frame */ public FrameType getFrameType() { return frameType; } public int getCodecId() { return codecId; } public boolean isConfig() { return config; } /** {@inheritDoc} */ @Override protected void releaseInternal() { if (data != null) { final IoBuffer localData = data; // null out the data first so we don't accidentally // return a valid reference first data = null; localData.clear(); localData.free(); } } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); frameType = (FrameType) in.readObject(); byte[] byteBuf = (byte[]) in.readObject(); if (byteBuf != null) { setData(IoBuffer.wrap(byteBuf)); } } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(frameType); if (data != null) { out.writeObject(data.array()); } else { out.writeObject(null); } } /** * Duplicate this message / event. * * @return duplicated event */ public VideoData duplicate() throws IOException, ClassNotFoundException { VideoData result = new VideoData(); // serialize ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); writeExternal(oos); oos.close(); // convert to byte array byte[] buf = baos.toByteArray(); baos.close(); // create input streams ByteArrayInputStream bais = new ByteArrayInputStream(buf); ObjectInputStream ois = new ObjectInputStream(bais); // deserialize result.readExternal(ois); ois.close(); bais.close(); // clone the header if there is one if (header != null) { result.setHeader(header.clone()); } return result; } /** {@inheritDoc} */ @Override public String toString() { return String.format("Video - ts: %s length: %s", getTimestamp(), (data != null ? data.limit() : '0')); } }
package it.unibas.bartgui.view.panel.editor.ConfEGTask; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.jdesktop.swingx.JXTitledSeparator; import org.netbeans.validation.api.Problem; import org.netbeans.validation.api.builtin.stringvalidation.StringValidators; import org.netbeans.validation.api.ui.ValidationGroup; import org.netbeans.validation.api.ui.swing.ValidationPanel; /** * * @author Grandinetti Giovanni <grandinetti.giovanni13@gmail.com> */ @SuppressWarnings("unchecked") public class ConfEGTaskEditPanel extends JPanel { private JButton okButton; private JButton cancelButton; private JXTitledSeparator title; private ValidationPanel panelValAcc; private ValidationGroup vg; private ConfEGTaskPanel panel; public ConfEGTaskEditPanel() { setLayout(new BorderLayout()); //InitTitle(); InitButton(); initPanel(); initListenerCheckbox(); //add(title,BorderLayout.NORTH); add(panelValAcc,BorderLayout.CENTER); } private void initPanel() { panelValAcc = new ValidationPanel(); getPanelValAcc().setBorder(new TitledBorder(new LineBorder(Color.BLACK), "EGTask Configuration", TitledBorder.CENTER,TitledBorder.TOP)); panel = new ConfEGTaskPanel(); getPanelValAcc().setInnerComponent(panel); vg = getPanelValAcc().getValidationGroup(); vg.add(panel.getExportCellChangesPathTextField(), StringValidators.REQUIRE_NON_EMPTY_STRING); vg.add(panel.getExportDirtyDbTypeTextField(),StringValidators.REQUIRE_NON_EMPTY_STRING); vg.add(panel.getExportDirtyDBPathTextField(), StringValidators.REQUIRE_NON_EMPTY_STRING); vg.add(panel.getCloneSuffixTextField(), StringValidators.REQUIRE_NON_EMPTY_STRING); //vg.add(panel.getQueryWxecutionTimeOutTextField(), StringValidators.REQUIRE_VALID_NUMBER); vg.add(panel.getSizeFactorReductionTextField(), StringValidators.REQUIRE_VALID_NUMBER); panel.getExportCellChangesPathTextField() .getDocument() .addDocumentListener(new ValidatorDocListener()); panel.getExportDirtyDbTypeTextField() .getDocument() .addDocumentListener(new ValidatorDocListener()); panel.getExportDirtyDBPathTextField() .getDocument() .addDocumentListener(new ValidatorDocListener()); panel.getCloneSuffixTextField() .getDocument() .addDocumentListener(new ValidatorDocListener()); panel.getSizeFactorReductionTextField() .getDocument() .addDocumentListener(new ValidatorDocListener()); } private void initListenerCheckbox() { panel.getExportCellChangesCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(panel.getExportCellChangesCheckBox().isSelected()) { panel.getExportCellChangesPathTextField().setEditable(true); panel.getExportCellChangesPathTextField().setEnabled(true); panel.getExportCellChangesButton().setEnabled(true); forceValidation(); }else{ panel.getExportCellChangesPathTextField().setEnabled(false); panel.getExportCellChangesButton().setEnabled(false); forceValidation(); } } }); panel.getExportDirtyDBCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(panel.getExportDirtyDBCheckBox().isSelected()) { panel.getExportDirtyDbTypeTextField().setEnabled(true); panel.getExportDirtyDBPathTextField().setEnabled(true); panel.getExportDirtyDbButton().setEnabled(true); forceValidation(); }else{ panel.getExportDirtyDbTypeTextField().setEnabled(false); panel.getExportDirtyDBPathTextField().setEnabled(false); panel.getExportDirtyDbButton().setEnabled(false); forceValidation(); } } }); panel.getCloneTargetSchemaCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(panel.getCloneTargetSchemaCheckBox().isSelected()) { panel.getCloneSuffixTextField().setEnabled(true); forceValidation(); }else{ panel.getCloneSuffixTextField().setEnabled(false); forceValidation(); } } }); } /*private void InitTitle() { title = new JXTitledSeparator(); getTitle().setIcon(ImageUtilities.image2Icon(ImageUtilities.loadImage(R.IMAGE_SETTINGS_Blu))); getTitle().setHorizontalAlignment(SwingConstants.CENTER); getTitle().setForeground(Color.BLUE.darker()); getTitle().setFont(new Font("Times New Roman", Font.ITALIC, 16)); getTitle().setTitle("EGTask Configuration"); }*/ public Object[] getButtons() { Object[] o = {getOkButton(),getCancelButton()}; return o; } private void InitButton() { okButton = new JButton("OK"); getOkButton().setEnabled(false); cancelButton = new JButton("Cancel"); } /** * @return the okButton */ public JButton getOkButton() { return okButton; } /** * @return the cancelButton */ public JButton getCancelButton() { return cancelButton; } /** * @return the title */ public JXTitledSeparator getTitle() { return title; } /** * @return the panelValAcc */ public ValidationPanel getPanelValAcc() { return panelValAcc; } /** * @return the vg */ public ValidationGroup getVg() { return vg; } /** * @return the panel */ public ConfEGTaskPanel getPanel() { return panel; } private void forceValidation() { Problem validateAll = vg.performValidation(); if (validateAll != null) { okButton.setEnabled(false); } else { okButton.setEnabled(true); } } private class ValidatorDocListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { checkValidation(); } @Override public void removeUpdate(DocumentEvent e) { checkValidation(); } @Override public void changedUpdate(DocumentEvent e) { checkValidation(); } private void checkValidation() { Problem validateAll = vg.performValidation(); if (validateAll != null) { okButton.setEnabled(false); } else { okButton.setEnabled(true); } } } }
package org.hisp.dhis.dataset.hibernate; /* * Copyright (c) 2004-2015, University of Oslo * 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 HISP project 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. */ import java.util.Collection; import java.util.Date; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataset.CompleteDataSetRegistration; import org.hisp.dhis.dataset.CompleteDataSetRegistrationStore; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.period.Period; import org.hisp.dhis.period.PeriodStore; /** * @author Lars Helge Overland * @version $Id$ */ public class HibernateCompleteDataSetRegistrationStore implements CompleteDataSetRegistrationStore { // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private SessionFactory sessionFactory; public void setSessionFactory( SessionFactory sessionFactory ) { this.sessionFactory = sessionFactory; } private PeriodStore periodStore; public void setPeriodStore( PeriodStore periodStore ) { this.periodStore = periodStore; } // ------------------------------------------------------------------------- // DataSetCompleteRegistrationStore implementation // ------------------------------------------------------------------------- @Override public void saveCompleteDataSetRegistration( CompleteDataSetRegistration registration ) { registration.setPeriod( periodStore.reloadForceAddPeriod( registration.getPeriod() ) ); sessionFactory.getCurrentSession().save( registration ); } @Override public void updateCompleteDataSetRegistration( CompleteDataSetRegistration registration ) { registration.setPeriod( periodStore.reloadForceAddPeriod( registration.getPeriod() ) ); sessionFactory.getCurrentSession().update( registration ); } @Override public CompleteDataSetRegistration getCompleteDataSetRegistration( DataSet dataSet, Period period, OrganisationUnit source, DataElementCategoryOptionCombo attributeOptionCombo ) { Period storedPeriod = periodStore.reloadPeriod( period ); if ( storedPeriod == null ) { return null; } Criteria criteria = sessionFactory.getCurrentSession().createCriteria( CompleteDataSetRegistration.class ); criteria.add( Restrictions.eq( "dataSet", dataSet ) ); criteria.add( Restrictions.eq( "period", storedPeriod ) ); criteria.add( Restrictions.eq( "source", source ) ); criteria.add( Restrictions.eq( "attributeOptionCombo", attributeOptionCombo ) ); return (CompleteDataSetRegistration) criteria.uniqueResult(); } @Override public void deleteCompleteDataSetRegistration( CompleteDataSetRegistration registration ) { sessionFactory.getCurrentSession().delete( registration ); } @Override @SuppressWarnings( "unchecked" ) public Collection<CompleteDataSetRegistration> getCompleteDataSetRegistrations( DataSet dataSet, Collection<OrganisationUnit> sources, Period period ) { Period storedPeriod = periodStore.reloadPeriod( period ); if ( storedPeriod == null ) { return null; } Criteria criteria = sessionFactory.getCurrentSession().createCriteria( CompleteDataSetRegistration.class ); criteria.add( Restrictions.eq( "dataSet", dataSet ) ); criteria.add( Restrictions.eq( "period", storedPeriod ) ); criteria.add( Restrictions.in( "source", sources ) ); return criteria.list(); } @Override @SuppressWarnings( "unchecked" ) public Collection<CompleteDataSetRegistration> getAllCompleteDataSetRegistrations() { return sessionFactory.getCurrentSession().createCriteria( CompleteDataSetRegistration.class ).list(); } @Override @SuppressWarnings( "unchecked" ) public Collection<CompleteDataSetRegistration> getCompleteDataSetRegistrations( Collection<DataSet> dataSets, Collection<OrganisationUnit> sources, Collection<Period> periods ) { for ( Period period : periods ) { period = periodStore.reloadPeriod( period ); } Criteria criteria = sessionFactory.getCurrentSession().createCriteria( CompleteDataSetRegistration.class ); criteria.add( Restrictions.in( "dataSet", dataSets ) ); criteria.add( Restrictions.in( "source", sources ) ); criteria.add( Restrictions.in( "period", periods ) ); return criteria.list(); } @Override @SuppressWarnings( "unchecked" ) public Collection<CompleteDataSetRegistration> getCompleteDataSetRegistrations( DataSet dataSet, Collection<OrganisationUnit> sources, Period period, Date deadline ) { Period storedPeriod = periodStore.reloadPeriod( period ); if ( storedPeriod == null ) { return null; } Criteria criteria = sessionFactory.getCurrentSession().createCriteria( CompleteDataSetRegistration.class ); criteria.add( Restrictions.eq( "dataSet", dataSet ) ); criteria.add( Restrictions.in( "source", sources ) ); criteria.add( Restrictions.eq( "period", period ) ); criteria.add( Restrictions.le( "date", deadline ) ); return criteria.list(); } @Override public void deleteCompleteDataSetRegistrations( DataSet dataSet ) { String hql = "delete from CompleteDataSetRegistration c where c.dataSet = :dataSet"; Query query = sessionFactory.getCurrentSession().createQuery( hql ); query.setEntity( "dataSet", dataSet ); query.executeUpdate(); } @Override public void deleteCompleteDataSetRegistrations( OrganisationUnit unit ) { String hql = "delete from CompleteDataSetRegistration c where c.source = :source"; Query query = sessionFactory.getCurrentSession().createQuery( hql ); query.setEntity( "source", unit ); query.executeUpdate(); } }
/* * Copyright 2015 Synced Synapse. 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 org.xbmc.kore.service.library; import android.content.ContentResolver; import android.content.ContentValues; import android.os.Bundle; import android.os.Handler; import org.xbmc.kore.jsonrpc.ApiCallback; import org.xbmc.kore.jsonrpc.ApiList; import org.xbmc.kore.jsonrpc.HostConnection; import org.xbmc.kore.jsonrpc.method.VideoLibrary; import org.xbmc.kore.jsonrpc.type.ListType; import org.xbmc.kore.jsonrpc.type.VideoType; import org.xbmc.kore.provider.MediaContract; import org.xbmc.kore.utils.LogUtils; import java.util.ArrayList; import java.util.List; public class SyncMovies extends SyncItem { public static final String TAG = LogUtils.makeLogTag(SyncMovies.class); private static final int LIMIT_SYNC_MOVIES = 300; private final int hostId; private final int movieId; private final Bundle syncExtras; /** * Syncs all the movies on selected XBMC to the local database * @param hostId XBMC host id */ public SyncMovies(final int hostId, Bundle syncExtras) { this.hostId = hostId; this.movieId = -1; this.syncExtras = syncExtras; } /** * Syncs a specific movie on selected XBMC to the local database * @param hostId XBMC host id */ public SyncMovies(final int hostId, final int movieId, Bundle syncExtras) { this.hostId = hostId; this.movieId = movieId; this.syncExtras = syncExtras; } /** {@inheritDoc} */ public String getDescription() { return (movieId != -1) ? "Sync movies for host: " + hostId : "Sync movie " + movieId + " for host: " + hostId; } /** {@inheritDoc} */ public String getSyncType() { return (movieId == -1) ? LibrarySyncService.SYNC_ALL_MOVIES : LibrarySyncService.SYNC_SINGLE_MOVIE; } /** {@inheritDoc} */ public Bundle getSyncExtras() { return syncExtras; } /** {@inheritDoc} */ public void sync(final SyncOrchestrator orchestrator, final HostConnection hostConnection, final Handler callbackHandler, final ContentResolver contentResolver) { String properties[] = { VideoType.FieldsMovie.TITLE, VideoType.FieldsMovie.GENRE, VideoType.FieldsMovie.YEAR, VideoType.FieldsMovie.RATING, VideoType.FieldsMovie.DIRECTOR, VideoType.FieldsMovie.TRAILER, VideoType.FieldsMovie.TAGLINE, VideoType.FieldsMovie.PLOT, // VideoType.FieldsMovie.PLOTOUTLINE, VideoType.FieldsMovie.ORIGINALTITLE, // VideoType.FieldsMovie.LASTPLAYED, VideoType.FieldsMovie.PLAYCOUNT, VideoType.FieldsMovie.DATEADDED, VideoType.FieldsMovie.WRITER, VideoType.FieldsMovie.STUDIO, VideoType.FieldsMovie.MPAA, VideoType.FieldsMovie.CAST, VideoType.FieldsMovie.COUNTRY, VideoType.FieldsMovie.IMDBNUMBER, VideoType.FieldsMovie.RUNTIME, VideoType.FieldsMovie.SET, // VideoType.FieldsMovie.SHOWLINK, VideoType.FieldsMovie.STREAMDETAILS, VideoType.FieldsMovie.TOP250, VideoType.FieldsMovie.VOTES, VideoType.FieldsMovie.FANART, VideoType.FieldsMovie.THUMBNAIL, VideoType.FieldsMovie.FILE, // VideoType.FieldsMovie.SORTTITLE, VideoType.FieldsMovie.RESUME, VideoType.FieldsMovie.SETID, // VideoType.FieldsMovie.DATEADDED, VideoType.FieldsMovie.TAG, // VideoType.FieldsMovie.ART }; if (movieId == -1) { syncAllMovies(orchestrator, hostConnection, callbackHandler, contentResolver, properties, 0); } else { // Sync a specific movie VideoLibrary.GetMovieDetails action = new VideoLibrary.GetMovieDetails(movieId, properties); action.execute(hostConnection, new ApiCallback<VideoType.DetailsMovie>() { @Override public void onSuccess(VideoType.DetailsMovie result) { deleteMovies(contentResolver, hostId, movieId); List<VideoType.DetailsMovie> movies = new ArrayList<VideoType.DetailsMovie>(1); movies.add(result); insertMovies(orchestrator, contentResolver, movies); orchestrator.syncItemFinished(); } @Override public void onError(int errorCode, String description) { // Ok, something bad happend, just quit orchestrator.syncItemFailed(errorCode, description); } }, callbackHandler); } } /** * Syncs all the movies, calling itself recursively * Uses the {@link VideoLibrary.GetMovies} version with limits to make sure * that Kodi doesn't blow up, and calls itself recursively until all the * movies are returned */ private void syncAllMovies(final SyncOrchestrator orchestrator, final HostConnection hostConnection, final Handler callbackHandler, final ContentResolver contentResolver, final String properties[], final int startIdx) { // Call GetMovies with the current limits set ListType.Limits limits = new ListType.Limits(startIdx, startIdx + LIMIT_SYNC_MOVIES); VideoLibrary.GetMovies action = new VideoLibrary.GetMovies(limits, properties); action.execute(hostConnection, new ApiCallback<ApiList<VideoType.DetailsMovie>>() { @Override public void onSuccess(ApiList<VideoType.DetailsMovie> result) { ListType.LimitsReturned limitsReturned = null; if (result != null) { limitsReturned = result.limits; } if (startIdx == 0) { // First call, delete movies from DB deleteMovies(contentResolver, hostId, -1); } if (!result.items.isEmpty()) { insertMovies(orchestrator, contentResolver, result.items); } LogUtils.LOGD(TAG, "syncAllMovies, movies gotten: " + result.items.size()); if (SyncUtils.moreItemsAvailable(limitsReturned)) { // Max limit returned, there may be some more movies // As we're going to recurse, these result objects can add up, so // let's help the GC and indicate that we don't need this memory // (hopefully this works) result = null; syncAllMovies(orchestrator, hostConnection, callbackHandler, contentResolver, properties, startIdx + LIMIT_SYNC_MOVIES); } else { // Less than the limit was returned so we can finish // (if it returned more there's a bug in Kodi but it // shouldn't be a problem as they got inserted in the DB) orchestrator.syncItemFinished(); } } @Override public void onError(int errorCode, String description) { // Ok, something bad happened, just quit orchestrator.syncItemFailed(errorCode, description); } }, callbackHandler); } /** * Deletes one or all movies from the database (pass -1 on movieId to delete all) */ private void deleteMovies(final ContentResolver contentResolver, int hostId, int movieId) { if (movieId == -1) { // Delete all movies String where = MediaContract.MoviesColumns.HOST_ID + "=?"; contentResolver.delete(MediaContract.MovieCast.CONTENT_URI, where, new String[]{String.valueOf(hostId)}); contentResolver.delete(MediaContract.Movies.CONTENT_URI, where, new String[]{String.valueOf(hostId)}); } else { // Delete a movie contentResolver.delete(MediaContract.MovieCast.buildMovieCastListUri(hostId, movieId), null, null); contentResolver.delete(MediaContract.Movies.buildMovieUri(hostId, movieId), null, null); } } /** * Inserts the given movies in the database */ private void insertMovies(final SyncOrchestrator orchestrator, final ContentResolver contentResolver, final List<VideoType.DetailsMovie> movies) { ContentValues movieValuesBatch[] = new ContentValues[movies.size()]; int castCount = 0; // Iterate on each movie for (int i = 0; i < movies.size(); i++) { VideoType.DetailsMovie movie = movies.get(i); movieValuesBatch[i] = SyncUtils.contentValuesFromMovie(hostId, movie); castCount += movie.cast.size(); } // Insert the movies contentResolver.bulkInsert(MediaContract.Movies.CONTENT_URI, movieValuesBatch); ContentValues movieCastValuesBatch[] = new ContentValues[castCount]; int count = 0; // Iterate on each movie/cast for (VideoType.DetailsMovie movie : movies) { for (VideoType.Cast cast : movie.cast) { movieCastValuesBatch[count] = SyncUtils.contentValuesFromCast(hostId, cast); movieCastValuesBatch[count].put(MediaContract.MovieCastColumns.MOVIEID, movie.movieid); count++; } } // Insert the cast list for this movie contentResolver.bulkInsert(MediaContract.MovieCast.CONTENT_URI, movieCastValuesBatch); } }
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.reflect.base; import java.lang.reflect.Array; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.mmm.util.component.base.AbstractComponent; import net.sf.mmm.util.lang.api.GenericBean; import net.sf.mmm.util.reflect.api.CollectionReflectionUtil; /** * This is the implementation of the {@link CollectionReflectionUtil} interface. * * @see #getInstance() * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.1 */ public class CollectionReflectionUtilImpl extends AbstractComponent implements CollectionReflectionUtil { private static final Logger LOG = LoggerFactory.getLogger(CollectionReflectionUtilImpl.class); /** * The default value for the maximum growth of the {@link #getSize(Object) size} of an array or {@link List} : * {@value} */ public static final int DEFAULT_MAXIMUM_LIST_GROWTH = 128; private static CollectionReflectionUtilImpl instance; private int maximumListGrowth; /** * The constructor. */ public CollectionReflectionUtilImpl() { super(); this.maximumListGrowth = DEFAULT_MAXIMUM_LIST_GROWTH; } /** * This method gets the singleton instance of this {@link CollectionReflectionUtilImpl}. <br> * <b>ATTENTION:</b><br> * Please prefer dependency-injection instead of using this method. * * @return the singleton instance. */ public static CollectionReflectionUtilImpl getInstance() { if (instance == null) { synchronized (CollectionReflectionUtilImpl.class) { if (instance == null) { CollectionReflectionUtilImpl util = new CollectionReflectionUtilImpl(); util.initialize(); instance = util; } } } return instance; } @Override protected void doInitialize() { super.doInitialize(); } /** * This method gets the maximum growth for arrays or {@link List}s. * * @see #set(Object, int, Object, GenericBean) * @see #setMaximumListGrowth(int) * * @return the maximumListGrowth */ public int getMaximumListGrowth() { return this.maximumListGrowth; } /** * This method sets the {@link #getMaximumListGrowth() maximumListGrowth}. * * @param maximumListGrowth is the maximumListGrowth to set. */ public void setMaximumListGrowth(int maximumListGrowth) { getInitializationState().requireNotInitilized(); this.maximumListGrowth = maximumListGrowth; } @Override public boolean isArrayOrList(Object object) { Objects.requireNonNull(object, "object"); Class<?> type = object.getClass(); if (type.isArray()) { return true; } else if (List.class.isAssignableFrom(type)) { return true; } return false; } @Override public int getSize(Object arrayMapOrCollection) { Objects.requireNonNull(arrayMapOrCollection, "arrayMapOrCollection"); Class<?> type = arrayMapOrCollection.getClass(); if (type.isArray()) { return Array.getLength(arrayMapOrCollection); } else if (Collection.class.isAssignableFrom(type)) { return ((Collection<?>) arrayMapOrCollection).size(); } else if (Map.class.isAssignableFrom(type)) { return ((Map<?, ?>) arrayMapOrCollection).size(); } else { throw new IllegalArgumentException(arrayMapOrCollection.getClass().getName()); } } @Override public Object get(Object arrayOrList, int index) { return get(arrayOrList, index, true); } @Override public Object get(Object arrayOrList, int index, boolean ignoreIndexOverflow) { Objects.requireNonNull(arrayOrList, "arrayOrList"); Class<?> type = arrayOrList.getClass(); if (type.isArray()) { if (ignoreIndexOverflow) { int length = Array.getLength(arrayOrList); if (index >= length) { return null; } } return Array.get(arrayOrList, index); } else if (List.class.isAssignableFrom(type)) { List<?> list = (List<?>) arrayOrList; if (ignoreIndexOverflow) { if (index >= list.size()) { return null; } } return list.get(index); } else { throw new IllegalArgumentException(arrayOrList.getClass().getName()); } } @Override public Object set(Object arrayOrList, int index, Object item) { return set(arrayOrList, index, item, null, this.maximumListGrowth); } @Override public Object set(Object arrayOrList, int index, Object item, GenericBean<Object> arrayReceiver) { return set(arrayOrList, index, item, arrayReceiver, this.maximumListGrowth); } @Override @SuppressWarnings({ "rawtypes", "unchecked", "null" }) public Object set(Object arrayOrList, int index, Object item, GenericBean<Object> arrayReceiver, int maximumGrowth) { Objects.requireNonNull(arrayOrList, "arrayOrList"); int maxGrowth = maximumGrowth; Class<?> type = arrayOrList.getClass(); List list = null; int size; if (type.isArray()) { size = Array.getLength(arrayOrList); if (arrayReceiver == null) { maxGrowth = 0; } } else if (List.class.isAssignableFrom(type)) { list = (List) arrayOrList; size = list.size(); } else { throw new IllegalArgumentException(arrayOrList.getClass().getName()); } int growth = index - size + 1; if (growth > maxGrowth) { throw new ContainerGrowthException(growth, maxGrowth); } if (type.isArray()) { if (growth > 0) { LOG.trace("Increasing array size by {}", Integer.valueOf(growth)); Object newArray = Array.newInstance(type.getComponentType(), index + 1); System.arraycopy(arrayOrList, 0, newArray, 0, size); Array.set(newArray, index, item); arrayReceiver.setValue(newArray); return null; } else { Object old = Array.get(arrayOrList, index); Array.set(arrayOrList, index, item); return old; } } else { // arrayOrList is list... // increase size of list if (growth > 0) { LOG.trace("Increasing list size by {}", Integer.valueOf(growth)); growth--; while (growth > 0) { list.add(null); growth--; } list.add(item); return null; } else { return list.set(index, item); } } } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Object add(Object arrayOrCollection, Object item) { Objects.requireNonNull(arrayOrCollection, "arrayOrCollection"); Class<?> type = arrayOrCollection.getClass(); if (type.isArray()) { int size = Array.getLength(arrayOrCollection); Object newArray = Array.newInstance(type.getComponentType(), size + 1); System.arraycopy(arrayOrCollection, 0, newArray, 0, size); Array.set(newArray, size, item); return newArray; } else if (Collection.class.isAssignableFrom(type)) { Collection collection = (Collection) arrayOrCollection; collection.add(item); } else { throw new IllegalArgumentException(arrayOrCollection.getClass().getName()); } return arrayOrCollection; } @Override @SuppressWarnings("rawtypes") public Object remove(Object arrayOrCollection, Object item) { Objects.requireNonNull(arrayOrCollection, "arrayOrCollection"); Class<?> type = arrayOrCollection.getClass(); if (type.isArray()) { int size = Array.getLength(arrayOrCollection); for (int index = 0; index < size; index++) { Object currentItem = Array.get(arrayOrCollection, index); if ((item == currentItem) || ((item != null) && (item.equals(currentItem)))) { // found Object newArray = Array.newInstance(type.getComponentType(), size - 1); System.arraycopy(arrayOrCollection, 0, newArray, 0, index); System.arraycopy(arrayOrCollection, index + 1, newArray, index, size - index - 1); return newArray; } } return null; } else if (Collection.class.isAssignableFrom(type)) { Collection collection = (Collection) arrayOrCollection; boolean removed = collection.remove(item); if (removed) { return arrayOrCollection; } else { return null; } } else { throw new IllegalArgumentException(arrayOrCollection.getClass().getName()); } } @Override public Object toArray(Collection<?> collection, Class<?> componentType) throws ClassCastException { Objects.requireNonNull(componentType, "componentType"); if (collection == null) { return null; } int length = collection.size(); Object array = Array.newInstance(componentType, length); Iterator<?> iterator = collection.iterator(); int i = 0; if (componentType.isPrimitive()) { while (iterator.hasNext()) { Array.set(array, i++, iterator.next()); } } else { Object[] objectArray = (Object[]) array; while (iterator.hasNext()) { objectArray[i++] = iterator.next(); } } return array; } @Override @SuppressWarnings("unchecked") public <T> T[] toArrayTyped(Collection<T> collection, Class<T> componentType) { return (T[]) toArray(collection, componentType); } }
package com.gentics.mesh.cache.impl; import java.time.Duration; import java.time.temporal.TemporalUnit; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import java.util.function.Function; import com.gentics.mesh.cache.EventAwareCache; import com.gentics.mesh.core.rest.MeshEvent; import com.gentics.mesh.etc.config.MeshOptions; import com.gentics.mesh.metric.CachingMetric; import com.gentics.mesh.metric.MetricsService; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import io.micrometer.core.instrument.Counter; import io.reactivex.Observable; import io.reactivex.functions.Predicate; import io.vertx.core.Vertx; import io.vertx.core.eventbus.EventBus; import io.vertx.core.eventbus.Message; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @see EventAwareCache */ public class EventAwareCacheImpl<K, V> implements EventAwareCache<K, V> { private static final Logger log = LoggerFactory.getLogger(EventAwareCacheImpl.class); private final Cache<K, V> cache; private final Vertx vertx; private final MeshOptions options; private final Predicate<Message<JsonObject>> filter; private BiConsumer<Message<JsonObject>, EventAwareCache<K, V>> onNext; private boolean disabled = false; private final Counter invalidateKeyCounter; private final Counter invalidateAllCounter; private final Counter missCounter; private final Counter hitCounter; public EventAwareCacheImpl(String name, long maxSize, Duration expireAfter, Duration expireAfterAccess, Vertx vertx, MeshOptions options, MetricsService metricsService, Predicate<Message<JsonObject>> filter, BiConsumer<Message<JsonObject>, EventAwareCache<K, V>> onNext, MeshEvent... events) { this.vertx = vertx; this.options = options; Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder().maximumSize(maxSize); if (expireAfter != null) { cacheBuilder = cacheBuilder.expireAfterWrite(expireAfter.getSeconds(), TimeUnit.SECONDS); } if (expireAfterAccess != null) { cacheBuilder = cacheBuilder.expireAfterAccess(expireAfterAccess.getSeconds(), TimeUnit.SECONDS); } this.cache = cacheBuilder.build(); this.filter = filter; this.onNext = onNext; registerEventHandlers(events); invalidateKeyCounter = metricsService.counter(new CachingMetric(CachingMetric.Event.CLEAR_SINGLE, name)); invalidateAllCounter = metricsService.counter(new CachingMetric(CachingMetric.Event.CLEAR_ALL, name)); missCounter = metricsService.counter(new CachingMetric(CachingMetric.Event.MISS, name)); hitCounter = metricsService.counter(new CachingMetric(CachingMetric.Event.HIT, name)); } private void registerEventHandlers(MeshEvent... events) { if (log.isTraceEnabled()) { log.trace("Registering to events"); } EventBus eb = vertx.eventBus(); Observable<Message<JsonObject>> o = rxEventBus(eb, events); if (filter != null) { o = o.filter(filter); } o.subscribe(event -> { // Use a default implementation which will invalidate the whole cache on every event if (onNext == null) { invalidate(); } else { onNext.accept(event, this); } }, error -> { log.error("Error while handling event in cache. Disabling cache.", error); disable(); }); } @Override public void disable() { disabled = true; } @Override public void enable() { disabled = false; } @Override public long size() { cache.cleanUp(); return cache.estimatedSize(); } @Override public void invalidate() { if (log.isTraceEnabled()) { log.trace("Invalidating full cache"); } if (options.getMonitoringOptions().isEnabled()) { invalidateAllCounter.increment(); } cache.invalidateAll(); } @Override public void invalidate(K key) { if (log.isTraceEnabled()) { log.trace("Invalidating entry with key {" + key + "}"); } if (options.getMonitoringOptions().isEnabled()) { invalidateKeyCounter.increment(); } cache.invalidate(key); } @Override public void put(K key, V value) { if (disabled) { return; } cache.put(key, value); } @Override public V get(K key) { if (disabled) { return null; } if (options.getMonitoringOptions().isEnabled()) { V value = cache.getIfPresent(key); if (value == null) { missCounter.increment(); } else { hitCounter.increment(); } return value; } else { return cache.getIfPresent(key); } } @Override public V get(K key, Function<? super K, ? extends V> mappingFunction) { if (disabled) { return mappingFunction.apply(key); } if (options.getMonitoringOptions().isEnabled()) { AtomicBoolean wasCached = new AtomicBoolean(true); V value = cache.get(key, k -> { wasCached.set(false); return mappingFunction.apply(k); }); if (wasCached.get()) { hitCounter.increment(); } else { missCounter.increment(); } return value; } else { return cache.get(key, mappingFunction); } } /** * Builder for caches. * * @param <K> * @param <V> */ public static class Builder<K, V> { private boolean disabled = false; private long maxSize = 1000; private Predicate<Message<JsonObject>> filter = null; private BiConsumer<Message<JsonObject>, EventAwareCache<K, V>> onNext = null; private MeshEvent[] events = null; private Vertx vertx; private Duration expireAfter; private Duration expireAfterAccess; private String name; private MeshOptions options; private MetricsService metricsService; /** * Build the cache instance. * * @return Created instance */ public EventAwareCache<K, V> build() { Objects.requireNonNull(events, "No events for the cache have been set"); Objects.requireNonNull(vertx, "No Vert.x instance has been set"); Objects.requireNonNull(name, "No name has been set"); EventAwareCacheImpl<K, V> c = new EventAwareCacheImpl<>(name, maxSize, expireAfter, expireAfterAccess, vertx, options, metricsService, filter, onNext, events); if (disabled) { c.disable(); } return c; } /** * Set the events to react upon. * * @param events * @return Fluent API */ public Builder<K, V> events(MeshEvent... events) { this.events = events; return this; } /** * Set the event filter. * * @param filter * @return Fluent API */ public Builder<K, V> filter(Predicate<Message<JsonObject>> filter) { this.filter = filter; return this; } /** * Action which will be invoked on every received event. * * @return Fluent API */ public Builder<K, V> action(BiConsumer<Message<JsonObject>, EventAwareCache<K, V>> onNext) { this.onNext = onNext; return this; } /** * Disable the created cache. * * @return Fluent API */ public Builder<K, V> disabled() { this.disabled = true; return this; } /** * Set the vertx instance to be used for eventbus communication. * * @param vertx * @return Fluent API */ public Builder<K, V> vertx(Vertx vertx) { this.vertx = vertx; return this; } /** * Sets the mesh options which will be used to determine if cache metrics are enabled. * * @param options * @return */ public Builder<K, V> meshOptions(MeshOptions options) { this.options = options; return this; } /** * Set the metrics service which will be used to track caching statistics. * * @param metricsService * @return */ public Builder<K, V> setMetricsService(MetricsService metricsService) { this.metricsService = metricsService; return this; } /** * Set the maximum size for the cache. * * @param maxSize * @return Fluent API */ public Builder<K, V> maxSize(long maxSize) { this.maxSize = maxSize; return this; } /** * Define when the cache should automatically expire. * * @param amount * @param unit * @return Fluent API */ public Builder<K, V> expireAfter(long amount, TemporalUnit unit) { this.expireAfter = Duration.of(amount, unit); return this; } /** * Define when the cache should automatically expire after last access * * @param amount * @param unit * @return Fluent API */ public Builder<K, V> expireAfterAccess(long amount, TemporalUnit unit) { this.expireAfterAccess = Duration.of(amount, unit); return this; } /** * Sets the name for the cache. This is used for caching metrics. * * @param name * @return Fluent API */ public Builder<K, V> name(String name) { this.name = name; return this; } } /** * Return an observable which emits eventbus messages for the given addresses. * * @param eventBus * Eventbus used for registration * @param addresses * Addresses to listen to * @return */ public static Observable<Message<JsonObject>> rxEventBus(EventBus eventBus, MeshEvent... addresses) { return Observable.fromArray(addresses) .flatMap(meshEvent -> Observable.using( () -> eventBus.<JsonObject>consumer(meshEvent.address), consumer -> Observable.create(sub -> consumer.handler(sub::onNext)), MessageConsumer::unregister)); } }
/* * Copyright (c) 2012-2016: Christopher J. Brody (aka Chris Brody) * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ package io.sqlc; import android.annotation.SuppressLint; import android.database.Cursor; import android.database.CursorWindow; import android.database.sqlite.SQLiteCursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import android.util.Base64; import android.util.Log; import java.io.File; import java.lang.IllegalArgumentException; import java.lang.Number; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Android Database helper class */ class SQLiteAndroidDatabase { private static final Pattern FIRST_WORD = Pattern.compile("^\\s*(\\S+)", Pattern.CASE_INSENSITIVE); private static final Pattern WHERE_CLAUSE = Pattern.compile("\\s+WHERE\\s+(.+)$", Pattern.CASE_INSENSITIVE); private static final Pattern UPDATE_TABLE_NAME = Pattern.compile("^\\s*UPDATE\\s+(\\S+)", Pattern.CASE_INSENSITIVE); private static final Pattern DELETE_TABLE_NAME = Pattern.compile("^\\s*DELETE\\s+FROM\\s+(\\S+)", Pattern.CASE_INSENSITIVE); File dbFile; SQLiteDatabase mydb; /** * NOTE: Using default constructor, no explicit constructor. */ /** * Open a database. * * @param dbfile The database File specification */ void open(File dbfile) throws Exception { dbFile = dbfile; // for possible bug workaround mydb = SQLiteDatabase.openOrCreateDatabase(dbfile, null); } /** * Close a database (in the current thread). */ void closeDatabaseNow() { if (mydb != null) { mydb.close(); mydb = null; } } void bugWorkaround() throws Exception { this.closeDatabaseNow(); this.open(dbFile); } /** * Executes a batch request and sends the results via cbc. * * @param queryarr Array of query strings * @param jsonparamsArr Array of JSON query parameters * @param cbc Callback context from Cordova API */ void executeSqlBatch(String[] queryarr, JSONArray[] jsonparamsArr, CallbackContext cbc) { if (mydb == null) { // not allowed - can only happen if someone has closed (and possibly deleted) a database and then re-used the database cbc.error("database has been closed"); return; } int len = queryarr.length; JSONArray batchResults = new JSONArray(); for (int i = 0; i < len; i++) { executeSqlBatchStatement(queryarr[i], jsonparamsArr[i], batchResults); } cbc.success(batchResults); } @SuppressLint("NewApi") private void executeSqlBatchStatement(String query, JSONArray json_params, JSONArray batchResults) { if (mydb == null) { // Should not happen here return; } else { int rowsAffectedCompat = 0; boolean needRowsAffectedCompat = false; JSONObject queryResult = null; String errorMessage = "unknown"; try { boolean needRawQuery = true; QueryType queryType = getQueryType(query); if (queryType == QueryType.update || queryType == queryType.delete) { if (android.os.Build.VERSION.SDK_INT >= 11) { SQLiteStatement myStatement = mydb.compileStatement(query); if (json_params != null) { bindArgsToStatement(myStatement, json_params); } int rowsAffected = -1; // (assuming invalid) // Use try & catch just in case android.os.Build.VERSION.SDK_INT >= 11 is lying: try { rowsAffected = myStatement.executeUpdateDelete(); // Indicate valid results: needRawQuery = false; } catch (SQLiteException ex) { // Indicate problem & stop this query: ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteStatement.executeUpdateDelete(): Error=" + errorMessage); needRawQuery = false; } catch (Exception ex) { // Assuming SDK_INT was lying & method not found: // do nothing here & try again with raw query. } // "finally" cleanup myStatement myStatement.close(); if (rowsAffected != -1) { queryResult = new JSONObject(); queryResult.put("rowsAffected", rowsAffected); } } if (needRawQuery) { // for pre-honeycomb behavior rowsAffectedCompat = countRowsAffectedCompat(queryType, query, json_params, mydb); needRowsAffectedCompat = true; } } // INSERT: if (queryType == QueryType.insert && json_params != null) { needRawQuery = false; SQLiteStatement myStatement = mydb.compileStatement(query); bindArgsToStatement(myStatement, json_params); long insertId = -1; // (invalid) try { insertId = myStatement.executeInsert(); // statement has finished with no constraint violation: queryResult = new JSONObject(); if (insertId != -1) { queryResult.put("insertId", insertId); queryResult.put("rowsAffected", 1); } else { queryResult.put("rowsAffected", 0); } } catch (SQLiteException ex) { // report error result with the error message // could be constraint violation or some other error ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteDatabase.executeInsert(): Error=" + errorMessage); } // "finally" cleanup myStatement myStatement.close(); } if (queryType == QueryType.begin) { needRawQuery = false; try { mydb.beginTransaction(); queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteDatabase.beginTransaction(): Error=" + errorMessage); } } if (queryType == QueryType.commit) { needRawQuery = false; try { mydb.setTransactionSuccessful(); mydb.endTransaction(); queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteDatabase.setTransactionSuccessful/endTransaction(): Error=" + errorMessage); } } if (queryType == QueryType.rollback) { needRawQuery = false; try { mydb.endTransaction(); queryResult = new JSONObject(); queryResult.put("rowsAffected", 0); } catch (SQLiteException ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteDatabase.endTransaction(): Error=" + errorMessage); } } // raw query for other statements: if (needRawQuery) { queryResult = this.executeSqlStatementQuery(mydb, query, json_params); if (needRowsAffectedCompat) { queryResult.put("rowsAffected", rowsAffectedCompat); } } } catch (Exception ex) { ex.printStackTrace(); errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + errorMessage); } try { if (queryResult != null) { JSONObject r = new JSONObject(); r.put("type", "success"); r.put("result", queryResult); batchResults.put(r); } else { JSONObject r = new JSONObject(); r.put("type", "error"); JSONObject er = new JSONObject(); er.put("message", errorMessage); r.put("result", er); batchResults.put(r); } } catch (JSONException ex) { ex.printStackTrace(); Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + ex.getMessage()); // TODO what to do? } } } private final int countRowsAffectedCompat(QueryType queryType, String query, JSONArray json_params, SQLiteDatabase mydb) throws JSONException { // quick and dirty way to calculate the rowsAffected in pre-Honeycomb. just do a SELECT // beforehand using the same WHERE clause. might not be perfect, but it's better than nothing Matcher whereMatcher = WHERE_CLAUSE.matcher(query); String where = ""; int pos = 0; while (whereMatcher.find(pos)) { where = " WHERE " + whereMatcher.group(1); pos = whereMatcher.start(1); } // WHERE clause may be omitted, and also be sure to find the last one, // e.g. for cases where there's a subquery // bindings may be in the update clause, so only take the last n int numQuestionMarks = 0; for (int j = 0; j < where.length(); j++) { if (where.charAt(j) == '?') { numQuestionMarks++; } } JSONArray subParams = null; if (json_params != null) { // only take the last n of every array of sqlArgs JSONArray origArray = json_params; subParams = new JSONArray(); int startPos = origArray.length() - numQuestionMarks; for (int j = startPos; j < origArray.length(); j++) { subParams.put(j - startPos, origArray.get(j)); } } if (queryType == QueryType.update) { Matcher tableMatcher = UPDATE_TABLE_NAME.matcher(query); if (tableMatcher.find()) { String table = tableMatcher.group(1); try { SQLiteStatement statement = mydb.compileStatement( "SELECT count(*) FROM " + table + where); if (subParams != null) { bindArgsToStatement(statement, subParams); } return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going Log.e(SQLiteAndroidDatabase.class.getSimpleName(), "uncaught", e); } } } else { // delete Matcher tableMatcher = DELETE_TABLE_NAME.matcher(query); if (tableMatcher.find()) { String table = tableMatcher.group(1); try { SQLiteStatement statement = mydb.compileStatement( "SELECT count(*) FROM " + table + where); bindArgsToStatement(statement, subParams); return (int)statement.simpleQueryForLong(); } catch (Exception e) { // assume we couldn't count for whatever reason, keep going Log.e(SQLiteAndroidDatabase.class.getSimpleName(), "uncaught", e); } } } return 0; } private void bindArgsToStatement(SQLiteStatement myStatement, JSONArray sqlArgs) throws JSONException { for (int i = 0; i < sqlArgs.length(); i++) { if (sqlArgs.get(i) instanceof Float || sqlArgs.get(i) instanceof Double) { myStatement.bindDouble(i + 1, sqlArgs.getDouble(i)); } else if (sqlArgs.get(i) instanceof Number) { myStatement.bindLong(i + 1, sqlArgs.getLong(i)); } else if (sqlArgs.isNull(i)) { myStatement.bindNull(i + 1); } else { myStatement.bindString(i + 1, sqlArgs.getString(i)); } } } /** * Get rows results from query cursor. * * @param cur Cursor into query results * @return results in string form */ private JSONObject executeSqlStatementQuery(SQLiteDatabase mydb, String query, JSONArray paramsAsJson) throws Exception { JSONObject rowsResult = new JSONObject(); Cursor cur = null; try { String[] params = null; params = new String[paramsAsJson.length()]; for (int j = 0; j < paramsAsJson.length(); j++) { if (paramsAsJson.isNull(j)) params[j] = ""; else params[j] = paramsAsJson.getString(j); } cur = mydb.rawQuery(query, params); } catch (Exception ex) { ex.printStackTrace(); String errorMessage = ex.getMessage(); Log.v("executeSqlBatch", "SQLiteAndroidDatabase.executeSql[Batch](): Error=" + errorMessage); throw ex; } // If query result has rows if (cur != null && cur.moveToFirst()) { JSONArray rowsArrayResult = new JSONArray(); String key = ""; int colCount = cur.getColumnCount(); // Build up JSON result object for each row do { JSONObject row = new JSONObject(); try { for (int i = 0; i < colCount; ++i) { key = cur.getColumnName(i); if (android.os.Build.VERSION.SDK_INT >= 11) { // Use try & catch just in case android.os.Build.VERSION.SDK_INT >= 11 is lying: try { bindPostHoneycomb(row, key, cur, i); } catch (Exception ex) { bindPreHoneycomb(row, key, cur, i); } } else { bindPreHoneycomb(row, key, cur, i); } } rowsArrayResult.put(row); } catch (JSONException e) { e.printStackTrace(); } } while (cur.moveToNext()); try { rowsResult.put("rows", rowsArrayResult); } catch (JSONException e) { e.printStackTrace(); } } if (cur != null) { cur.close(); } return rowsResult; } @SuppressLint("NewApi") private void bindPostHoneycomb(JSONObject row, String key, Cursor cur, int i) throws JSONException { int curType = cur.getType(i); switch (curType) { case Cursor.FIELD_TYPE_NULL: row.put(key, JSONObject.NULL); break; case Cursor.FIELD_TYPE_INTEGER: row.put(key, cur.getLong(i)); break; case Cursor.FIELD_TYPE_FLOAT: row.put(key, cur.getDouble(i)); break; /* ** Read BLOB as Base-64 DISABLED in this branch: case Cursor.FIELD_TYPE_BLOB: row.put(key, new String(Base64.encode(cur.getBlob(i), Base64.DEFAULT))); break; // ** Read BLOB as Base-64 DISABLED to HERE. */ case Cursor.FIELD_TYPE_STRING: default: /* (not expected) */ row.put(key, cur.getString(i)); break; } } private void bindPreHoneycomb(JSONObject row, String key, Cursor cursor, int i) throws JSONException { // Since cursor.getType() is not available pre-honeycomb, this is // a workaround so we don't have to bind everything as a string // Details here: http://stackoverflow.com/q/11658239 SQLiteCursor sqLiteCursor = (SQLiteCursor) cursor; CursorWindow cursorWindow = sqLiteCursor.getWindow(); int pos = cursor.getPosition(); if (cursorWindow.isNull(pos, i)) { row.put(key, JSONObject.NULL); } else if (cursorWindow.isLong(pos, i)) { row.put(key, cursor.getLong(i)); } else if (cursorWindow.isFloat(pos, i)) { row.put(key, cursor.getDouble(i)); /* ** Read BLOB as Base-64 DISABLED in this branch: } else if (cursorWindow.isBlob(pos, i)) { row.put(key, new String(Base64.encode(cursor.getBlob(i), Base64.DEFAULT))); // ** Read BLOB as Base-64 DISABLED to HERE. */ } else { // string row.put(key, cursor.getString(i)); } } static QueryType getQueryType(String query) { Matcher matcher = FIRST_WORD.matcher(query); if (matcher.find()) { try { return QueryType.valueOf(matcher.group(1).toLowerCase()); } catch (IllegalArgumentException ignore) { // unknown verb } } return QueryType.other; } static enum QueryType { update, insert, delete, select, begin, commit, rollback, other } } /* vim: set expandtab : */
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.event.simulator.core.internal.generator.database.core; import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.pool.PoolInitializationException; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wso2.carbon.event.simulator.core.exception.*; import org.wso2.carbon.event.simulator.core.internal.bean.DBSimulationDTO; import org.wso2.carbon.event.simulator.core.internal.generator.EventGenerator; import org.wso2.carbon.event.simulator.core.internal.generator.database.util.DatabaseConnector; import org.wso2.carbon.event.simulator.core.internal.util.EventConverter; import org.wso2.carbon.event.simulator.core.internal.util.EventSimulatorConstants; import org.wso2.carbon.event.simulator.core.model.DBConnectionModel; import org.wso2.carbon.event.simulator.core.service.EventSimulatorDataHolder; import org.wso2.carbon.event.simulator.core.util.SourceConfigLogger; import org.wso2.carbon.stream.processor.common.exception.ResourceNotFoundException; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.query.api.definition.Attribute; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.wso2.carbon.event.simulator.core.internal.util.CommonOperations.checkAvailability; /** * DatabaseEventGenerator class is used to generate events from a database */ public class DatabaseEventGenerator implements EventGenerator { private static final Logger log = LoggerFactory.getLogger(DatabaseEventGenerator.class); private long startTimestamp; private long endTimestamp; private long currentTimestamp; private DBSimulationDTO dbSimulationConfig; private Event nextEvent = null; private ResultSet resultSet; private DatabaseConnector databaseConnection; private List<Attribute> streamAttributes; private List<String> columnNames; public DatabaseEventGenerator() { } /** * init() initializes database event generator and set the timestamp start and end time. * * @param sourceConfig JSON object containing configuration for database event generation * @param startTimestamp least possible value for timestamp * @param endTimestamp maximum possible value for timestamp * @throws InvalidConfigException if the database source configuration is invalid * @throws ResourceNotFoundException if resources required for simulation are not available */ @Override public void init(JSONObject sourceConfig, long startTimestamp, long endTimestamp, String simulationName) throws SimulationValidationException { //retrieve stream attributes try { streamAttributes = EventSimulatorDataHolder.getInstance().getEventStreamService() .getStreamAttributes(sourceConfig.getString(EventSimulatorConstants.EXECUTION_PLAN_NAME), sourceConfig.getString(EventSimulatorConstants.STREAM_NAME)); } catch (ResourceNotFoundException e) { log.error(e.getResourceTypeString() + " '" + e.getResourceName() + "' specified for database simulation does not exist. Invalid source configuration : " + sourceConfig.toString(), e); throw new SimulatorInitializationException(e.getResourceTypeString() + " '" + e.getResourceName() + "' " + "specified for database simulation does not exist. " + "Invalid source configuration : " +sourceConfig.toString(), e); } dbSimulationConfig = createDBConfiguration(sourceConfig, simulationName); //set timestamp boundary this.startTimestamp = startTimestamp; this.endTimestamp = endTimestamp; if (log.isDebugEnabled()) { log.debug("Timestamp range initiated for database event generator for stream '" + dbSimulationConfig.getStreamName() + "'. Timestamp start time : " + startTimestamp + " and timestamp end time : " + endTimestamp); } if (dbSimulationConfig.getTimestampAttribute() == null) { currentTimestamp = startTimestamp; } columnNames = dbSimulationConfig.getColumnNames(); try { databaseConnection = new DatabaseConnector(); databaseConnection.connectToDatabase(dbSimulationConfig.getDriver(), dbSimulationConfig.getDataSourceLocation(), dbSimulationConfig.getUsername(), dbSimulationConfig.getPassword()); databaseConnection.closeConnection(); } catch (PoolInitializationException e) { throw new SimulationValidationException( dbSimulationConfig.getDataSourceLocation(), ResourceNotFoundException.ResourceType.DATABASE, "Error occurred when creating connection to database ' " + dbSimulationConfig.getDataSourceLocation() + "' to simulate to simulate stream '" + dbSimulationConfig.getStreamName() + "'. Please check connection and config settings. ", e); } } /** * start() method is used to retrieve the resultSet from the data source and to obtain the first event */ @Override public void start() { try { databaseConnection.connectToDatabase(dbSimulationConfig.getDriver(), dbSimulationConfig.getDataSourceLocation(), dbSimulationConfig.getUsername(), dbSimulationConfig.getPassword()); } catch (PoolInitializationException e) { throw new EventGenerationException("Error occurred when creating connection to database ' " + dbSimulationConfig.getDataSourceLocation() + "' to simulate to simulate stream '" + dbSimulationConfig.getStreamName() + "'. Please check connection and config settings. ", e); } if (startTimestamp == -1 && "-1".equals(dbSimulationConfig.getTimestampAttribute())) { startTimestamp = System.currentTimeMillis(); } try { resultSet = databaseConnection.getDatabaseEventItems(dbSimulationConfig.getTableName(), dbSimulationConfig.getColumnNames(), dbSimulationConfig.getTimestampAttribute(), startTimestamp, endTimestamp); if (resultSet != null && !resultSet.isBeforeFirst()) { throw new EventGenerationException("Table '" + dbSimulationConfig.getTableName() + "' contains no entries for the columns specified in " + "source configuration " + dbSimulationConfig.toString()); } getNextEvent(); } catch (SQLException e) { log.error("Error occurred when retrieving resultset from database ' " + dbSimulationConfig.getDataSourceLocation() + "' to simulate to simulate stream '" + dbSimulationConfig.getStreamName() + "' using source configuration " + dbSimulationConfig.toString(), e); throw new SimulatorInitializationException("Error occurred when retrieving resultset from database ' " +dbSimulationConfig.getDataSourceLocation() + "' to simulate to simulate stream '" + dbSimulationConfig.getStreamName() + "' using source configuration " + dbSimulationConfig.toString(), e); } if (log.isDebugEnabled() && resultSet != null) { log.debug("Retrieved resultset to simulate stream '" + dbSimulationConfig.getStreamName() + "' and initialized variable nextEvent."); } if (log.isDebugEnabled()) { log.debug("Start database generator for stream '" + dbSimulationConfig.getStreamName() + "'"); } } /** * stop() method is used to close database resources held by the database event generator */ @Override public void stop() { currentTimestamp = -1; if (databaseConnection != null) { databaseConnection.closeConnection(); } if (log.isDebugEnabled()) { log.debug("Stop database generator for stream '" + dbSimulationConfig.getStreamName() + "'"); } } /** * resume() method */ @Override public void resume() { if (null == dbSimulationConfig.getTimestampAttribute()) { currentTimestamp = System.currentTimeMillis(); nextEvent.setTimestamp(currentTimestamp); currentTimestamp += dbSimulationConfig.getTimestampInterval(); } if (log.isDebugEnabled()) { log.debug("Stop random generator for stream '" + dbSimulationConfig.getStreamName() + "'"); } } /** * poll() method is used to retrieve the nextEvent of generator and assign the next event of with least timestamp * as nextEvent * * @return nextEvent */ @Override public Event poll() { /* * if nextEvent is not null, it implies that more events may be generated by the generator. Hence call * getNExtEvent() method to assign the next event with least timestamp as nextEvent. * else if nextEvent == null, it implies that generator will not generate any more events. Hence return null. * */ Event tempEvent = nextEvent; if (tempEvent != null) { getNextEvent(); } return tempEvent; } /** * peek() method is used to access the nextEvent of generator * * @return nextEvent */ @Override public Event peek() { return nextEvent; } /** * getNextEvent() method is used to get the next event with least timestamp */ @Override public void getNextEvent() { try { /* * if the resultset has a next entry, create an event using that entry and assign it to nextEvent * else, assign null to nextEvent * */ if (resultSet != null) { if (resultSet.next()) { Object[] attributeValues = new Object[streamAttributes.size()]; long timestamp = -1; /* * if timestamp attribute is specified use the value of the respective column as timestamp * else, calculate the timestamp. * timestamp of first event will be currentTimestamp and timestamp of successive event * will be (last event timestamp + interval) * */ if (dbSimulationConfig.getTimestampAttribute() != null) { timestamp = resultSet.getLong(dbSimulationConfig.getTimestampAttribute()); } else if (endTimestamp == -1 || currentTimestamp <= endTimestamp) { // If the start timestamp is not given, then the system timestamp will be used. if (currentTimestamp == -1) { currentTimestamp = System.currentTimeMillis(); } timestamp = currentTimestamp; currentTimestamp += dbSimulationConfig.getTimestampInterval(); } if (timestamp != -1) { int i = 0; /* * For each attribute in streamAttributes, use attribute type to determine the getter method * to be used to access the resultset and use the attribute name to access a particular field * in resultset * */ for (Attribute attribute : streamAttributes) { switch (attribute.getType()) { case STRING: attributeValues[i] = resultSet.getString(columnNames.get(i++)); break; case INT: attributeValues[i] = resultSet.getInt(columnNames.get(i++)); break; case DOUBLE: attributeValues[i] = resultSet.getDouble(columnNames.get(i++)); break; case FLOAT: attributeValues[i] = resultSet.getFloat(columnNames.get(i++)); break; case BOOL: attributeValues[i] = resultSet.getBoolean(columnNames.get(i++)); break; case LONG: attributeValues[i] = resultSet.getLong(columnNames.get(i++)); break; default: // this statement is never reaches since attribute type is an enum } } } nextEvent = EventConverter.eventConverter(streamAttributes, attributeValues, timestamp); } else { nextEvent = null; } } } catch (EventGenerationException e) { log.error("Error occurred when generating event using database event " + "generator to simulate stream '" + dbSimulationConfig.getStreamName() + "' using source configuration " + dbSimulationConfig.toString() + "Drop event and create next event. ", e); getNextEvent(); } catch (SQLException e) { throw new EventGenerationException("Error occurred when accessing result set to simulate to simulate " + "stream '" + dbSimulationConfig.getStreamName() + "' using source configuration " + dbSimulationConfig.toString(), e); } } /** * getStreamName() method returns the name of the stream to which events are generated * * @return stream name */ @Override public String getStreamName() { return dbSimulationConfig.getStreamName(); } /** * getSiddhiAppName() method returns the name of the execution plan to which events are generated * * @return execution plan name */ @Override public String getSiddhiAppName() { return dbSimulationConfig.getSiddhiAppName(); } /** * validateDBConfiguration() method validates the database simulation source configuration * * @param sourceConfig JSON object containing configuration required dor database simulation * @throws InvalidConfigException if the stream configuration is invalid * @throws InsufficientAttributesException if the number of columns specified is not equal to number of stream * attributes * @throws ResourceNotFoundException if resources required for simulation are not available */ @Override public void validateSourceConfiguration(JSONObject sourceConfig, String simulationName) throws SimulationValidationException { /* * Perform the following checks prior to setting the properties. * 1. has * 2. isNull * 3. isEmpty * * if any of the above checks fail, throw an exception indicating which property is missing. * */ try { if (!checkAvailability(sourceConfig, EventSimulatorConstants.STREAM_NAME)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Stream name is required for database simulation. Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.EXECUTION_PLAN_NAME)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.EXECUTION_PLAN_NAME), "Siddhi app name is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } // retrieve the stream definition try { streamAttributes = EventSimulatorDataHolder.getInstance().getEventStreamService() .getStreamAttributes(sourceConfig.getString(EventSimulatorConstants.EXECUTION_PLAN_NAME), sourceConfig.getString(EventSimulatorConstants.STREAM_NAME)); } catch (ResourceNotFoundException e) { throw new SimulationValidationException( e.getResourceTypeString() + " '" + e.getResourceName() + "' specified for database " + "simulation does not exist. Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig), e); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.DRIVER)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.DRIVER), "A driver name is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.DATA_SOURCE_LOCATION)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION), "Data source location is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.USER_NAME)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.USER_NAME), "Username is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration : " + sourceConfig.toString()); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.PASSWORD)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.PASSWORD), "Password is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid " + "source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } if (!checkAvailability(sourceConfig, EventSimulatorConstants.TABLE_NAME)) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.TABLE_NAME), "Table name is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } try { DBConnectionModel connectionDetails = new DBConnectionModel(); connectionDetails .setDataSourceLocation(sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION)); connectionDetails.setDriver(sourceConfig.getString(EventSimulatorConstants.DRIVER)); connectionDetails.setPassword(sourceConfig.getString(EventSimulatorConstants.PASSWORD)); connectionDetails.setUsername(sourceConfig.getString(EventSimulatorConstants.USER_NAME)); HikariDataSource dataSource = DatabaseConnector.initializeDatasource(connectionDetails); Connection dbConnection = dataSource.getConnection(); dbConnection.close(); dataSource.close(); } catch (PoolInitializationException | SQLException e) { throw new SimulationValidationException( "Error occurred when creating connection to database ' " + sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION) + "' to simulate to simulate stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Please check " + "connection and config settings in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig), ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION), e); } catch (Exception e) { throw new SimulationValidationException( e.getCause().getCause() +" when creating connection to database ' " + sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION) + "' to " + "simulate to simulate stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Please check " + "connection and config settings in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig), ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION), e); } /* * either a timestamp attribute must be specified or the timestampInterval between timestamps of 2 * consecutive events must be specified. * timestamp interval will be considered only if timestamp attribute is not given * */ if (!checkAvailability(sourceConfig, EventSimulatorConstants.TIMESTAMP_ATTRIBUTE)) { if (checkAvailability(sourceConfig, EventSimulatorConstants.TIMESTAMP_INTERVAL)) { if (sourceConfig.getLong(EventSimulatorConstants.TIMESTAMP_INTERVAL) < 0) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.TIMESTAMP_ATTRIBUTE), "Time interval must be a positive value for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } } } if (sourceConfig.has(EventSimulatorConstants.COLUMN_NAMES_LIST)) { if (!sourceConfig.isNull(EventSimulatorConstants.COLUMN_NAMES_LIST)) { if (!sourceConfig.getString(EventSimulatorConstants.COLUMN_NAMES_LIST).isEmpty()) { List<String> columns = Arrays.asList(sourceConfig.getString( EventSimulatorConstants.COLUMN_NAMES_LIST).split("\\s*,\\s*")); if (columns.contains("")) { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE_SIMULATION, sourceConfig.getString(EventSimulatorConstants.COLUMN_NAMES_LIST), "Column name cannot contain empty values for database simulation of " + "stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } else if (columns.size() != streamAttributes.size()) { log.error("Stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "' has " + streamAttributes.size() + " attribute(s) but database source " + "configuration contains values for only " + columns.size() + " attribute(s). " + "Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); throw new InsufficientAttributesException( ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "' has " + streamAttributes.size() + " attribute(s) but database source " + "configuration contains values for only " + columns.size() + " attribute(s). Invalid source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } } else { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Column names list is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid " + "source configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } } } else { throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Column names list is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig)); } } catch (JSONException e) { log.error("Error occurred when accessing database simulation configuration of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig), e); throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Error occurred when accessing database simulation configuration of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration provided in '" + simulationName + "' simulation.\n" + SourceConfigLogger.getLoggedEnabledSourceConfig(sourceConfig), e); } } /** * validateDBConfiguration() method parses the database simulation configuration into a DBSimulationDTO object * * @param sourceConfig JSON object containing configuration required to simulate stream * @return DBSimulationDTO containing database simulation configuration * @throws InvalidConfigException if the stream configuration is invalid */ private DBSimulationDTO createDBConfiguration(JSONObject sourceConfig, String simulationName) throws InvalidConfigException { try { /* * either a timestamp attribute must be specified or the timestampInterval between timestamps of 2 * consecutive events must be specified. * if time interval is specified the timestamp of the first event will be the startTimestamp and * consecutive event will have timestamp = last timestamp + time interval * if both timestamp attribute and time interval are not specified set timestamp interval to 1 second * */ String timestampAttribute = null; long timestampInterval = -1; if (checkAvailability(sourceConfig, EventSimulatorConstants.TIMESTAMP_ATTRIBUTE)) { timestampAttribute = sourceConfig.getString(EventSimulatorConstants.TIMESTAMP_ATTRIBUTE); } else if (checkAvailability(sourceConfig, EventSimulatorConstants.TIMESTAMP_INTERVAL)) { timestampInterval = sourceConfig.getLong(EventSimulatorConstants.TIMESTAMP_INTERVAL); } else { log.warn("Either timestamp end time or time interval is required for database simulation of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Time interval will be set to 1 second for source configuration in '" + simulationName + "' simulation"); timestampInterval = 1000; } /* * if the column names are null. this is inferred as user implying that the column names * are identical to the stream attribute names * */ //create DBSimulationDTO object containing db simulation configuration DBSimulationDTO dbSimulationDTO = new DBSimulationDTO(); dbSimulationDTO.setStreamName(sourceConfig.getString(EventSimulatorConstants.STREAM_NAME)); dbSimulationDTO.setSiddhiAppName(sourceConfig.getString(EventSimulatorConstants.EXECUTION_PLAN_NAME)); dbSimulationDTO.setDriver(sourceConfig.getString(EventSimulatorConstants.DRIVER)); dbSimulationDTO.setDataSourceLocation(sourceConfig.getString(EventSimulatorConstants.DATA_SOURCE_LOCATION)); dbSimulationDTO.setUsername(sourceConfig.getString(EventSimulatorConstants.USER_NAME)); dbSimulationDTO.setPassword(sourceConfig.getString(EventSimulatorConstants.PASSWORD)); dbSimulationDTO.setTableName(sourceConfig.getString(EventSimulatorConstants.TABLE_NAME)); dbSimulationDTO.setTimestampAttribute(timestampAttribute); dbSimulationDTO.setTimestampInterval(timestampInterval); if (sourceConfig.isNull(EventSimulatorConstants.COLUMN_NAMES_LIST)) { List<String> columns = new ArrayList<>(); streamAttributes.forEach(attribute -> columns.add(attribute.getName())); dbSimulationDTO.setColumnNames(columns); } else { dbSimulationDTO.setColumnNames(Arrays.asList(sourceConfig.getString( EventSimulatorConstants.COLUMN_NAMES_LIST).split("\\s*,\\s*"))); } return dbSimulationDTO; } catch (JSONException e) { log.error("Error occurred when accessing database simulation configuration of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source configuration provided : " + sourceConfig.toString() + ". ", e); throw new InvalidConfigException( ResourceNotFoundException.ResourceType.DATABASE, sourceConfig.getString(EventSimulatorConstants.STREAM_NAME), "Error occurred when accessing database simulation configuration of stream '" + sourceConfig.getString(EventSimulatorConstants.STREAM_NAME) + "'. Invalid source " + "configuration provided : " + sourceConfig.toString() + ". ", e); } } @Override public String toString() { return dbSimulationConfig.toString(); } @Override public void setStartTimestamp(long startTimestamp) { this.startTimestamp = startTimestamp; } }
/* * 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.cassandra.cql3; import static org.apache.cassandra.cql3.Constants.UNSET_VALUE; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.cassandra.schema.ColumnMetadata; import org.apache.cassandra.cql3.functions.Function; import org.apache.cassandra.db.*; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.Int32Type; import org.apache.cassandra.db.marshal.ListType; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.serializers.CollectionSerializer; import org.apache.cassandra.serializers.MarshalException; import org.apache.cassandra.transport.ProtocolVersion; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.UUIDGen; /** * Static helper methods and classes for lists. */ public abstract class Lists { private Lists() {} public static ColumnSpecification indexSpecOf(ColumnSpecification column) { return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("idx(" + column.name + ")", true), Int32Type.instance); } public static ColumnSpecification valueSpecOf(ColumnSpecification column) { return new ColumnSpecification(column.ksName, column.cfName, new ColumnIdentifier("value(" + column.name + ")", true), ((ListType<?>)column.type).getElementsType()); } /** * Tests that the list with the specified elements can be assigned to the specified column. * * @param receiver the receiving column * @param elements the list elements */ public static AssignmentTestable.TestResult testListAssignment(ColumnSpecification receiver, List<? extends AssignmentTestable> elements) { if (!(receiver.type instanceof ListType)) return AssignmentTestable.TestResult.NOT_ASSIGNABLE; // If there is no elements, we can't say it's an exact match (an empty list if fundamentally polymorphic). if (elements.isEmpty()) return AssignmentTestable.TestResult.WEAKLY_ASSIGNABLE; ColumnSpecification valueSpec = valueSpecOf(receiver); return AssignmentTestable.TestResult.testAll(receiver.ksName, valueSpec, elements); } /** * Create a <code>String</code> representation of the list containing the specified elements. * * @param elements the list elements * @return a <code>String</code> representation of the list */ public static String listToString(List<?> elements) { return listToString(elements, Object::toString); } /** * Create a <code>String</code> representation of the list from the specified items associated to * the list elements. * * @param items items associated to the list elements * @param mapper the mapper used to map the items to the <code>String</code> representation of the list elements * @return a <code>String</code> representation of the list */ public static <T> String listToString(Iterable<T> items, java.util.function.Function<T, String> mapper) { return StreamSupport.stream(items.spliterator(), false) .map(e -> mapper.apply(e)) .collect(Collectors.joining(", ", "[", "]")); } /** * Returns the exact ListType from the items if it can be known. * * @param items the items mapped to the list elements * @param mapper the mapper used to retrieve the element types from the items * @return the exact ListType from the items if it can be known or <code>null</code> */ public static <T> AbstractType<?> getExactListTypeIfKnown(List<T> items, java.util.function.Function<T, AbstractType<?>> mapper) { Optional<AbstractType<?>> type = items.stream().map(mapper).filter(Objects::nonNull).findFirst(); return type.isPresent() ? ListType.getInstance(type.get(), false) : null; } public static class Literal extends Term.Raw { private final List<Term.Raw> elements; public Literal(List<Term.Raw> elements) { this.elements = elements; } public Term prepare(String keyspace, ColumnSpecification receiver) throws InvalidRequestException { validateAssignableTo(keyspace, receiver); ColumnSpecification valueSpec = Lists.valueSpecOf(receiver); List<Term> values = new ArrayList<>(elements.size()); boolean allTerminal = true; for (Term.Raw rt : elements) { Term t = rt.prepare(keyspace, valueSpec); if (t.containsBindMarker()) throw new InvalidRequestException(String.format("Invalid list literal for %s: bind variables are not supported inside collection literals", receiver.name)); if (t instanceof Term.NonTerminal) allTerminal = false; values.add(t); } DelayedValue value = new DelayedValue(values); return allTerminal ? value.bind(QueryOptions.DEFAULT) : value; } private void validateAssignableTo(String keyspace, ColumnSpecification receiver) throws InvalidRequestException { if (!(receiver.type instanceof ListType)) throw new InvalidRequestException(String.format("Invalid list literal for %s of type %s", receiver.name, receiver.type.asCQL3Type())); ColumnSpecification valueSpec = Lists.valueSpecOf(receiver); for (Term.Raw rt : elements) { if (!rt.testAssignment(keyspace, valueSpec).isAssignable()) throw new InvalidRequestException(String.format("Invalid list literal for %s: value %s is not of type %s", receiver.name, rt, valueSpec.type.asCQL3Type())); } } public AssignmentTestable.TestResult testAssignment(String keyspace, ColumnSpecification receiver) { return testListAssignment(receiver, elements); } @Override public AbstractType<?> getExactTypeIfKnown(String keyspace) { return getExactListTypeIfKnown(elements, p -> p.getExactTypeIfKnown(keyspace)); } public String getText() { return listToString(elements, Term.Raw::getText); } } public static class Value extends Term.MultiItemTerminal { public final List<ByteBuffer> elements; public Value(List<ByteBuffer> elements) { this.elements = elements; } public static Value fromSerialized(ByteBuffer value, ListType type, ProtocolVersion version) throws InvalidRequestException { try { // Collections have this small hack that validate cannot be called on a serialized object, // but compose does the validation (so we're fine). List<?> l = type.getSerializer().deserializeForNativeProtocol(value, version); List<ByteBuffer> elements = new ArrayList<>(l.size()); for (Object element : l) // elements can be null in lists that represent a set of IN values elements.add(element == null ? null : type.getElementsType().decompose(element)); return new Value(elements); } catch (MarshalException e) { throw new InvalidRequestException(e.getMessage()); } } public ByteBuffer get(ProtocolVersion protocolVersion) { return CollectionSerializer.pack(elements, elements.size(), protocolVersion); } public boolean equals(ListType lt, Value v) { if (elements.size() != v.elements.size()) return false; for (int i = 0; i < elements.size(); i++) if (lt.getElementsType().compare(elements.get(i), v.elements.get(i)) != 0) return false; return true; } public List<ByteBuffer> getElements() { return elements; } } /** * Basically similar to a Value, but with some non-pure function (that need * to be evaluated at execution time) in it. * * Note: this would also work for a list with bind markers, but we don't support * that because 1) it's not excessively useful and 2) we wouldn't have a good * column name to return in the ColumnSpecification for those markers (not a * blocker per-se but we don't bother due to 1)). */ public static class DelayedValue extends Term.NonTerminal { private final List<Term> elements; public DelayedValue(List<Term> elements) { this.elements = elements; } public boolean containsBindMarker() { // False since we don't support them in collection return false; } public void collectMarkerSpecification(VariableSpecifications boundNames) { } public Terminal bind(QueryOptions options) throws InvalidRequestException { List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(elements.size()); for (Term t : elements) { ByteBuffer bytes = t.bindAndGet(options); if (bytes == null) throw new InvalidRequestException("null is not supported inside collections"); if (bytes == ByteBufferUtil.UNSET_BYTE_BUFFER) return UNSET_VALUE; buffers.add(bytes); } return new Value(buffers); } public void addFunctionsTo(List<Function> functions) { Terms.addFunctions(elements, functions); } } /** * A marker for List values and IN relations */ public static class Marker extends AbstractMarker { protected Marker(int bindIndex, ColumnSpecification receiver) { super(bindIndex, receiver); assert receiver.type instanceof ListType; } public Terminal bind(QueryOptions options) throws InvalidRequestException { ByteBuffer value = options.getValues().get(bindIndex); if (value == null) return null; if (value == ByteBufferUtil.UNSET_BYTE_BUFFER) return UNSET_VALUE; return Value.fromSerialized(value, (ListType)receiver.type, options.getProtocolVersion()); } } /* * For prepend, we need to be able to generate unique but decreasing time * UUID, which is a bit challenging. To do that, given a time in milliseconds, * we adds a number representing the 100-nanoseconds precision and make sure * that within the same millisecond, that number is always decreasing. We * do rely on the fact that the user will only provide decreasing * milliseconds timestamp for that purpose. */ private static class PrecisionTime { // Our reference time (1 jan 2010, 00:00:00) in milliseconds. private static final long REFERENCE_TIME = 1262304000000L; private static final AtomicReference<PrecisionTime> last = new AtomicReference<>(new PrecisionTime(Long.MAX_VALUE, 0)); public final long millis; public final int nanos; PrecisionTime(long millis, int nanos) { this.millis = millis; this.nanos = nanos; } static PrecisionTime getNext(long millis) { while (true) { PrecisionTime current = last.get(); assert millis <= current.millis; PrecisionTime next = millis < current.millis ? new PrecisionTime(millis, 9999) : new PrecisionTime(millis, Math.max(0, current.nanos - 1)); if (last.compareAndSet(current, next)) return next; } } } public static class Setter extends Operation { public Setter(ColumnMetadata column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { Term.Terminal value = t.bind(params.options); if (value == UNSET_VALUE) return; // delete + append if (column.type.isMultiCell()) params.setComplexDeletionTimeForOverwrite(column); Appender.doAppend(value, column, params); } } private static int existingSize(Row row, ColumnMetadata column) { if (row == null) return 0; ComplexColumnData complexData = row.getComplexColumnData(column); return complexData == null ? 0 : complexData.cellsCount(); } public static class SetterByIndex extends Operation { private final Term idx; public SetterByIndex(ColumnMetadata column, Term idx, Term t) { super(column, t); this.idx = idx; } @Override public boolean requiresRead() { return true; } @Override public void collectMarkerSpecification(VariableSpecifications boundNames) { super.collectMarkerSpecification(boundNames); idx.collectMarkerSpecification(boundNames); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { // we should not get here for frozen lists assert column.type.isMultiCell() : "Attempted to set an individual element on a frozen list"; ByteBuffer index = idx.bindAndGet(params.options); ByteBuffer value = t.bindAndGet(params.options); if (index == null) throw new InvalidRequestException("Invalid null value for list index"); if (index == ByteBufferUtil.UNSET_BYTE_BUFFER) throw new InvalidRequestException("Invalid unset value for list index"); Row existingRow = params.getPrefetchedRow(partitionKey, params.currentClustering()); int existingSize = existingSize(existingRow, column); int idx = ByteBufferUtil.toInt(index); if (existingSize == 0) throw new InvalidRequestException("Attempted to set an element on a list which is null"); if (idx < 0 || idx >= existingSize) throw new InvalidRequestException(String.format("List index %d out of bound, list has size %d", idx, existingSize)); CellPath elementPath = existingRow.getComplexColumnData(column).getCellByIndex(idx).path(); if (value == null) params.addTombstone(column, elementPath); else if (value != ByteBufferUtil.UNSET_BYTE_BUFFER) params.addCell(column, elementPath, value); } } public static class Appender extends Operation { public Appender(ColumnMetadata column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to append to a frozen list"; Term.Terminal value = t.bind(params.options); doAppend(value, column, params); } static void doAppend(Term.Terminal value, ColumnMetadata column, UpdateParameters params) throws InvalidRequestException { if (column.type.isMultiCell()) { // If we append null, do nothing. Note that for Setter, we've // already removed the previous value so we're good here too if (value == null) return; for (ByteBuffer buffer : ((Value) value).elements) { ByteBuffer uuid = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes()); params.addCell(column, CellPath.create(uuid), buffer); } } else { // for frozen lists, we're overwriting the whole cell value if (value == null) params.addTombstone(column); else params.addCell(column, value.get(ProtocolVersion.CURRENT)); } } } public static class Prepender extends Operation { public Prepender(ColumnMetadata column, Term t) { super(column, t); } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to prepend to a frozen list"; Term.Terminal value = t.bind(params.options); if (value == null || value == UNSET_VALUE) return; long time = PrecisionTime.REFERENCE_TIME - (System.currentTimeMillis() - PrecisionTime.REFERENCE_TIME); List<ByteBuffer> toAdd = ((Value) value).elements; for (int i = toAdd.size() - 1; i >= 0; i--) { PrecisionTime pt = PrecisionTime.getNext(time); ByteBuffer uuid = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes(pt.millis, pt.nanos)); params.addCell(column, CellPath.create(uuid), toAdd.get(i)); } } } public static class Discarder extends Operation { public Discarder(ColumnMetadata column, Term t) { super(column, t); } @Override public boolean requiresRead() { return true; } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to delete from a frozen list"; // We want to call bind before possibly returning to reject queries where the value provided is not a list. Term.Terminal value = t.bind(params.options); Row existingRow = params.getPrefetchedRow(partitionKey, params.currentClustering()); ComplexColumnData complexData = existingRow == null ? null : existingRow.getComplexColumnData(column); if (value == null || value == UNSET_VALUE || complexData == null) return; // Note: below, we will call 'contains' on this toDiscard list for each element of existingList. // Meaning that if toDiscard is big, converting it to a HashSet might be more efficient. However, // the read-before-write this operation requires limits its usefulness on big lists, so in practice // toDiscard will be small and keeping a list will be more efficient. List<ByteBuffer> toDiscard = ((Value)value).elements; for (Cell cell : complexData) { if (toDiscard.contains(cell.value())) params.addTombstone(column, cell.path()); } } } public static class DiscarderByIndex extends Operation { public DiscarderByIndex(ColumnMetadata column, Term idx) { super(column, idx); } @Override public boolean requiresRead() { return true; } public void execute(DecoratedKey partitionKey, UpdateParameters params) throws InvalidRequestException { assert column.type.isMultiCell() : "Attempted to delete an item by index from a frozen list"; Term.Terminal index = t.bind(params.options); if (index == null) throw new InvalidRequestException("Invalid null value for list index"); if (index == Constants.UNSET_VALUE) return; Row existingRow = params.getPrefetchedRow(partitionKey, params.currentClustering()); int existingSize = existingSize(existingRow, column); int idx = ByteBufferUtil.toInt(index.get(params.options.getProtocolVersion())); if (existingSize == 0) throw new InvalidRequestException("Attempted to delete an element from a list which is null"); if (idx < 0 || idx >= existingSize) throw new InvalidRequestException(String.format("List index %d out of bound, list has size %d", idx, existingSize)); params.addTombstone(column, existingRow.getComplexColumnData(column).getCellByIndex(idx).path()); } } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.core.rule.constraint; import org.drools.core.base.EvaluatorWrapper; import org.drools.core.base.mvel.MVELCompilationUnit; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.Declaration; import org.drools.core.spi.Tuple; import org.drools.core.util.MVELSafeHelper; import org.mvel2.MVEL; import org.mvel2.ParserConfiguration; import org.mvel2.ParserContext; import org.mvel2.ast.ASTNode; import org.mvel2.ast.And; import org.mvel2.ast.BinaryOperation; import org.mvel2.ast.BooleanNode; import org.mvel2.ast.Contains; import org.mvel2.ast.LineLabel; import org.mvel2.ast.Negation; import org.mvel2.ast.Or; import org.mvel2.ast.Substatement; import org.mvel2.compiler.CompiledExpression; import org.mvel2.compiler.ExecutableAccessor; import org.mvel2.compiler.ExecutableLiteral; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import org.mvel2.util.ASTLinkedList; import java.util.HashMap; import java.util.Map; import static org.drools.core.rule.constraint.EvaluatorHelper.valuesAsMap; public class MvelConditionEvaluator implements ConditionEvaluator { protected final Declaration[] declarations; private final EvaluatorWrapper[] operators; private final String conditionClass; private final ParserConfiguration parserConfiguration; protected ExecutableStatement executableStatement; protected MVELCompilationUnit compilationUnit; private boolean evaluated = false; public MvelConditionEvaluator(ParserConfiguration configuration, String expression, Declaration[] declarations, EvaluatorWrapper[] operators, String conditionClass) { this(null, configuration, (ExecutableStatement)MVEL.compileExpression(expression, new ParserContext(configuration)), declarations, operators, conditionClass); } public MvelConditionEvaluator(MVELCompilationUnit compilationUnit, ParserConfiguration parserConfiguration, ExecutableStatement executableStatement, Declaration[] declarations, EvaluatorWrapper[] operators, String conditionClass) { this.declarations = declarations; this.operators = operators; this.conditionClass = conditionClass; this.compilationUnit = compilationUnit; this.parserConfiguration = parserConfiguration; this.executableStatement = executableStatement; } public boolean evaluate(InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple) { return evaluate(executableStatement, handle, workingMemory, tuple); } public boolean evaluate(ExecutableStatement statement, InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple) { if (compilationUnit == null) { Map<String, Object> vars = valuesAsMap(handle.getObject(), workingMemory, tuple, declarations); if (operators.length > 0) { if (vars == null) { vars = new HashMap<String, Object>(); } InternalFactHandle[] handles = tuple != null ? tuple.toFactHandles() : new InternalFactHandle[0]; for (EvaluatorWrapper operator : operators) { vars.put( operator.getBindingName(), operator ); operator.loadHandles(workingMemory, handles, handle); } } return evaluate(statement, handle.getObject(), vars); } VariableResolverFactory factory = compilationUnit.createFactory(); compilationUnit.updateFactory( null, null, handle, tuple, null, workingMemory, workingMemory.getGlobalResolver(), factory ); return (Boolean) MVELSafeHelper.getEvaluator().executeExpression( statement, handle.getObject(), factory ); } private boolean evaluate(ExecutableStatement statement, Object object, Map<String, Object> vars) { return vars == null ? (Boolean)MVELSafeHelper.getEvaluator().executeExpression(statement, object) : (Boolean)MVELSafeHelper.getEvaluator().executeExpression(statement, object, vars); } ConditionAnalyzer.Condition getAnalyzedCondition() { return new ConditionAnalyzer(executableStatement, declarations, operators, conditionClass).analyzeCondition(); } ConditionAnalyzer.Condition getAnalyzedCondition(InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple leftTuple) { ensureCompleteEvaluation(handle, workingMemory, leftTuple); return new ConditionAnalyzer(executableStatement, declarations, operators, conditionClass).analyzeCondition(); } private void ensureCompleteEvaluation(InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple) { if (!evaluated) { ASTNode rootNode = getRootNode(); if (rootNode != null) { ensureCompleteEvaluation(rootNode, handle, workingMemory, tuple); } evaluated = true; } } private void ensureCompleteEvaluation(ASTNode node, InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple) { node = unwrap(node); if (!(node instanceof And || node instanceof Or)) { return; } ensureBranchEvaluation(handle, workingMemory, tuple, ((BooleanNode)node).getLeft()); ensureBranchEvaluation(handle, workingMemory, tuple, ((BooleanNode)node).getRight()); } private ASTNode unwrap(ASTNode node) { while (node instanceof Negation || node instanceof LineLabel || node instanceof Substatement) { node = unwrapNegation(node); node = unwrapSubstatement(node); } return node; } private void ensureBranchEvaluation(InternalFactHandle handle, InternalWorkingMemory workingMemory, Tuple tuple, ASTNode node) { if (!isEvaluated(node)) { ASTNode next = node.nextASTNode; node.nextASTNode = null; evaluate(asCompiledExpression(node), handle, workingMemory, tuple); node.nextASTNode = next; } ensureCompleteEvaluation(node, handle, workingMemory, tuple); } private ASTNode unwrapNegation(ASTNode node) { if (node instanceof Negation) { ExecutableStatement statement = ((Negation)node).getStatement(); return statement instanceof ExecutableAccessor ? ((ExecutableAccessor)statement).getNode() : null; } return node; } private ASTNode unwrapSubstatement(ASTNode node) { if (node instanceof LineLabel) { return node.nextASTNode; } return node instanceof Substatement ? ((ExecutableAccessor)((Substatement)node).getStatement()).getNode() : node; } private boolean isEvaluated(ASTNode node) { node = unwrapSubstatement(node); if (node instanceof Contains) { return ((Contains)node).getFirstStatement().getAccessor() != null; } return node instanceof BinaryOperation ? ((BooleanNode) node).getLeft().getAccessor() != null : node.getAccessor() != null; } private CompiledExpression asCompiledExpression(ASTNode node) { return new CompiledExpression(new ASTLinkedList(node), null, Object.class, parserConfiguration, false); } private ASTNode getRootNode() { if (executableStatement instanceof ExecutableLiteral) { return null; } return executableStatement instanceof CompiledExpression ? ((CompiledExpression) executableStatement).getFirstNode() : ((ExecutableAccessor) executableStatement).getNode(); } }
package com.communote.server.model.blog; import java.io.Serializable; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.StringUtils; import com.communote.server.model.external.ExternalObject; import com.communote.server.model.follow.Followable; import com.communote.server.model.global.GlobalId; import com.communote.server.model.property.Propertyable; import com.communote.server.model.tag.Tag; import com.communote.server.model.tag.Taggable; /** * <p> * A blog is just a blog with single user tagged items. * </p> * * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> */ public class Blog implements Serializable, Followable, Propertyable, Taggable { /** * Constructs new instances of {@link Blog}. */ public static final class Factory { /** * Constructs a new instance of {@link Blog}. */ public static Blog newInstance() { return new Blog(); } /** * Constructs a new instance of {@link Blog}, taking all possible properties (except the * identifier(s))as arguments. */ public static Blog newInstance(String title, String description, Timestamp creationDate, String nameIdentifier, Timestamp lastModificationDate, Timestamp crawlLastModificationDate, boolean allCanRead, boolean allCanWrite, boolean publicAccess, boolean createSystemNotes, boolean toplevelTopic, Set<Tag> tags, GlobalId globalId, Set<BlogMember> members, Set<ExternalObject> externalObjects, Set<BlogProperty> properties, Set<Blog> parents, Set<Blog> children) { final Blog entity = new Blog(); entity.setTitle(title); entity.setDescription(description); entity.setCreationDate(creationDate); entity.setNameIdentifier(nameIdentifier); entity.setLastModificationDate(lastModificationDate); entity.setCrawlLastModificationDate(crawlLastModificationDate); entity.setAllCanRead(allCanRead); entity.setAllCanWrite(allCanWrite); entity.setPublicAccess(publicAccess); entity.setCreateSystemNotes(createSystemNotes); entity.setToplevelTopic(toplevelTopic); entity.setTags(tags); entity.setGlobalId(globalId); entity.setMembers(members); entity.setExternalObjects(externalObjects); entity.setProperties(properties); entity.setParents(parents); entity.setChildren(children); return entity; } /** * Constructs a new instance of {@link Blog}, taking all required and/or read-only * properties as arguments. */ public static Blog newInstance(String title, Timestamp creationDate, String nameIdentifier, Timestamp lastModificationDate, Timestamp crawlLastModificationDate, boolean allCanRead, boolean allCanWrite, boolean publicAccess, boolean createSystemNotes, boolean toplevelTopic) { final Blog entity = new Blog(); entity.setTitle(title); entity.setCreationDate(creationDate); entity.setNameIdentifier(nameIdentifier); entity.setLastModificationDate(lastModificationDate); entity.setCrawlLastModificationDate(crawlLastModificationDate); entity.setAllCanRead(allCanRead); entity.setAllCanWrite(allCanWrite); entity.setPublicAccess(publicAccess); entity.setCreateSystemNotes(createSystemNotes); entity.setToplevelTopic(toplevelTopic); return entity; } } /** * The serial version UID of this class. Needed for serialization. */ private static final long serialVersionUID = -7308570661723098257L; private String title; private String description; private Timestamp creationDate; private String nameIdentifier; private Timestamp lastModificationDate; private Timestamp crawlLastModificationDate; private boolean allCanRead; private boolean allCanWrite; private boolean publicAccess; private boolean createSystemNotes; private boolean toplevelTopic; private Long id; private Set<Tag> tags = new HashSet<Tag>(); private com.communote.server.model.global.GlobalId globalId; private Set<BlogMember> members = new HashSet<BlogMember>(); private Set<ExternalObject> externalObjects = new HashSet<ExternalObject>(); private Set<BlogProperty> properties = new HashSet<BlogProperty>(); private Set<Blog> parents = new HashSet<Blog>(); private Set<Blog> children = new HashSet<Blog>(); /** * Builds a string showing the current attribute values */ public String attributesToString() { StringBuilder sb = new StringBuilder(); sb.append("class='"); sb.append(this.getClass().getName()); sb.append("', "); sb.append("title='"); sb.append(title); sb.append("', "); sb.append("description='"); sb.append(description); sb.append("', "); sb.append("creationDate='"); sb.append(creationDate); sb.append("', "); sb.append("nameIdentifier='"); sb.append(nameIdentifier); sb.append("', "); sb.append("lastModificationDate='"); sb.append(lastModificationDate); sb.append("', "); sb.append("crawlLastModificationDate='"); sb.append(crawlLastModificationDate); sb.append("', "); sb.append("allCanRead='"); sb.append(allCanRead); sb.append("', "); sb.append("allCanWrite='"); sb.append(allCanWrite); sb.append("', "); sb.append("publicAccess='"); sb.append(publicAccess); sb.append("', "); sb.append("createSystemNotes='"); sb.append(createSystemNotes); sb.append("', "); sb.append("toplevelTopic='"); sb.append(toplevelTopic); sb.append("', "); sb.append("id='"); sb.append(id); sb.append("', "); return sb.toString(); } /** * Returns <code>true</code> if the argument is an Blog instance and all identifiers for this * entity equal the identifiers of the argument entity. Returns <code>false</code> otherwise. */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof Blog)) { return false; } final Blog that = (Blog) object; if (this.id == null || that.getId() == null || !this.id.equals(that.getId())) { return false; } return true; } /** * */ public Set<Blog> getChildren() { return this.children; } /** * <p> * The last modification date of the blog. * </p> */ public Timestamp getCrawlLastModificationDate() { return this.crawlLastModificationDate; } /** * <p> * The creation date of the blog. * </p> */ public Timestamp getCreationDate() { return this.creationDate; } /** * <p> * The description of the blog. * </p> */ public String getDescription() { return this.description; } /** * */ public Set<ExternalObject> getExternalObjects() { return this.externalObjects; } @Override public GlobalId getFollowId() { return getGlobalId(); } /** * */ @Override public GlobalId getGlobalId() { return this.globalId; } /** * */ public Long getId() { return this.id; } /** * <p> * The last modification date of the blog. * </p> */ public Timestamp getLastModificationDate() { return this.lastModificationDate; } /** * */ public Set<BlogMember> getMembers() { return this.members; } /** * <p> * The identifier of the blog. * </p> */ public String getNameIdentifier() { return this.nameIdentifier; } /** * */ public Set<Blog> getParents() { return this.parents; } /** * */ @Override public Set<BlogProperty> getProperties() { return this.properties; } /** * */ @Override public Set<Tag> getTags() { return this.tags; } /** * <p> * The title of the blog. * </p> */ public String getTitle() { return this.title; } /** * Returns a hash code based on this entity's identifiers. */ @Override public int hashCode() { int hashCode = 0; hashCode = 29 * hashCode + (id == null ? 0 : id.hashCode()); return hashCode; } /** * Return whether all Communote users are allowed to read the notes of this topic. If all users * are allowed to write notes to this topic, they can also read the * notes. That is, if {@link #isAllCanWrite()} returns true, this method returns true too. * * @return true, if all Communote users are allowed to read the notes of this topic/blog. */ public boolean isAllCanRead() { if (allCanWrite) { return true; } return this.allCanRead; } /** * @return true, if all Communote users are allowed to read the notes of and write notes to this topic/blog. */ public boolean isAllCanWrite() { return this.allCanWrite; } /** * <p> * whether notes with creation source 'SYSTEM' will be created in this blog. * </p> */ public boolean isCreateSystemNotes() { return this.createSystemNotes; } /** * <p> * This option determines whether a blog can be accesses by public or not. Default is false. * </p> */ public boolean isPublicAccess() { return this.publicAccess; } /** * */ public boolean isToplevelTopic() { return this.toplevelTopic; } public void setAllCanRead(boolean allCanRead) { this.allCanRead = allCanRead; } public void setAllCanWrite(boolean allCanWrite) { this.allCanWrite = allCanWrite; } public void setChildren(Set<Blog> children) { this.children = children; } public void setCrawlLastModificationDate(Timestamp crawlLastModificationDate) { this.crawlLastModificationDate = crawlLastModificationDate; } public void setCreateSystemNotes(boolean createSystemNotes) { this.createSystemNotes = createSystemNotes; } public void setCreationDate(Timestamp creationDate) { this.creationDate = creationDate; } public void setDescription(String description) { this.description = description; } public void setExternalObjects(Set<ExternalObject> externalObjects) { this.externalObjects = externalObjects; } @Override public void setGlobalId(GlobalId globalId) { this.globalId = globalId; } public void setId(Long id) { this.id = id; } public void setLastModificationDate(Timestamp lastModificationDate) { this.lastModificationDate = lastModificationDate; // also set the crawl last modification date if the given last modification is younger if (getCrawlLastModificationDate() == null) { this.setCrawlLastModificationDate(lastModificationDate); } else if (lastModificationDate != null && lastModificationDate.getTime() > getCrawlLastModificationDate().getTime()) { this.setCrawlLastModificationDate(lastModificationDate); } } public void setMembers(Set<BlogMember> members) { this.members = members; } public void setNameIdentifier(String nameIdentifier) { // force lower case identifiers this.nameIdentifier = StringUtils.lowerCase(nameIdentifier); } public void setParents(Set<Blog> parents) { this.parents = parents; } public void setProperties(Set<BlogProperty> properties) { this.properties = properties; } public void setPublicAccess(boolean publicAccess) { this.publicAccess = publicAccess; } @Override public void setTags(Set<Tag> tags) { this.tags = tags; } public void setTitle(String title) { this.title = title; } public void setToplevelTopic(boolean toplevelTopic) { this.toplevelTopic = toplevelTopic; } }
package com.vzome.core.algebra; import java.util.Arrays; import com.vzome.core.math.RealVector; /** * @author vorth * */ public final class AlgebraicVector implements Comparable<AlgebraicVector> { public static final int X = 0, Y = 1, Z = 2; public static final int W4 = 0, X4 = 1, Y4 = 2, Z4 = 3; private final AlgebraicNumber[] coordinates; private final AlgebraicField field; public AlgebraicVector( AlgebraicNumber... n ) { coordinates = new AlgebraicNumber[ n.length ]; for ( int i = 0; i < n.length; i++ ) { coordinates[ i ] = n[ i ]; } this .field = n[ 0 ] .getField(); } public AlgebraicVector( AlgebraicField field, int dims ) { coordinates = new AlgebraicNumber[ dims ]; for ( int i = 0; i < dims; i++ ) { coordinates[ i ] = field .zero(); } this .field = field; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode( coordinates ); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; AlgebraicVector other = (AlgebraicVector) obj; if(!field.equals( other.field )) { String reason = "Invalid comparison of " + getClass().getSimpleName() + "s" + "with different fields: " + field.getName() + " and " + other.field.getName(); throw new IllegalStateException(reason); } return Arrays.equals( coordinates, other.coordinates ); } @Override public int compareTo(AlgebraicVector other) { if ( this == other ) { return 0; } if (other.equals(this)) { // intentionally throws a NullPointerException if other is null // or an IllegalStateException if fields are different return 0; } int comparison = Integer.compare(coordinates.length, other.coordinates.length); if(comparison != 0) { return comparison; } for(int i=0; i < coordinates.length; i++) { AlgebraicNumber n1 = this. coordinates[i]; AlgebraicNumber n2 = other.coordinates[i]; comparison = n1.compareTo(n2); if (comparison != 0) { return comparison; } } return comparison; } public final RealVector toRealVector() { return new RealVector( this .coordinates[ 0 ] .evaluate(), this .coordinates[ 1 ] .evaluate(), this .coordinates[ 2 ] .evaluate() ); } /** * @return A String with no extended characters so it's suitable for writing * to an 8 bit stream such as System.out or an ASCII text log file in Windows. * Contrast this with {@link toString()} which contains extended characters (e.g. \u03C6 (phi)) */ public final String toASCIIString() { return this .getVectorExpression( AlgebraicField .EXPRESSION_FORMAT ); } /** * @return A String representation that can be persisted to XML and parsed by XmlSaveFormat.parseRationalVector(). */ public final String toParsableString() { return this .getVectorExpression( AlgebraicField .ZOMIC_FORMAT ); } @Override public final String toString() { return this .getVectorExpression( AlgebraicField .DEFAULT_FORMAT ); } public AlgebraicNumber getComponent( int i ) { return this .coordinates[ i ]; } public AlgebraicVector setComponent( int component, AlgebraicNumber coord ) { this .coordinates[ component ] = coord; return this; } public AlgebraicVector negate() { AlgebraicNumber[] result = new AlgebraicNumber[ this .coordinates .length ]; for ( int i = 0; i < result .length; i++ ) { result[ i ] = this .coordinates[ i ] .negate(); } return new AlgebraicVector( result ); } public AlgebraicVector scale( AlgebraicNumber scale ) { AlgebraicNumber[] result = new AlgebraicNumber[ this .coordinates .length ]; for ( int i = 0; i < result .length; i++ ) { result[ i ] = this .coordinates[ i ] .times( scale ); } return new AlgebraicVector( result ); } public boolean isOrigin() { for (AlgebraicNumber coordinate : this .coordinates) { if (!coordinate.isZero()) { return false; } } return true; } public AlgebraicVector plus( AlgebraicVector that ) { AlgebraicNumber[] result = new AlgebraicNumber[ this .coordinates .length ]; for ( int i = 0; i < result .length; i++ ) { result[ i ] = this .coordinates[ i ] .plus( that .coordinates[ i ] ); } return new AlgebraicVector( result ); } public AlgebraicVector minus( AlgebraicVector that ) { AlgebraicNumber[] result = new AlgebraicNumber[ this .coordinates .length ]; for ( int i = 0; i < result .length; i++ ) { result[ i ] = this .coordinates[ i ] .minus( that .coordinates[ i ] ); } return new AlgebraicVector( result ); } public int dimension() { return this .coordinates .length; } public AlgebraicVector cross( AlgebraicVector that ) { AlgebraicNumber[] result = new AlgebraicNumber[ this .coordinates .length ]; for ( int i = 0; i < result.length; i++ ) { int j = ( i + 1 ) % 3; int k = ( i + 2 ) % 3; result[ i ] = this .coordinates[ j ] .times( that .coordinates[ k ] ) .minus( this .coordinates[ k ] .times( that .coordinates[ j ] ) ); } return new AlgebraicVector( result ); } public AlgebraicVector inflateTo4d() { return this .inflateTo4d( true ); } public AlgebraicVector inflateTo4d( boolean wFirst ) { if ( this .coordinates .length == 4 ) { if ( wFirst ) return this; else return new AlgebraicVector( this .coordinates[ 1 ], this .coordinates[ 2 ], this .coordinates[ 3 ], this .coordinates[ 0 ] ); } if ( wFirst ) return new AlgebraicVector( this .field .zero(), this .coordinates[ 0 ], this .coordinates[ 1 ], this .coordinates[ 2 ] ); else // the older usage return new AlgebraicVector( this .coordinates[ 0 ], this .coordinates[ 1 ], this .coordinates[ 2 ], this .field .zero() ); } public AlgebraicVector projectTo3d( boolean wFirst ) { if ( dimension() == 3 ) return this; if ( wFirst ) return new AlgebraicVector( this .coordinates[ 1 ], this .coordinates[ 2 ], this .coordinates[ 3 ] ); else return new AlgebraicVector( this .coordinates[ 0 ], this .coordinates[ 1 ], this .coordinates[ 2 ] ); } public void getVectorExpression( StringBuffer buf, int format ) { if ( format == AlgebraicField.DEFAULT_FORMAT ) buf .append( "(" ); for ( int i = 0; i < this.coordinates.length; i++ ) { if ( i > 0 ) if ( format == AlgebraicField.VEF_FORMAT || format == AlgebraicField.ZOMIC_FORMAT ) buf.append( " " ); else buf.append( ", " ); this .coordinates[ i ] .getNumberExpression( buf, format ); } if ( format == AlgebraicField.DEFAULT_FORMAT ) buf .append( ")" ); } public String getVectorExpression( int format ) { StringBuffer buf = new StringBuffer(); this .getVectorExpression( buf, format ); return buf.toString(); } public AlgebraicNumber dot( AlgebraicVector that ) { AlgebraicNumber result = this .field .zero(); for ( int i = 0; i < that.dimension(); i++ ) { result = result .plus( this .coordinates[ i ] .times( that .coordinates[ i ] ) ); } return result; } public AlgebraicNumber getLength( AlgebraicVector unit ) { for ( int i = 0; i < this.coordinates.length; i++ ) { if ( this .coordinates[ i ] .isZero() ) continue; return this .coordinates[ i ] .dividedBy( unit .coordinates[ i ] ); } throw new IllegalStateException( "vector is the origin!" ); } public AlgebraicField getField() { return this .field; } }
/* * 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.camel.component.aws.s3.springboot; import javax.annotation.Generated; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.EncryptionMaterials; import org.apache.camel.component.aws.s3.S3Operations; import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon; import org.springframework.boot.context.properties.ConfigurationProperties; /** * The aws-s3 component is used for storing and retrieving objecct from Amazon * S3 Storage Service. * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @ConfigurationProperties(prefix = "camel.component.aws-s3") public class S3ComponentConfiguration extends ComponentConfigurationPropertiesCommon { /** * Whether to enable auto configuration of the aws-s3 component. This is * enabled by default. */ private Boolean enabled; /** * The AWS S3 default configuration */ private S3ConfigurationNestedConfiguration configuration; /** * Amazon AWS Access Key */ private String accessKey; /** * Amazon AWS Secret Key */ private String secretKey; /** * The region where the bucket is located. This option is used in the * com.amazonaws.services.s3.model.CreateBucketRequest. */ private String region; /** * Whether the component should resolve property placeholders on itself when * starting. Only properties which are of String type can use property * placeholders. */ private Boolean resolvePropertyPlaceholders = true; /** * Whether the component should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities */ private Boolean basicPropertyBinding = false; public S3ConfigurationNestedConfiguration getConfiguration() { return configuration; } public void setConfiguration( S3ConfigurationNestedConfiguration configuration) { this.configuration = configuration; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Boolean getResolvePropertyPlaceholders() { return resolvePropertyPlaceholders; } public void setResolvePropertyPlaceholders( Boolean resolvePropertyPlaceholders) { this.resolvePropertyPlaceholders = resolvePropertyPlaceholders; } public Boolean getBasicPropertyBinding() { return basicPropertyBinding; } public void setBasicPropertyBinding(Boolean basicPropertyBinding) { this.basicPropertyBinding = basicPropertyBinding; } public static class S3ConfigurationNestedConfiguration { public static final Class CAMEL_NESTED_CLASS = org.apache.camel.component.aws.s3.S3Configuration.class; /** * Setup the partSize which is used in multi part upload, the default * size is 25M. */ private Long partSize = 26214400L; /** * If it is true, camel will upload the file with multi part format, the * part size is decided by the option of `partSize` */ private Boolean multiPartUpload = false; /** * Amazon AWS Access Key */ private String accessKey; /** * Amazon AWS Secret Key */ private String secretKey; /** * Reference to a `com.amazonaws.services.s3.AmazonS3` in the registry. */ private AmazonS3 amazonS3Client; /** * The prefix which is used in the * com.amazonaws.services.s3.model.ListObjectsRequest to only consume * objects we are interested in. */ private String prefix; /** * The delimiter which is used in the * com.amazonaws.services.s3.model.ListObjectsRequest to only consume * objects we are interested in. */ private String delimiter; /** * Name of the bucket. The bucket will be created if it doesn't already * exists. */ private String bucketName; /** * To get the object from the bucket with the given file name */ private String fileName; /** * The region in which S3 client needs to work. When using this * parameter, the configuration will expect the capitalized name of the * region (for example AP_EAST_1) You'll need to use the name * Regions.EU_WEST_1.name() */ private String region; /** * If it is true, the exchange body will be set to a stream to the * contents of the file. If false, the headers will be set with the S3 * object metadata, but the body will be null. This option is strongly * related to autocloseBody option. In case of setting includeBody to * true and autocloseBody to false, it will be up to the caller to close * the S3Object stream. Setting autocloseBody to true, will close the * S3Object stream automatically. */ private Boolean includeBody = true; /** * Delete objects from S3 after they have been retrieved. The delete is * only performed if the Exchange is committed. If a rollback occurs, * the object is not deleted. <p/> If this option is false, then the * same objects will be retrieve over and over again on the polls. * Therefore you need to use the Idempotent Consumer EIP in the route to * filter out duplicates. You can filter using the {@link * S3Constants#BUCKET_NAME} and {@link S3Constants#KEY} headers, or only * the {@link S3Constants#KEY} header. */ private Boolean deleteAfterRead = true; /** * Delete file object after the S3 file has been uploaded */ private Boolean deleteAfterWrite = false; /** * The policy for this queue to set in the * `com.amazonaws.services.s3.AmazonS3#setBucketPolicy()` method. */ private String policy; /** * The storage class to set in the * `com.amazonaws.services.s3.model.PutObjectRequest` request. */ private String storageClass; /** * Sets the server-side encryption algorithm when encrypting the object * using AWS-managed keys. For example use <tt>AES256</tt>. */ private String serverSideEncryption; /** * To define a proxy host when instantiating the SQS client */ private String proxyHost; /** * Specify a proxy port to be used inside the client definition. */ private Integer proxyPort; /** * Whether or not the S3 client should use path style access */ private Boolean pathStyleAccess = false; /** * The operation to do in case the user don't want to do only an upload */ private S3Operations operation; /** * If this option is true and includeBody is true, then the * S3Object.close() method will be called on exchange completion. This * option is strongly related to includeBody option. In case of setting * includeBody to true and autocloseBody to false, it will be up to the * caller to close the S3Object stream. Setting autocloseBody to true, * will close the S3Object stream automatically. */ private Boolean autocloseBody = true; /** * The encryption materials to use in case of Symmetric/Asymmetric * client usage */ private EncryptionMaterials encryptionMaterials; /** * Define if encryption must be used or not */ private Boolean useEncryption = false; /** * Define if KMS must be used or not */ private Boolean useAwsKMS = false; /** * Define the id of KMS key to use in case KMS is enabled */ private String awsKMSKeyId; /** * Define if disabled Chunked Encoding is true or false */ private Boolean chunkedEncodingDisabled = false; /** * Define if Accelerate Mode enabled is true or false */ private Boolean accelerateModeEnabled = false; /** * Define if Dualstack enabled is true or false */ private Boolean dualstackEnabled = false; /** * Define if Payload Signing enabled is true or false */ private Boolean payloadSigningEnabled = false; /** * Define if Force Global Bucket Access enabled is true or false */ private Boolean forceGlobalBucketAccessEnabled = false; /** * Set whether the S3 client should expect to load credentials on an EC2 * instance or to expect static credentials to be passed in. */ private Boolean useIAMCredentials = false; /** * Setting the autocreation of the bucket */ private Boolean autoCreateBucket = true; /** * Setting the key name for an element in the bucket through endpoint * parameter */ private String keyName; public Long getPartSize() { return partSize; } public void setPartSize(Long partSize) { this.partSize = partSize; } public Boolean getMultiPartUpload() { return multiPartUpload; } public void setMultiPartUpload(Boolean multiPartUpload) { this.multiPartUpload = multiPartUpload; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public AmazonS3 getAmazonS3Client() { return amazonS3Client; } public void setAmazonS3Client(AmazonS3 amazonS3Client) { this.amazonS3Client = amazonS3Client; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getDelimiter() { return delimiter; } public void setDelimiter(String delimiter) { this.delimiter = delimiter; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Boolean getIncludeBody() { return includeBody; } public void setIncludeBody(Boolean includeBody) { this.includeBody = includeBody; } public Boolean getDeleteAfterRead() { return deleteAfterRead; } public void setDeleteAfterRead(Boolean deleteAfterRead) { this.deleteAfterRead = deleteAfterRead; } public Boolean getDeleteAfterWrite() { return deleteAfterWrite; } public void setDeleteAfterWrite(Boolean deleteAfterWrite) { this.deleteAfterWrite = deleteAfterWrite; } public String getPolicy() { return policy; } public void setPolicy(String policy) { this.policy = policy; } public String getStorageClass() { return storageClass; } public void setStorageClass(String storageClass) { this.storageClass = storageClass; } public String getServerSideEncryption() { return serverSideEncryption; } public void setServerSideEncryption(String serverSideEncryption) { this.serverSideEncryption = serverSideEncryption; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public Boolean getPathStyleAccess() { return pathStyleAccess; } public void setPathStyleAccess(Boolean pathStyleAccess) { this.pathStyleAccess = pathStyleAccess; } public S3Operations getOperation() { return operation; } public void setOperation(S3Operations operation) { this.operation = operation; } public Boolean getAutocloseBody() { return autocloseBody; } public void setAutocloseBody(Boolean autocloseBody) { this.autocloseBody = autocloseBody; } public EncryptionMaterials getEncryptionMaterials() { return encryptionMaterials; } public void setEncryptionMaterials( EncryptionMaterials encryptionMaterials) { this.encryptionMaterials = encryptionMaterials; } public Boolean getUseEncryption() { return useEncryption; } public void setUseEncryption(Boolean useEncryption) { this.useEncryption = useEncryption; } public Boolean getUseAwsKMS() { return useAwsKMS; } public void setUseAwsKMS(Boolean useAwsKMS) { this.useAwsKMS = useAwsKMS; } public String getAwsKMSKeyId() { return awsKMSKeyId; } public void setAwsKMSKeyId(String awsKMSKeyId) { this.awsKMSKeyId = awsKMSKeyId; } public Boolean getChunkedEncodingDisabled() { return chunkedEncodingDisabled; } public void setChunkedEncodingDisabled(Boolean chunkedEncodingDisabled) { this.chunkedEncodingDisabled = chunkedEncodingDisabled; } public Boolean getAccelerateModeEnabled() { return accelerateModeEnabled; } public void setAccelerateModeEnabled(Boolean accelerateModeEnabled) { this.accelerateModeEnabled = accelerateModeEnabled; } public Boolean getDualstackEnabled() { return dualstackEnabled; } public void setDualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; } public Boolean getPayloadSigningEnabled() { return payloadSigningEnabled; } public void setPayloadSigningEnabled(Boolean payloadSigningEnabled) { this.payloadSigningEnabled = payloadSigningEnabled; } public Boolean getForceGlobalBucketAccessEnabled() { return forceGlobalBucketAccessEnabled; } public void setForceGlobalBucketAccessEnabled( Boolean forceGlobalBucketAccessEnabled) { this.forceGlobalBucketAccessEnabled = forceGlobalBucketAccessEnabled; } public Boolean getUseIAMCredentials() { return useIAMCredentials; } public void setUseIAMCredentials(Boolean useIAMCredentials) { this.useIAMCredentials = useIAMCredentials; } public Boolean getAutoCreateBucket() { return autoCreateBucket; } public void setAutoCreateBucket(Boolean autoCreateBucket) { this.autoCreateBucket = autoCreateBucket; } public String getKeyName() { return keyName; } public void setKeyName(String keyName) { this.keyName = keyName; } } }
package com.planet_ink.coffee_mud.WebMacros.grinder; import com.planet_ink.coffee_web.interfaces.*; import com.planet_ink.coffee_mud.WebMacros.RoomData; 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.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.Faction.FactionChangeEvent; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.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 2008-2016 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 GrinderFactions { public String name() { return "GrinderFactions"; } public static String modifyFaction(HTTPRequest httpReq, java.util.Map<String,String> parms, Faction F) { final String replaceCommand=httpReq.getUrlParameter("REPLACE"); if((replaceCommand != null) && (replaceCommand.length()>0) && (replaceCommand.indexOf('=')>0)) { final int eq=replaceCommand.indexOf('='); final String field=replaceCommand.substring(0,eq); final String value=replaceCommand.substring(eq+1); httpReq.addFakeUrlParameter(field, value); httpReq.addFakeUrlParameter("REPLACE",""); } String old; old=httpReq.getUrlParameter("NAME"); F.setName(old==null?("NAME"):old); old=httpReq.getUrlParameter("SHOWINSCORE"); F.setShowInScore((old!=null)&&(old.equalsIgnoreCase("on"))); old=httpReq.getUrlParameter("SHOWINFACTIONS"); F.setShowInFactionsCommand((old!=null)&&(old.equalsIgnoreCase("on"))); old=httpReq.getUrlParameter("SHOWINEDITOR"); F.setShowInEditor((old!=null)&&(old.equalsIgnoreCase("on"))); old=httpReq.getUrlParameter("SHOWINREPORTS"); F.setShowInSpecialReported((old!=null)&&(old.equalsIgnoreCase("on"))); int num=0; for(final Enumeration<Faction.FRange> e=F.ranges();e.hasMoreElements();) F.delRange(e.nextElement()); while(httpReq.getUrlParameter("RANGENAME"+num)!=null) { old=httpReq.getUrlParameter("RANGENAME"+num); String code=httpReq.getUrlParameter("RANGECODE"+num); if(old.length()>0) { if(code.length()==0) code=CMStrings.replaceAll(old.toUpperCase().trim()," ","_"); final int low=CMath.s_int(httpReq.getUrlParameter("RANGELOW"+num)); int high=CMath.s_int(httpReq.getUrlParameter("RANGEHIGH"+num)); if(high<low) high=low; final String flag=httpReq.getUrlParameter("RANGEFLAG"+num); F.addRange(low+";"+high+";"+old+";"+code+";"+flag); } num++; } old=httpReq.getUrlParameter("PLAYERCHOICETEXT"); F.setChoiceIntro(old==null?"":old); final String[] prefixes={"AUTOVALUE","DEFAULTVALUE","PLAYERCHOICE"}; for(int i=0;i<prefixes.length;i++) { final String prefix=prefixes[i]; final Vector<String> V=new Vector<String>(); num=0; while(httpReq.getUrlParameter(prefix+num)!=null) { final String value=httpReq.getUrlParameter(prefix+num); if(value.length()>0) { final String mask=httpReq.getUrlParameter(prefix+"MASK"+num); V.addElement((CMath.s_long(value)+" "+mask).trim()); } num++; } switch(i) { case 0: F.setAutoDefaults(V); break; case 1: F.setDefaults(V); break; case 2: F.setChoices(V); break; } } F.clearChangeEvents(); num=0; while(httpReq.getUrlParameter("CHANGESTRIGGER"+num)!=null) { old=httpReq.getUrlParameter("CHANGESTRIGGER"+num); if(old.length()>0) { final String ctparms=httpReq.getUrlParameter("CHANGESTPARM"+num); if(ctparms.trim().length()>0) old+="("+ctparms.trim()+")"; old+=";"; old+=Faction.FactionChangeEvent.CHANGE_DIRECTION_DESCS[CMath.s_int(httpReq.getUrlParameter("CHANGESDIR"+num))]; old+=";"; old+=CMath.toPct(httpReq.getUrlParameter("CHANGESFACTOR"+num)); old+=";"; String id=""; int x=0; for(;httpReq.isUrlParameter("CHANGESFLAGS"+num+"_"+id);id=""+(++x)) old+=" "+httpReq.getUrlParameter("CHANGESFLAGS"+num+"_"+id).toUpperCase(); old+=";"; old+=httpReq.getUrlParameter("CHANGESMASK"+num); F.createChangeEvent(old); } num++; } for(final Enumeration<Faction.FZapFactor> e=F.factors();e.hasMoreElements();) F.delFactor(e.nextElement()); num=0; while(httpReq.getUrlParameter("ADJFACTOR"+num)!=null) { old=httpReq.getUrlParameter("ADJFACTOR"+num); if(old.length()>0) { final double gain=CMath.s_pct(httpReq.getUrlParameter("ADJFACTORGAIN"+num)); final double loss=CMath.s_pct(httpReq.getUrlParameter("ADJFACTORLOSS"+num)); F.addFactor(gain,loss,old); } num++; } num=0; for(final Enumeration<String> e=F.relationFactions();e.hasMoreElements();) F.delRelation(e.nextElement()); while(httpReq.getUrlParameter("RELATIONS"+num)!=null) { old=httpReq.getUrlParameter("RELATIONS"+num); if(old.length()>0) F.addRelation(old,CMath.s_pct(httpReq.getUrlParameter("RELATIONSAMT"+num))); num++; } num=0; final TriadVector<String,String,String> affBehav=new TriadVector<String,String,String>(); final HashSet<String> affBehavKeepers=new HashSet<String>(); // its done this strange way to minimize impact on mob recalculations. while(httpReq.getUrlParameter("AFFBEHAV"+num)!=null) { old=httpReq.getUrlParameter("AFFBEHAV"+num); if(old.length()>0) { final String parm=""+httpReq.getUrlParameter("AFFBEHAVPARM"+num); final String mask=""+httpReq.getUrlParameter("AFFBEHAVMASK"+num); final String[] oldParms=F.getAffectBehav(old); if((oldParms==null)||(!oldParms[0].equals(parm))||(!oldParms[1].equals(mask))) affBehav.addElement(old.toUpperCase().trim(),parm,mask); else affBehavKeepers.add(old.toUpperCase().trim()); } num++; } for(final Enumeration<String> e=F.affectsBehavs();e.hasMoreElements();) { old=e.nextElement(); if(!affBehavKeepers.contains(old.toUpperCase().trim())) F.delAffectBehav(old); } for(int d=0;d<affBehav.size();d++) { F.delAffectBehav(affBehav.get(d).first); F.addAffectBehav(affBehav.get(d).first,affBehav.get(d).second,affBehav.get(d).third); } num=0; for(final Enumeration<Faction.FAbilityUsage> e=F.abilityUsages();e.hasMoreElements();) F.delAbilityUsage(e.nextElement()); while(httpReq.getUrlParameter("ABILITYUSE"+num)!=null) { old=httpReq.getUrlParameter("ABILITYUSE"+num); if(old.length()>0) { final int usedType=CMLib.factions().getAbilityFlagType(old); if(usedType>0) { int x=-1; while(httpReq.isUrlParameter("ABILITYUSE"+num+"_"+(++x))) { final String s=httpReq.getUrlParameter("ABILITYUSE"+num+"_"+x); if(s.length()>0) { old+=" "+s.toUpperCase().trim(); } } } old+=";"+CMath.s_int(httpReq.getUrlParameter("ABILITYMIN"+num)); old+=";"+CMath.s_int(httpReq.getUrlParameter("ABILITYMAX"+num)); F.addAbilityUsage(old); } num++; } num=0; for(final Enumeration<Faction.FReactionItem> e=F.reactions();e.hasMoreElements();) F.delReaction(e.nextElement()); while(httpReq.getUrlParameter("REACTIONRANGE"+num)!=null) { old=httpReq.getUrlParameter("REACTIONRANGE"+num); final String old1=httpReq.getUrlParameter("REACTIONMASK"+num); final String old2=httpReq.getUrlParameter("REACTIONABC"+num); final String old3=httpReq.getUrlParameter("REACTIONPARM"+num); if(old.length()>0) F.addReaction(old,old1,old2,old3); num++; } old=httpReq.getUrlParameter("USELIGHTREACTIONS"); F.setLightReactions((old!=null)&&(old.equalsIgnoreCase("on"))); old=httpReq.getUrlParameter("RATEMODIFIER"); F.setRateModifier(old==null?0.0:CMath.s_pct(old)); old=httpReq.getUrlParameter("AFFECTONEXP"); F.setExperienceFlag(old); return ""; } }
package std.algs; import std.libs.*; /************************************************************************* * Compilation: javac IndexMaxPQ.java * Execution: java IndexMaxPQ * * Maximum-oriented indexed PQ implementation using a binary heap. * *********************************************************************/ import java.util.Iterator; import java.util.NoSuchElementException; /** * The <tt>IndexMaxPQ</tt> class represents an indexed priority queue of generic keys. * It supports the usual <em>insert</em> and <em>delete-the-maximum</em> * operations, along with <em>delete</em> and <em>change-the-key</em> * methods. In order to let the client refer to items on the priority queue, * an integer between 0 and NMAX-1 is associated with each key&mdash;the client * uses this integer to specify which key to delete or change. * It also supports methods for peeking at a maximum key, * testing if the priority queue is empty, and iterating through * the keys. * <p> * This implementation uses a binary heap along with an array to associate * keys with integers in the given range. * The <em>insert</em>, <em>delete-the-maximum</em>, <em>delete</em>, * <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em> * operations take logarithmic time. * The <em>is-empty</em>, <em>size</em>, <em>max-index</em>, <em>max-key</em>, and <em>key-of</em> * operations take constant time. * Construction takes time proportional to the specified capacity. * <p> * For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public class IndexMaxPQ<Key extends Comparable<Key>> implements Iterable<Integer> { private int N; // number of elements on PQ private int[] pq; // binary heap using 1-based indexing private int[] qp; // inverse of pq - qp[pq[i]] = pq[qp[i]] = i private Key[] keys; // keys[i] = priority of i /** * Initializes an empty indexed priority queue with indices between 0 and NMAX-1. * @param NMAX the keys on the priority queue are index from 0 to NMAX-1 * @throws IllegalArgumentException if NMAX < 0 */ public IndexMaxPQ(int NMAX) { keys = (Key[]) new Comparable[NMAX + 1]; // make this of length NMAX?? pq = new int[NMAX + 1]; qp = new int[NMAX + 1]; // make this of length NMAX?? for (int i = 0; i <= NMAX; i++) qp[i] = -1; } /** * Is the priority queue empty? * @return true if the priority queue is empty; false otherwise */ public boolean isEmpty() { return N == 0; } /** * Is i an index on the priority queue? * @param i an index * @throws IndexOutOfBoundsException unless (0 &le; i < NMAX) */ public boolean contains(int i) { return qp[i] != -1; } /** * Returns the number of keys on the priority queue. * @return the number of keys on the priority queue */ public int size() { return N; } /** * Associate key with index i. * @param i an index * @param key the key to associate with index i * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @throws java.util.IllegalArgumentException if there already is an item associated with index i */ public void insert(int i, Key key) { if (contains(i)) throw new IllegalArgumentException("index is already in the priority queue"); N++; qp[i] = N; pq[N] = i; keys[i] = key; swim(N); } /** * Returns an index associated with a maximum key. * @return an index associated with a maximum key * @throws java.util.NoSuchElementException if priority queue is empty */ public int maxIndex() { if (N == 0) throw new NoSuchElementException("Priority queue underflow"); return pq[1]; } /** * Return a maximum key. * @return a maximum key * @throws java.util.NoSuchElementException if priority queue is empty */ public Key maxKey() { if (N == 0) throw new NoSuchElementException("Priority queue underflow"); return keys[pq[1]]; } /** * Removes a maximum key and returns its associated index. * @return an index associated with a maximum key * @throws java.util.NoSuchElementException if priority queue is empty */ public int delMax() { if (N == 0) throw new NoSuchElementException("Priority queue underflow"); int min = pq[1]; exch(1, N--); sink(1); qp[min] = -1; // delete keys[pq[N+1]] = null; // to help with garbage collection pq[N+1] = -1; // not needed return min; } /** * Returns the key associated with index i. * @param i the index of the key to return * @return the key associated with index i * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @throws java.util.NoSuchElementException no key is associated with index i */ public Key keyOf(int i) { if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); else return keys[i]; } /** * Change the key associated with index i to the specified value. * @param i the index of the key to change * @param key change the key assocated with index i to this key * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @deprecated Replaced by changeKey() */ @Deprecated public void change(int i, Key key) { changeKey(i, key); } /** * Change the key associated with index i to the specified value. * @param i the index of the key to change * @param key change the key assocated with index i to this key * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX */ public void changeKey(int i, Key key) { if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); keys[i] = key; swim(qp[i]); sink(qp[i]); } /** * Increase the key associated with index i to the specified value. * @param i the index of the key to increase * @param key increase the key assocated with index i to this key * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @throws IllegalArgumentException if key &le; key associated with index i * @throws java.util.NoSuchElementException no key is associated with index i */ public void increaseKey(int i, Key key) { if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); if (keys[i].compareTo(key) >= 0) throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key"); keys[i] = key; swim(qp[i]); } /** * Decrease the key associated with index i to the specified value. * @param i the index of the key to decrease * @param key decrease the key assocated with index i to this key * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @throws IllegalArgumentException if key &ge; key associated with index i * @throws java.util.NoSuchElementException no key is associated with index i */ public void decreaseKey(int i, Key key) { if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); if (keys[i].compareTo(key) <= 0) throw new IllegalArgumentException("Calling decreaseKey() with given argument would not strictly decrease the key"); keys[i] = key; sink(qp[i]); } /** * Remove the key associated with index i. * @param i the index of the key to remove * @throws IndexOutOfBoundsException unless 0 &le; i < NMAX * @throws java.util.NoSuchElementException no key is associated with index i */ public void delete(int i) { if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); int index = qp[i]; exch(index, N--); swim(index); sink(index); keys[i] = null; qp[i] = -1; } /************************************************************** * General helper functions **************************************************************/ private boolean less(int i, int j) { return keys[pq[i]].compareTo(keys[pq[j]]) < 0; } private void exch(int i, int j) { int swap = pq[i]; pq[i] = pq[j]; pq[j] = swap; qp[pq[i]] = i; qp[pq[j]] = j; } /************************************************************** * Heap helper functions **************************************************************/ private void swim(int k) { while (k > 1 && less(k/2, k)) { exch(k, k/2); k = k/2; } } private void sink(int k) { while (2*k <= N) { int j = 2*k; if (j < N && less(j, j+1)) j++; if (!less(k, j)) break; exch(k, j); k = j; } } /*********************************************************************** * Iterators **********************************************************************/ /** * Returns an iterator that iterates over the keys on the * priority queue in descending order. * The iterator doesn't implement <tt>remove()</tt> since it's optional. * @return an iterator that iterates over the keys in descending order */ public Iterator<Integer> iterator() { return new HeapIterator(); } private class HeapIterator implements Iterator<Integer> { // create a new pq private IndexMaxPQ<Key> copy; // add all elements to copy of heap // takes linear time since already in heap order so no keys move public HeapIterator() { copy = new IndexMaxPQ<Key>(pq.length - 1); for (int i = 1; i <= N; i++) copy.insert(pq[i], keys[pq[i]]); } public boolean hasNext() { return !copy.isEmpty(); } public void remove() { throw new UnsupportedOperationException(); } public Integer next() { if (!hasNext()) throw new NoSuchElementException(); return copy.delMax(); } } /** * Unit tests the <tt>IndexMaxPQ</tt> data type. */ public static void main(String[] args) { // insert a bunch of strings String[] strings = { "it", "was", "the", "best", "of", "times", "it", "was", "the", "worst" }; IndexMaxPQ<String> pq = new IndexMaxPQ<String>(strings.length); for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // print each key using the iterator for (int i : pq) { StdOut.println(i + " " + strings[i]); } StdOut.println(); // increase or decrease the key for (int i = 0; i < strings.length; i++) { if (StdRandom.uniform() < 0.5) pq.increaseKey(i, strings[i] + strings[i]); else pq.decreaseKey(i, strings[i].substring(0, 1)); } // delete and print each key while (!pq.isEmpty()) { String key = pq.maxKey(); int i = pq.delMax(); StdOut.println(i + " " + key); } StdOut.println(); // reinsert the same strings for (int i = 0; i < strings.length; i++) { pq.insert(i, strings[i]); } // delete them in random order int[] perm = new int[strings.length]; for (int i = 0; i < strings.length; i++) perm[i] = i; StdRandom.shuffle(perm); for (int i = 0; i < perm.length; i++) { String key = pq.keyOf(perm[i]); pq.delete(perm[i]); StdOut.println(perm[i] + " " + key); } } }
/* * Copyright (c) 2009, James Leigh 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 openrdf.org nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package org.openrdf.repository.object.composition; import org.openrdf.model.URI; import org.openrdf.repository.object.composition.helpers.BehaviourConstructor; import org.openrdf.repository.object.composition.helpers.BehaviourProviderService; import org.openrdf.repository.object.composition.helpers.ClassComposer; import org.openrdf.repository.object.exceptions.ObjectCompositionException; import org.openrdf.repository.object.exceptions.ObjectStoreConfigException; import org.openrdf.repository.object.managers.PropertyMapper; import org.openrdf.repository.object.managers.RoleMapper; import org.openrdf.repository.object.managers.helpers.DirUtil; import org.openrdf.repository.object.managers.helpers.RoleClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static java.lang.reflect.Modifier.isAbstract; /** * Find a proxy class that can be used for a set of rdf:types. * * @author James Leigh * */ public class ClassResolver { private static final Set<URI> EMPTY_SET = Collections.emptySet(); private static final String PKG_PREFIX = "object.proxies._"; private static final String CLASS_PREFIX = "_EntityProxy"; private static RoleMapper newRoleMapper(ClassLoader cl) throws ObjectStoreConfigException { if (cl == null) { return newRoleMapper(ClassResolver.class.getClassLoader()); } else { RoleMapper mapper = new RoleMapper(); new RoleClassLoader(mapper).loadRoles(cl); return mapper; } } private final Logger logger = LoggerFactory.getLogger(ClassResolver.class); private final PropertyMapper properties; private final ClassFactory cp; private final Collection<Class<?>> baseClassRoles; private final RoleMapper mapper; private final Class<?> blank; private final ConcurrentMap<Set<URI>, Class<?>> multiples = new ConcurrentHashMap<Set<URI>, Class<?>>(); private final BehaviourProviderService behaviourService; public ClassResolver() throws ObjectStoreConfigException { this(Thread.currentThread().getContextClassLoader()); } public ClassResolver(ClassLoader cl) throws ObjectStoreConfigException { this(newRoleMapper(cl), cl == null ? ClassResolver.class.getClassLoader() : cl); } public ClassResolver(RoleMapper mapper, ClassLoader cl) throws ObjectStoreConfigException { this(mapper, new PropertyMapper(cl, mapper.isNamedTypePresent()), cl); } public ClassResolver(RoleMapper mapper, PropertyMapper properties, ClassLoader cl) throws ObjectStoreConfigException { this.mapper = mapper; this.properties = properties; try { File dir = DirUtil.createTempDir("classes"); DirUtil.deleteOnExit(dir); this.cp = new ClassFactory(dir, cl); behaviourService = BehaviourProviderService.newInstance(cp); Collection<Class<?>> baseClassRoles = mapper.getConceptClasses(); this.baseClassRoles = new ArrayList<Class<?>>(baseClassRoles.size()); for (Class<?> base : baseClassRoles) { try { // ensure the base class has a default constructor base.getConstructor(); this.baseClassRoles.add(base); } catch (NoSuchMethodException e) { logger.warn("Concept will only be mergable: {}", base); } } blank = resolveBlankEntity(EMPTY_SET); } catch (IOException e) { throw new ObjectStoreConfigException(e); } } public RoleMapper getRoleMapper() { return mapper; } public PropertyMapper getPropertyMapper() { return properties; } public ClassLoader getClassLoader() { return cp; } public Class<?> resolveBlankEntity() { return blank; } public Class<?> resolveBlankEntity(Set<URI> types) { Class<?> proxy = multiples.get(types); if (proxy != null) return proxy; Collection<Class<?>> roles = new ArrayList<Class<?>>(); proxy = resolveRoles(mapper.findRoles(types, roles)); multiples.putIfAbsent(types, proxy); return proxy; } public Class<?> resolveEntity(URI resource) { if (resource != null && mapper.isIndividualRolesPresent(resource)) return resolveIndividualEntity(resource, EMPTY_SET); return resolveBlankEntity(); } public Class<?> resolveEntity(URI resource, Set<URI> types) { if (resource != null && mapper.isIndividualRolesPresent(resource)) return resolveIndividualEntity(resource, types); return resolveBlankEntity(types); } private Class<?> resolveIndividualEntity(URI resource, Collection<URI> types) { Collection<Class<?>> roles = new ArrayList<Class<?>>(); roles = mapper.findIndividualRoles(resource, roles); roles = mapper.findRoles(types, roles); return resolveRoles(roles); } private Class<?> resolveRoles(Collection<Class<?>> roles) { try { String className = getJavaClassName(roles); return getComposedBehaviours(className, roles); } catch (Exception e) { List<String> roleNames = new ArrayList<String>(); for (Class<?> f : roles) { roleNames.add(f.getSimpleName()); } throw new ObjectCompositionException(e.toString() + " for entity with roles: " + roleNames, e); } } private Class<?> getComposedBehaviours(String className, Collection<Class<?>> roles) throws Exception { synchronized (cp) { try { return cp.classForName(className); } catch (ClassNotFoundException e1) { return composeBehaviours(className, roles); } } } private Class<?> composeBehaviours(String className, Collection<Class<?>> roles) throws Exception { List<Class<?>> types = new ArrayList<Class<?>>(roles.size()); types.addAll(roles); types = removeSuperClasses(types); ClassComposer cc = new ClassComposer(className, types.size()); cc.setClassFactory(cp); Set<Class<?>> behaviours = new LinkedHashSet<Class<?>>(types.size()); Set<BehaviourConstructor> concretes = new LinkedHashSet<BehaviourConstructor>(types.size()); Set<Class<?>> bases = new LinkedHashSet<Class<?>>(); Class<?> baseClass = Object.class; for (Class<?> role : types) { if (role.isInterface()) { cc.addInterface(role); } else { if (baseClassRoles.contains(role)) { if (baseClass != null && baseClass.isAssignableFrom(role)) { baseClass = role; } else if (!role.equals(baseClass)) { baseClass = null; } bases.add(role); } else if (!isAbstract(role.getModifiers())) { try { concretes.add(new BehaviourConstructor(role)); } catch (NoSuchMethodException e) { // ignore } } behaviours.add(role); } } if (baseClass == null) { logger.error("Cannot compose multiple concept classes: " + types); } else { cc.setBaseClass(baseClass); } Set<Class<?>> allRoles = new HashSet<Class<?>>(behaviours.size() + cc.getInterfaces().size()); allRoles.addAll(behaviours); allRoles.addAll(cc.getInterfaces()); PropertyMapper pm = properties; cc.addAllBehaviours(concretes); cc.addAllBehaviours(behaviourService.findImplementations(pm, allRoles, bases)); return cc.compose(); } private List<Class<?>> removeSuperClasses(List<Class<?>> classes) { for (int i = classes.size() - 1; i >= 0; i--) { Class<?> c = classes.get(i); for (int j = classes.size() - 1; j >= 0; j--) { Class<?> d = classes.get(j); if (i != j && c.isAssignableFrom(d) && c.isInterface() == d.isInterface()) { classes.remove(i); break; } } } return classes; } private String getJavaClassName(Collection<Class<?>> javaClasses) { String phex = packagesToHexString(javaClasses); String chex = classesToHexString(javaClasses); return PKG_PREFIX + phex + "." + CLASS_PREFIX + chex; } private String packagesToHexString(Collection<Class<?>> javaClasses) { TreeSet<String> names = new TreeSet<String>(); for (Class<?> clazz : javaClasses) { if (clazz.getPackage() != null) { names.add(clazz.getPackage().getName()); } } return toHexString(names); } private String classesToHexString(Collection<Class<?>> javaClasses) { TreeSet<String> names = new TreeSet<String>(); for (Class<?> clazz : javaClasses) { names.add(clazz.getName()); } return toHexString(names); } private String toHexString(TreeSet<String> names) { long hashCode = 0; for (String name : names) { hashCode = 31 * hashCode + name.hashCode(); } return Long.toHexString(hashCode); } }
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package org.opencloudb.parser; import java.sql.SQLSyntaxErrorException; import java.util.Map; import java.util.Set; import junit.framework.Assert; import org.junit.Test; import org.opencloudb.mpp.ColumnRoutePair; import org.opencloudb.mpp.JoinRel; import org.opencloudb.mpp.SelectParseInf; import org.opencloudb.mpp.SelectSQLAnalyser; import org.opencloudb.mpp.ShardingParseInfo; import com.foundationdb.sql.StandardException; import com.foundationdb.sql.parser.QueryTreeNode; public class TestSelectSQLAnalyser { @Test public void testSelectRoute() throws SQLSyntaxErrorException, StandardException { SelectParseInf parsInf = new SelectParseInf(); parsInf.ctx = new ShardingParseInfo(); Map<String, Map<String, Set<ColumnRoutePair>>> tablesAndCondtions = null; Map<String, Set<ColumnRoutePair>> columnsMap = null; String sql = null; QueryTreeNode ast = null; sql = "select a.id,a.name,b.type from db1.a a join b on a.id=b.id where a.sharding_id=4 or a.sharding_id=5 limit 2,10"; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // Assert.assertEquals(true, parsInf.isContainsSchema()); // System.out.println("sql:" + new NodeToString().toString(ast)); // two tables Assert.assertEquals(2, tablesAndCondtions.size()); // a condtion is 2 Assert.assertEquals(1, tablesAndCondtions.get("A").size()); Assert.assertEquals(2, tablesAndCondtions.get("A").get("sharding_id".toUpperCase()) .size()); Assert.assertEquals(1, parsInf.ctx.joinList.size()); parsInf.clear(); sql = "select user"; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // NO tables Assert.assertEquals(0, tablesAndCondtions.size()); parsInf.ctx.tablesAndConditions.clear(); sql = "SELECT last_name, job_id FROM demo.employees WHERE job_id = (SELECT job_id FROM employeesBack WHERE employee_id = 141) and (sharding_id='5' or sharding_id in (22,33,44))"; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // 2 tables Assert.assertEquals(2, tablesAndCondtions.size()); // a condtion is Assert.assertEquals(1, tablesAndCondtions .get("employees".toUpperCase()).size()); Assert.assertEquals(4, tablesAndCondtions .get("employees".toUpperCase()) .get("sharding_id".toUpperCase()).size()); Assert.assertEquals(1, tablesAndCondtions.get("employeesBack".toUpperCase()).size()); parsInf.clear(); sql = "SELECT ID,NAME FROM Aa WHERE EXISTS (SELECT * FROM demo2.B B WHERE B.AID=3) "; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(2, tablesAndCondtions.size()); // condtion Assert.assertEquals(1, tablesAndCondtions.get("B").size()); // test table alias parsInf.clear(); sql = "SELECT * FROM B baLias WHERE baLias.AID=1 "; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion Assert.assertEquals(1, tablesAndCondtions.get("B").size()); // test column alias , parsInf.clear(); sql = "SELECT ID ,count(*) as count FROM B baLias WHERE baLias.AID=1 and count=5 "; ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion Assert.assertEquals(2, tablesAndCondtions.get("B").size()); Assert.assertEquals(1, tablesAndCondtions.get("B").get("count".toUpperCase()).size()); // test select union sql = "select * from offer A where a.member_id='abc' union select * from product_visit b where B.offer_id =123"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(2, tablesAndCondtions.size()); // condtion Map<String, Set<ColumnRoutePair>> product_visitCond = tablesAndCondtions .get("product_visit".toUpperCase()); Assert.assertEquals(1, product_visitCond.size()); Assert.assertEquals(1, product_visitCond.get("offer_id".toUpperCase()) .size()); // not operater sql = "select * from A where not sharding_id=50"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion Assert.assertEquals(0, tablesAndCondtions.get("A").size()); // in operater sql = "select * from A where sharding_id in(1,222,333)"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); columnsMap = tablesAndCondtions.get("A"); // condtion Assert.assertEquals(1, columnsMap.size()); Assert.assertEquals(3, columnsMap.get("sharding_id".toUpperCase()) .size()); // in operater sql = "select * from A where sharding_id in('222','333')"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); columnsMap = tablesAndCondtions.get("A"); // condtion Assert.assertEquals(1, columnsMap.size()); Assert.assertEquals(2, columnsMap.get("sharding_id".toUpperCase()) .size()); // not operater 2 sql = "select * from A where sharding_id not in(222,333)"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion Assert.assertEquals(0, tablesAndCondtions.get("A").size()); // // not join sql = "select * from A where sharding_id not in(select id from B)"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(2, tablesAndCondtions.size()); // condtion Assert.assertEquals(0, tablesAndCondtions.get("A").size()); // // not join sql = "select * from COMPANY where (sharding_id=10000 ) or not (sharding_id=10010)"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion columnsMap = tablesAndCondtions.get("COMPANY"); Assert.assertEquals(1, columnsMap.size()); Assert.assertEquals(1, columnsMap.get("sharding_id".toUpperCase()) .size()); sql = "select * from COMPANY where (sharding_id=10000 ) or (sharding_id=10010)"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); // condtion Assert.assertEquals( 2, tablesAndCondtions.get("COMPANY") .get("sharding_id".toUpperCase()).size()); sql = "select * from offer where (offer_id, group_id ) in ((123,234),(222,444))"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); Map<String, Set<ColumnRoutePair>> offerCondMap = tablesAndCondtions .get("OFFER"); // condtion Assert.assertEquals(2, offerCondMap.get("offer_id".toUpperCase()) .size()); Assert.assertEquals(2, offerCondMap.get("group_id".toUpperCase()) .size()); sql = "SELECT * FROM offer WHERE FALSE OR offer_id = 123 AND member_ID = 123 OR member_id = 123 AND member_id = 234 OR member_id = 123 AND member_id = 345 OR member_id = 123 AND member_id = 456 OR offer_id = 234 AND group_id = 123 OR offer_id = 234 AND group_id = 234 OR offer_id = 234 AND group_id = 345 OR offer_id = 234 AND group_id = 456 OR offer_id = 345 AND group_id = 123 OR offer_id = 345 AND group_id = 234 OR offer_id = 345 AND group_id = 345 OR offer_id = 345 AND group_id = 456 OR offer_id = 456 AND group_id = 123 OR offer_id = 456 AND group_id = 234 OR offer_id = 456 AND group_id = 345 OR offer_id = 456 AND group_id = 456"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); offerCondMap = tablesAndCondtions.get("OFFER"); Assert.assertEquals(4, offerCondMap.get("member_id".toUpperCase()) .size()); sql = "select * from(select * from offer_detail where custmer='Mr I') offer,mydb.B where offer.id=B.id and b.columA=3333"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(2, tablesAndCondtions.size()); offerCondMap = tablesAndCondtions.get("offer_detail".toUpperCase()); Assert.assertEquals(1, offerCondMap.get("custmer".toUpperCase()).size()); sql = "select count(*) from (select * from(select * from offer_detail where offer_id='123' or offer_id='234' limit 88)offer where offer.member_id='abc' limit 60) w " + " where w.member_id ='pavarotti17' limit 99"; // sql="select * from(select * from offer_detail where offer_id='123' or offer_id='234' limit 88)offer where offer.member_id='abc'"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); offerCondMap = tablesAndCondtions.get("offer_detail".toUpperCase()); Assert.assertEquals(2, offerCondMap.get("offer_id".toUpperCase()) .size()); sql = "select * from wp_image where `seLect`='pavarotti17' "; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; // tables Assert.assertEquals(1, tablesAndCondtions.size()); offerCondMap = tablesAndCondtions.get("wp_image".toUpperCase()); Assert.assertEquals(1, offerCondMap.get("seLect".toUpperCase()).size()); sql = "select * from customer,orders where customer.id=orders.customer_id"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; sql = "select o.*,d.* from (select * from ordera) o left join(select * from download) d on d.currentdate = o.currentdate"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(2, tablesAndCondtions.size()); Assert.assertEquals(0, tablesAndCondtions.get("ordera".toUpperCase()) .size()); Assert.assertEquals(0, tablesAndCondtions.get("download".toUpperCase()) .size()); Assert.assertEquals( "download".toUpperCase() + "." + "currentdate".toUpperCase() + "=" + "ordera".toUpperCase() + "." + "currentdate".toUpperCase(), parsInf.ctx.joinList.get(0).joinSQLExp); sql = "select i.*,Description,DescriptionType,QuestionNumber,Name,RelationType,q.Gender,q.Birthday,q.DepartmentName,q.SimpleDescription,q.StateDescription,q.ExamedTag,q.ExamedDescription,q.DiseaseTag,q.IsSystem,q.Attachment,q.Age,q.AgeType,q.LocalID,ap.NickName AS PatientName,ad.Realname AS DoctorName from bjd_consult_inquiry i left join bjd_consult_question q on q.QuestionID=i.QuestionID left join bjd_account ap on ap.AccountID=i.PatientID left join bjd_doctor ad on ad.AccountID=i.DoctorID where q.LocalID='301002' and q.IsSystem=true and i.State in (6,5,9) order by q.IsSystem desc limit 0,5"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(4, tablesAndCondtions.size()); Assert.assertEquals(3, parsInf.ctx.joinList.size()); Assert.assertEquals(4, parsInf.ctx.tableAliasMap.size()); Assert.assertEquals(1, parsInf.ctx.tablesAndConditions.get("BJD_CONSULT_INQUIRY").size()); Assert.assertEquals(2, parsInf.ctx.tablesAndConditions.get("BJD_CONSULT_QUESTION").size()); sql = "select distinct c.*,l.Name LocalName from tablea c left join bjd_local l on c.LocalID=l.LocalID where ContentID='xxxxxb838'"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(2, tablesAndCondtions.size()); Assert.assertEquals(true, tablesAndCondtions.get("TABLEA").containsKey("CONTENTID")); sql="SELECT A.names FROM (SELECT * FROM (SELECT * FROM customer WHERE sharding_ID = '10000') B LEFT JOIN (SELECT NAME NAMES FROM employee WHERE sharding_ID = '10000') C ON B.name = C.names UNION ALL SELECT * FROM (SELECT * FROM customer WHERE sharding_ID = '10000') B LEFT JOIN (SELECT NAME NAMES FROM employee WHERE sharding_ID = '10000') C ON B.name = C.names) AS A ORDER BY NAME DESC"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(2, tablesAndCondtions.size()); sql="select * from T1 inner join T2 on T1.id = T2.id and T2.type=T1.type"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(1, parsInf.ctx.joinList.size()); Assert.assertEquals(new JoinRel("T1","id","T2","id"), parsInf.ctx.joinList.get(0)); Assert.assertEquals(2, tablesAndCondtions.size()); sql="select * from T1 inner join T2 on T1.id = T2.id or T2.type=T1.type"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(1, parsInf.ctx.joinList.size()); Assert.assertEquals(new JoinRel("T1","id","T2","id"), parsInf.ctx.joinList.get(0)); Assert.assertEquals(2, tablesAndCondtions.size()); sql="SELECT * from ismp_ocs_record_sn_ocs_in where cycle_id=null"; parsInf.clear(); ast = SQLParserDelegate.parse(sql, SQLParserDelegate.DEFAULT_CHARSET); SelectSQLAnalyser.analyse(parsInf, ast); tablesAndCondtions = parsInf.ctx.tablesAndConditions; Assert.assertEquals(0, parsInf.ctx.tablesAndConditions.get("ismp_ocs_record_sn_ocs_in".toUpperCase()).size()); } }
/* * Benchmark of risk-based anonymization in ARX 3.0.0 * Copyright 2015 - Fabian Prasser * * 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.deidentifier.arx.benchmark; import java.io.IOException; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.ARXPopulationModel; import org.deidentifier.arx.ARXPopulationModel.Region; import org.deidentifier.arx.ARXSolverConfiguration; import org.deidentifier.arx.AttributeType.Hierarchy; import org.deidentifier.arx.Data; import org.deidentifier.arx.criteria.KAnonymity; import org.deidentifier.arx.criteria.PopulationUniqueness; import org.deidentifier.arx.criteria.SampleUniqueness; import org.deidentifier.arx.metric.Metric; import org.deidentifier.arx.metric.Metric.AggregateFunction; import org.deidentifier.arx.risk.RiskModelPopulationUniqueness.PopulationUniquenessModel; /** * This class encapsulates most of the parameters of a benchmark run * @author Fabian Prasser */ public class BenchmarkSetup { public static enum BenchmarkDataset { ADULT { @Override public String toString() { return "Adult"; } }, CUP { @Override public String toString() { return "Cup"; } }, FARS { @Override public String toString() { return "Fars"; } }, ATUS { @Override public String toString() { return "Atus"; } }, IHIS { @Override public String toString() { return "Ihis"; } }, } public static enum BenchmarkPrivacyModel { K_ANONYMITY { @Override public String toString() { return "k-anonymity"; } }, UNIQUENESS_DANKAR { @Override public String toString() { return "p-uniqueness (dankar)"; } }, UNIQUENESS_PITMAN { @Override public String toString() { return "p-uniqueness (pitman)"; } }, UNIQUENESS_SNB { @Override public String toString() { return "p-uniqueness (snb)"; } }, UNIQUENESS_ZAYATZ { @Override public String toString() { return "p-uniqueness (zayatz)"; } }, UNIQUENESS_SAMPLE { @Override public String toString() { return "p-sample-uniqueness"; } }, } public static enum BenchmarkUtilityMeasure { ENTROPY { @Override public String toString() { return "Entropy"; } }, LOSS { @Override public String toString() { return "Loss"; } }, } private static final double[][] SOLVER_START_VALUES = getSolverStartValues(); /** * Returns a configuration for the ARX framework * @param dataset * @param criteria * @param uniqueness * @return * @throws IOException */ public static ARXConfiguration getConfiguration(BenchmarkDataset dataset, BenchmarkUtilityMeasure utility, BenchmarkPrivacyModel criterion, double uniqueness) throws IOException { ARXConfiguration config = ARXConfiguration.create(); switch (utility) { case ENTROPY: config.setMetric(Metric.createPrecomputedNormalizedEntropyMetric(1.0d, AggregateFunction.SUM)); break; case LOSS: config.setMetric(Metric.createPrecomputedLossMetric(1.0d, AggregateFunction.GEOMETRIC_MEAN)); break; default: throw new IllegalArgumentException(""); } config.setMaxOutliers(1.0d); switch (criterion) { case UNIQUENESS_DANKAR: config.addCriterion(new PopulationUniqueness(uniqueness, PopulationUniquenessModel.DANKAR, ARXPopulationModel.create(Region.USA), ARXSolverConfiguration.create().preparedStartValues(SOLVER_START_VALUES).iterationsPerTry(15))); break; case UNIQUENESS_SNB: config.addCriterion(new PopulationUniqueness(uniqueness, PopulationUniquenessModel.SNB, ARXPopulationModel.create(Region.USA), ARXSolverConfiguration.create().preparedStartValues(SOLVER_START_VALUES).iterationsPerTry(15))); break; case UNIQUENESS_PITMAN: config.addCriterion(new PopulationUniqueness(uniqueness, PopulationUniquenessModel.PITMAN, ARXPopulationModel.create(Region.USA), ARXSolverConfiguration.create().preparedStartValues(SOLVER_START_VALUES).iterationsPerTry(15))); break; case UNIQUENESS_ZAYATZ: config.addCriterion(new PopulationUniqueness(uniqueness, PopulationUniquenessModel.ZAYATZ, ARXPopulationModel.create(Region.USA), ARXSolverConfiguration.create().preparedStartValues(SOLVER_START_VALUES).iterationsPerTry(15))); break; case UNIQUENESS_SAMPLE: config.addCriterion(new SampleUniqueness(uniqueness)); break; case K_ANONYMITY: config.addCriterion(new KAnonymity(getK(uniqueness))); break; default: throw new RuntimeException("Invalid criterion"); } return config; } /** * Configures and returns the dataset * @param dataset * @param criteria * @return * @throws IOException */ public static Data getData(BenchmarkDataset dataset) throws IOException { Data data = null; switch (dataset) { case ADULT: data = Data.create("data/adult.csv", ';'); break; case ATUS: data = Data.create("data/atus.csv", ';'); break; case CUP: data = Data.create("data/cup.csv", ';'); break; case FARS: data = Data.create("data/fars.csv", ';'); break; case IHIS: data = Data.create("data/ihis.csv", ';'); break; default: throw new RuntimeException("Invalid dataset"); } for (String qi : getQuasiIdentifyingAttributes(dataset)) { data.getDefinition().setAttributeType(qi, getHierarchy(dataset, qi)); } return data; } /** * Returns all datasets * @return */ public static BenchmarkDataset[] getDatasets() { return new BenchmarkDataset[] { BenchmarkDataset.ADULT, BenchmarkDataset.CUP, BenchmarkDataset.FARS, BenchmarkDataset.ATUS, BenchmarkDataset.IHIS }; } /** * Returns the generalization hierarchy for the dataset and attribute * @param dataset * @param attribute * @return * @throws IOException */ public static Hierarchy getHierarchy(BenchmarkDataset dataset, String attribute) throws IOException { switch (dataset) { case ADULT: return Hierarchy.create("hierarchies/adult_hierarchy_" + attribute + ".csv", ';'); case ATUS: return Hierarchy.create("hierarchies/atus_hierarchy_" + attribute + ".csv", ';'); case CUP: return Hierarchy.create("hierarchies/cup_hierarchy_" + attribute + ".csv", ';'); case FARS: return Hierarchy.create("hierarchies/fars_hierarchy_" + attribute + ".csv", ';'); case IHIS: return Hierarchy.create("hierarchies/ihis_hierarchy_" + attribute + ".csv", ';'); default: throw new RuntimeException("Invalid dataset"); } } /** * Returns the quasi-identifiers for the dataset * @param dataset * @return */ public static String[] getQuasiIdentifyingAttributes(BenchmarkDataset dataset) { switch (dataset) { case ADULT: return new String[] { "age", "education", "marital-status", "native-country", "race", "salary-class", "sex", "workclass", "occupation" }; case ATUS: return new String[] { "Age", "Birthplace", "Citizenship status", "Labor force status", "Marital status", "Race", "Region", "Sex", "Highest level of school completed" }; case CUP: return new String[] { "AGE", "GENDER", "INCOME", "MINRAMNT", "NGIFTALL", "STATE", "ZIP", "RAMNTALL" }; case FARS: return new String[] { "iage", "ideathday", "ideathmon", "ihispanic", "iinjury", "irace", "isex", "istatenum" }; case IHIS: return new String[] { "AGE", "MARSTAT", "PERNUM", "QUARTER", "RACEA", "REGION", "SEX", "YEAR", "EDUC" }; default: throw new RuntimeException("Invalid dataset"); } } /** * Returns a set of utility measures * @return */ public static BenchmarkUtilityMeasure[] getUtilityMeasures() { return new BenchmarkUtilityMeasure[]{BenchmarkUtilityMeasure.ENTROPY, BenchmarkUtilityMeasure.LOSS}; } public static int getK(double uniqueness) { if (uniqueness == 0.001d) { return 3; } else if (uniqueness == 0.002d) { return 4; } else if (uniqueness == 0.003d) { return 5; } else if (uniqueness == 0.004d) { return 10; } else if (uniqueness == 0.005d) { return 15; } else if (uniqueness == 0.006d) { return 20; } else if (uniqueness == 0.007d) { return 25; } else if (uniqueness == 0.008d) { return 50; } else if (uniqueness == 0.009d) { return 75; } else if (uniqueness == 0.01d) { return 100; } else { throw new IllegalArgumentException("Unknown uniqueness parameter"); } } /** * Creates start values for the solver * @return */ private static double[][] getSolverStartValues() { double[][] result = new double[16][]; int index = 0; for (double d1 = 0d; d1 < 1d; d1 += 0.33d) { for (double d2 = 0d; d2 < 1d; d2 += 0.33d) { result[index++] = new double[] { d1, d2 }; } } return result; } }
/* * Copyright 2000-2013 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.openapi.vfs.impl.local; import com.intellij.ide.GeneralSettings; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileAttributes; import com.intellij.openapi.util.io.FileSystemUtil; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.vfs.newvfs.VfsImplUtil; import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.PathUtil; import com.intellij.util.Processor; import com.intellij.util.ThrowableConsumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.io.SafeFileOutputStream; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * @author Dmitry Avdeev */ public abstract class LocalFileSystemBase extends LocalFileSystem { protected static final Logger LOG = Logger.getInstance(LocalFileSystemBase.class); private static final FileAttributes FAKE_ROOT_ATTRIBUTES = new FileAttributes(true, false, false, false, DEFAULT_LENGTH, DEFAULT_TIMESTAMP, false); private final List<LocalFileOperationsHandler> myHandlers = new ArrayList<LocalFileOperationsHandler>(); @Override @Nullable public VirtualFile findFileByPath(@NotNull String path) { return VfsImplUtil.findFileByPath(this, path); } @Override public VirtualFile findFileByPathIfCached(@NotNull String path) { return VfsImplUtil.findFileByPathIfCached(this, path); } @Override @Nullable public VirtualFile refreshAndFindFileByPath(@NotNull String path) { return VfsImplUtil.refreshAndFindFileByPath(this, path); } @Override public VirtualFile findFileByIoFile(@NotNull File file) { String path = file.getAbsolutePath(); return findFileByPath(path.replace(File.separatorChar, '/')); } @NotNull protected static File convertToIOFile(@NotNull final VirtualFile file) { String path = file.getPath(); if (StringUtil.endsWithChar(path, ':') && path.length() == 2 && (SystemInfo.isWindows || SystemInfo.isOS2)) { path += "/"; // Make 'c:' resolve to a root directory for drive c:, not the current directory on that drive } return new File(path); } @NotNull private static File convertToIOFileAndCheck(@NotNull final VirtualFile file) throws FileNotFoundException { final File ioFile = convertToIOFile(file); final FileAttributes attributes = FileSystemUtil.getAttributes(ioFile); if (attributes != null && !attributes.isFile()) { LOG.warn("not a file: " + ioFile + ", " + attributes); throw new FileNotFoundException("Not a file: " + ioFile); } return ioFile; } @Override public boolean exists(@NotNull final VirtualFile file) { return getAttributes(file) != null; } @Override public long getLength(@NotNull final VirtualFile file) { final FileAttributes attributes = getAttributes(file); return attributes != null ? attributes.length : DEFAULT_LENGTH; } @Override public long getTimeStamp(@NotNull final VirtualFile file) { final FileAttributes attributes = getAttributes(file); return attributes != null ? attributes.lastModified : DEFAULT_TIMESTAMP; } @Override public boolean isDirectory(@NotNull final VirtualFile file) { final FileAttributes attributes = getAttributes(file); return attributes != null && attributes.isDirectory(); } @Override public boolean isWritable(@NotNull final VirtualFile file) { final FileAttributes attributes = getAttributes(file); return attributes != null && attributes.isWritable(); } @Override public boolean isSymLink(@NotNull final VirtualFile file) { final FileAttributes attributes = getAttributes(file); return attributes != null && attributes.isSymLink(); } @Override public String resolveSymLink(@NotNull VirtualFile file) { return FileSystemUtil.resolveSymLink(file.getPath()); } @Override @NotNull public String[] list(@NotNull final VirtualFile file) { if (file.getParent() == null) { final File[] roots = File.listRoots(); if (roots.length == 1 && roots[0].getName().isEmpty()) { final String[] list = roots[0].list(); if (list != null) return list; LOG.warn("Root '" + roots[0] + "' has no children - is it readable?"); return ArrayUtil.EMPTY_STRING_ARRAY; } if (file.getName().isEmpty()) { // return drive letter names for the 'fake' root on windows final String[] names = new String[roots.length]; for (int i = 0; i < names.length; i++) { String name = roots[i].getPath(); if (name.endsWith(File.separator)) { name = name.substring(0, name.length() - File.separator.length()); } names[i] = name; } return names; } } final String[] names = convertToIOFile(file).list(); return names == null ? ArrayUtil.EMPTY_STRING_ARRAY : names; } @Override @NotNull public String getProtocol() { return PROTOCOL; } @Override @Nullable protected String normalize(@NotNull String path) { if (path.isEmpty()) { try { path = new File("").getCanonicalPath(); } catch (IOException e) { return path; } } else if (SystemInfo.isWindows) { if (path.charAt(0) == '/' && !path.startsWith("//")) { path = path.substring(1); // hack over new File(path).toURI().toURL().getFile() } if (path.contains("~")) { try { path = new File(FileUtil.toSystemDependentName(path)).getCanonicalPath(); } catch (IOException e) { return null; } } } File file = new File(path); if (!isAbsoluteFileOrDriveLetter(file)) { path = file.getAbsolutePath(); } return FileUtil.normalize(path); } private static boolean isAbsoluteFileOrDriveLetter(File file) { String path = file.getPath(); if (SystemInfo.isWindows && path.length() == 2 && path.charAt(1) == ':') { // just drive letter. // return true, despite the fact that technically it's not an absolute path return true; } return file.isAbsolute(); } @Override public VirtualFile refreshAndFindFileByIoFile(@NotNull File file) { String path = file.getAbsolutePath(); return refreshAndFindFileByPath(path.replace(File.separatorChar, '/')); } @Override public void refreshIoFiles(@NotNull Iterable<File> files) { refreshIoFiles(files, false, false, null); } @Override public void refreshIoFiles(@NotNull Iterable<File> files, boolean async, boolean recursive, @Nullable Runnable onFinish) { final VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); Application app = ApplicationManager.getApplication(); boolean fireCommonRefreshSession = app.isDispatchThread() || app.isWriteAccessAllowed(); if (fireCommonRefreshSession) manager.fireBeforeRefreshStart(false); try { List<VirtualFile> filesToRefresh = new ArrayList<VirtualFile>(); for (File file : files) { final VirtualFile virtualFile = refreshAndFindFileByIoFile(file); if (virtualFile != null) { filesToRefresh.add(virtualFile); } } RefreshQueue.getInstance().refresh(async, recursive, onFinish, filesToRefresh); } finally { if (fireCommonRefreshSession) manager.fireAfterRefreshFinish(false); } } @Override public void refreshFiles(@NotNull Iterable<VirtualFile> files) { refreshFiles(files, false, false, null); } @Override public void refreshFiles(@NotNull Iterable<VirtualFile> files, boolean async, boolean recursive, @Nullable Runnable onFinish) { RefreshQueue.getInstance().refresh(async, recursive, onFinish, ContainerUtil.toCollection(files)); } @Override public void registerAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) { if (myHandlers.contains(handler)) { LOG.error("Handler " + handler + " already registered."); } myHandlers.add(handler); } @Override public void unregisterAuxiliaryFileOperationsHandler(@NotNull LocalFileOperationsHandler handler) { if (!myHandlers.remove(handler)) { LOG.error("Handler" + handler + " haven't been registered or already unregistered."); } } @Override public boolean processCachedFilesInSubtree(@NotNull final VirtualFile file, @NotNull Processor<VirtualFile> processor) { return file.getFileSystem() != this || processFile((NewVirtualFile)file, processor); } private static boolean processFile(@NotNull NewVirtualFile file, @NotNull Processor<VirtualFile> processor) { if (!processor.process(file)) return false; if (file.isDirectory()) { for (final VirtualFile child : file.getCachedChildren()) { if (!processFile((NewVirtualFile)child, processor)) return false; } } return true; } private boolean auxDelete(@NotNull VirtualFile file) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { if (handler.delete(file)) return true; } return false; } private boolean auxMove(@NotNull VirtualFile file, @NotNull VirtualFile toDir) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { if (handler.move(file, toDir)) return true; } return false; } private void auxNotifyCompleted(@NotNull ThrowableConsumer<LocalFileOperationsHandler, IOException> consumer) { for (LocalFileOperationsHandler handler : myHandlers) { handler.afterDone(consumer); } } @Nullable private File auxCopy(@NotNull VirtualFile file, @NotNull VirtualFile toDir, @NotNull String copyName) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { final File copy = handler.copy(file, toDir, copyName); if (copy != null) return copy; } return null; } private boolean auxRename(@NotNull VirtualFile file, @NotNull String newName) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { if (handler.rename(file, newName)) return true; } return false; } private boolean auxCreateFile(@NotNull VirtualFile dir, @NotNull String name) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { if (handler.createFile(dir, name)) return true; } return false; } private boolean auxCreateDirectory(@NotNull VirtualFile dir, @NotNull String name) throws IOException { for (LocalFileOperationsHandler handler : myHandlers) { if (handler.createDirectory(dir, name)) return true; } return false; } private static void delete(@NotNull File physicalFile) throws IOException { if (!FileUtil.delete(physicalFile)) { throw new IOException(VfsBundle.message("file.delete.error", physicalFile.getPath())); } } @Override @NotNull public VirtualFile createChildDirectory(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String dir) throws IOException { final File ioDir = new File(convertToIOFile(parent), dir); final boolean succeed = auxCreateDirectory(parent, dir) || ioDir.mkdirs(); auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.createDirectory(parent, dir); } }); if (!succeed) { throw new IOException("Failed to create directory: " + ioDir.getPath()); } return new FakeVirtualFile(parent, dir); } @Override public VirtualFile createChildFile(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String file) throws IOException { final File ioFile = new File(convertToIOFile(parent), file); final boolean succeed = auxCreateFile(parent, file) || FileUtil.createIfDoesntExist(ioFile); auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.createFile(parent, file); } }); if (!succeed) { throw new IOException("Failed to create child file at " + ioFile.getPath()); } return new FakeVirtualFile(parent, file); } @Override public void deleteFile(final Object requestor, @NotNull final VirtualFile file) throws IOException { if (!auxDelete(file)) { delete(convertToIOFile(file)); } auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.delete(file); } }); } @Override public boolean isCaseSensitive() { return SystemInfo.isFileSystemCaseSensitive; } @Override @NotNull public InputStream getInputStream(@NotNull final VirtualFile file) throws IOException { return new BufferedInputStream(new FileInputStream(convertToIOFileAndCheck(file))); } @Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file) throws IOException { final FileInputStream stream = new FileInputStream(convertToIOFileAndCheck(file)); try { long l = file.getLength(); if (l > Integer.MAX_VALUE) throw new IOException("File is too large: " + l + ", " + file); final int length = (int)l; if (length < 0) throw new IOException("Invalid file length: " + length + ", " + file); return FileUtil.loadBytes(stream, length); } finally { stream.close(); } } @Override @NotNull public OutputStream getOutputStream(@NotNull VirtualFile file, Object requestor, long modStamp, final long timeStamp) throws IOException { final File ioFile = convertToIOFileAndCheck(file); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final OutputStream stream = shallUseSafeStream(requestor, file) ? new SafeFileOutputStream(ioFile, SystemInfo.isUnix) : new FileOutputStream(ioFile); return new BufferedOutputStream(stream) { @Override public void close() throws IOException { super.close(); if (timeStamp > 0 && ioFile.exists()) { if (!ioFile.setLastModified(timeStamp)) { LOG.warn("Failed: " + ioFile.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified()); } } } }; } private static boolean shallUseSafeStream(final Object requestor, @NotNull VirtualFile file) { return requestor instanceof SafeWriteRequestor && GeneralSettings.getInstance().isUseSafeWrite() && !file.is(VFileProperty.SYMLINK); } @Override public void moveFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final VirtualFile newParent) throws IOException { if (!auxMove(file, newParent)) { final File ioFrom = convertToIOFile(file); final File ioParent = convertToIOFile(newParent); if (!ioParent.isDirectory()) { throw new IOException("Target '" + ioParent + "' is not a directory"); } if (!ioFrom.renameTo(new File(ioParent, file.getName()))) { throw new IOException("Move failed: '" + file.getPath() + "' to '" + newParent.getPath() +"'"); } } auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.move(file, newParent); } }); } @Override public void renameFile(final Object requestor, @NotNull final VirtualFile file, @NotNull final String newName) throws IOException { if (!file.exists()) { throw new IOException("File to move does not exist: " + file.getPath()); } final VirtualFile parent = file.getParent(); assert parent != null; if (!auxRename(file, newName)) { final File target = new File(convertToIOFile(parent), newName); if (!convertToIOFile(file).renameTo(target)) { if (target.exists()) { throw new IOException("Destination already exists: " + parent.getPath() + "/" + newName); } else { throw new IOException("Unable to rename " + file.getPath()); } } } auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.rename(file, newName); } }); } @Override public VirtualFile copyFile(final Object requestor, @NotNull final VirtualFile vFile, @NotNull final VirtualFile newParent, @NotNull final String copyName) throws IOException { if (!PathUtil.isValidFileName(copyName)) { throw new IOException("Invalid file name: " + copyName); } FileAttributes attributes = getAttributes(vFile); if (attributes == null || attributes.isSpecial()) { throw new FileNotFoundException("Not a file: " + vFile); } File physicalFile = convertToIOFile(vFile); File physicalCopy = auxCopy(vFile, newParent, copyName); try { if (physicalCopy == null) { File newPhysicalParent = convertToIOFile(newParent); physicalCopy = new File(newPhysicalParent, copyName); try { if (attributes.isDirectory()) { FileUtil.copyDir(physicalFile, physicalCopy); } else { FileUtil.copy(physicalFile, physicalCopy); } } catch (IOException e) { FileUtil.delete(physicalCopy); throw e; } } } finally { auxNotifyCompleted(new ThrowableConsumer<LocalFileOperationsHandler, IOException>() { @Override public void consume(LocalFileOperationsHandler handler) throws IOException { handler.copy(vFile, newParent, copyName); } }); } return new FakeVirtualFile(newParent, copyName); } @Override public void setTimeStamp(@NotNull final VirtualFile file, final long timeStamp) { final File ioFile = convertToIOFile(file); if (ioFile.exists() && !ioFile.setLastModified(timeStamp)) { LOG.warn("Failed: " + file.getPath() + ", new:" + timeStamp + ", old:" + ioFile.lastModified()); } } @Override public void setWritable(@NotNull final VirtualFile file, final boolean writableFlag) throws IOException { FileUtil.setReadOnlyAttribute(file.getPath(), !writableFlag); final File ioFile = convertToIOFile(file); if (ioFile.canWrite() != writableFlag) { throw new IOException("Failed to change read-only flag for " + ioFile.getPath()); } } @NotNull @Override protected String extractRootPath(@NotNull final String path) { if (path.isEmpty()) { try { return extractRootPath(new File("").getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } } if (SystemInfo.isWindows) { if (path.length() >= 2 && path.charAt(1) == ':') { // Drive letter return path.substring(0, 2).toUpperCase(Locale.US); } if (path.startsWith("//") || path.startsWith("\\\\")) { // UNC. Must skip exactly two path elements like [\\ServerName\ShareName]\pathOnShare\file.txt // Root path is in square brackets here. int slashCount = 0; int idx; for (idx = 2; idx < path.length() && slashCount < 2; idx++) { final char c = path.charAt(idx); if (c == '\\' || c == '/') { slashCount++; idx--; } } return path.substring(0, idx); } return ""; } return StringUtil.startsWithChar(path, '/') ? "/" : ""; } @Override public int getRank() { return 1; } @Override public boolean markNewFilesAsDirty() { return true; } @Override public String getCanonicallyCasedName(@NotNull final VirtualFile file) { if (isCaseSensitive()) { return super.getCanonicallyCasedName(file); } final String originalFileName = file.getName(); try { final File ioFile = convertToIOFile(file); final File ioCanonicalFile = ioFile.getCanonicalFile(); String canonicalFileName = ioCanonicalFile.getName(); if (!SystemInfo.isUnix) { return canonicalFileName; } // linux & mac support symbolic links // unfortunately canonical file resolves sym links // so its name may differ from name of origin file // // Here FS is case sensitive, so let's check that original and // canonical file names are equal if we ignore name case if (canonicalFileName.compareToIgnoreCase(originalFileName) == 0) { // p.s. this should cover most cases related to not symbolic links return canonicalFileName; } // Ok, names are not equal. Let's try to find corresponding file name // among original file parent directory final File parentFile = ioFile.getParentFile(); if (parentFile != null) { // I hope ls works fast on Unix final String[] canonicalFileNames = parentFile.list(); if (canonicalFileNames != null) { for (String name : canonicalFileNames) { // if names are equals if (name.compareToIgnoreCase(originalFileName) == 0) { return name; } } } } // No luck. So ein mist! // Ok, garbage in, garbage out. We may return original or canonical name // no difference. Let's return canonical name just to preserve previous // behaviour of this code. return canonicalFileName; } catch (IOException e) { return originalFileName; } } @Override public FileAttributes getAttributes(@NotNull final VirtualFile file) { String path = normalize(file.getPath()); if (path == null) return null; if (file.getParent() == null && path.startsWith("//")) { return FAKE_ROOT_ATTRIBUTES; // fake Windows roots } return FileSystemUtil.getAttributes(FileUtil.toSystemDependentName(path)); } @Override public void refresh(final boolean asynchronous) { RefreshQueue.getInstance().refresh(asynchronous, true, null, ManagingFS.getInstance().getRoots(this)); } }
/* * 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 gov.nasa.jpl.mudrod.weblog.pre; import gov.nasa.jpl.mudrod.driver.ESDriver; import gov.nasa.jpl.mudrod.driver.SparkDriver; import gov.nasa.jpl.mudrod.main.MudrodConstants; import gov.nasa.jpl.mudrod.weblog.structure.ApacheAccessLog; import gov.nasa.jpl.mudrod.weblog.structure.FtpLog; import org.apache.spark.api.java.JavaRDD; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.spark.rdd.api.java.JavaEsSpark; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * Supports ability to parse and process FTP and HTTP log files */ public class ImportLogFile extends LogAbstract { private static final Logger LOG = LoggerFactory.getLogger(ImportLogFile.class); /** * */ private static final long serialVersionUID = 1L; String logEntryPattern = "^([\\d.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] " + "\"(.+?)\" (\\d{3}) (\\d+|-) \"((?:[^\"]|\")+)\" \"([^\"]+)\""; public static final int NUM_FIELDS = 9; Pattern p = Pattern.compile(logEntryPattern); transient Matcher matcher; /** * Constructor supporting a number of parameters documented below. * * @param props a {@link java.util.Map} containing K,V of type String, String * respectively. * @param es the {@link ESDriver} used to persist log * files. * @param spark the {@link SparkDriver} used to process * input log files. */ public ImportLogFile(Properties props, ESDriver es, SparkDriver spark) { super(props, es, spark); } @Override public Object execute() { LOG.info("Starting Log Import {}", props.getProperty(MudrodConstants.TIME_SUFFIX)); startTime = System.currentTimeMillis(); readFile(); endTime = System.currentTimeMillis(); LOG.info("Log Import complete. Time elapsed {} seconds", (endTime - startTime) / 1000); es.refreshIndex(); return null; } /** * Utility function to aid String to Number formatting such that three letter * months such as 'Jan' are converted to the Gregorian integer equivalent. * * @param time the input {@link java.lang.String} to convert to int. * @return the converted Month as an int. */ public String switchtoNum(String time) { String newTime = time; if (newTime.contains("Jan")) { newTime = newTime.replace("Jan", "1"); } else if (newTime.contains("Feb")) { newTime = newTime.replace("Feb", "2"); } else if (newTime.contains("Mar")) { newTime = newTime.replace("Mar", "3"); } else if (newTime.contains("Apr")) { newTime = newTime.replace("Apr", "4"); } else if (newTime.contains("May")) { newTime = newTime.replace("May", "5"); } else if (newTime.contains("Jun")) { newTime = newTime.replace("Jun", "6"); } else if (newTime.contains("Jul")) { newTime = newTime.replace("Jul", "7"); } else if (newTime.contains("Aug")) { newTime = newTime.replace("Aug", "8"); } else if (newTime.contains("Sep")) { newTime = newTime.replace("Sep", "9"); } else if (newTime.contains("Oct")) { newTime = newTime.replace("Oct", "10"); } else if (newTime.contains("Nov")) { newTime = newTime.replace("Nov", "11"); } else if (newTime.contains("Dec")) { newTime = newTime.replace("Dec", "12"); } return newTime; } public void readFile() { String httplogpath = null; String ftplogpath = null; File directory = new File(props.getProperty(MudrodConstants.DATA_DIR)); File[] fList = directory.listFiles(); for (File file : fList) { if (file.isFile() && file.getName().contains(props.getProperty(MudrodConstants.TIME_SUFFIX))) { if (file.getName().contains(props.getProperty(MudrodConstants.HTTP_PREFIX))) { httplogpath = file.getAbsolutePath(); } if (file.getName().contains(props.getProperty(MudrodConstants.FTP_PREFIX))) { ftplogpath = file.getAbsolutePath(); } } } if(httplogpath == null || ftplogpath == null) { LOG.error("WWW file or FTP logs cannot be found, please check your data directory."); return; } String processingType = props.getProperty(MudrodConstants.PROCESS_TYPE, "parallel"); if (processingType.equals("sequential")) { readFileInSequential(httplogpath, ftplogpath); } else if (processingType.equals("parallel")) { readFileInParallel(httplogpath, ftplogpath); } } /** * Read the FTP or HTTP log path with the intention of processing lines from * log files. * * @param httplogpath path to the parent directory containing http logs * @param ftplogpath path to the parent directory containing ftp logs */ public void readFileInSequential(String httplogpath, String ftplogpath) { es.createBulkProcessor(); try { readLogFile(httplogpath, "http", logIndex, httpType); readLogFile(ftplogpath, "FTP", logIndex, ftpType); } catch (IOException e) { LOG.error("Error whilst reading log file.", e); } es.destroyBulkProcessor(); } /** * Read the FTP or HTTP log path with the intention of processing lines from * log files. * * @param httplogpath path to the parent directory containing http logs * @param ftplogpath path to the parent directory containing ftp logs */ public void readFileInParallel(String httplogpath, String ftplogpath) { importHttpfile(httplogpath); importFtpfile(ftplogpath); } public void importHttpfile(String httplogpath) { // import http logs JavaRDD<String> accessLogs = spark.sc.textFile(httplogpath, this.partition).map(s -> ApacheAccessLog.parseFromLogLine(s)).filter(ApacheAccessLog::checknull); JavaEsSpark.saveJsonToEs(accessLogs, logIndex + "/" + this.httpType); } public void importFtpfile(String ftplogpath) { // import ftp logs JavaRDD<String> ftpLogs = spark.sc.textFile(ftplogpath, this.partition).map(s -> FtpLog.parseFromLogLine(s)).filter(FtpLog::checknull); JavaEsSpark.saveJsonToEs(ftpLogs, logIndex + "/" + this.ftpType); } /** * Process a log path on local file system which contains the relevant * parameters as below. * * @param fileName the {@link java.lang.String} path to the log directory on file * system * @param protocol whether to process 'http' or 'FTP' * @param index the index name to write logs to * @param type one of the available protocols from which Mudrod logs are obtained. * @throws IOException if there is an error reading anything from the fileName provided. */ public void readLogFile(String fileName, String protocol, String index, String type) throws IOException { BufferedReader br = new BufferedReader(new FileReader(fileName)); int count = 0; try { String line = br.readLine(); while (line != null) { if ("FTP".equals(protocol)) { parseSingleLineFTP(line, index, type); } else { parseSingleLineHTTP(line, index, type); } line = br.readLine(); count++; } } catch (FileNotFoundException e) { LOG.error("File not found.", e); } catch (IOException e) { LOG.error("Error reading input directory.", e); } finally { br.close(); LOG.info("Num of {} entries:\t{}", protocol, count); } } /** * Parse a single FTP log entry * * @param log a single log line * @param index the index name we wish to persist the log line to * @param type one of the available protocols from which Mudrod logs are obtained. */ public void parseSingleLineFTP(String log, String index, String type) { String ip = log.split(" +")[6]; String time = log.split(" +")[1] + ":" + log.split(" +")[2] + ":" + log.split(" +")[3] + ":" + log.split(" +")[4]; time = switchtoNum(time); SimpleDateFormat formatter = new SimpleDateFormat("MM:dd:HH:mm:ss:yyyy"); Date date = null; try { date = formatter.parse(time); } catch (ParseException e) { LOG.error("Error whilst parsing the date.", e); } String bytes = log.split(" +")[7]; String request = log.split(" +")[8].toLowerCase(); if (!request.contains("/misc/") && !request.contains("readme")) { IndexRequest ir; try { ir = new IndexRequest(index, type) .source(jsonBuilder().startObject().field("LogType", "ftp").field("IP", ip).field("Time", date).field("Request", request).field("Bytes", Long.parseLong(bytes)).endObject()); es.getBulkProcessor().add(ir); } catch (NumberFormatException e) { LOG.error("Error whilst processing numbers", e); } catch (IOException e) { LOG.error("IOError whilst adding to the bulk processor.", e); } } } /** * Parse a single HTTP log entry * * @param log a single log line * @param index the index name we wish to persist the log line to * @param type one of the available protocols from which Mudrod logs are obtained. */ public void parseSingleLineHTTP(String log, String index, String type) { matcher = p.matcher(log); if (!matcher.matches() || NUM_FIELDS != matcher.groupCount()) { return; } String time = matcher.group(4); time = switchtoNum(time); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss"); Date date = null; try { date = formatter.parse(time); } catch (ParseException e) { LOG.error("Error whilst attempting to parse date.", e); } String bytes = matcher.group(7); if ("-".equals(bytes)) { bytes = "0"; } String request = matcher.group(5).toLowerCase(); String agent = matcher.group(9); CrawlerDetection crawlerDe = new CrawlerDetection(this.props, this.es, this.spark); if (!crawlerDe.checkKnownCrawler(agent)) { boolean tag = false; String[] mimeTypes = { ".js", ".css", ".jpg", ".png", ".ico", "image_captcha", "autocomplete", ".gif", "/alldata/", "/api/", "get / http/1.1", ".jpeg", "/ws/" }; for (int i = 0; i < mimeTypes.length; i++) { if (request.contains(mimeTypes[i])) { tag = true; break; } } if (!tag) { IndexRequest ir = null; executeBulkRequest(ir, index, type, matcher, date, bytes); } } } private void executeBulkRequest(IndexRequest ir, String index, String type, Matcher matcher, Date date, String bytes) { IndexRequest newIr = ir; try { newIr = new IndexRequest(index, type).source( jsonBuilder().startObject().field("LogType", "PO.DAAC").field("IP", matcher.group(1)).field("Time", date).field("Request", matcher.group(5)).field("Response", matcher.group(6)) .field("Bytes", Integer.parseInt(bytes)).field("Referer", matcher.group(8)).field("Browser", matcher.group(9)).endObject()); es.getBulkProcessor().add(newIr); } catch (NumberFormatException e) { LOG.error("Error whilst processing numbers", e); } catch (IOException e) { LOG.error("IOError whilst adding to the bulk processor.", e); } } @Override public Object execute(Object o) { return null; } }
/* * Copyright 2010 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. */ /* * 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.drools.util; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; import org.drools.KnowledgeBaseFactoryService; import org.drools.Service; import org.drools.SystemEventListenerService; import org.drools.builder.KnowledgeBuilderFactoryService; import org.drools.concurrent.ExecutorProvider; import org.drools.io.ResourceFactoryService; import org.drools.marshalling.MarshallerProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is an internal class, not for public consumption. */ public class ServiceRegistryImpl implements ServiceRegistry { private static ServiceRegistry instance = new ServiceRegistryImpl(); protected static final transient Logger logger = LoggerFactory.getLogger(ServiceRegistryImpl.class); private Map<String, Callable< ? >> registry = new HashMap<String, Callable< ? >>(); private Map<String, Callable< ? >> defaultServices = new HashMap<String, Callable< ? >>(); public static synchronized ServiceRegistry getInstance() { return ServiceRegistryImpl.instance; } public ServiceRegistryImpl() { init(); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#registerLocator(java.lang.String, java.util.concurrent.Callable) */ public synchronized void registerLocator(Class cls, Callable cal) { this.registry.put( cls.getName(), cal ); } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ public synchronized void unregisterLocator(Class cls) { this.registry.remove( cls.getName() ); } synchronized void registerInstance(Service service, Map map) { //this.context.getProperties().put( "org.dr, value ) logger.info( "regInstance : " + map ); String[] values = ( String[] ) map.get( "objectClass" ); for ( String v : values ) { logger.info( v ); } // logger.info( "register : " + service ); this.registry.put( service.getClass().getInterfaces()[0].getName(), new ReturnInstance<Service>( service ) ); // // BundleContext bc = this.context.getBundleContext(); // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // // try { // Configuration conf = admin.getConfiguration( (String) confAdminRef.getProperty( "service.id" ) ); // Dictionary properties = conf.getProperties(); // properties.put( values[0], "true" ); // conf.update( properties ); // } catch ( IOException e ) { // logger.error("error", e); // } } /* (non-Javadoc) * @see org.drools.util.internal.ServiceRegistry#unregisterLocator(java.lang.String) */ synchronized void unregisterInstance(Service service, Map map) { logger.info( "unregister : " + map ); String name = service.getClass().getInterfaces()[0].getName(); this.registry.remove( name ); this.registry.put( name, this.defaultServices.get( name ) ); } // ConfigurationAdmin confAdmin; // synchronized void setConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = confAdmin; // logger.info( "ConfAdmin : " + this.confAdmin ); // } // // synchronized void unsetConfigurationAdmin(ConfigurationAdmin confAdmin) { // this.confAdmin = null; // } // private ComponentContext context; // void activate(ComponentContext context) { // logger.info( "reg comp" + context.getProperties() ); // this.context = context; // // // // BundleContext bc = this.context.getBundleContext(); // // ServiceReference confAdminRef = bc.getServiceReference( ConfigurationAdmin.class.getName() ); // ConfigurationAdmin admin = ( ConfigurationAdmin ) bc.getService( confAdminRef ); // logger.info( "conf admin : " + admin ); // //context. // // log = (LogService) context.locateService("LOG"); // } // void deactivate(ComponentContext context ){ // // } public synchronized <T> T get(Class<T> cls) { Callable< ? > cal = this.registry.get( cls.getName() ); if ( cal != null ) { try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } else { cal = this.defaultServices.get( cls.getName() ); try { return cls.cast( cal.call() ); } catch ( Exception e ) { throw new IllegalArgumentException( "Unable to instantiate service for Class '" + (cls != null ? cls.getName() : null) + "'", e ); } } } private void init() { addDefault( KnowledgeBuilderFactoryService.class, "org.drools.impl.KnowledgeBuilderFactoryServiceImpl" ); addDefault( KnowledgeBaseFactoryService.class, "org.drools.impl.KnowledgeBaseFactoryServiceImpl" ); addDefault( ResourceFactoryService.class, "org.drools.impl.ResourceFactoryServiceImpl" ); addDefault( MarshallerProvider.class, "org.drools.core.marshalling.impl.MarshallerProviderImpl"); addDefault( ExecutorProvider.class, "org.drools.core.concurrent.ExecutorProviderImpl"); // addDefault( SystemE.class, // "org.drools.io.impl.ResourceFactoryServiceImpl" ); } public synchronized void addDefault(Class cls, String impl) { ReflectionInstantiator<Service> resourceRi = new ReflectionInstantiator<Service>( impl ); defaultServices.put( cls.getName(), resourceRi ); } static class ReflectionInstantiator<V> implements Callable<V> { private String name; public ReflectionInstantiator(String name) { this.name = name; } public V call() throws Exception { return (V) newInstance( name ); } static <T> T newInstance(String name) { try { Class<T> cls = (Class<T>) Class.forName( name ); return cls.newInstance(); } catch ( Exception e2 ) { throw new IllegalArgumentException( "Unable to instantiate '" + name + "'", e2 ); } } } static class ReturnInstance<V> implements Callable<V> { private Service service; public ReturnInstance(Service service) { this.service = service; } public V call() throws Exception { return (V) service; } } }
/* * Copyright 2010 Brad Cupit * * 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.googlecode.easiest.cache.ever.caches; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; 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 net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.ObjectExistsException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.googlecode.easiest.cache.ever.CacheConfig; import com.googlecode.easiest.cache.ever.CacheConstants; import com.googlecode.easiest.cache.ever.Time; import com.rits.cloning.Cloner; /** * unit test for {@link DefaultCacheService} * * @author Brad Cupit */ public class DefaultCacheServiceTest { /** some number large enough that size won't be a factor in the test */ private static final int DONT_CARE_ABOUT_SIZE = 1000; private final CacheConfig cacheConfig = new CacheConfig(DONT_CARE_ABOUT_SIZE, CacheConstants.NO_EXPIRATION, null); private final String cacheId = "cacheId"; private final String cacheKey = "cacheKey"; private final String expectedValue = "expected value"; private final CacheManager ehCacheManager = new CacheManager(); private DefaultCacheService cacheService; private final CacheManager mockEhcacheManager = mock(CacheManager.class); private final Ehcache mockEhcache = mock(Ehcache.class); @Before public void before() { cacheService = new DefaultCacheService(); cacheService.setCloner(new Cloner()); cacheService.setEhcacheManager(ehCacheManager); } @After public void after() { ehCacheManager.shutdown(); } @Test public void createCacheIfNecessaryShouldCreateNewCacheWhenCacheIdNotFound() throws Exception { cacheService.setEhcacheManager(mockEhcacheManager); cacheService.createCacheIfNecessary(cacheId, cacheConfig); verify(mockEhcacheManager).addCache(Mockito.any(Ehcache.class)); } @Test public void createCacheIfNecessaryShouldNotCreateCacheWhenItAlreadyExists() throws Exception { when(mockEhcacheManager.cacheExists(cacheId)).thenReturn(true); cacheService.setEhcacheManager(mockEhcacheManager); cacheService.createCacheIfNecessary(cacheId, cacheConfig); verify(mockEhcacheManager, never()).addCache((Ehcache) null); verify(mockEhcacheManager, never()).addCache((Cache) null); verify(mockEhcacheManager, never()).addCache((String) null); } @Test public void retrieveShouldRemoveLeastRecentlyUsedItemWhenMaxSizeReached() throws Exception { int oneItemMax = 1; CacheConfig cacheConfig = new CacheConfig(oneItemMax, CacheConstants.NO_EXPIRATION, null); cacheService.createCacheIfNecessary(cacheId, cacheConfig); String firstCacheKey = "1"; String firstCachedValue = "1st val to be cached"; cacheService.add(cacheId, firstCacheKey, firstCachedValue); assertNotNull(cacheService.retrieve(cacheId, firstCacheKey).value()); cacheService.add(cacheId, "2nd cache key", "this value should push the 1st value out of the cache"); assertNull(cacheService.retrieve(cacheId, firstCacheKey).value()); } @Test public void retrieveShouldExpireCachedElementsWithAnExpirationTime() throws Exception { int expirationTimeInSeconds = 1; CacheConfig cacheConfig = new CacheConfig(DONT_CARE_ABOUT_SIZE, expirationTimeInSeconds, Time.SECONDS); cacheService.createCacheIfNecessary(cacheId, cacheConfig); String valueToBeCached = "value that will be added to the cache"; cacheService.add(cacheId, cacheKey, valueToBeCached); assertNotNull(cacheService.retrieve(cacheId, cacheKey).value()); TimeUnit.SECONDS.sleep(expirationTimeInSeconds + 1); assertNull(cacheService.retrieve(cacheId, cacheKey).value()); } /** * when ehcache's timeToLiveSeconds = 0, the element will never expire. * if the user configures a very small timeout (like 10 milliseconds) * that may convert to 0 seconds, and therefore never expire. Instead, * we should round up to 1 second. * If the user wants eternal, they should use {@link CacheConstants#NO_EXPIRATION} */ @Test public void createCacheIfNecessaryShouldNotSetZeroSecondExpirationTimeForVerySmallTimeValue() throws Exception { CacheConfig cacheConfig = new CacheConfig(100, 10, Time.MILLISECONDS); cacheService.createCacheIfNecessary(cacheId, cacheConfig); Cache cache = ehCacheManager.getCache(cacheId); assertTrue(!cache.getCacheConfiguration().isEternal()); int roundedUpTime = 1; assertEquals(roundedUpTime, cache.getCacheConfiguration().getTimeToLiveSeconds()); } public void addShouldAddObjectToCache() { cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, cacheKey, expectedValue); String retrieved = (String) cacheService.retrieve(cacheId, cacheKey).value(); assertThat(expectedValue, equalTo(retrieved)); } public void addShouldPutObjectInEhcache() { cacheService.setEhcacheManager(mockEhcacheManager); when(mockEhcacheManager.getEhcache(cacheId)).thenReturn(mockEhcache); cacheService.add(cacheId, cacheKey, expectedValue); verify(mockEhcache).put(new Element(cacheKey, expectedValue)); } /** * tests a clone of the object is put in the cache. * * This is for thread safety. Example: * thread 1 puts object in cache * thread 2 gets object from cache * thread 1 modifies the object it put in the cache * thread 2 sees modifications <-- thread safety issue (unless object-in-cache is thread safe, which is unlikely) */ @Test public void addShouldStoreClonedObjectForThreadSafety() throws Exception { String initialValue = "initial value"; Cacheable original = new Cacheable(); original.field = initialValue; cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, cacheKey, original); original.field = "new value doesn't change value in cache"; Cacheable retrieved = (Cacheable) cacheService.retrieve(cacheId, cacheKey).value(); assertNotSame(original, retrieved); assertEquals(initialValue, retrieved.field); } public void retrieveShouldReturnCachedValueWithWasFoundEqualToTrueWhenObjectInCache() { cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, cacheKey, "value doesn't matter just that something is actually cached"); CachedValue cachedValue = cacheService.retrieve(cacheId, cacheKey); assertThat(cachedValue.wasFound(), is(true)); } public void retrieveShouldReturnCachedValueWithWasFoundEqualToFalseWhenObjectNotInCache() { cacheService.createCacheIfNecessary(cacheId, cacheConfig); CachedValue cachedValue = cacheService.retrieve(cacheId, cacheKey); assertThat(cachedValue.wasFound(), is(false)); } public void retrieveShouldGetObjectFromEhcache() { cacheService.setEhcacheManager(mockEhcacheManager); when(mockEhcacheManager.getEhcache(cacheId)).thenReturn(mockEhcache); cacheService.retrieve(cacheId, cacheKey); verify(mockEhcache).get(cacheKey); } /** * tests the retrieved object is a clone of the object in the cache * * This is for thread safety. Example: * thread 1 gets object from cache * thread 2 gets object from cache * thread 1 modifies the object it got * thread 2 sees modifications <-- thread safety issue (unless object-in-cache is thread safe, which is unlikely) */ @Test public void retrieveShouldReturnClonedObjectForThreadSafety() throws Exception { Cacheable original = new Cacheable(); original.field = "initial value"; cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, cacheKey, original); Cacheable firstRetrieved = (Cacheable) cacheService.retrieve(cacheId, cacheKey).value(); firstRetrieved.field = "new value doesn't change value in cache"; Cacheable secondRetrieved = (Cacheable) cacheService.retrieve(cacheId, cacheKey).value(); assertNotSame(firstRetrieved, secondRetrieved); assertTrue(!firstRetrieved.field.equals(secondRetrieved.field)); assertEquals(original.field, secondRetrieved.field); } /** * test {@link DefaultCacheService#retrieve(String, String)} handles nulls */ @Test public void retrieveShouldReturnNullValueWhenGivenNullValue() throws Exception { final String nullCacheValue = null; cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, cacheKey, nullCacheValue); CachedValue cachedValue = cacheService.retrieve(cacheId, cacheKey); assertTrue(cachedValue.wasFound()); assertNull(cachedValue.value()); } /** * ehcache 1.6 does not allow null keys (since they switched to * {@link ConcurrentHashMap}, which also doesn't support null * keys. We need that support. For example: if we're caching * a method with one input param, and that parameter is null. * We need a single entry in the cache with a key of 'null' * in order to cache all input parameters. * * We added special code to work around the lack of null keys. * This test proves that special code is working. */ @Test public void retrieveShouldFindCorrectValueForNullKey() throws Exception { final String nullCacheKey = null; cacheService.createCacheIfNecessary(cacheId, cacheConfig); cacheService.add(cacheId, nullCacheKey, expectedValue); CachedValue cachedValue = cacheService.retrieve(cacheId, nullCacheKey); assertTrue(cachedValue.wasFound()); assertNotNull(cachedValue.value()); assertEquals(expectedValue, cachedValue.value()); } /** * This is a thread-safety test. If this library had a thread-safety issue, * this test may incorrectly pass sometimes, however, if it fails * even once due to an {@link ObjectExistsException}, it means there * is a thread-safety issue (our synchronization isn't working). */ @Test public void createCacheIfNecessaryShouldNotThrowThreadSafetyException() throws Exception { cacheService.setEhcacheManager(new CacheManager() { @Override public boolean cacheExists(String cacheName) throws IllegalStateException { boolean cacheExists = super.cacheExists(cacheName); // make our data stale. won't do anything in properly synchronized // code, but in unsynchronized code, will increase chances of an error letAnotherThreadRun(); return cacheExists; } }); int numThreads = 100; List<? extends Callable<Void>> eachThreadDoesTheSameThing = Collections.nCopies(numThreads, new Callable<Void>() { public Void call() throws Exception { cacheService.createCacheIfNecessary(cacheId, cacheConfig); return null; } }); ExecutorService executorService = Executors.newFixedThreadPool(numThreads); List<Future<Void>> results = executorService.invokeAll(eachThreadDoesTheSameThing); rethrowAnyExceptionsThatOccurred(results); } private void rethrowAnyExceptionsThatOccurred(List<Future<Void>> results) throws InterruptedException, ExecutionException { for (Future<Void> future : results) { future.get(); } } private void letAnotherThreadRun() { try { Thread.sleep(1); } catch (InterruptedException exception) { throw new RuntimeException(exception); } } /** * Helper class for unit tests * * @author Brad Cupit */ private static class Cacheable { private String field; } }
/* * Copyright 2017 Hippo Seven * * 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.hippo.stage; /* * Created by Hippo on 4/20/2017. */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import android.support.annotation.NonNull; import org.junit.Before; import org.junit.Test; public class SceneStackTest { private SceneStack stack; private int pushed; private int popped; private Scene pushedScene; private Scene poppedScene; @Before public void before() { stack = new SceneStack(new SceneStack.Callback() { @Override public void onPush(@NonNull Scene scene) { pushed++; pushedScene = scene; poppedScene = null; } @Override public void onPop(@NonNull Scene scene, boolean willRecreate) { popped++; pushedScene = null; poppedScene = scene; } }); } @Test public void testIsEmpty() { assertTrue(stack.isEmpty()); stack.push(new TestScene()); assertFalse(stack.isEmpty()); stack.push(new TestScene()); assertFalse(stack.isEmpty()); stack.pop(); assertFalse(stack.isEmpty()); stack.pop(); assertTrue(stack.isEmpty()); } @Test public void testSize() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(0, stack.size()); stack.push(scene1); assertEquals(1, stack.size()); stack.pop(scene1); assertEquals(0, stack.size()); stack.push(scene2); stack.push(scene3); assertEquals(2, stack.size()); stack.pop(scene2); assertEquals(1, stack.size()); stack.pop(scene3); assertEquals(0, stack.size()); stack.pop(scene1); assertEquals(0, stack.size()); } @Test public void testPeek() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(null, stack.peek()); stack.push(scene1); assertEquals(scene1, stack.peek()); stack.push(scene2); assertEquals(scene2, stack.peek()); stack.push(scene3); assertEquals(scene3, stack.peek()); stack.pop(scene2); assertEquals(scene3, stack.peek()); stack.pop(scene3); assertEquals(scene1, stack.peek()); stack.pop(scene1); assertEquals(null, stack.peek()); stack.pop(scene3); assertEquals(null, stack.peek()); } @Test public void testTail() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(null, stack.tail()); stack.push(scene1); assertEquals(scene1, stack.tail()); stack.push(scene2); assertEquals(scene1, stack.tail()); stack.push(scene3); assertEquals(scene1, stack.tail()); stack.pop(scene2); assertEquals(scene1, stack.tail()); stack.pop(scene1); assertEquals(scene3, stack.tail()); stack.pop(scene3); assertEquals(null, stack.tail()); stack.pop(scene2); assertEquals(null, stack.tail()); } @Test public void testPushPop() { assertNull(stack.pop()); Scene scene1 = new TestScene(); stack.push(scene1); Scene scene2 = new TestScene(); stack.push(scene2); assertEquals(scene2, stack.pop()); assertEquals(scene1, stack.pop()); assertNull(stack.pop()); } @Test public void testPopScene() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); assertEquals(-1, stack.pop(scene1)); stack.push(scene1); stack.push(scene2); assertEquals(-1, stack.pop(scene3)); assertEquals(1, stack.pop(scene1)); assertEquals(0, stack.pop(scene2)); assertEquals(-1, stack.pop(scene1)); } @Test public void testCallback() { Scene scene1 = new TestScene(); Scene scene2 = new TestScene(); Scene scene3 = new TestScene(); stack.pop(); assertEquals(0, pushed); assertEquals(0, popped); assertEquals(null, pushedScene); assertEquals(null, poppedScene); stack.push(scene1); assertEquals(1, pushed); assertEquals(0, popped); assertEquals(scene1, pushedScene); assertEquals(null, poppedScene); stack.push(scene2); assertEquals(2, pushed); assertEquals(0, popped); assertEquals(scene2, pushedScene); assertEquals(null, poppedScene); stack.pop(scene3); assertEquals(2, pushed); assertEquals(0, popped); assertEquals(scene2, pushedScene); assertEquals(null, poppedScene); stack.pop(scene1); assertEquals(2, pushed); assertEquals(1, popped); assertEquals(null, pushedScene); assertEquals(scene1, poppedScene); stack.pop(scene2); assertEquals(2, pushed); assertEquals(2, popped); assertEquals(null, pushedScene); assertEquals(scene2, poppedScene); stack.pop(scene1); assertEquals(2, pushed); assertEquals(2, popped); assertEquals(null, pushedScene); assertEquals(scene2, poppedScene); } }
/* * 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.facebook.presto.sql.planner; import com.facebook.presto.expressions.LogicalRowExpressions; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.ConnectorId; import com.facebook.presto.spi.TableHandle; import com.facebook.presto.spi.block.SortOrder; import com.facebook.presto.spi.function.OperatorType; import com.facebook.presto.spi.plan.AggregationNode; import com.facebook.presto.spi.plan.FilterNode; import com.facebook.presto.spi.plan.LimitNode; import com.facebook.presto.spi.plan.Ordering; import com.facebook.presto.spi.plan.OrderingScheme; import com.facebook.presto.spi.plan.PlanNode; import com.facebook.presto.spi.plan.PlanNodeId; import com.facebook.presto.spi.plan.ProjectNode; import com.facebook.presto.spi.plan.TableScanNode; import com.facebook.presto.spi.plan.TopNNode; import com.facebook.presto.spi.plan.UnionNode; import com.facebook.presto.spi.predicate.Domain; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.facebook.presto.sql.planner.plan.JoinNode; import com.facebook.presto.sql.planner.plan.SemiJoinNode; import com.facebook.presto.sql.planner.plan.SortNode; import com.facebook.presto.sql.planner.plan.WindowNode; import com.facebook.presto.sql.relational.FunctionResolution; import com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator; import com.facebook.presto.sql.relational.RowExpressionDomainTranslator; import com.facebook.presto.testing.TestingHandle; import com.facebook.presto.testing.TestingMetadata; import com.facebook.presto.testing.TestingTransactionHandle; import com.google.common.base.Preconditions; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import static com.facebook.presto.expressions.LogicalRowExpressions.FALSE_CONSTANT; import static com.facebook.presto.expressions.LogicalRowExpressions.TRUE_CONSTANT; import static com.facebook.presto.expressions.LogicalRowExpressions.and; import static com.facebook.presto.expressions.LogicalRowExpressions.or; import static com.facebook.presto.spi.function.OperatorType.EQUAL; import static com.facebook.presto.spi.function.OperatorType.GREATER_THAN; import static com.facebook.presto.spi.function.OperatorType.LESS_THAN; import static com.facebook.presto.spi.function.OperatorType.LESS_THAN_OR_EQUAL; import static com.facebook.presto.spi.plan.AggregationNode.globalAggregation; import static com.facebook.presto.spi.plan.AggregationNode.singleGroupingSet; import static com.facebook.presto.spi.plan.LimitNode.Step.FINAL; import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.IS_NULL; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes; import static com.facebook.presto.sql.planner.RowExpressionEqualityInference.Builder.nonInferrableConjuncts; import static com.facebook.presto.sql.planner.iterative.rule.test.PlanBuilder.assignment; import static com.facebook.presto.sql.planner.optimizations.AggregationNodeUtils.count; import static com.facebook.presto.sql.relational.Expressions.call; import static com.facebook.presto.sql.relational.Expressions.constant; import static com.facebook.presto.sql.relational.Expressions.specialForm; import static org.testng.Assert.assertEquals; public class TestRowExpressionPredicateExtractor { private static final TableHandle DUAL_TABLE_HANDLE = new TableHandle( new ConnectorId("test"), new TestingMetadata.TestingTableHandle(), TestingTransactionHandle.create(), Optional.empty()); private static final TableHandle DUAL_TABLE_HANDLE_WITH_LAYOUT = new TableHandle( new ConnectorId("test"), new TestingMetadata.TestingTableHandle(), TestingTransactionHandle.create(), Optional.of(TestingHandle.INSTANCE)); private static final VariableReferenceExpression AV = new VariableReferenceExpression("a", BIGINT); private static final VariableReferenceExpression BV = new VariableReferenceExpression("b", BIGINT); private static final VariableReferenceExpression CV = new VariableReferenceExpression("c", BIGINT); private static final VariableReferenceExpression DV = new VariableReferenceExpression("d", BIGINT); private static final VariableReferenceExpression EV = new VariableReferenceExpression("e", BIGINT); private static final VariableReferenceExpression FV = new VariableReferenceExpression("f", BIGINT); private static final VariableReferenceExpression GV = new VariableReferenceExpression("g", BIGINT); private final Metadata metadata = MetadataManager.createTestMetadataManager(); private final LogicalRowExpressions logicalRowExpressions = new LogicalRowExpressions( new RowExpressionDeterminismEvaluator(metadata.getFunctionManager()), new FunctionResolution(metadata.getFunctionManager()), metadata.getFunctionManager()); private final RowExpressionPredicateExtractor effectivePredicateExtractor = new RowExpressionPredicateExtractor( new RowExpressionDomainTranslator(metadata), metadata.getFunctionManager(), metadata.getTypeManager()); private Map<VariableReferenceExpression, ColumnHandle> scanAssignments; private TableScanNode baseTableScan; @BeforeClass public void setUp() { scanAssignments = ImmutableMap.<VariableReferenceExpression, ColumnHandle>builder() .put(AV, new TestingMetadata.TestingColumnHandle("a")) .put(BV, new TestingMetadata.TestingColumnHandle("b")) .put(CV, new TestingMetadata.TestingColumnHandle("c")) .put(DV, new TestingMetadata.TestingColumnHandle("d")) .put(EV, new TestingMetadata.TestingColumnHandle("e")) .put(FV, new TestingMetadata.TestingColumnHandle("f")) .build(); Map<VariableReferenceExpression, ColumnHandle> assignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV, DV, EV, FV))); baseTableScan = new TableScanNode( newId(), DUAL_TABLE_HANDLE, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.all(), TupleDomain.all()); } @Test public void testAggregation() { PlanNode node = new AggregationNode(newId(), filter(baseTableScan, and( equals(AV, DV), equals(BV, EV), equals(CV, FV), lessThan(DV, bigintLiteral(10)), lessThan(CV, DV), greaterThan(AV, bigintLiteral(2)), equals(EV, FV))), ImmutableMap.of( CV, count(metadata.getFunctionManager()), DV, count(metadata.getFunctionManager())), singleGroupingSet(ImmutableList.of(AV, BV, CV)), ImmutableList.of(), AggregationNode.Step.FINAL, Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Rewrite in terms of group by symbols assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( lessThan(AV, bigintLiteral(10)), lessThan(BV, AV), greaterThan(AV, bigintLiteral(2)), equals(BV, CV))); } @Test public void testGroupByEmpty() { PlanNode node = new AggregationNode( newId(), filter(baseTableScan, FALSE_CONSTANT), ImmutableMap.of(), globalAggregation(), ImmutableList.of(), AggregationNode.Step.FINAL, Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(effectivePredicate, TRUE_CONSTANT); } @Test public void testFilter() { PlanNode node = filter(baseTableScan, and( greaterThan(AV, call(metadata.getFunctionManager(), "rand", DOUBLE, ImmutableList.of())), lessThan(BV, bigintLiteral(10)))); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Non-deterministic functions should be purged assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(lessThan(BV, bigintLiteral(10)))); } @Test public void testProject() { PlanNode node = new ProjectNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))), assignment(DV, AV, EV, CV)); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Rewrite in terms of project output symbols assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( lessThan(DV, bigintLiteral(10)), equals(DV, EV))); } @Test public void testTopN() { PlanNode node = new TopNNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))), 1, new OrderingScheme(ImmutableList.of(new Ordering(AV, SortOrder.ASC_NULLS_FIRST))), TopNNode.Step.PARTIAL); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Pass through assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))); } @Test public void testLimit() { PlanNode node = new LimitNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))), 1, FINAL); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Pass through assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))); } @Test public void testSort() { PlanNode node = new SortNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))), new OrderingScheme(ImmutableList.of(new Ordering(AV, SortOrder.ASC_NULLS_LAST))), false); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Pass through assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))); } @Test public void testWindow() { PlanNode node = new WindowNode(newId(), filter(baseTableScan, and( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))), new WindowNode.Specification( ImmutableList.of(AV), Optional.of(new OrderingScheme( ImmutableList.of(new Ordering(AV, SortOrder.ASC_NULLS_LAST))))), ImmutableMap.of(), Optional.empty(), ImmutableSet.of(), 0); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Pass through assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts( equals(AV, BV), equals(BV, CV), lessThan(CV, bigintLiteral(10)))); } @Test public void testTableScan() { // Effective predicate is True if there is no effective predicate Map<VariableReferenceExpression, ColumnHandle> assignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV, DV))); PlanNode node = new TableScanNode( newId(), DUAL_TABLE_HANDLE, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.all(), TupleDomain.all()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(effectivePredicate, TRUE_CONSTANT); node = new TableScanNode( newId(), DUAL_TABLE_HANDLE_WITH_LAYOUT, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.none(), TupleDomain.all()); effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(effectivePredicate, FALSE_CONSTANT); node = new TableScanNode( newId(), DUAL_TABLE_HANDLE_WITH_LAYOUT, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.withColumnDomains(ImmutableMap.of(scanAssignments.get(AV), Domain.singleValue(BIGINT, 1L))), TupleDomain.all()); effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(equals(bigintLiteral(1L), AV))); node = new TableScanNode( newId(), DUAL_TABLE_HANDLE_WITH_LAYOUT, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.withColumnDomains(ImmutableMap.of( scanAssignments.get(AV), Domain.singleValue(BIGINT, 1L), scanAssignments.get(BV), Domain.singleValue(BIGINT, 2L))), TupleDomain.all()); effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(equals(bigintLiteral(2L), BV), equals(bigintLiteral(1L), AV))); node = new TableScanNode( newId(), DUAL_TABLE_HANDLE, ImmutableList.copyOf(assignments.keySet()), assignments, TupleDomain.all(), TupleDomain.all()); effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(effectivePredicate, TRUE_CONSTANT); } @Test public void testUnion() { PlanNode node = new UnionNode(newId(), ImmutableList.of( filter(baseTableScan, greaterThan(AV, bigintLiteral(10))), filter(baseTableScan, and(greaterThan(AV, bigintLiteral(10)), lessThan(AV, bigintLiteral(100)))), filter(baseTableScan, and(greaterThan(AV, bigintLiteral(10)), lessThan(AV, bigintLiteral(100))))), ImmutableList.of(AV), ImmutableMap.of(AV, ImmutableList.of(BV, CV, EV))); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Only the common conjuncts can be inferred through a Union assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(greaterThan(AV, bigintLiteral(10)))); } @Test public void testInnerJoin() { ImmutableList.Builder<JoinNode.EquiJoinClause> criteriaBuilder = ImmutableList.builder(); criteriaBuilder.add(new JoinNode.EquiJoinClause(AV, DV)); criteriaBuilder.add(new JoinNode.EquiJoinClause(BV, EV)); List<JoinNode.EquiJoinClause> criteria = criteriaBuilder.build(); Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, and( lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), equals(GV, bigintLiteral(10)))); FilterNode right = filter(rightScan, and( equals(DV, EV), lessThan(FV, bigintLiteral(100)))); PlanNode node = new JoinNode(newId(), JoinNode.Type.INNER, left, right, criteria, ImmutableList.<VariableReferenceExpression>builder() .addAll(left.getOutputVariables()) .addAll(right.getOutputVariables()) .build(), Optional.of(lessThanOrEqual(BV, EV)), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // All predicates having output symbol should be carried through assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), equals(DV, EV), lessThan(FV, bigintLiteral(100)), equals(AV, DV), equals(BV, EV), lessThanOrEqual(BV, EV))); } @Test public void testInnerJoinPropagatesPredicatesViaEquiConditions() { Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, equals(AV, bigintLiteral(10))); // predicates on "a" column should be propagated to output symbols via join equi conditions PlanNode node = new JoinNode(newId(), JoinNode.Type.INNER, left, rightScan, ImmutableList.of(new JoinNode.EquiJoinClause(AV, DV)), ImmutableList.<VariableReferenceExpression>builder() .addAll(rightScan.getOutputVariables()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals( normalizeConjuncts(effectivePredicate), normalizeConjuncts(equals(DV, bigintLiteral(10)))); } @Test public void testInnerJoinWithFalseFilter() { Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); PlanNode node = new JoinNode(newId(), JoinNode.Type.INNER, leftScan, rightScan, ImmutableList.of(new JoinNode.EquiJoinClause(AV, DV)), ImmutableList.<VariableReferenceExpression>builder() .addAll(leftScan.getOutputVariables()) .addAll(rightScan.getOutputVariables()) .build(), Optional.of(FALSE_CONSTANT), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); assertEquals(effectivePredicate, FALSE_CONSTANT); } @Test public void testLeftJoin() { ImmutableList.Builder<JoinNode.EquiJoinClause> criteriaBuilder = ImmutableList.builder(); criteriaBuilder.add(new JoinNode.EquiJoinClause(AV, DV)); criteriaBuilder.add(new JoinNode.EquiJoinClause(BV, EV)); List<JoinNode.EquiJoinClause> criteria = criteriaBuilder.build(); Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, and( lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), equals(GV, bigintLiteral(10)))); FilterNode right = filter(rightScan, and( equals(DV, EV), lessThan(FV, bigintLiteral(100)))); PlanNode node = new JoinNode(newId(), JoinNode.Type.LEFT, left, right, criteria, ImmutableList.<VariableReferenceExpression>builder() .addAll(left.getOutputVariables()) .addAll(right.getOutputVariables()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // All right side symbols having output symbols should be checked against NULL assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), or(equals(DV, EV), and(isNull(DV), isNull(EV))), or(lessThan(FV, bigintLiteral(100)), isNull(FV)), or(equals(AV, DV), isNull(DV)), or(equals(BV, EV), isNull(EV)))); } @Test public void testLeftJoinWithFalseInner() { List<JoinNode.EquiJoinClause> criteria = ImmutableList.of(new JoinNode.EquiJoinClause(AV, DV)); Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, and( lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), equals(GV, bigintLiteral(10)))); FilterNode right = filter(rightScan, FALSE_CONSTANT); PlanNode node = new JoinNode(newId(), JoinNode.Type.LEFT, left, right, criteria, ImmutableList.<VariableReferenceExpression>builder() .addAll(left.getOutputVariables()) .addAll(right.getOutputVariables()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // False literal on the right side should be ignored assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), or(equals(AV, DV), isNull(DV)))); } @Test public void testRightJoin() { ImmutableList.Builder<JoinNode.EquiJoinClause> criteriaBuilder = ImmutableList.builder(); criteriaBuilder.add(new JoinNode.EquiJoinClause(AV, DV)); criteriaBuilder.add(new JoinNode.EquiJoinClause(BV, EV)); List<JoinNode.EquiJoinClause> criteria = criteriaBuilder.build(); Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, and( lessThan(BV, AV), lessThan(CV, bigintLiteral(10)), equals(GV, bigintLiteral(10)))); FilterNode right = filter(rightScan, and( equals(DV, EV), lessThan(FV, bigintLiteral(100)))); PlanNode node = new JoinNode(newId(), JoinNode.Type.RIGHT, left, right, criteria, ImmutableList.<VariableReferenceExpression>builder() .addAll(left.getOutputVariables()) .addAll(right.getOutputVariables()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // All left side symbols should be checked against NULL assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(or(lessThan(BV, AV), and(isNull(BV), isNull(AV))), or(lessThan(CV, bigintLiteral(10)), isNull(CV)), equals(DV, EV), lessThan(FV, bigintLiteral(100)), or(equals(AV, DV), isNull(AV)), or(equals(BV, EV), isNull(BV)))); } @Test public void testRightJoinWithFalseInner() { List<JoinNode.EquiJoinClause> criteria = ImmutableList.of(new JoinNode.EquiJoinClause(AV, DV)); Map<VariableReferenceExpression, ColumnHandle> leftAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(AV, BV, CV))); TableScanNode leftScan = tableScanNode(leftAssignments); Map<VariableReferenceExpression, ColumnHandle> rightAssignments = Maps.filterKeys(scanAssignments, Predicates.in(ImmutableList.of(DV, EV, FV))); TableScanNode rightScan = tableScanNode(rightAssignments); FilterNode left = filter(leftScan, FALSE_CONSTANT); FilterNode right = filter(rightScan, and( equals(DV, EV), lessThan(FV, bigintLiteral(100)))); PlanNode node = new JoinNode(newId(), JoinNode.Type.RIGHT, left, right, criteria, ImmutableList.<VariableReferenceExpression>builder() .addAll(left.getOutputVariables()) .addAll(right.getOutputVariables()) .build(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // False literal on the left side should be ignored assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(equals(DV, EV), lessThan(FV, bigintLiteral(100)), or(equals(AV, DV), isNull(AV)))); } @Test public void testSemiJoin() { PlanNode node = new SemiJoinNode(newId(), filter(baseTableScan, and(greaterThan(AV, bigintLiteral(10)), lessThan(AV, bigintLiteral(100)))), filter(baseTableScan, greaterThan(AV, bigintLiteral(5))), AV, BV, CV, Optional.empty(), Optional.empty(), Optional.empty()); RowExpression effectivePredicate = effectivePredicateExtractor.extract(node); // Currently, only pull predicates through the source plan assertEquals(normalizeConjuncts(effectivePredicate), normalizeConjuncts(and(greaterThan(AV, bigintLiteral(10)), lessThan(AV, bigintLiteral(100))))); } private static TableScanNode tableScanNode(Map<VariableReferenceExpression, ColumnHandle> scanAssignments) { return new TableScanNode( newId(), DUAL_TABLE_HANDLE, ImmutableList.copyOf(scanAssignments.keySet()), scanAssignments, TupleDomain.all(), TupleDomain.all()); } private static PlanNodeId newId() { return new PlanNodeId(UUID.randomUUID().toString()); } private static FilterNode filter(PlanNode source, RowExpression predicate) { return new FilterNode(newId(), source, predicate); } private static RowExpression bigintLiteral(long number) { return constant(number, BIGINT); } private RowExpression equals(RowExpression expression1, RowExpression expression2) { return compare(EQUAL, expression1, expression2); } private RowExpression lessThan(RowExpression expression1, RowExpression expression2) { return compare(LESS_THAN, expression1, expression2); } private RowExpression lessThanOrEqual(RowExpression expression1, RowExpression expression2) { return compare(LESS_THAN_OR_EQUAL, expression1, expression2); } private RowExpression greaterThan(RowExpression expression1, RowExpression expression2) { return compare(GREATER_THAN, expression1, expression2); } private RowExpression compare(OperatorType type, RowExpression left, RowExpression right) { return call( type.getFunctionName().getFunctionName(), metadata.getFunctionManager().resolveOperator(type, fromTypes(left.getType(), right.getType())), BOOLEAN, left, right); } private static RowExpression isNull(RowExpression expression) { return specialForm(IS_NULL, BOOLEAN, expression); } private Set<RowExpression> normalizeConjuncts(RowExpression... conjuncts) { return normalizeConjuncts(Arrays.asList(conjuncts)); } private Set<RowExpression> normalizeConjuncts(Collection<RowExpression> conjuncts) { return normalizeConjuncts(logicalRowExpressions.combineConjuncts(conjuncts)); } private Set<RowExpression> normalizeConjuncts(RowExpression predicate) { // Normalize the predicate by identity so that the EqualityInference will produce stable rewrites in this test // and thereby produce comparable Sets of conjuncts from this method. // Equality inference rewrites and equality generation will always be stable across multiple runs in the same JVM RowExpressionEqualityInference inference = RowExpressionEqualityInference.createEqualityInference(metadata, predicate); Set<RowExpression> rewrittenSet = new HashSet<>(); for (RowExpression expression : nonInferrableConjuncts(metadata, predicate)) { RowExpression rewritten = inference.rewriteExpression(expression, Predicates.alwaysTrue()); Preconditions.checkState(rewritten != null, "Rewrite with full symbol scope should always be possible"); rewrittenSet.add(rewritten); } rewrittenSet.addAll(inference.generateEqualitiesPartitionedBy(Predicates.alwaysTrue()).getScopeEqualities()); return rewrittenSet; } }
package org.csap.agent.stats.service ; import java.io.IOException ; import java.io.InterruptedIOException ; import java.lang.management.ManagementFactory ; import java.net.SocketTimeoutException ; import java.util.HashMap ; import java.util.List ; import java.util.Map ; import java.util.concurrent.Callable ; import java.util.concurrent.Executors ; import java.util.concurrent.Future ; import java.util.concurrent.ScheduledExecutorService ; import java.util.concurrent.TimeUnit ; import java.util.stream.Collectors ; import java.util.stream.Stream ; import javax.management.MBeanServer ; import javax.management.MBeanServerConnection ; import javax.management.remote.JMXConnector ; import javax.management.remote.JMXConnectorFactory ; import javax.management.remote.JMXServiceURL ; import org.apache.commons.lang3.concurrent.BasicThreadFactory ; import org.apache.commons.lang3.text.WordUtils ; import org.csap.agent.CsapApis ; import org.csap.agent.CsapConstants ; import org.csap.agent.model.Application ; import org.csap.agent.model.ServiceAlertsEnum ; import org.csap.agent.model.ServiceInstance ; import org.csap.agent.stats.ServiceCollector ; import org.csap.helpers.CSAP ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; import com.fasterxml.jackson.databind.ObjectMapper ; public class JmxCollector { final Logger logger = LoggerFactory.getLogger( JmxCollector.class ) ; ObjectMapper jacksonMapper = new ObjectMapper( ) ; CsapApis csapApis ; private ServiceCollector serviceCollector ; private JmxCommonCollector javaCommonCollector = new JmxCommonCollector( ) ; private JmxCustomCollector javaCustomCollector ; public JmxCollector ( CsapApis csapApis, ServiceCollector serviceCollector ) { this.csapApis = csapApis ; this.serviceCollector = serviceCollector ; javaCustomCollector = new JmxCustomCollector( serviceCollector, csapApis ) ; } private int numberOfCollectionAttempts = 0 ; public int getNumberOfCollectionAttempts ( ) { return numberOfCollectionAttempts ; } long collectionStart = 0 ; public void collectServicesOnHost ( ) { collectionStart = System.currentTimeMillis( ) ; // Java GC can very occasionally prevent collection // retries are limited to avoid impacting subsequent collections numberOfCollectionAttempts = 0 ; var timer = csapApis.metrics( ).startTimer( ) ; Stream<ServiceInstance> serviceToCollectStream = csapApis.application( ) .getActiveProject( ) .getServicesOnHost( csapApis.application( ).getCsapHostName( ) ) ; numberOfCollectionAttempts = 0 ; while ( true ) { numberOfCollectionAttempts++ ; // Strictly for tracking List<ServiceInstance> failedToCollectInstances = serviceToCollectStream .filter( ServiceInstance::isJavaJmxCollectionEnabled ) .filter( instance -> ! instance.isHttpCollectionEnabled( ) ) .filter( this::collectJmxDataForService ) .collect( Collectors.toList( ) ) ; if ( failedToCollectInstances.size( ) > 0 ) { csapApis.metrics( ).incrementCounter( "collect-java.connection-retry" ) ; serviceToCollectStream = failedToCollectInstances.stream( ) ; try { logger.info( "*jmxCollectionFailure item count: {} , attempts taken: {}, sleeping for 1s and trying again.", failedToCollectInstances.size( ), numberOfCollectionAttempts ) ; Thread.sleep( 1000 ) ; } catch ( InterruptedException e ) { logger.debug( "jmxRetry faile", e ) ; } } else { break ; } } csapApis.metrics( ).stopTimer( timer, "csap.collect-jmx" ) ; } /** * GC will cause connection failures; retry until * MAX_TIME_TO_COLLECT_INTERVAL_MS * * @param serviceInstance * @return */ public boolean collectJmxDataForService ( ServiceInstance serviceInstance ) { boolean isIgnoreCollectionFailure = true ; if ( System.currentTimeMillis( ) - collectionStart > serviceCollector.getMaxCollectionMillis( ) ) { isIgnoreCollectionFailure = false ; logger.warn( "Final collection attempt due to collection time is longer then {} seconds", serviceCollector.getMaxCollectionMillis( ) / 1000 ) ; } return ! executeJmxCollection( serviceInstance, isIgnoreCollectionFailure ) ; } private boolean executeJmxCollection ( ServiceInstance serviceInstance , boolean isIgnoreCollectionFailure ) { String serviceNamePort = serviceInstance.getServiceName_Port( ) ; logger.debug( "{} Getting JMX Metrics, isIgnoreCollectionFailure: {}, custom metrics is: {}", serviceNamePort, isIgnoreCollectionFailure, serviceInstance.getServiceMeters( ) ) ; var serviceTimer = csapApis.metrics( ).startTimer( ) ; // default value is 0 - gets updated if service is online ServiceCollectionResults applicationResults = new ServiceCollectionResults( serviceInstance, serviceCollector.getInMemoryCacheSize( ) ) ; serviceInstance .getServiceMeters( ) .stream( ) .filter( meter -> ! meter.getMeterType( ).isHttp( ) ) .forEach( serviceMeter -> { applicationResults.addCustomResultLong( serviceMeter.getCollectionId( ), 0l ) ; } ) ; // Only connect to active instances if ( ! serviceInstance.getDefaultContainer( ).isRunning( ) && ! serviceInstance.isRemoteCollection( ) && ! csapApis.application( ).isJunit( ) ) { logger.debug( "{} is inactive, skipping collection", serviceNamePort ) ; serviceInstance.getDefaultContainer( ).setHealthReportCollected( null ) ; } else { logger.debug( "{} is active, starting JMX collection ", serviceNamePort ) ; // String opHost = csapApis.application().getCsapHostName(); String jmxHost = "localhost" ; if ( csapApis.application( ).isAllowRemoteJmx( ) ) { jmxHost = csapApis.application( ).getHostFqdn( ) ; } String jmxPort = serviceInstance.getJmxPort( ) ; if ( Application.isRunningOnDesktop( ) ) { jmxHost = ServiceCollector.TEST_HOST ; if ( serviceCollector.isShowWarnings( ) ) { logger.warn( "JmxConnection using " + jmxHost + " For desktop testing" ) ; } } if ( serviceInstance.isRemoteCollection( ) ) { jmxHost = serviceInstance.getCollectHost( ) ; jmxPort = serviceInstance.getCollectPort( ) ; if ( ! serviceCollector.getServiceRemoteHost( ).containsKey( serviceNamePort ) ) { serviceCollector.getServiceRemoteHost( ).put( serviceNamePort, jmxHost ) ; } } long maxJmxCollectionMs = csapApis.application( ) .rootProjectEnvSettings( ) .getMaxJmxCollectionMs( ) ; if ( serviceCollector.getTestServiceTimeout( ) > 0 && serviceInstance.getServiceName_Port( ).equals( serviceCollector.getTestServiceTimeoutName( ) ) && getNumberOfCollectionAttempts( ) < serviceCollector.getTestNumRetries( ) ) { maxJmxCollectionMs = serviceCollector.getTestServiceTimeout( ) ; } // String serviceUrl = "service:jmx:rmi://" + opHost // + "/jndi/rmi://" + opHost + ":" + opPort + "/jmxrmi"; String serviceUrl = "service:jmx:rmi:///jndi/rmi://" + jmxHost + ":" + jmxPort + "/jmxrmi" ; JMXConnector connector = null ; try { // REF. http://wiki.apache.org/tomcat/FAQ/Monitoring MBeanServerConnection mbeanConn = null ; // keepRunning is set to false in junits if ( serviceInstance .getName( ) .equals( CsapConstants.AGENT_NAME ) && serviceCollector.isKeepRunning( ) ) { // optimize local collect mbeanConn = (MBeanServer) ManagementFactory.getPlatformMBeanServer( ) ; } else { var connectionTimer = csapApis.metrics( ).startTimer( ) ; // connector = JMXConnectorFactory.connect(new // JMXServiceURL(serviceUrl)); // Add a max of 2 retries to handle GC collections try { var connectionOptions = new HashMap<String, Object>( ) ; var credentials = new String[] { "csap", "csap" } ; if ( csapApis.application( ).getCsapCoreService( ) != null && csapApis.application( ).getCsapCoreService( ).isJmxAuthentication( ) ) { credentials = new String[] { csapApis.application( ).getCsapCoreService( ).getJmxUser( ), csapApis.application( ).getCsapCoreService( ).getJmxPass( ) } ; } connectionOptions.put( JMXConnector.CREDENTIALS, credentials ) ; connector = connectWithTimeout( new JMXServiceURL( serviceUrl ), maxJmxCollectionMs, TimeUnit.MILLISECONDS, connectionOptions ) ; } catch ( Exception connectException ) { csapApis.metrics( ).incrementCounter( "collect-jmx." + serviceInstance.getName( ) + ".connect" + ".failures" ) ; logger.warn( "\n *** Failed connecting to: {} using: {}, due to: {}", serviceInstance.getName( ), serviceUrl, connectException.getClass( ).getName( ) ) ; logger.debug( "Reason: {}", CSAP.buildCsapStack( connectException ) ) ; if ( isIgnoreCollectionFailure ) { return false ; // try agains will occur } else { // too many attempts will cause timers to overlap. throw connectException ; } } finally { csapApis.metrics( ).stopTimer( connectionTimer, "collect-jmx.connect-" + serviceInstance .getName( ) ) ; } mbeanConn = connector.getMBeanServerConnection( ) ; } // NOTE: We use a single connection to collect first the // JMX // info, then optionally any custom attributes javaCommonCollector.collect( mbeanConn, applicationResults ) ; if ( serviceInstance.hasServiceMeters( ) ) { javaCustomCollector.collect( mbeanConn, applicationResults ) ; } logger.debug( "\n ******* App Collection Complete: {} \n{}\n", serviceInstance.getServiceName_Port( ), WordUtils.wrap( applicationResults.toString( ), 200 ) ) ; } catch ( Exception e ) { csapApis.metrics( ).incrementCounter( "csap.collect-jmx.failures" ) ; csapApis.metrics( ).incrementCounter( "collect-jmx.failures." + serviceInstance.getName( ) ) ; logger.debug( "{} Failed to get jmx data for service", serviceNamePort, e ) ; if ( serviceCollector.isShowWarnings( ) ) { String reason = e.getMessage( ) ; if ( reason != null && reason.length( ) > 60 ) { reason = e .getClass( ) .getName( ) ; } logger.warn( "\n **** Failed to collect {} for service {}\n Reason: {}, Cause: {}", "commmon attributes", serviceNamePort, reason, e.getCause( ) ) ; } // resultNode.put("error", "Failed to invoke JMX" // + Application.getCustomStackTrace(e)); } finally { try { if ( connector != null ) { logger.debug( "{} Closing JMX connection id: {}", serviceInstance.getServiceName_Port( ), connector.getConnectionId( ) ) ; connector.close( ) ; logger.debug( "{} --Closed JMX connection", serviceInstance.getServiceName_Port( ) ) ; } } catch ( Exception e ) { logger.debug( "Failed closing connection: {} due to: {}", serviceNamePort, CSAP.buildCsapStack( e ) ) ; if ( ! e .getMessage( ) .contains( "Not connected" ) ) { logger.error( "Failed closing connection for: " + serviceNamePort + " reason: " + e.getMessage( ) ) ; } } } } applicationResults.add_results_to_java_collection( serviceCollector.getServiceToJavaMetrics( ), serviceInstance.getName( ) ) ; applicationResults.add_results_to_application_collection( serviceCollector.getServiceToAppMetrics( ), serviceInstance.getName( ) ) ; if ( serviceCollector.isPublishSummaryAndPerformHeartBeat( ) || serviceCollector.isTestHeartBeat( ) ) { // update instance settings for availability checks serviceInstance.getDefaultContainer( ).setNumTomcatConns( applicationResults.getHttpConn( ) ) ; serviceInstance.getDefaultContainer( ).setJvmThreadCount( applicationResults.getJvmThreadCount( ) ) ; if ( serviceInstance.isApplicationHealthMeter( ) ) { serviceInstance.getDefaultContainer( ) .setJmxHeartbeatMs( applicationResults.getCustomResult( ServiceAlertsEnum.JAVA_HEARTBEAT ) ) ; } serviceCollector.getLastCollectedResults( ).put( serviceInstance.getServiceName_Port( ), applicationResults ) ; } csapApis.metrics( ).stopTimer( serviceTimer, "collect-jmx." + serviceInstance.getName( ) ) ; return true ; // results were recorded. } private BasicThreadFactory jmxConnectionMonitorFactory = new BasicThreadFactory.Builder( ) .namingPattern( "CsapJmxMonitor-%d" ) .daemon( true ) .priority( Thread.NORM_PRIORITY ) .build( ) ; ScheduledExecutorService jmxConnectionMonitorExecutor = Executors.newScheduledThreadPool( 1, jmxConnectionMonitorFactory ) ; /** * Hack needed in order to get JMX timeouts * http://weblogs.java.net/blog/emcmanus /archive/2007/05/making_a_jmx_co.html * * Total timeout = 2 x params. First to connect, then for calls * * @param url * @param requestTimeout * @param requestUnit * @return * @throws IOException */ private JMXConnector connectWithTimeout ( final JMXServiceURL url , long requestTimeout , TimeUnit requestUnit , Map<String, Object> connectionOptions ) throws IOException { logger.debug( "xxx Attempting connection to: {} with timeout : {} ms", url, requestTimeout ) ; Future<Object> connectionResults = jmxConnectionMonitorExecutor.submit( // new Callable<Object>( ) { public Object call ( ) { try { Map<String, Object> environment = new HashMap<String, Object>( ) ; // Disable client checks - java 9 hides the variable. It can // be set // jmx.remote.x.client.connection.check.period // environment.put( EnvHelp.CLIENT_CONNECTION_CHECK_PERIOD, // 0 ); environment.put( "jmx.remote.x.client.connection.check.period", 0l ) ; environment.putAll( connectionOptions ) ; logger.debug( "xxx connectionOptions {}", environment ) ; JMXConnector connector = JMXConnectorFactory.connect( url, environment ) ; return connector ; } catch ( Throwable t ) { return t ; } } } ) ; Object result ; try { result = connectionResults.get( requestTimeout, requestUnit ) ; } catch ( Exception e ) { throw initCause( new InterruptedIOException( e.getMessage( ) ), e ) ; } finally { // jmxConnectionMonitorExecutor.shutdown(); connectionResults.cancel( true ) ; } if ( result == null ) { throw new SocketTimeoutException( "xxx Connect timed out: " + url ) ; } if ( result instanceof JMXConnector ) { final JMXConnector connector = (JMXConnector) result ; @SuppressWarnings ( "unused" ) Future<Object> closeResults = jmxConnectionMonitorExecutor.schedule( ( new Callable<Object>( ) { public Object call ( ) { Object result = "" ; try { logger.debug( "xxx Closing connection: " + url ) ; connector.close( ) ; } catch ( Throwable t ) { logger.error( "xxx Failed to close connection", t ) ; } return result ; } } ), requestTimeout, requestUnit ) ; return (JMXConnector) result ; } try { throw (Throwable) result ; } catch ( IOException e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Error e ) { throw e ; } catch ( Throwable e ) { // In principle this can't happen but we wrap it anyway throw new IOException( e.toString( ), e ) ; } } private static <T extends Throwable> T initCause ( T wrapper , Throwable wrapped ) { wrapper.initCause( wrapped ) ; return wrapper ; } }
/* * Copyright 2013-2014 Richard M. Hightower * 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. * * __________ _____ __ .__ * \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____ * | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\ * | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ > * |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ / * \/ \/ \/ \/ \/ \//_____/ * ____. ___________ _____ ______________.___. * | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | | * | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | | * /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ | * \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______| * \/ \/ \/ \/ \/ \/ */ package org.boon.datarepo.impl.decorators; import org.boon.criteria.Update; import org.boon.datarepo.ObjectEditor; import java.util.logging.Level; import java.util.logging.Logger; import static org.boon.Exceptions.requireNonNull; public class ObjectEditorLogNullCheckDecorator<KEY, ITEM> extends ObjectEditorDecoratorBase<KEY, ITEM> { Logger logger = Logger.getLogger( ObjectEditorLogNullCheckDecorator.class.getName() ); Level level = Level.FINER; private boolean debug = false; void log( final String msg, final Object... items ) { if ( debug ) { System.out.printf( msg, items ); } String message = String.format( msg, items ); logger.log( level, message ); } public void setLevel( Level level ) { this.level = level; } public void setDebug( boolean debug ) { this.debug = debug; } public void setLogger( Logger logger ) { this.logger = logger; } public ObjectEditorLogNullCheckDecorator() { } public ObjectEditorLogNullCheckDecorator( ObjectEditor oe ) { super( oe ); } @Override public void put( ITEM item ) { requireNonNull( item, "item cannot be null" ); log( "put (item=%s)", item ); super.put( item ); } @Override public boolean add( ITEM item ) { requireNonNull( item, "item cannot be null" ); log( "addObject (item=%s)", item ); return super.add( item ); } @Override public ITEM get( KEY key ) { requireNonNull( key, "key cannot be null" ); log( "get (key=%s)", key ); return super.get( key ); } @Override public void modify( ITEM item ) { requireNonNull( item, "item cannot be null" ); log( "modify (item=%s)", item ); super.modify( item ); } @Override public void modify( ITEM item, String property, Object value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modifyByValue( ITEM item, String property, String value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modifyByValue( item, property, value ); } @Override public void modify( ITEM item, String property, int value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, long value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, char value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, short value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, byte value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, float value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, String property, double value ) { requireNonNull( item, "item cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "modify (item=%s, property=%s, set=%s)", item, property, value ); super.modify( item, property, value ); } @Override public void modify( ITEM item, Update... values ) { requireNonNull( item, "item cannot be null" ); requireNonNull( values, "value cannot be null" ); log( "modify (item=%s, property=%s, update=%s)", item, values ); super.modify( item, values ); } @Override public void update( KEY key, String property, Object value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void updateByValue( KEY key, String property, String value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "updateByValue (key=%s, property=%s, set=%s)", key, property, value ); super.updateByValue( key, property, value ); } @Override public void update( KEY key, String property, int value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, long value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, char value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, short value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, byte value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, float value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, String property, double value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "update (key=%s, property=%s, set=%s)", key, property, value ); super.update( key, property, value ); } @Override public void update( KEY key, Update... values ) { requireNonNull( key, "key cannot be null" ); requireNonNull( values, "values cannot be null" ); log( "update (key=%s, update=%s)", key, values ); super.update( key, values ); } @Override public boolean compareAndUpdate( KEY key, String property, Object compare, Object value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, int compare, int value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, long compare, long value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, char compare, char value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, short compare, short value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, byte compare, byte value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, float compare, float value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndUpdate( KEY key, String property, double compare, double value ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); requireNonNull( value, "value cannot be null" ); log( "compareAndUpdate (key=%s, property=%s, compare=%s, set=%s)", key, property, compare, value ); return super.compareAndUpdate( key, property, compare, value ); } @Override public boolean compareAndIncrement( KEY key, String property, int compare ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); log( "compareAndIncrement (key=%s, property=%s, compare=%s)", key, property, compare ); return super.compareAndIncrement( key, property, compare ); } @Override public boolean compareAndIncrement( KEY key, String property, long compare ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); log( "compareAndIncrement (key=%s, property=%s, compare=%s)", key, property, compare ); return super.compareAndIncrement( key, property, compare ); } @Override public boolean compareAndIncrement( KEY key, String property, short compare ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); log( "compareAndIncrement (key=%s, property=%s, set=%s)", key, property, compare ); return super.compareAndIncrement( key, property, compare ); } @Override public boolean compareAndIncrement( KEY key, String property, byte compare ) { requireNonNull( key, "key cannot be null" ); requireNonNull( property, "property cannot be null" ); requireNonNull( compare, "compare cannot be null" ); log( "compareAndIncrement (key=%s, property=%s, set=%s)", key, property, compare ); return super.compareAndIncrement( key, property, compare ); } }
package org.webdsl.search; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.lucene.analysis.WhitespaceAnalyzer; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.spell.Dictionary; import org.apache.lucene.search.spell.LuceneDictionary; import org.apache.lucene.search.spell.SpellChecker; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.hibernate.TransientObjectException; import org.hibernate.search.FullTextSession; import org.hibernate.search.SearchFactory; import org.hibernate.search.reader.ReaderProvider; import org.hibernate.search.store.DirectoryProvider; import org.hibernate.search.store.FSDirectoryProvider; import org.webdsl.WebDSLEntity; import org.webdsl.logging.Logger; public abstract class AbstractIndexManager { protected static String currentNamespace = null; protected static IndexReader currentNamespaceReader = null; protected static IndexReader currentSourceReader = null; protected static long lastFacetReaderRenewal; static { // keep track of last renewal of facet readers lastFacetReaderRenewal = 0; } protected static void cleanupUnusedSuggestIndices(Class<?> entityClass, Iterator<String> namespacesIt) { String className = entityClass.getName(); final ArrayList<String> namespacesEncoded = new ArrayList<String>(); // {indexdir}/{SpellCheck|AutoComplete}/{class.name.here}.{namespace}/field final Pattern pattern = Pattern.compile(className.replaceAll("\\.", "\\\\.") + "\\.(.+)"); String ns, nsEncoded; while (namespacesIt.hasNext()) { ns = namespacesIt.next(); try { nsEncoded = java.net.URLEncoder.encode(ns, "UTF-8"); } catch (java.io.UnsupportedEncodingException ex) { nsEncoded = ns; } if (!ns.isEmpty()) { namespacesEncoded.add(nsEncoded); } } FileFilter activeNamespaceDirFilter = new FileFilter() { public boolean accept(File file) { Matcher m = pattern.matcher(file.getAbsolutePath()); m.find(); try { return (file.isDirectory() && !namespacesEncoded.contains(m .group(1))); } catch (java.lang.IllegalStateException exception) { return false; } } }; File dir; dir = new File(indexDir() + "/SpellCheck"); if (dir.exists()) { File[] files = dir.listFiles(activeNamespaceDirFilter); for (File file : files) { String pathKey = file.getAbsolutePath().substring( file.getAbsolutePath().indexOf(indexDir())); SearchSuggester.forceSpellCheckerRenewal(pathKey); log("Removing unused suggestion index: " + file.getAbsolutePath()); delete(file); } } dir = new File(indexDir() + "/AutoComplete"); if (dir.exists()) { File[] files = dir.listFiles(activeNamespaceDirFilter); for (File file : files) { String pathKey = file.getAbsolutePath().substring( file.getAbsolutePath().indexOf(indexDir())); SearchSuggester.forceAutoCompleterRenewal(pathKey); log("Removing unused suggestion index: " + file.getAbsolutePath()); delete(file); } } } protected static boolean clearIndex(File path) { try { if (path == null || !path.exists()) return true; // if path doesnt exist, then there is nothing to // clear FSDirectory indexDir = new FSDirectoryProvider().getDirectory(); IndexWriter writer = new IndexWriter(indexDir.open(path), new IndexWriterConfig(Version.LUCENE_CURRENT, new WhitespaceAnalyzer(Version.LUCENE_CURRENT))); writer.deleteAll(); writer.close(); return true; } catch (Exception ex) { org.webdsl.logging.Logger.error( "Error while clearing index on location: " + path, ex); return false; } } protected static void delete(File f) { if (f == null) return; if (f.isDirectory()) { for (File c : f.listFiles()) delete(c); } if (!f.delete()) org.webdsl.logging.Logger.error("EXCEPTION", new FileNotFoundException("Failed to delete file: " + f)); } protected static FullTextSession getFullTextSession() { return org.hibernate.search.Search .getFullTextSession(utils.HibernateUtil.getCurrentSession()); } public static long getModifiedTimeIndex(Class<?> entityClass) { try { DirectoryProvider[] directoryProviders = getSearchFactory() .getDirectoryProviders(entityClass); if (directoryProviders == null || directoryProviders.length < 1) return 0; Directory dir = directoryProviders[0].getDirectory(); if (dir == null) return 0; return IndexReader.lastModified(dir); } catch (Exception ex) { org.webdsl.logging.Logger.error( "Could not retrieve modified timestamp of search index.", ex); return 0; } } protected static synchronized IndexReader getNamespaceFilteredReader( IndexReader sourceReader, String namespace) { if (namespace == null || namespace.isEmpty()) { return sourceReader; } if (currentSourceReader == sourceReader && currentNamespace == namespace && currentNamespaceReader != null) { return currentNamespaceReader; } // create namespace reader currentSourceReader = sourceReader; currentNamespace = namespace; Query negatedNamespaceQuery = mustNotNamespaceQuery(currentNamespace); String tmpIndexPath = indexDir() + "/tmp"; Directory tmpDir = null; IndexWriter nsIndexWriter = null; try { tmpDir = FSDirectory.open(new File(tmpIndexPath)); // first close previous instance if (currentNamespaceReader != null) { try { currentNamespaceReader.close(); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } currentNamespaceReader = null; } tmpDir = FSDirectory.open(new File(tmpIndexPath)); // writer in create mode, old docs are removed IndexWriterConfig writerCfg = new IndexWriterConfig( Version.LUCENE_CURRENT, new WhitespaceAnalyzer( Version.LUCENE_CURRENT)) .setRAMBufferSizeMB((int) IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB); writerCfg.setOpenMode(OpenMode.CREATE); nsIndexWriter = new IndexWriter(tmpDir, writerCfg); // copy source dir nsIndexWriter.addIndexes(sourceReader); // remove all documents from namespaces other than currentNamespace nsIndexWriter.deleteDocuments(negatedNamespaceQuery); nsIndexWriter.optimize(); } catch (Exception ex) { org.webdsl.logging.Logger.error( "Error during renewal of suggestion indexes", ex); } finally { if (nsIndexWriter != null) { try { nsIndexWriter.close(); } catch (Exception ex2) { org.webdsl.logging.Logger.error("EXCEPTION", ex2); } } } try { currentNamespaceReader = IndexReader.open(tmpDir); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } try { tmpDir.close(); } catch (IOException ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } return currentNamespaceReader; } protected static SearchFactory getSearchFactory() { return getFullTextSession().getSearchFactory(); } protected static String indexdir = ""; public static String indexDir() { return indexdir; }// to be overridden in subclass public static String indexDirAutoComplete(Class<?> entityClass, String field) { return indexDir() + "/AutoComplete/" + entityClass.getName() + "/" + field; } public static String indexDirAutoComplete(Class<?> entityClass, String field, String namespace) { if (namespace == null || namespace.isEmpty()) return indexDirAutoComplete(entityClass, field); try { return indexDir() + "/AutoComplete/" + entityClass.getName() + "." + java.net.URLEncoder.encode(namespace, "UTF-8") + "/" + field; } catch (java.io.UnsupportedEncodingException ex) { org.webdsl.logging.Logger.error( "Could not encode namespace property '" + namespace + "'", ex); // just try unencoded return indexDir() + "/AutoComplete/" + entityClass.getName() + "." + namespace + "/" + field; } } public static String indexDirSpellCheck(Class<?> entityClass, String field) { return indexDir() + "/SpellCheck/" + entityClass.getName() + "/" + field; } public static String indexDirSpellCheck(Class<?> entityClass, String field, String namespace) { if (namespace == null || namespace.isEmpty()) return indexDirSpellCheck(entityClass, field); try { return indexDir() + "/SpellCheck/" + entityClass.getName() + "." + java.net.URLEncoder.encode(namespace, "UTF-8") + "/" + field; } catch (java.io.UnsupportedEncodingException ex) { org.webdsl.logging.Logger.error( "Could not encode namespace property '" + namespace + "'", ex); // just try unencoded return indexDir() + "/SpellCheck/" + entityClass.getName() + "." + namespace + "/" + field; } } protected static void log(String message) { org.webdsl.logging.Logger.info(message); } protected static Query mustNotNamespaceQuery(String namespace) { BooleanQuery q = new BooleanQuery(); q.add(new MatchAllDocsQuery(), Occur.SHOULD); // needed to perform a // must not query q.add(new TermQuery(new Term(SearchHelper.NAMESPACEFIELD, namespace)), Occur.MUST_NOT); return q; } public static void optimizeIndex() { log("Optimizing search index started."); getSearchFactory().optimize(); log("Optimizing search index finished succesfully."); } public static void reindex(List<? extends WebDSLEntity> ents) { for (WebDSLEntity webDSLEntity : ents) { reindex(webDSLEntity); } } public static void reindex(WebDSLEntity ent) { if(ent != null){ try{ getFullTextSession().index(ent); } catch (TransientObjectException toe) { Logger.warn("Error during reindex of " + ent.get_WebDslEntityType() + " with id " + ent.getNaturalId() + " - " + toe.getMessage()); } } } protected static void reindexAutoCompletion(IndexReader sourceReader, Class<?> entityClass, String[] completionFields, String namespace, long lastModified) { Directory acDir = null; AutoCompleter ac = null; IndexReader rdr = null; String namespaceInfo = (namespace == null || namespace.isEmpty()) ? "" : ", namespace: " + namespace; String entityName = entityClass.getName().substring( entityClass.getPackage().getName().length() + 1); for (String field : completionFields) { if (org.webdsl.servlet.ServletState.isServletDestroying()) { return; } log("Creating/updating autocomplete index [field: " + entityName + ">" + field + namespaceInfo + "]"); try { String acPath = indexDirAutoComplete(entityClass, field, namespace); File f = new File(acPath); if (f.exists()) { acDir = FSDirectory.open(f); if (IndexReader.lastModified(acDir) > lastModified) { log("no updates"); continue; } } else { acDir = FSDirectory.open(f); } rdr = getNamespaceFilteredReader(sourceReader, namespace); if (rdr.numDocs() < 1) { log("no updates"); continue; } ac = new AutoCompleter(acDir); ac.indexDictionary(rdr, field); SearchSuggester.forceAutoCompleterRenewal(acPath); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } finally { if (ac != null) { try { ac.close(); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } ac = null; } if (acDir != null) { try { acDir.close(); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } acDir = null; } } log("Done"); } } protected static boolean reindexEntityClass(Class<?> c) { String entityName = c.getName().substring( c.getPackage().getName().length() + 1); log("---Reindexing: " + entityName + "---"); long time = System.currentTimeMillis(); org.hibernate.search.FullTextSession ftSession = getFullTextSession(); try { ftSession .createIndexer(c) .progressMonitor( new org.webdsl.search.IndexProgressMonitor(2000, entityName)).batchSizeToLoadObjects(15) .threadsToLoadObjects(1).threadsForSubsequentFetching(2) .threadsForIndexWriter(1).purgeAllOnStart(true) .startAndWait(); } catch (Exception ex) { org.webdsl.logging.Logger.error( "Error during reindexing of entity: " + entityName, ex); return false; } finally { if (ftSession != null) { ftSession.close(); ftSession = null; } } time = System.currentTimeMillis() - time; log("---Done in " + time + "ms.---"); return true; } protected static void reindexSpellCheck(IndexReader sourceReader, Class<?> entityClass, String[] spellCheckFields, String namespace, long lastModified) { Directory scDir = null; SpellChecker sc = null; IndexReader rdr = null; String namespaceInfo = (namespace == null || namespace.isEmpty()) ? ", namespace: " + namespace : ""; String entityName = entityClass.getName().substring( entityClass.getPackage().getName().length() + 1); for (String field : spellCheckFields) { if (org.webdsl.servlet.ServletState.isServletDestroying()) { return; } log("Creating/updating spellcheck index [field: " + entityName + ">" + field + namespaceInfo + "]"); try { String scPath = indexDirSpellCheck(entityClass, field, namespace); File f = new File(scPath); if (f.exists()) { scDir = FSDirectory.open(f); if (IndexReader.lastModified(scDir) > lastModified) { log("no updates"); continue; } } else { scDir = FSDirectory.open(f); } rdr = getNamespaceFilteredReader(sourceReader, namespace); if (rdr.numDocs() < 1) { log("no updates"); continue; } sc = new SpellChecker(scDir); Dictionary dictionary = new LuceneDictionary(rdr, field); sc.indexDictionary(dictionary, new IndexWriterConfig( Version.LUCENE_CURRENT, new WhitespaceAnalyzer( Version.LUCENE_CURRENT)), true); SearchSuggester.forceSpellCheckerRenewal(scPath); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } finally { if (sc != null) { try { sc.close(); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } sc = null; } if (scDir != null) { try { scDir.close(); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } scDir = null; } } log("Done "); } } public static void reindexSuggestions(Class<?> entityClass, String[] completionFields, String[] spellcheckFields) { reindexSuggestions(entityClass, completionFields, spellcheckFields, null); } // Reindex suggestions for a single entity. The spellcheck and // autocompletion fields to be reindexed need to be specified. // A single namespace can be reindexed by specifying the namespace argument. // If namespace is null or empty, all namespaces are reindexed // Reindexing a single namespace also triggers reindexing of suggestion // index for the whole (i.e. non namespace aware) index @SuppressWarnings("deprecation") public synchronized static void reindexSuggestions(Class<?> entityClass, String[] completionFields, String[] spellcheckFields, List<String> namespaces) { SearchFactory searchFactory = getSearchFactory(); DirectoryProvider[] directoryProviders = searchFactory .getDirectoryProviders(entityClass); ReaderProvider readerProvider = searchFactory.getReaderProvider(); IndexReader sourceReader = readerProvider .openReader(directoryProviders); Directory sourceDir = (Directory) directoryProviders[0].getDirectory(); try { LuceneDictionary dict = null; Iterator<String> namespaceIt; long lastModified; try { lastModified = IndexReader.lastModified(sourceDir); } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); lastModified = 0; } if (namespaces == null || namespaces.isEmpty()) { dict = new LuceneDictionary(sourceReader, SearchHelper.NAMESPACEFIELD); namespaceIt = dict.getWordsIterator(); } else { namespaceIt = namespaces.iterator(); } // Autocompletions for all namespaces and fields reindexAutoCompletion(sourceReader, entityClass, completionFields, null, lastModified); // Spellcheck for all namespaces and fields reindexSpellCheck(sourceReader, entityClass, spellcheckFields, null, lastModified); try { String currentNamespace = ""; while (namespaceIt.hasNext() && !org.webdsl.servlet.ServletState .isServletDestroying()) { currentNamespace = namespaceIt.next(); try { reindexAutoCompletion(sourceReader, entityClass, completionFields, currentNamespace, lastModified); reindexSpellCheck(sourceReader, entityClass, spellcheckFields, currentNamespace, lastModified); } catch (Exception ex) { org.webdsl.logging.Logger.error( "Error during renewal of suggestion indexes:", ex); } finally { if (currentNamespaceReader != null) { try { currentNamespaceReader.close(); } catch (Exception ex) { org.webdsl.logging.Logger .error("Could not close temporary namespace index reader:", ex); } currentNamespaceReader = null; } } } } catch (Exception ex) { org.webdsl.logging.Logger.error("EXCEPTION", ex); } if (dict != null) { cleanupUnusedSuggestIndices(entityClass, dict.getWordsIterator()); } } finally { readerProvider.closeReader(sourceReader); } } public static void removeFromIndex(org.webdsl.WebDSLEntity ent) { getFullTextSession().purge(ent.getClass(), ent.getId()); } public static void tryDropIndex() { if ("create-drop".equals(utils.BuildProperties.getDbMode())) { log("Db-mode is set to create-drop -> Clearing search indexes"); FullTextSession fts = getFullTextSession(); fts.purgeAll(Object.class); fts.getSearchFactory().optimize(); fts.flushToIndexes(); log("Clearing search indexes successful"); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying * LICENSE file. */ package com.gemstone.org.jgroups; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.Random; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.experimental.categories.Category; import com.gemstone.junit.UnitTest; import com.gemstone.org.jgroups.stack.IpAddress; @Ignore @Category(UnitTest.class) public class JChannelJUnitTest extends TestCase { static String mcastAddress = "239.192.81.1"; static int mcastPort = getRandomAvailableMCastPort(mcastAddress); static String jchannelConfig = "com.gemstone.org.jgroups.protocols.UDP(" + " discard_incompatible_packets=true;" + " enable_diagnostics=false;" + " tos=16;" + " mcast_port=" + mcastPort + "; mcast_addr=" + mcastAddress +";" + " loopback=false;" + " use_incoming_packet_handler=false;" + " use_outgoing_packet_handler=false;" + " ip_ttl=0; down_thread=false; up_thread=false;)?" + "com.gemstone.org.jgroups.protocols.PING(" + " timeout=5000;" + " down_thread=false; up_thread=false;" + " num_initial_members=2; num_ping_requests=1)?" + "com.gemstone.org.jgroups.protocols.FD_SOCK(" + " num_tries=2; connect_timeout=5000;" + " up_thread=false; down_thread=false)?" + "com.gemstone.org.jgroups.protocols.VERIFY_SUSPECT(" + " timeout=5000; up_thread=false; down_thread=false)?" + "com.gemstone.org.jgroups.protocols.pbcast.NAKACK(" + " use_mcast_xmit=false; gc_lag=10;" + " retransmit_timeout=400,800,1200,2400,4800;" + " down_thread=false; up_thread=false;" + " discard_delivered_msgs=true)?" + "com.gemstone.org.jgroups.protocols.UNICAST(" + " timeout=400,800,1200,2400,4800;" + " down_thread=false; up_thread=false)?" + "com.gemstone.org.jgroups.protocols.pbcast.STABLE(" + " stability_delay=50;" + " desired_avg_gossip=2000;" + " down_thread=false; up_thread=false;" + " max_bytes=400000)?" + "com.gemstone.org.jgroups.protocols.pbcast.GMS(" + " disable_initial_coord=false;" + " print_local_addr=false;" + " join_timeout=5000;" + " join_retry_timeout=2000;" + " up_thread=false; down_thread=false;" + " shun=true)?" + "com.gemstone.org.jgroups.protocols.FRAG2(" + " frag_size=20000;" + " down_thread=false;" + " up_thread=false)"; private static int getRandomAvailableMCastPort(String addr) { InetAddress iAddr = null; try { iAddr = InetAddress.getByName(addr); } catch (Exception e) { throw new RuntimeException(e); } while (true) { int port = getRandomWildcardBindPortNumber(); if (isPortAvailable(port, iAddr)) { return port; } } } private static int getRandomWildcardBindPortNumber() { int rangeBase; int rangeTop; // wcb port range on Windows is 1024..5000 (and Linux?) // wcb port range on Solaris is 32768..65535 // if (System.getProperty("os.name").equals("SunOS")) { // rangeBase=32768; // rangeTop=65535; // } else { // rangeBase=1024; // rangeTop=5000; // } rangeBase = 20001; // 20000/udp is securid rangeTop = 29999; // 30000/tcp is spoolfax Random rand = new Random(); return rand.nextInt(rangeTop-rangeBase) + rangeBase; } public JChannelJUnitTest(String name) { super(name); } private static boolean isPortAvailable(int port, InetAddress addr) { DatagramSocket socket = null; try { socket = new MulticastSocket(); socket.setSoTimeout(Integer.getInteger("AvailablePort.timeout", 2000).intValue()); byte[] buffer = new byte[4]; buffer[0] = (byte)'p'; buffer[1] = (byte)'i'; buffer[2] = (byte)'n'; buffer[3] = (byte)'g'; SocketAddress mcaddr = new InetSocketAddress(addr, port); DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, mcaddr); socket.send(packet); try { socket.receive(packet); packet.getData(); // make sure there's data, but no need to process it return false; } catch (SocketTimeoutException ste) { //System.out.println("socket read timed out"); return true; } catch (Exception e) { e.printStackTrace(); return false; } } catch (java.io.IOException ioe) { if (ioe.getMessage().equals("Network is unreachable")) { throw new RuntimeException(ioe.getMessage(), ioe); } ioe.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void setUp() throws Exception { super.setUp(); // System.setProperty("JGroups.DEBUG", "true"); } @Override public void tearDown() throws Exception { super.tearDown(); // System.getProperties().remove("JGroups.DEBUG"); } public void testAddressEquality() throws Exception { IpAddress addr1 = new IpAddress(InetAddress.getLocalHost(), 1234); IpAddress addr2 = new IpAddress(addr1.getIpAddress(), addr1.getPort()); if (!addr1.equals(addr2)) { fail("expected addresses to be equal"); } addr2.setBirthViewId(4); if (!addr1.equals(addr2)) { fail("expected addresses to be equal"); } addr1.setBirthViewId(0); int comparison = addr1.compareTo(addr2); if (comparison >= 0) { fail("expected addresses to be unequal but compareTo returned " + comparison); } } public void testConnectAndSendMessage() throws Exception { String properties = jchannelConfig; System.out.println("creating channel 1"); JChannel channel1 = new JChannel(properties); System.out.println("creating channel 2"); JChannel channel2 = new JChannel(properties); String channelName = "JChannelJUnitTest"; System.out.println("connecting channel 1"); channel1.connect(channelName); try { System.out.println("connecting channel 2"); channel2.connect(channelName); try { long giveupTime = System.currentTimeMillis() + 20000; String failure; do { failure = null; // There should be two members in the views if (channel1.getView().size() < 2) { failure = "expected 2 members to be in the view: " + channel1.getView(); } if (channel2.getView().size() < 2) { failure = "expected 2 members to be in the view: " + channel2.getView(); } } while (failure != null && System.currentTimeMillis() < giveupTime); if (failure != null) { fail(failure); } // Send a unicast message using one channel and receive it on the other channel sendAndReceive("JGroups test message", channel1, channel2, false); // Send a multicast message using one channel and receive it on the other channel sendAndReceive("JGroups test message", channel1, channel2, true); } finally { channel2.disconnect(); } } finally { channel1.disconnect(); } } private void sendAndReceive(String str, JChannel channel1, JChannel channel2, boolean multicast) throws Exception { Message msg = new Message(true); String sourceStr = "JGroups test message"; msg.setObject(sourceStr); msg.setSrc(channel1.getLocalAddress()); if (!multicast) { msg.setDest(channel2.getLocalAddress()); } channel1.send(msg); Object obj = receive(channel2, 30000); String result = (String)((Message)obj).getObject(); if ( !result.equals(sourceStr) ) { fail("expected to receive a message containing \""+sourceStr+"\" but received \""+result+"\""); } } private Object receive(JChannel channel, long timeoutMS) throws Exception { Long giveupTime = System.currentTimeMillis() + timeoutMS; Object obj; do { try { obj = channel.receive(1000); } catch (TimeoutException e) { obj = null; } } while ( !(obj instanceof Message) && System.currentTimeMillis() < giveupTime ); if (obj == null || !(obj instanceof Message)) { fail("expected to receive a Message but received " + obj); } return obj; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.appservice.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.appservice.models.HostingEnvironmentProfile; import com.azure.resourcemanager.appservice.models.KeyVaultSecretStatus; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; /** Certificate resource specific properties. */ @Fluent public final class CertificateProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(CertificateProperties.class); /* * Friendly name of the certificate. */ @JsonProperty(value = "friendlyName", access = JsonProperty.Access.WRITE_ONLY) private String friendlyName; /* * Subject name of the certificate. */ @JsonProperty(value = "subjectName", access = JsonProperty.Access.WRITE_ONLY) private String subjectName; /* * Host names the certificate applies to. */ @JsonProperty(value = "hostNames") private List<String> hostNames; /* * Pfx blob. */ @JsonProperty(value = "pfxBlob") private byte[] pfxBlob; /* * App name. */ @JsonProperty(value = "siteName", access = JsonProperty.Access.WRITE_ONLY) private String siteName; /* * Self link. */ @JsonProperty(value = "selfLink", access = JsonProperty.Access.WRITE_ONLY) private String selfLink; /* * Certificate issuer. */ @JsonProperty(value = "issuer", access = JsonProperty.Access.WRITE_ONLY) private String issuer; /* * Certificate issue Date. */ @JsonProperty(value = "issueDate", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime issueDate; /* * Certificate expiration date. */ @JsonProperty(value = "expirationDate", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime expirationDate; /* * Certificate password. */ @JsonProperty(value = "password", required = true) private String password; /* * Certificate thumbprint. */ @JsonProperty(value = "thumbprint", access = JsonProperty.Access.WRITE_ONLY) private String thumbprint; /* * Is the certificate valid?. */ @JsonProperty(value = "valid", access = JsonProperty.Access.WRITE_ONLY) private Boolean valid; /* * Raw bytes of .cer file */ @JsonProperty(value = "cerBlob", access = JsonProperty.Access.WRITE_ONLY) private byte[] cerBlob; /* * Public key hash. */ @JsonProperty(value = "publicKeyHash", access = JsonProperty.Access.WRITE_ONLY) private String publicKeyHash; /* * Specification for the App Service Environment to use for the * certificate. */ @JsonProperty(value = "hostingEnvironmentProfile", access = JsonProperty.Access.WRITE_ONLY) private HostingEnvironmentProfile hostingEnvironmentProfile; /* * Key Vault Csm resource Id. */ @JsonProperty(value = "keyVaultId") private String keyVaultId; /* * Key Vault secret name. */ @JsonProperty(value = "keyVaultSecretName") private String keyVaultSecretName; /* * Status of the Key Vault secret. */ @JsonProperty(value = "keyVaultSecretStatus", access = JsonProperty.Access.WRITE_ONLY) private KeyVaultSecretStatus keyVaultSecretStatus; /* * Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms" + "/{appServicePlanName}". */ @JsonProperty(value = "serverFarmId") private String serverFarmId; /** * Get the friendlyName property: Friendly name of the certificate. * * @return the friendlyName value. */ public String friendlyName() { return this.friendlyName; } /** * Get the subjectName property: Subject name of the certificate. * * @return the subjectName value. */ public String subjectName() { return this.subjectName; } /** * Get the hostNames property: Host names the certificate applies to. * * @return the hostNames value. */ public List<String> hostNames() { return this.hostNames; } /** * Set the hostNames property: Host names the certificate applies to. * * @param hostNames the hostNames value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withHostNames(List<String> hostNames) { this.hostNames = hostNames; return this; } /** * Get the pfxBlob property: Pfx blob. * * @return the pfxBlob value. */ public byte[] pfxBlob() { return CoreUtils.clone(this.pfxBlob); } /** * Set the pfxBlob property: Pfx blob. * * @param pfxBlob the pfxBlob value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withPfxBlob(byte[] pfxBlob) { this.pfxBlob = CoreUtils.clone(pfxBlob); return this; } /** * Get the siteName property: App name. * * @return the siteName value. */ public String siteName() { return this.siteName; } /** * Get the selfLink property: Self link. * * @return the selfLink value. */ public String selfLink() { return this.selfLink; } /** * Get the issuer property: Certificate issuer. * * @return the issuer value. */ public String issuer() { return this.issuer; } /** * Get the issueDate property: Certificate issue Date. * * @return the issueDate value. */ public OffsetDateTime issueDate() { return this.issueDate; } /** * Get the expirationDate property: Certificate expiration date. * * @return the expirationDate value. */ public OffsetDateTime expirationDate() { return this.expirationDate; } /** * Get the password property: Certificate password. * * @return the password value. */ public String password() { return this.password; } /** * Set the password property: Certificate password. * * @param password the password value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withPassword(String password) { this.password = password; return this; } /** * Get the thumbprint property: Certificate thumbprint. * * @return the thumbprint value. */ public String thumbprint() { return this.thumbprint; } /** * Get the valid property: Is the certificate valid?. * * @return the valid value. */ public Boolean valid() { return this.valid; } /** * Get the cerBlob property: Raw bytes of .cer file. * * @return the cerBlob value. */ public byte[] cerBlob() { return CoreUtils.clone(this.cerBlob); } /** * Get the publicKeyHash property: Public key hash. * * @return the publicKeyHash value. */ public String publicKeyHash() { return this.publicKeyHash; } /** * Get the hostingEnvironmentProfile property: Specification for the App Service Environment to use for the * certificate. * * @return the hostingEnvironmentProfile value. */ public HostingEnvironmentProfile hostingEnvironmentProfile() { return this.hostingEnvironmentProfile; } /** * Get the keyVaultId property: Key Vault Csm resource Id. * * @return the keyVaultId value. */ public String keyVaultId() { return this.keyVaultId; } /** * Set the keyVaultId property: Key Vault Csm resource Id. * * @param keyVaultId the keyVaultId value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withKeyVaultId(String keyVaultId) { this.keyVaultId = keyVaultId; return this; } /** * Get the keyVaultSecretName property: Key Vault secret name. * * @return the keyVaultSecretName value. */ public String keyVaultSecretName() { return this.keyVaultSecretName; } /** * Set the keyVaultSecretName property: Key Vault secret name. * * @param keyVaultSecretName the keyVaultSecretName value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withKeyVaultSecretName(String keyVaultSecretName) { this.keyVaultSecretName = keyVaultSecretName; return this; } /** * Get the keyVaultSecretStatus property: Status of the Key Vault secret. * * @return the keyVaultSecretStatus value. */ public KeyVaultSecretStatus keyVaultSecretStatus() { return this.keyVaultSecretStatus; } /** * Get the serverFarmId property: Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms" + "/{appServicePlanName}". * * @return the serverFarmId value. */ public String serverFarmId() { return this.serverFarmId; } /** * Set the serverFarmId property: Resource ID of the associated App Service plan, formatted as: * "/subscriptions/{subscriptionID}/resourceGroups/{groupName}/providers/Microsoft.Web/serverfarms" + "/{appServicePlanName}". * * @param serverFarmId the serverFarmId value to set. * @return the CertificateProperties object itself. */ public CertificateProperties withServerFarmId(String serverFarmId) { this.serverFarmId = serverFarmId; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (password() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property password in model CertificateProperties")); } if (hostingEnvironmentProfile() != null) { hostingEnvironmentProfile().validate(); } } }
package com.babytrak24.controller; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import com.babytrak24.model.Login; import com.babytrak24.model.Transaction; import com.babytrak24.model.UberImage; import com.babytrak24.service.ImageService; import com.babytrak24.service.TransactionService; import com.babytrak24.util.CustomFileUtils; @Controller @EnableWebMvc @SessionAttributes("login") public class BabyTrak24AppController { @Autowired private TransactionService transactionService; private ImageService imageService = new ImageService(); public static final Logger logger = LoggerFactory.getLogger(BabyTrak24AppController.class); /** * Redirect to the Home Page ( View Mapping ) */ @GetMapping("") public String index(ModelMap model) { return "redirect:/login"; } /** * View and Model retrieved Retrieve all user transactions matching login email, * and looping through the transactions to retrieve all image details from S3 * Load all the details to a UberImage POJO for easy looping in JSTL */ @RequestMapping(value = "/home", method = RequestMethod.GET) public ModelAndView showAllImages(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") Login login) { ModelAndView mav = new ModelAndView("home"); Transaction transaction = new Transaction(); transaction.setEmail(login.getEmail()); List<Transaction> imageTransactions = transactionService.findAll(Example.<Transaction>of(transaction, ExampleMatcher.matching().withMatcher("email", ExampleMatcher.GenericPropertyMatchers.ignoreCase()))); List<UberImage> uberImages = new ArrayList<UberImage>(); imageTransactions.forEach(imageTran -> { UberImage uberImage = new UberImage(); uberImage.setImagePath(imageService.read(imageTran.getFileName())); uberImage.setTransaction(imageTran); uberImages.add(uberImage); }); mav.addObject("login", login); mav.addObject("uberImages", uberImages); return mav; } /** * View Mapping Display the Upload View */ @RequestMapping(value = "/upload", method = RequestMethod.GET) public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") Login login) { ModelAndView mav = new ModelAndView("upload"); mav.addObject("login", login); return mav; } /** * View Mapping Display the Update View similar to Upload, however this display * Image and its details Find Image using the transaction id of the image */ @RequestMapping(value = "/update", method = RequestMethod.GET) public ModelAndView update(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") Login login, @RequestParam("id") Long id) { Transaction transaction = transactionService.findOne(id); UberImage uberImage = new UberImage(); uberImage.setImagePath(imageService.read(transaction.getFileName())); uberImage.setTransaction(transaction); ModelAndView mav = new ModelAndView("update"); mav.addObject("login", login); mav.addObject("uberImage", uberImage); return mav; } /** * View Mapping Display the Delete View similar to Upload, however this will * just have a button to delete Find Image using the transaction id of the image */ @RequestMapping(value = "/delete", method = RequestMethod.GET) public ModelAndView delete(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("login") Login login, @RequestParam("id") Long id) { Transaction transaction = transactionService.findOne(id); UberImage uberImage = new UberImage(); uberImage.setImagePath(imageService.read(transaction.getFileName())); uberImage.setTransaction(transaction); ModelAndView mav = new ModelAndView("delete"); mav.addObject("login", login); mav.addObject("uberImage", uberImage); return mav; } /** * Multipart file retrieved is converted to a file, using CustomUtils and * uploaded to S3 The transaction details along with fileName, fileDescription * is updated in the Transacations table */ @PostMapping("/uploadImage") public String uploadImage(@ModelAttribute("login") Login login, @RequestParam("file") MultipartFile mpartfile, @ModelAttribute("transaction") Transaction transaction, ModelMap modelMap) { String nextlocation = "redirect:/home"; try { File file = CustomFileUtils.convertFromMultiPart(mpartfile); if (!(file.length() / 1024 / 1024 > 1)) { imageService.add(transaction.getFileName(), file); transaction.setEmail(login.getEmail()); transaction.setProfileImageS3Path(file.getName()); transaction.setUploadTime(new Date()); transaction.setUpdatedTime(new Date()); transactionService.save(transaction); } else { nextlocation = "redirect:/upload"; modelMap.put("message", "Please upload image that is less than 1MB"); } } catch (Exception e) { nextlocation = "upload"; modelMap.put("message", "Sorry !! failed to Upload to S3, please try again"); } return nextlocation; } /** * Multipart file retrieved is converted to a file, using CustomUtils and * uploaded to S3 The transaction details along with fileName, fileDescription * is updated in the Transacations table */ @PostMapping("/updateImage") public String updateImage(@ModelAttribute("login") Login login, @RequestParam("file") MultipartFile mpartfile, @RequestParam("id") Long id, @ModelAttribute("transaction") Transaction transaction, ModelMap modelMap) { String nextlocation = "redirect:/home"; try { Transaction updatableTransaction = transactionService.findOne(id); File file = CustomFileUtils.convertFromMultiPart(mpartfile); imageService.add(updatableTransaction.getFileName(), file); updatableTransaction.setFileDescription(transaction.getFileDescription()); updatableTransaction.setUpdatedTime(new Date()); transactionService.saveAndFlush(updatableTransaction); } catch (Exception e) { nextlocation = "upload"; modelMap.put("message", "Sorry !! failed to Upload to S3, please try again"); } return nextlocation; } /** * Using the transaction id, fileName details are retrieved from Transaction * table and file is deleted from S3 along with transaction in the Transaction * table */ @PostMapping("/deleteImage") public String deleteImage(@ModelAttribute("login") Login login, @RequestParam("id") Long id, ModelMap modelMap) { String nextlocation = "redirect:/home"; try { Transaction deleteTransaction = transactionService.findOne(id); imageService.delete(deleteTransaction.getFileName()); transactionService.delete(id); } catch (Exception e) { nextlocation = "redirect:/delete?id=" + id; modelMap.put("message", "Sorry !! failed to Delete in S3, please try again"); } return nextlocation; } }
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.yms.app.ytb; import org.onosproject.yangutils.datamodel.YangAugment; import org.onosproject.yangutils.datamodel.YangAugmentableNode; import org.onosproject.yangutils.datamodel.YangCase; import org.onosproject.yangutils.datamodel.YangChoice; import org.onosproject.yangutils.datamodel.YangDerivedInfo; import org.onosproject.yangutils.datamodel.YangLeaf; import org.onosproject.yangutils.datamodel.YangLeafList; import org.onosproject.yangutils.datamodel.YangLeafRef; import org.onosproject.yangutils.datamodel.YangLeavesHolder; import org.onosproject.yangutils.datamodel.YangNode; import org.onosproject.yangutils.datamodel.YangSchemaNode; import org.onosproject.yangutils.datamodel.YangSchemaNodeIdentifier; import org.onosproject.yangutils.datamodel.YangType; import org.onosproject.yangutils.datamodel.exceptions.DataModelException; import org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes; import org.onosproject.yms.app.utils.TraversalType; import org.onosproject.yms.app.ydt.YdtExtendedBuilder; import org.onosproject.yms.app.ydt.YdtExtendedContext; import org.onosproject.yms.app.ysr.YangSchemaRegistry; import org.onosproject.yms.ydt.YdtContextOperationType; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes.EMPTY; import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getCapitalCase; import static org.onosproject.yms.app.utils.TraversalType.CHILD; import static org.onosproject.yms.app.utils.TraversalType.PARENT; import static org.onosproject.yms.app.utils.TraversalType.ROOT; import static org.onosproject.yms.app.utils.TraversalType.SIBLING; import static org.onosproject.yms.app.ydt.AppType.YTB; import static org.onosproject.yms.app.ytb.YtbUtil.PERIOD; import static org.onosproject.yms.app.ytb.YtbUtil.STR_NULL; import static org.onosproject.yms.app.ytb.YtbUtil.getAttributeFromInheritance; import static org.onosproject.yms.app.ytb.YtbUtil.getAttributeOfObject; import static org.onosproject.yms.app.ytb.YtbUtil.getClassLoaderForAugment; import static org.onosproject.yms.app.ytb.YtbUtil.getInterfaceClassFromImplClass; import static org.onosproject.yms.app.ytb.YtbUtil.getJavaName; import static org.onosproject.yms.app.ytb.YtbUtil.getNodeOpType; import static org.onosproject.yms.app.ytb.YtbUtil.getOpTypeName; import static org.onosproject.yms.app.ytb.YtbUtil.getParentObjectOfNode; import static org.onosproject.yms.app.ytb.YtbUtil.getStringFromType; import static org.onosproject.yms.app.ytb.YtbUtil.isAugmentNode; import static org.onosproject.yms.app.ytb.YtbUtil.isMultiInstanceNode; import static org.onosproject.yms.app.ytb.YtbUtil.isNodeProcessCompleted; import static org.onosproject.yms.app.ytb.YtbUtil.isNonProcessableNode; import static org.onosproject.yms.app.ytb.YtbUtil.isTypePrimitive; import static org.onosproject.yms.app.ytb.YtbUtil.isValueOrSelectLeafSet; import static org.onosproject.yms.app.ytb.YtbUtil.nonEmpty; import static org.onosproject.yms.ydt.YdtContextOperationType.NONE; /** * Implements traversal of YANG node and its corresponding object, resulting * in building of the YDT tree. */ public class YdtBuilderFromYo { private static final String STR_TYPE = "type"; private static final String STR_SUBJECT = "subject"; private static final String TRUE = "true"; private static final String IS_LEAF_VALUE_SET_METHOD = "isLeafValueSet"; private static final String IS_SELECT_LEAF_SET_METHOD = "isSelectLeaf"; private static final String OUTPUT = "output"; private static final String YANG_AUGMENTED_INFO_MAP = "yangAugmentedInfoMap"; private static final String FALSE = "false"; /** * Application YANG schema registry. */ private final YangSchemaRegistry registry; /** * Current instance of the YDT builder where the tree is built. */ private final YdtExtendedBuilder extBuilder; /** * YANG root object that is required for walking along with the YANG node. */ private Object rootObj; /** * YANG root node that is required for walking along with the YANG object. */ private YangSchemaNode rootSchema; /** * Creates YDT builder from YANG object by assigning the mandatory values. * * @param rootBuilder root node builder * @param rootObj root node object * @param registry application schema registry */ public YdtBuilderFromYo(YdtExtendedBuilder rootBuilder, Object rootObj, YangSchemaRegistry registry) { extBuilder = rootBuilder; this.rootObj = rootObj; this.registry = registry; } /** * Returns schema root node, received from YSR, which searches based on * the object received from YAB or YCH. * * @param object root node object */ public void getModuleNodeFromYsr(Object object) { Class interfaceClass = getInterfaceClassFromImplClass(object); rootSchema = registry .getYangSchemaNodeUsingGeneratedRootNodeInterfaceFileName( interfaceClass.getName()); } /** * Returns schema root node, received from YSR, which searches based on * the object received from YNH. * * @param object notification event object */ public void getRootNodeWithNotificationFromYsr(Object object) { rootSchema = registry.getRootYangSchemaNodeForNotification( object.getClass().getName()); } /** * Creates the module node for in YDT before beginning with notification * root node traversal. Collects sufficient information to fill YDT with * notification root node in the traversal. */ public void createModuleInYdt() { extBuilder.addChild(NONE, rootSchema); rootSchema = getSchemaNodeOfNotification(); rootObj = getObjOfNotification(); } /** * Creates the module and RPC node, in YDT tree, from the logical root * node received from request workbench. The output schema node is taken * from the child schema of RPC YANG node. * * @param rootNode logical root node */ public void createModuleAndRpcInYdt(YdtExtendedContext rootNode) { YdtExtendedContext moduleNode = (YdtExtendedContext) rootNode.getFirstChild(); extBuilder.addChild(NONE, moduleNode.getYangSchemaNode()); YdtExtendedContext rpcNode = (YdtExtendedContext) moduleNode.getFirstChild(); YangSchemaNode rpcSchemaNode = rpcNode.getYangSchemaNode(); extBuilder.addChild(NONE, rpcSchemaNode); // Defines a schema identifier for output node. YangSchemaNodeIdentifier schemaId = new YangSchemaNodeIdentifier(); schemaId.setName(OUTPUT); schemaId.setNameSpace(rpcSchemaNode.getNameSpace()); try { // Gets the output schema node from RPC child schema. rootSchema = rpcSchemaNode.getChildSchema(schemaId).getSchemaNode(); } catch (DataModelException e) { throw new YtbException(e); } } /** * Creates YDT tree from the root object, by traversing through YANG data * model node, and simultaneously checking the object nodes presence and * walking the object. */ public void createYdtFromRootObject() { YangNode curNode = (YangNode) rootSchema; TraversalType curTraversal = ROOT; YtbNodeInfo listNodeInfo = null; YtbNodeInfo augmentNodeInfo = null; while (curNode != null) { /* * Processes the node, if it is being visited for the first time in * the schema, also if the schema node is being retraced in a multi * instance node. */ if (curTraversal != PARENT || isMultiInstanceNode(curNode)) { if (curTraversal == PARENT && isMultiInstanceNode(curNode)) { /* * If the schema is being retraced for a multi-instance * node, it has already entered for this multi-instance * node. Now this re-processes the same schema node for * any additional list object. */ listNodeInfo = getCurNodeInfoAndTraverseBack(); } if (curTraversal == ROOT && !isAugmentNode(curNode)) { /* * In case of RPC output, the root node is augmentative, * so when the root traversal is coming for augment this * flow is skipped. This adds only the root node in the YDT. */ processApplicationRootNode(); } else { /* * Gets the object corresponding to current schema node. * If object exists, this adds the corresponding YDT node * to the tree and returns the object. Else returns null. */ Object processedObject = processCurSchemaNodeAndAddToYdt( curNode, listNodeInfo); /* * Clears the list info of processed node. The next time * list info is taken newly and accordingly. */ listNodeInfo = null; if (processedObject == null && !isAugmentNode(curNode)) { /* * Checks the presence of next sibling of the node, by * breaking the complete chain of the current node, * when the object value is not present, or when the * list entries are completely retraced. The augment * may have sibling, so this doesn't process for * augment. */ YtbTraversalInfo traverseInfo = getProcessableInfo(curNode); curNode = traverseInfo.getYangNode(); curTraversal = traverseInfo.getTraverseType(); continue; /* * Irrespective of root or parent, sets the traversal * type as parent, when augment node doesn't have any * value. So, the other sibling augments can be * processed, if present. */ } else if (processedObject == null && isAugmentNode(curNode)) { curTraversal = PARENT; /* * The second content in the list will be having * parent traversal, in such case it cannot go to its * child in the flow, so it is made as child * traversal and proceeded to continue. */ } else if (curTraversal == PARENT && isMultiInstanceNode(curNode)) { curTraversal = CHILD; } } } /* * Checks for the sibling augment when the first augment node is * getting completed. From the current augment node the previous * node info is taken for augment and the traversal is changed to * child, so as to check for the presence of sibling augment. */ if (curTraversal == PARENT && isAugmentNode(curNode)) { curNode = ((YangAugment) curNode).getAugmentedNode(); augmentNodeInfo = getParentYtbInfo(); curTraversal = CHILD; } /* * Creates an augment iterator for the first time or takes the * previous augment iterator for more than one time, whenever an * augmentative node arrives. If augment is present it goes back * for processing. If its null, the augmentative nodes process is * continued. */ if (curTraversal != PARENT && curNode instanceof YangAugmentableNode) { YangNode augmentNode = getAugmentInsideSchemaNode( curNode, augmentNodeInfo); if (augmentNode != null) { curNode = augmentNode; continue; } } /* * Processes the child, after processing the node. If complete * child depth is over, it takes up sibling and processes it. * Once child and sibling is over, it is traversed back to the * parent, without processing. In multi instance case, before * going to parent or schema sibling, its own list sibling is * processed. Skips the processing of RPC,notification and * augment, as these nodes are dealt in a different flow. */ if (curTraversal != PARENT && curNode.getChild() != null) { augmentNodeInfo = null; listNodeInfo = null; curTraversal = CHILD; curNode = curNode.getChild(); if (isNonProcessableNode(curNode)) { YtbTraversalInfo traverseInfo = getProcessableInfo(curNode); curNode = traverseInfo.getYangNode(); curTraversal = traverseInfo.getTraverseType(); } } else if (curNode.getNextSibling() != null) { if (isNodeProcessCompleted(curNode, curTraversal)) { break; } if (isMultiInstanceNode(curNode)) { listNodeInfo = getCurNodeInfoAndTraverseBack(); augmentNodeInfo = null; continue; } curTraversal = SIBLING; augmentNodeInfo = null; traverseToParent(curNode); curNode = curNode.getNextSibling(); if (isNonProcessableNode(curNode)) { YtbTraversalInfo traverseInfo = getProcessableInfo(curNode); curNode = traverseInfo.getYangNode(); curTraversal = traverseInfo.getTraverseType(); } } else { if (isNodeProcessCompleted(curNode, curTraversal)) { break; } if (isMultiInstanceNode(curNode)) { listNodeInfo = getCurNodeInfoAndTraverseBack(); augmentNodeInfo = null; continue; } curTraversal = PARENT; traverseToParent(curNode); curNode = getParentSchemaNode(curNode); } } } /** * Returns parent schema node of current node. * * @param curNode current schema node * @return parent schema node */ private YangNode getParentSchemaNode(YangNode curNode) { if (curNode instanceof YangAugment) { /* * If curNode is augment, either next augment or augmented node * has to be processed. So traversal type is changed to parent, * but node is not changed. */ return curNode; } return curNode.getParent(); } /** * Processes root YANG node and adds it as a child to the YDT * extended builder which is created earlier. */ private void processApplicationRootNode() { YtbNodeInfo nodeInfo = new YtbNodeInfo(); YangNode rootYang = (YangNode) rootSchema; addChildNodeInYdt(rootObj, rootYang, nodeInfo); // If root node has leaf or leaf-list those will be processed. processLeaves(rootYang); processLeavesList(rootYang); } /** * Traverses to parent, based on the schema node that requires to be * traversed. Skips traversal of parent for choice and case node, as they * don't get added to the YDT tree. * * @param curNode current YANG node */ private void traverseToParent(YangNode curNode) { if (curNode instanceof YangCase || curNode instanceof YangChoice || curNode instanceof YangAugment) { return; } extBuilder.traverseToParentWithoutValidation(); } /** * Returns the current YTB info of the YDT builder, and then traverses back * to parent. In case of multi instance node the previous node info is * used for iterating through the list. * * @return current YTB app info */ private YtbNodeInfo getCurNodeInfoAndTraverseBack() { YtbNodeInfo appInfo = getParentYtbInfo(); extBuilder.traverseToParentWithoutValidation(); return appInfo; } /** * Returns augment node for an augmented node. From the list of augment * nodes it has, one of the nodes is taken and provided linearly. If the * node is not augmented or the all the augment nodes are processed, then * it returns null. * * @param curNode current YANG node * @param augmentNodeInfo previous augment node info * @return YANG augment node */ private YangNode getAugmentInsideSchemaNode(YangNode curNode, YtbNodeInfo augmentNodeInfo) { if (augmentNodeInfo == null) { List<YangAugment> augmentList = ((YangAugmentableNode) curNode) .getAugmentedInfoList(); if (nonEmpty(augmentList)) { YtbNodeInfo parentNodeInfo = getParentYtbInfo(); Iterator<YangAugment> augmentItr = augmentList.listIterator(); parentNodeInfo.setAugmentIterator(augmentItr); return augmentItr.next(); } } else if (augmentNodeInfo.getAugmentIterator() != null) { if (augmentNodeInfo.getAugmentIterator().hasNext()) { return augmentNodeInfo.getAugmentIterator().next(); } } return null; } /** * Processes the current YANG node and if necessary adds it to the YDT * builder tree by extracting the information from the corresponding * class object. * * @param curNode current YANG node * @param listNodeInfo previous node info for list * @return object of the schema node */ private Object processCurSchemaNodeAndAddToYdt(YangNode curNode, YtbNodeInfo listNodeInfo) { YtbNodeInfo curNodeInfo = new YtbNodeInfo(); Object nodeObj = null; YtbNodeInfo parentNodeInfo = getParentYtbInfo(); switch (curNode.getYangSchemaNodeType()) { case YANG_SINGLE_INSTANCE_NODE: nodeObj = processSingleInstanceNode(curNode, curNodeInfo, parentNodeInfo); break; case YANG_MULTI_INSTANCE_NODE: nodeObj = processMultiInstanceNode( curNode, curNodeInfo, listNodeInfo, parentNodeInfo); break; case YANG_CHOICE_NODE: nodeObj = processChoiceNode(curNode, parentNodeInfo); break; case YANG_NON_DATA_NODE: if (curNode instanceof YangCase) { nodeObj = processCaseNode(curNode, parentNodeInfo); } break; case YANG_AUGMENT_NODE: nodeObj = processAugmentNode(curNode, parentNodeInfo); break; default: throw new YtbException( "Non processable schema node has arrived for adding " + "it in YDT tree"); } // Processes leaf/leaf-list only when object has value, else it skips. if (nodeObj != null) { processLeaves(curNode); processLeavesList(curNode); } return nodeObj; } /** * Processes single instance node which is added to the YDT tree. * * @param curNode current YANG node * @param curNodeInfo current YDT node info * @param parentNodeInfo parent YDT node info * @return object of the current node */ private Object processSingleInstanceNode(YangNode curNode, YtbNodeInfo curNodeInfo, YtbNodeInfo parentNodeInfo) { Object childObj = getChildObject(curNode, parentNodeInfo); if (childObj != null) { addChildNodeInYdt(childObj, curNode, curNodeInfo); } return childObj; } /** * Processes multi instance node which has to be added to the YDT tree. * For the first instance in the list, iterator is created and added to * the list. For second instance or more the iterator from first instance * is taken and iterated through to get the object of parent. * * @param curNode current list node * @param curNodeInfo current node info for list * @param listNodeInfo previous instance node info of list * @param parentNodeInfo parent node info of list * @return object of the current instance */ private Object processMultiInstanceNode(YangNode curNode, YtbNodeInfo curNodeInfo, YtbNodeInfo listNodeInfo, YtbNodeInfo parentNodeInfo) { Object childObj = null; /* * When YANG list comes to this flow for first time, its YTB node * will be null. When it comes for the second or more content, then * the list would have been already set for that node. According to * set or not set this flow will be proceeded. */ if (listNodeInfo == null) { List<Object> childObjList = (List<Object>) getChildObject( curNode, parentNodeInfo); if (nonEmpty(childObjList)) { Iterator<Object> listItr = childObjList.iterator(); if (!listItr.hasNext()) { return null; //TODO: Handle the subtree filtering with no list entries. } childObj = listItr.next(); /* * For that node the iterator is set. So the next time for * the list this iterator will be taken. */ curNodeInfo.setListIterator(listItr); } } else { /* * If the list value comes for second or more time, that list * node will be having YTB node info, where iterator can be * retrieved and check if any more contents are present. If * present those will be processed. */ curNodeInfo.setListIterator(listNodeInfo.getListIterator()); if (listNodeInfo.getListIterator().hasNext()) { childObj = listNodeInfo.getListIterator().next(); } } if (childObj != null) { addChildNodeInYdt(childObj, curNode, curNodeInfo); } return childObj; } /** * Processes choice node which adds a map to the parent node info of * choice name and the case object. The object taken for choice node is * of case object with choice name. Also, this Skips the addition of choice * to YDT. * * @param curNode current choice node * @param parentNodeInfo parent YTB node info * @return object of the choice node */ private Object processChoiceNode(YangNode curNode, YtbNodeInfo parentNodeInfo) { /* * Retrieves the parent YTB info, to take the object of parent, so as * to check the child attribute from the object. */ Object childObj = getChildObject(curNode, parentNodeInfo); if (childObj != null) { Map<String, Object> choiceCaseMap = parentNodeInfo .getChoiceCaseMap(); if (choiceCaseMap == null) { choiceCaseMap = new HashMap<>(); parentNodeInfo.setChoiceCaseMap(choiceCaseMap); } choiceCaseMap.put(curNode.getName(), childObj); } return childObj; } /** * Processes case node from the map contents that is filled by choice * nodes. Object of choice is taken when choice name and case class name * matches. When the case node is not present in the map it returns null. * * @param curNode current case node * @param parentNodeInfo choice parent node info * @return object of the case node */ private Object processCaseNode(YangNode curNode, YtbNodeInfo parentNodeInfo) { Object childObj = null; if (parentNodeInfo.getChoiceCaseMap() != null) { childObj = getCaseObjectFromChoice(parentNodeInfo, curNode); } if (childObj != null) { /* * Sets the case object in parent info, so that rest of the case * children can use it as parent. Case is not added in YDT. */ parentNodeInfo.setCaseObject(childObj); } return childObj; } /** * Processes augment node, which is not added in the YDT, but binds * itself to the parent YTB info, so rest of its child nodes can use for * adding themselves to the YDT tree. If there is no augment node added * in map or if the augment module is not registered, then it returns null. * * @param curNode current augment node * @param parentNodeInfo augment parent node info * @return object of the augment node */ private Object processAugmentNode(YangNode curNode, YtbNodeInfo parentNodeInfo) { String className = curNode.getJavaClassNameOrBuiltInType(); String pkgName = curNode.getJavaPackage(); Object parentObj = getParentObjectOfNode(parentNodeInfo, curNode.getParent()); Map augmentMap; try { augmentMap = (Map) getAttributeOfObject(parentObj, YANG_AUGMENTED_INFO_MAP); /* * Gets the registered module class. Loads the class and gets the * augment class. */ Class moduleClass = getClassLoaderForAugment(curNode, registry); if (moduleClass == null) { return null; } Class augmentClass = moduleClass.getClassLoader().loadClass( pkgName + PERIOD + className); Object childObj = augmentMap.get(augmentClass); parentNodeInfo.setAugmentObject(childObj); return childObj; } catch (ClassNotFoundException | NoSuchMethodException e) { throw new YtbException(e); } } /** * Returns the YTB info from the parent node, so that its own bounded * object can be taken out. * * @return parent node YTB node info */ private YtbNodeInfo getParentYtbInfo() { YdtExtendedContext parentExtContext = extBuilder.getCurNode(); return (YtbNodeInfo) parentExtContext.getAppInfo(YTB); } /** * Returns the child object from the parent object. Uses java name of the * current node to search the attribute in the parent object. * * @param curNode current YANG node * @param parentNodeInfo parent YTB node info * @return object of the child node */ private Object getChildObject(YangNode curNode, YtbNodeInfo parentNodeInfo) { String nodeJavaName = curNode.getJavaAttributeName(); Object parentObj = getParentObjectOfNode(parentNodeInfo, curNode.getParent()); try { return getAttributeOfObject(parentObj, nodeJavaName); } catch (NoSuchMethodException e) { throw new YtbException(e); } } /** * Adds the child node to the YDT by taking operation type from the * object. Also, binds the object to the YDT node through YTB node info. * * @param childObj node object * @param curNode current YANG node * @param curNodeInfo current YTB info */ private void addChildNodeInYdt(Object childObj, YangNode curNode, YtbNodeInfo curNodeInfo) { YdtContextOperationType opType = getNodeOpType(childObj, getOpTypeName(curNode)); extBuilder.addChild(opType, curNode); YdtExtendedContext curExtContext = extBuilder.getCurNode(); curNodeInfo.setYangObject(childObj); curExtContext.addAppInfo(YTB, curNodeInfo); } /** * Processes every leaf in a YANG node. Iterates through the leaf, takes * value from the leaf and adds it to the YDT with value. If value is not * present, and select leaf is set, adds it to the YDT without value. * * @param yangNode leaves holder node */ private void processLeaves(YangNode yangNode) { if (yangNode instanceof YangLeavesHolder) { List<YangLeaf> leavesList = ((YangLeavesHolder) yangNode) .getListOfLeaf(); if (leavesList != null) { for (YangLeaf yangLeaf : leavesList) { YtbNodeInfo parentYtbInfo = getParentYtbInfo(); Object parentObj = getParentObjectOfNode(parentYtbInfo, yangNode); Object leafType; try { leafType = getAttributeOfObject(parentObj, getJavaName(yangLeaf)); } catch (NoSuchMethodException e) { throw new YtbException(e); } addLeafWithValue(yangNode, yangLeaf, parentObj, leafType); addLeafWithoutValue(yangNode, yangLeaf, parentObj); } } } } /** * Processes every leaf-list in a YANG node for adding the value in YDT. * * @param yangNode list of leaf-list holder node */ private void processLeavesList(YangNode yangNode) { if (yangNode instanceof YangLeavesHolder) { List<YangLeafList> listOfLeafList = ((YangLeavesHolder) yangNode).getListOfLeafList(); if (listOfLeafList != null) { for (YangLeafList yangLeafList : listOfLeafList) { addToBuilder(yangNode, yangLeafList); } } } } /** * Processes the list of objects of the leaf list and adds the leaf list * value to the builder. * * @param yangNode YANG node * @param leafList YANG leaf list */ private void addToBuilder(YangNode yangNode, YangLeafList leafList) { YtbNodeInfo ytbNodeInfo = getParentYtbInfo(); Object parentObj = getParentObjectOfNode(ytbNodeInfo, yangNode); List<Object> obj; try { obj = (List<Object>) getAttributeOfObject(parentObj, getJavaName(leafList)); } catch (NoSuchMethodException e) { throw new YtbException(e); } if (obj != null) { addLeafListValue(yangNode, parentObj, leafList, obj); } } /** * Adds the leaf list value to the YDT builder by taking the string value * from the data type. * * @param yangNode YANG node * @param parentObj parent object * @param leafList YANG leaf list * @param obj list of objects */ private void addLeafListValue(YangNode yangNode, Object parentObj, YangLeafList leafList, List<Object> obj) { Set<String> leafListVal = new LinkedHashSet<>(); boolean isEmpty = false; for (Object object : obj) { String val = getStringFromType(yangNode, parentObj, getJavaName(leafList), object, leafList.getDataType()); isEmpty = isTypeEmpty(val, leafList.getDataType()); if (isEmpty) { if (val.equals(TRUE)) { addLeafList(leafListVal, leafList); } break; } if (!val.equals("")) { leafListVal.add(val); } } if (!isEmpty && !leafListVal.isEmpty()) { addLeafList(leafListVal, leafList); } } /** * Adds set of leaf list values in the builder and traverses back to the * holder. * * @param leafListVal set of values * @param leafList YANG leaf list */ private void addLeafList(Set<String> leafListVal, YangLeafList leafList) { extBuilder.addLeafList(leafListVal, leafList); extBuilder.traverseToParentWithoutValidation(); } /** * Returns the schema node of notification from the root node. Gets the * enum value from event object and gives it to the root schema node for * getting back the notification schema node. * * @return YANG schema node of notification */ private YangSchemaNode getSchemaNodeOfNotification() { Object eventObjType = getAttributeFromInheritance(rootObj, STR_TYPE); String opTypeValue = String.valueOf(eventObjType); if (opTypeValue.equals(STR_NULL) || opTypeValue.isEmpty()) { throw new YtbException( "There is no notification present for the event. Invalid " + "input for notification."); } try { return rootSchema.getNotificationSchemaNode(opTypeValue); } catch (DataModelException e) { throw new YtbException(e); } } /** * Returns the object of the notification by retrieving the attributes * from the event class object. * * @return notification YANG object */ private Object getObjOfNotification() { Object eventSubjectObj = getAttributeFromInheritance(rootObj, STR_SUBJECT); String notificationName = rootSchema.getJavaAttributeName(); try { return getAttributeOfObject(eventSubjectObj, notificationName); } catch (NoSuchMethodException e) { throw new YtbException(e); } } /** * Returns case object from the map that is bound to the parent node * info. For any case node, only when the key and value is matched the * object of the case is provided. If a match is not found, null is * returned. * * @param parentNodeInfo parent YTB node info * @param caseNode case schema node * @return object of the case node */ private Object getCaseObjectFromChoice(YtbNodeInfo parentNodeInfo, YangSchemaNode caseNode) { String javaName = getCapitalCase( caseNode.getJavaClassNameOrBuiltInType()); String choiceName = ((YangNode) caseNode).getParent().getName(); Map<String, Object> mapObj = parentNodeInfo.getChoiceCaseMap(); Object caseObj = mapObj.get(choiceName); Class<?> interfaceClass = getInterfaceClassFromImplClass(caseObj); return interfaceClass.getSimpleName().equals(javaName) ? caseObj : null; } /** * Adds leaf to YDT when value is present. For primitive types, in order * to avoid default values, the value select is set or not is checked and * then added. * * @param holder leaf holder * @param yangLeaf YANG leaf node * @param parentObj leaf holder object * @param leafType object of leaf type */ private void addLeafWithValue(YangSchemaNode holder, YangLeaf yangLeaf, Object parentObj, Object leafType) { String fieldValue = null; if (isTypePrimitive(yangLeaf.getDataType())) { fieldValue = getLeafValueFromValueSetFlag(holder, parentObj, yangLeaf, leafType); /* * Checks the object is present or not, when type is * non-primitive. And adds the value from the respective data type. */ } else if (leafType != null) { fieldValue = getStringFromType(holder, parentObj, getJavaName(yangLeaf), leafType, yangLeaf.getDataType()); } if (nonEmpty(fieldValue)) { boolean isEmpty = isTypeEmpty(fieldValue, yangLeaf.getDataType()); if (isEmpty) { if (!fieldValue.equals(TRUE)) { return; } fieldValue = null; } extBuilder.addLeaf(fieldValue, yangLeaf); extBuilder.traverseToParentWithoutValidation(); } } /** * Returns the value as true if direct or referred type from leafref or * derived points to empty data type; false otherwise. * * @param fieldValue value of the leaf * @param dataType type of the leaf * @return true if type is empty; false otherwise. */ private boolean isTypeEmpty(String fieldValue, YangType<?> dataType) { if (fieldValue.equals(TRUE) || fieldValue.equals(FALSE)) { switch (dataType.getDataType()) { case EMPTY: return true; case LEAFREF: YangLeafRef leafRef = (YangLeafRef) dataType.getDataTypeExtendedInfo(); return isTypeEmpty(fieldValue, leafRef.getEffectiveDataType()); case DERIVED: YangDerivedInfo info = (YangDerivedInfo) dataType .getDataTypeExtendedInfo(); YangDataTypes type = info.getEffectiveBuiltInType(); return type == EMPTY; default: return false; } } return false; } /** * Adds leaf without value, when the select leaf bit is set. * * @param holder leaf holder * @param yangLeaf YANG leaf node * @param parentObj leaf holder object */ private void addLeafWithoutValue(YangSchemaNode holder, YangLeaf yangLeaf, Object parentObj) { String selectLeaf; try { selectLeaf = isValueOrSelectLeafSet(holder, parentObj, getJavaName(yangLeaf), IS_SELECT_LEAF_SET_METHOD); } catch (NoSuchMethodException e) { selectLeaf = FALSE; } if (selectLeaf.equals(TRUE)) { extBuilder.addLeaf(null, yangLeaf); extBuilder.traverseToParentWithoutValidation(); } } /** * Returns the value of type, after checking the value leaf flag. If the * flag is set, then it takes the value else returns null. * * @param holder leaf holder * @param parentObj parent object * @param yangLeaf YANG leaf node * @param leafType object of leaf type * @return value of type */ private String getLeafValueFromValueSetFlag(YangSchemaNode holder, Object parentObj, YangLeaf yangLeaf, Object leafType) { String valueOfLeaf; try { valueOfLeaf = isValueOrSelectLeafSet(holder, parentObj, getJavaName(yangLeaf), IS_LEAF_VALUE_SET_METHOD); } catch (NoSuchMethodException e) { throw new YtbException(e); } if (valueOfLeaf.equals(TRUE)) { return getStringFromType(holder, parentObj, getJavaName(yangLeaf), leafType, yangLeaf.getDataType()); } return null; } /** * Returns the node info which can be processed, by eliminating the nodes * which need not to be processed at normal conditions such as RPC, * notification and augment. * * @param curNode current node * @return info of node which needs processing */ private YtbTraversalInfo getProcessableInfo(YangNode curNode) { if (curNode.getNextSibling() != null) { YangNode sibling = curNode.getNextSibling(); while (isNonProcessableNode(sibling)) { sibling = sibling.getNextSibling(); } if (sibling != null) { return new YtbTraversalInfo(sibling, SIBLING); } } return new YtbTraversalInfo(curNode.getParent(), PARENT); } }
/******************************************************************************* * 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.ofbiz.workeffort.workeffort; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.URISyntaxException; import java.sql.Timestamp; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Dur; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterList; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyList; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.ValidationException; import net.fortuna.ical4j.model.component.VAlarm; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.component.VToDo; import net.fortuna.ical4j.model.parameter.Cn; import net.fortuna.ical4j.model.parameter.PartStat; import net.fortuna.ical4j.model.parameter.XParameter; import net.fortuna.ical4j.model.property.Action; import net.fortuna.ical4j.model.property.Attendee; import net.fortuna.ical4j.model.property.CalScale; import net.fortuna.ical4j.model.property.Clazz; import net.fortuna.ical4j.model.property.Completed; import net.fortuna.ical4j.model.property.Created; import net.fortuna.ical4j.model.property.Description; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStamp; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.Duration; import net.fortuna.ical4j.model.property.LastModified; import net.fortuna.ical4j.model.property.Location; import net.fortuna.ical4j.model.property.Organizer; import net.fortuna.ical4j.model.property.PercentComplete; import net.fortuna.ical4j.model.property.Priority; import net.fortuna.ical4j.model.property.ProdId; import net.fortuna.ical4j.model.property.Status; import net.fortuna.ical4j.model.property.Summary; import net.fortuna.ical4j.model.property.Uid; import net.fortuna.ical4j.model.property.Version; import net.fortuna.ical4j.model.property.XProperty; import org.ofbiz.base.util.DateRange; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.TimeDuration; import org.ofbiz.base.util.UtilGenerics; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityQuery; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelParam; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; import org.ofbiz.service.calendar.TemporalExpression; import org.ofbiz.service.calendar.TemporalExpressionWorker; import org.ofbiz.workeffort.workeffort.ICalWorker.ResponseProperties; /** iCalendar converter class. This class uses the <a href="http://ical4j.sourceforge.net/index.html"> * iCal4J</a> library. */ public class ICalConverter { protected static final String module = ICalConverter.class.getName(); protected static final String partyIdXParamName = "X-ORG-APACHE-OFBIZ-PARTY-ID"; protected static final ProdId prodId = new ProdId("-//Apache Open For Business//Work Effort Calendar//EN"); protected static final String workEffortIdParamName = "X-ORG-APACHE-OFBIZ-WORKEFFORT-ID"; protected static final String uidPrefix = "ORG-APACHE-OFBIZ-WE-"; protected static final String workEffortIdXPropName = "X-ORG-APACHE-OFBIZ-WORKEFFORT-ID"; protected static final String reminderXPropName = "X-ORG-APACHE-OFBIZ-REMINDER-ID"; protected static final Map<String, String> fromStatusMap = UtilMisc.toMap("TENTATIVE", "CAL_TENTATIVE", "CONFIRMED", "CAL_CONFIRMED", "CANCELLED", "CAL_CANCELLED", "NEEDS-ACTION", "CAL_NEEDS_ACTION", "COMPLETED", "CAL_COMPLETED", "IN-PROCESS", "CAL_ACCEPTED"); protected static final Map<String, Status> toStatusMap = UtilMisc.toMap("CAL_TENTATIVE", Status.VEVENT_TENTATIVE, "CAL_CONFIRMED", Status.VEVENT_CONFIRMED, "CAL_CANCELLED", Status.VEVENT_CANCELLED, "CAL_NEEDS_ACTION", Status.VTODO_NEEDS_ACTION, "CAL_COMPLETED", Status.VTODO_COMPLETED, "CAL_ACCEPTED", Status.VTODO_IN_PROCESS); protected static final Map<String, PartStat> toPartStatusMap = UtilMisc.toMap( "PRTYASGN_OFFERED", PartStat.TENTATIVE, "PRTYASGN_ASSIGNED", PartStat.ACCEPTED); protected static final Map<String, String> fromPartStatusMap = UtilMisc.toMap( "TENTATIVE", "PRTYASGN_OFFERED", "ACCEPTED", "PRTYASGN_ASSIGNED"); protected static final Map<String, String> fromRoleMap = UtilMisc.toMap("ATTENDEE", "CAL_ATTENDEE", "CONTACT", "CONTACT", "ORGANIZER", "CAL_ORGANIZER"); protected static VAlarm createAlarm(GenericValue workEffortEventReminder) { VAlarm alarm = null; Timestamp reminderStamp = workEffortEventReminder.getTimestamp("reminderDateTime"); if (reminderStamp != null) { alarm = new VAlarm(new DateTime(reminderStamp)); } else { TimeDuration duration = TimeDuration.fromNumber(workEffortEventReminder.getLong("reminderOffset")); alarm = new VAlarm(new Dur(duration.days(), duration.hours(), duration.minutes(), duration.seconds())); } return alarm; } protected static Attendee createAttendee(GenericValue partyValue, Map<String, Object> context) { Attendee attendee = new Attendee(); loadPartyAssignment(attendee, partyValue, context); return attendee; } protected static Organizer createOrganizer(GenericValue partyValue, Map<String, Object> context) { Organizer organizer = new Organizer(); loadPartyAssignment(organizer, partyValue, context); return organizer; } protected static ResponseProperties createWorkEffort(Component component, Map<String, Object> context) { Map<String, Object> serviceMap = FastMap.newInstance(); setWorkEffortServiceMap(component, serviceMap); serviceMap.put("workEffortTypeId", "VTODO".equals(component.getName()) ? "TASK" : "EVENT"); serviceMap.put("currentStatusId", "VTODO".equals(component.getName()) ? "CAL_NEEDS_ACTION" : "CAL_TENTATIVE"); serviceMap.put("partyId", ((GenericValue) context.get("userLogin")).get("partyId")); serviceMap.put("roleTypeId", "CAL_OWNER"); serviceMap.put("statusId", "PRTYASGN_ASSIGNED"); Map<String, Object> serviceResult = invokeService("createWorkEffortAndPartyAssign", serviceMap, context); if (ServiceUtil.isError(serviceResult)) { return ICalWorker.createPartialContentResponse(ServiceUtil.getErrorMessage(serviceResult)); } String workEffortId = (String) serviceResult.get("workEffortId"); if (workEffortId != null) { replaceProperty(component.getProperties(), toXProperty(workEffortIdXPropName, workEffortId)); serviceMap.clear(); serviceMap.put("workEffortIdFrom", context.get("workEffortId")); serviceMap.put("workEffortIdTo", workEffortId); serviceMap.put("workEffortAssocTypeId", "WORK_EFF_DEPENDENCY"); serviceMap.put("fromDate", new Timestamp(System.currentTimeMillis())); serviceResult = invokeService("createWorkEffortAssoc", serviceMap, context); if (ServiceUtil.isError(serviceResult)) { return ICalWorker.createPartialContentResponse(ServiceUtil.getErrorMessage(serviceResult)); } storePartyAssignments(workEffortId, component, context); } return null; } protected static String fromClazz(PropertyList propertyList) { Clazz iCalObj = (Clazz) propertyList.getProperty(Clazz.CLASS); if (iCalObj == null) { return null; } return "WES_".concat(iCalObj.getValue()); } protected static Timestamp fromCompleted(PropertyList propertyList) { Completed iCalObj = (Completed) propertyList.getProperty(Completed.COMPLETED); if (iCalObj == null) { return null; } Date date = iCalObj.getDate(); return new Timestamp(date.getTime()); } protected static String fromDescription(PropertyList propertyList) { Description iCalObj = (Description) propertyList.getProperty(Description.DESCRIPTION); if (iCalObj == null) { return null; } return iCalObj.getValue(); } protected static Timestamp fromDtEnd(PropertyList propertyList) { DtEnd iCalObj = (DtEnd) propertyList.getProperty(DtEnd.DTEND); if (iCalObj == null) { return null; } Date date = iCalObj.getDate(); return new Timestamp(date.getTime()); } protected static Timestamp fromDtStart(PropertyList propertyList) { DtStart iCalObj = (DtStart) propertyList.getProperty(DtStart.DTSTART); if (iCalObj == null) { return null; } Date date = iCalObj.getDate(); return new Timestamp(date.getTime()); } protected static Double fromDuration(PropertyList propertyList) { Duration iCalObj = (Duration) propertyList.getProperty(Duration.DURATION); if (iCalObj == null) { return null; } Dur dur = iCalObj.getDuration(); TimeDuration td = new TimeDuration(0, 0, (dur.getWeeks() * 7) + dur.getDays(), dur.getHours(), dur.getMinutes(), dur.getSeconds(), 0); return new Double(TimeDuration.toLong(td)); } protected static Timestamp fromLastModified(PropertyList propertyList) { LastModified iCalObj = (LastModified) propertyList.getProperty(LastModified.LAST_MODIFIED); if (iCalObj == null) { return null; } Date date = iCalObj.getDate(); return new Timestamp(date.getTime()); } protected static String fromLocation(PropertyList propertyList) { Location iCalObj = (Location) propertyList.getProperty(Location.LOCATION); if (iCalObj == null) { return null; } return iCalObj.getValue(); } protected static String fromParticipationStatus(Parameter status) { if (status == null) { return null; } return fromPartStatusMap.get(status.getValue()); } protected static Long fromPercentComplete(PropertyList propertyList) { PercentComplete iCalObj = (PercentComplete) propertyList.getProperty(PercentComplete.PERCENT_COMPLETE); if (iCalObj == null) { return null; } return new Long(iCalObj.getPercentage()); } protected static Double fromPriority(PropertyList propertyList) { Priority iCalObj = (Priority) propertyList.getProperty(Priority.PRIORITY); if (iCalObj == null) { return null; } return new Double(iCalObj.getLevel()); } protected static String fromStatus(PropertyList propertyList) { Status iCalObj = (Status) propertyList.getProperty(Status.STATUS); if (iCalObj == null) { return null; } return fromStatusMap.get(iCalObj.getValue()); } protected static String fromSummary(PropertyList propertyList) { Summary iCalObj = (Summary) propertyList.getProperty(Summary.SUMMARY); if (iCalObj == null) { return null; } return iCalObj.getValue(); } protected static String fromUid(PropertyList propertyList) { Uid iCalObj = (Uid) propertyList.getProperty(Uid.UID); if (iCalObj == null) { return null; } return iCalObj.getValue(); } protected static String fromXParameter(ParameterList parameterList, String parameterName) { if (parameterName == null) { return null; } Parameter parameter = parameterList.getParameter(parameterName); if (parameter != null) { return parameter.getValue(); } return null; } protected static String fromXProperty(PropertyList propertyList, String propertyName) { if (propertyName == null) { return null; } Property property = propertyList.getProperty(propertyName); if (property != null) { return property.getValue(); } return null; } protected static void getAlarms(GenericValue workEffort, ComponentList alarms) throws GenericEntityException { Description description = null; if (workEffort.get("description") != null) { description = new Description(workEffort.getString("description")); } else { description = new Description(workEffort.getString("workEffortName")); } Summary summary = new Summary(UtilProperties.getMessage("WorkEffortUiLabels", "WorkEffortEventReminder", Locale.getDefault())); Delegator delegator = workEffort.getDelegator(); String workEffortId = workEffort.getString("workEffortId"); List<GenericValue> reminderList = EntityQuery.use(delegator).from("WorkEffortEventReminder").where("workEffortId", workEffort.get("workEffortId")).queryList(); for (GenericValue reminder : reminderList) { String reminderId = workEffortId + "-" + reminder.getString("sequenceId"); VAlarm alarm = null; PropertyList alarmProps = null; boolean newAlarm = true; Iterator<VAlarm> i = UtilGenerics.cast(alarms.iterator()); while (i.hasNext()) { alarm = i.next(); Property xProperty = alarm.getProperty(reminderXPropName); if (xProperty != null && reminderId.equals(xProperty.getValue())) { newAlarm = false; alarmProps = alarm.getProperties(); // TODO: Write update code. For now, just re-create alarmProps.clear(); break; } } if (newAlarm) { alarm = createAlarm(reminder); alarms.add(alarm); alarmProps = alarm.getProperties(); alarmProps.add(new XProperty(reminderXPropName, reminderId)); } GenericValue contactMech = reminder.getRelatedOne("ContactMech", false); if (contactMech != null && "EMAIL_ADDRESS".equals(contactMech.get("contactMechTypeId"))) { try { alarmProps.add(new Attendee(contactMech.getString("infoString"))); alarmProps.add(Action.EMAIL); alarmProps.add(summary); alarmProps.add(description); } catch (URISyntaxException e) { alarmProps.add(Action.DISPLAY); alarmProps.add(new Description("Error encountered while creating iCalendar: " + e)); } } else { alarmProps.add(Action.DISPLAY); alarmProps.add(description); } if (Debug.verboseOn()) { try { alarm.validate(true); Debug.logVerbose("iCalendar alarm passes validation", module); } catch (ValidationException e) { Debug.logVerbose("iCalendar alarm fails validation: " + e, module); } } } } /** Returns a calendar derived from a Work Effort calendar publish point. * @param workEffortId ID of a work effort with <code>workEffortTypeId</code> equal to * <code>PUBLISH_PROPS</code>. * @param context The conversion context * @return An iCalendar as a <code>String</code>, or <code>null</code> * if <code>workEffortId</code> is invalid. * @throws GenericEntityException */ public static ResponseProperties getICalendar(String workEffortId, Map<String, Object> context) throws GenericEntityException { Delegator delegator = (Delegator) context.get("delegator"); GenericValue publishProperties = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne(); if (!isCalendarPublished(publishProperties)) { Debug.logInfo("WorkEffort calendar is not published: " + workEffortId, module); return ICalWorker.createNotFoundResponse(null); } if (!"WES_PUBLIC".equals(publishProperties.get("scopeEnumId"))) { if (context.get("userLogin") == null) { return ICalWorker.createNotAuthorizedResponse(null); } if (!hasPermission(workEffortId, "VIEW", context)) { return ICalWorker.createForbiddenResponse(null); } } Calendar calendar = makeCalendar(publishProperties, context); ComponentList components = calendar.getComponents(); List<GenericValue> workEfforts = getRelatedWorkEfforts(publishProperties, context); if (workEfforts != null) { for (GenericValue workEffort : workEfforts) { ResponseProperties responseProps = toCalendarComponent(components, workEffort, context); if (responseProps != null) { return responseProps; } } } if (Debug.verboseOn()) { try { calendar.validate(true); Debug.logVerbose("iCalendar passes validation", module); } catch (ValidationException e) { Debug.logVerbose("iCalendar fails validation: " + e, module); } } return ICalWorker.createOkResponse(calendar.toString()); } protected static void getPartyUrl(Property property, GenericValue partyAssign, Map<String, Object> context) { Map<String, ? extends Object> serviceMap = UtilMisc.toMap("partyId", partyAssign.get("partyId")); Map<String, Object> resultMap = invokeService("getPartyICalUrl", serviceMap, context); String iCalUrl = (String) resultMap.get("iCalUrl"); if (iCalUrl != null) { if (!iCalUrl.contains(":") && iCalUrl.contains("@")) { iCalUrl = "MAILTO:".concat(iCalUrl); } try { property.setValue(iCalUrl); } catch (Exception e) { Debug.logError(e, "Error while setting party URI: ", module); } } } protected static List<GenericValue> getRelatedWorkEfforts(GenericValue workEffort, Map<String, Object> context) throws GenericEntityException { Map<String, ? extends Object> serviceMap = UtilMisc.toMap("workEffortId", workEffort.getString("workEffortId")); Map<String, Object> resultMap = invokeService("getICalWorkEfforts", serviceMap, context); List<GenericValue> workEfforts = UtilGenerics.checkList(resultMap.get("workEfforts"), GenericValue.class); if (workEfforts != null) { return WorkEffortWorker.removeDuplicateWorkEfforts(workEfforts); } return null; } protected static boolean hasPermission(String workEffortId, String action, Map<String, Object> context) { if (context.get("userLogin") == null) { return false; } Map<String, ? extends Object> serviceMap = UtilMisc.toMap("workEffortId", workEffortId, "mainAction", action); Map<String, Object> serviceResult = invokeService("workEffortICalendarPermission", serviceMap, context); Boolean hasPermission = (Boolean) serviceResult.get("hasPermission"); if (hasPermission != null) { return hasPermission.booleanValue(); } else { return false; } } protected static Map<String, Object> invokeService(String serviceName, Map<String, ? extends Object> serviceMap, Map<String, Object> context) { LocalDispatcher dispatcher = (LocalDispatcher) context.get("dispatcher"); Map<String, Object> localMap = FastMap.newInstance(); try { ModelService modelService = null; modelService = dispatcher.getDispatchContext().getModelService(serviceName); for (ModelParam modelParam: modelService.getInModelParamList()) { if (serviceMap.containsKey(modelParam.name)) { Object value = serviceMap.get(modelParam.name); if (UtilValidate.isNotEmpty(modelParam.type)) { value = ObjectType.simpleTypeConvert(value, modelParam.type, null, null, null, true); } localMap.put(modelParam.name, value); } } } catch (Exception e) { String errMsg = "Error while creating service Map for service " + serviceName + ": "; Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg + e); } if (context.get("userLogin") != null) { localMap.put("userLogin", context.get("userLogin")); } localMap.put("locale", context.get("locale")); try { return dispatcher.runSync(serviceName, localMap); } catch (GenericServiceException e) { String errMsg = "Error while invoking service " + serviceName + ": "; Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg + e); } } protected static boolean isCalendarPublished(GenericValue publishProperties) { if (publishProperties == null || !"PUBLISH_PROPS".equals(publishProperties.get("workEffortTypeId"))) { return false; } DateRange range = new DateRange(publishProperties.getTimestamp("actualStartDate"), publishProperties.getTimestamp("actualCompletionDate")); return range.includesDate(new Date()); } protected static void loadPartyAssignment(Property property, GenericValue partyAssign, Map<String, Object> context) { getPartyUrl(property, partyAssign, context); if (UtilValidate.isEmpty(property.getValue())) { try { // RFC 2445 4.8.4.1 and 4.8.4.3 Value must be a URL property.setValue("MAILTO:ofbiz-test@example.com"); } catch (Exception e) { Debug.logError(e, "Error while setting Property value: ", module); } } ParameterList parameterList = property.getParameters(); if (partyAssign != null) { replaceParameter(parameterList, toXParameter(partyIdXParamName, partyAssign.getString("partyId"))); replaceParameter(parameterList, new Cn(makePartyName(partyAssign))); replaceParameter(parameterList, toParticipationStatus(partyAssign.getString("assignmentStatusId"))); } } protected static void loadRelatedParties(List<GenericValue> relatedParties, PropertyList componentProps, Map<String, Object> context) { PropertyList attendees = componentProps.getProperties("ATTENDEE"); for (GenericValue partyValue : relatedParties) { if ("CAL_ORGANIZER~CAL_OWNER".contains(partyValue.getString("roleTypeId"))) { // RFC 2445 4.6.1, 4.6.2, and 4.6.3 ORGANIZER can appear only once replaceProperty(componentProps, createOrganizer(partyValue, context)); } else { String partyId = partyValue.getString("partyId"); boolean newAttendee = true; Attendee attendee = null; Iterator<Attendee> i = UtilGenerics.cast(attendees.iterator()); while (i.hasNext()) { attendee = i.next(); Parameter xParameter = attendee.getParameter(partyIdXParamName); if (xParameter != null && partyId.equals(xParameter.getValue())) { loadPartyAssignment(attendee, partyValue, context); newAttendee = false; break; } } if (newAttendee) { attendee = createAttendee(partyValue, context); componentProps.add(attendee); } } } } protected static void loadWorkEffort(PropertyList componentProps, GenericValue workEffort) { replaceProperty(componentProps, new DtStamp()); // iCalendar object created date/time replaceProperty(componentProps, toClazz(workEffort.getString("scopeEnumId"))); replaceProperty(componentProps, toCreated(workEffort.getTimestamp("createdDate"))); replaceProperty(componentProps, toDescription(workEffort.getString("description"))); replaceProperty(componentProps, toDtStart(workEffort.getTimestamp("estimatedStartDate"))); replaceProperty(componentProps, toLastModified(workEffort.getTimestamp("lastModifiedDate"))); replaceProperty(componentProps, toPriority(workEffort.getLong("priority"))); replaceProperty(componentProps, toLocation(workEffort.getString("locationDesc"))); replaceProperty(componentProps, toStatus(workEffort.getString("currentStatusId"))); replaceProperty(componentProps, toSummary(workEffort.getString("workEffortName"))); Property uid = componentProps.getProperty(Uid.UID); if (uid == null) { // Don't overwrite UIDs created by calendar clients replaceProperty(componentProps, toUid(workEffort.getString("workEffortId"))); } replaceProperty(componentProps, toXProperty(workEffortIdXPropName, workEffort.getString("workEffortId"))); } protected static Calendar makeCalendar(GenericValue workEffort, Map<String, Object> context) throws GenericEntityException { String iCalData = null; GenericValue iCalValue = workEffort.getRelatedOne("WorkEffortIcalData", false); if (iCalValue != null) { iCalData = iCalValue.getString("icalData"); } boolean newCalendar = true; Calendar calendar = null; if (iCalData == null) { Debug.logVerbose("iCalendar Data not found, creating new Calendar", module); calendar = new Calendar(); } else { Debug.logVerbose("iCalendar Data found, using saved Calendar", module); StringReader reader = new StringReader(iCalData); CalendarBuilder builder = new CalendarBuilder(); try { calendar = builder.build(reader); newCalendar = false; } catch (Exception e) { Debug.logError(e, "Error while parsing saved iCalendar, creating new iCalendar: ", module); calendar = new Calendar(); } } PropertyList propList = calendar.getProperties(); replaceProperty(propList, prodId); replaceProperty(propList, new XProperty(workEffortIdXPropName, workEffort.getString("workEffortId"))); if (newCalendar) { propList.add(Version.VERSION_2_0); propList.add(CalScale.GREGORIAN); // TODO: Get time zone from publish properties value java.util.TimeZone tz = java.util.TimeZone.getDefault(); TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); net.fortuna.ical4j.model.TimeZone timezone = registry.getTimeZone(tz.getID()); calendar.getComponents().add(timezone.getVTimeZone()); } return calendar; } protected static String makePartyName(GenericValue partyAssign) { String partyName = partyAssign.getString("groupName"); if (UtilValidate.isEmpty(partyName)) { partyName = partyAssign.getString("firstName") + " " + partyAssign.getString("lastName"); } return partyName; } protected static void replaceParameter(ParameterList parameterList, Parameter parameter) { if (parameter == null) { return; } Parameter existingParam = parameterList.getParameter(parameter.getName()); if (existingParam != null) { parameterList.remove(existingParam); } parameterList.add(parameter); } protected static void replaceProperty(PropertyList propertyList, Property property) { if (property == null) { return; } Property existingProp = propertyList.getProperty(property.getName()); if (existingProp != null) { propertyList.remove(existingProp); } propertyList.add(property); } protected static void setMapElement(Map<String, Object> map, String key, Object value) { if (map == null || key == null || value == null) { return; } map.put(key, value); } protected static void setPartyIdFromUrl(Property property, Map<String, Object> context) { Map<String, ? extends Object> serviceMap = UtilMisc.toMap("address", property.getValue(), "caseInsensitive", "Y"); Map<String, Object> resultMap = invokeService("findPartyFromEmailAddress", serviceMap, context); String partyId = (String) resultMap.get("partyId"); if (partyId != null) { replaceParameter(property.getParameters(), toXParameter(partyIdXParamName, partyId)); } } protected static void setWorkEffortServiceMap(Component component, Map<String, Object> serviceMap) { PropertyList propertyList = component.getProperties(); setMapElement(serviceMap, "scopeEnumId", fromClazz(propertyList)); setMapElement(serviceMap, "description", fromDescription(propertyList)); setMapElement(serviceMap, "locationDesc", fromLocation(propertyList)); setMapElement(serviceMap, "priority", fromPriority(propertyList)); setMapElement(serviceMap, "currentStatusId", fromStatus(propertyList)); setMapElement(serviceMap, "workEffortName", fromSummary(propertyList)); setMapElement(serviceMap, "universalId", fromUid(propertyList)); // Set some fields to null so calendar clients can revert changes serviceMap.put("estimatedStartDate", null); serviceMap.put("estimatedCompletionDate", null); serviceMap.put("estimatedMilliSeconds", null); serviceMap.put("lastModifiedDate", null); serviceMap.put("actualCompletionDate", null); serviceMap.put("percentComplete", null); setMapElement(serviceMap, "estimatedStartDate", fromDtStart(propertyList)); setMapElement(serviceMap, "estimatedMilliSeconds", fromDuration(propertyList)); setMapElement(serviceMap, "lastModifiedDate", fromLastModified(propertyList)); if ("VTODO".equals(component.getName())) { setMapElement(serviceMap, "actualCompletionDate", fromCompleted(propertyList)); setMapElement(serviceMap, "percentComplete", fromPercentComplete(propertyList)); } else { setMapElement(serviceMap, "estimatedCompletionDate", fromDtEnd(propertyList)); } } /** Update work efforts from an incoming iCalendar request. * @param is * @param context * @throws IOException * @throws ParserException * @throws GenericEntityException * @throws GenericServiceException */ public static ResponseProperties storeCalendar(InputStream is, Map<String, Object> context) throws IOException, ParserException, GenericEntityException, GenericServiceException { CalendarBuilder builder = new CalendarBuilder(); Calendar calendar = null; try { calendar = builder.build(is); } finally { if (is != null) { is.close(); } } if (Debug.verboseOn()) { Debug.logVerbose("Processing calendar:\r\n" + calendar, module); } String workEffortId = fromXProperty(calendar.getProperties(), workEffortIdXPropName); if (workEffortId == null) { workEffortId = (String) context.get("workEffortId"); } if (!workEffortId.equals(context.get("workEffortId"))) { Debug.logWarning("Spoof attempt: received calendar workEffortId " + workEffortId + " on URL workEffortId " + context.get("workEffortId"), module); return ICalWorker.createForbiddenResponse(null); } Delegator delegator = (Delegator) context.get("delegator"); GenericValue publishProperties = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne(); if (!isCalendarPublished(publishProperties)) { Debug.logInfo("WorkEffort calendar is not published: " + workEffortId, module); return ICalWorker.createNotFoundResponse(null); } if (context.get("userLogin") == null) { return ICalWorker.createNotAuthorizedResponse(null); } if (!hasPermission(workEffortId, "UPDATE", context)) { return ICalWorker.createForbiddenResponse(null); } boolean hasCreatePermission = hasPermission(workEffortId, "CREATE", context); List<GenericValue> workEfforts = getRelatedWorkEfforts(publishProperties, context); Set<String> validWorkEfforts = FastSet.newInstance(); if (UtilValidate.isNotEmpty(workEfforts)) { // Security issue: make sure only related work efforts get updated for (GenericValue workEffort : workEfforts) { validWorkEfforts.add(workEffort.getString("workEffortId")); } } List<Component> components = UtilGenerics.checkList(calendar.getComponents(), Component.class); ResponseProperties responseProps = null; for (Component component : components) { if (Component.VEVENT.equals(component.getName()) || Component.VTODO.equals(component.getName())) { workEffortId = fromXProperty(component.getProperties(), workEffortIdXPropName); if (workEffortId == null) { Property uid = component.getProperty(Uid.UID); if (uid != null) { GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("universalId", uid.getValue()).queryFirst(); if (workEffort != null) { workEffortId = workEffort.getString("workEffortId"); } } } if (workEffortId != null) { if (validWorkEfforts.contains(workEffortId)) { replaceProperty(component.getProperties(), toXProperty(workEffortIdXPropName, workEffortId)); responseProps = storeWorkEffort(component, context); } else { Debug.logWarning("Spoof attempt: unrelated workEffortId " + workEffortId + " on URL workEffortId " + context.get("workEffortId"), module); responseProps = ICalWorker.createForbiddenResponse(null); } } else if (hasCreatePermission) { responseProps = createWorkEffort(component, context); } if (responseProps != null) { return responseProps; } } } Map<String, ? extends Object> serviceMap = UtilMisc.toMap("workEffortId", context.get("workEffortId"), "icalData", calendar.toString()); GenericValue iCalData = publishProperties.getRelatedOne("WorkEffortIcalData", false); Map<String, Object> serviceResult = null; if (iCalData == null) { serviceResult = invokeService("createWorkEffortICalData", serviceMap, context); } else { serviceResult = invokeService("updateWorkEffortICalData", serviceMap, context); } if (ServiceUtil.isError(serviceResult)) { return ICalWorker.createPartialContentResponse(ServiceUtil.getErrorMessage(serviceResult)); } return ICalWorker.createOkResponse(null); } protected static ResponseProperties storePartyAssignments(String workEffortId, Component component, Map<String, Object> context) { ResponseProperties responseProps = null; Map<String, Object> serviceMap = FastMap.newInstance(); List<Property> partyList = FastList.newInstance(); partyList.addAll(UtilGenerics.checkList(component.getProperties("ATTENDEE"), Property.class)); partyList.addAll(UtilGenerics.checkList(component.getProperties("CONTACT"), Property.class)); partyList.addAll(UtilGenerics.checkList(component.getProperties("ORGANIZER"), Property.class)); for (Property property : partyList) { String partyId = fromXParameter(property.getParameters(), partyIdXParamName); if (partyId == null) { serviceMap.clear(); String address = property.getValue(); if (address.toUpperCase().startsWith("MAILTO:")) { address = address.substring(7); } serviceMap.put("address", address); Map<String, Object> result = invokeService("findPartyFromEmailAddress", serviceMap, context); partyId = (String) result.get("partyId"); if (partyId == null) { continue; } replaceParameter(property.getParameters(), toXParameter(partyIdXParamName, partyId)); } serviceMap.clear(); serviceMap.put("workEffortId", workEffortId); serviceMap.put("partyId", partyId); serviceMap.put("roleTypeId", fromRoleMap.get(property.getName())); Delegator delegator = (Delegator) context.get("delegator"); List<GenericValue> assignments = null; try { assignments = EntityQuery.use(delegator).from("WorkEffortPartyAssignment").where(serviceMap).filterByDate().queryList(); if (assignments.size() == 0) { serviceMap.put("statusId", "PRTYASGN_OFFERED"); serviceMap.put("fromDate", new Timestamp(System.currentTimeMillis())); invokeService("assignPartyToWorkEffort", serviceMap, context); } } catch (GenericEntityException e) { responseProps = ICalWorker.createPartialContentResponse(e.getMessage()); break; } } return responseProps; } protected static ResponseProperties storeWorkEffort(Component component, Map<String, Object> context) throws GenericEntityException, GenericServiceException { PropertyList propertyList = component.getProperties(); String workEffortId = fromXProperty(propertyList, workEffortIdXPropName); Delegator delegator = (Delegator) context.get("delegator"); GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne(); if (workEffort == null) { return ICalWorker.createNotFoundResponse(null); } if (!hasPermission(workEffortId, "UPDATE", context)) { return null; } Map<String, Object> serviceMap = FastMap.newInstance(); serviceMap.put("workEffortId", workEffortId); setWorkEffortServiceMap(component, serviceMap); invokeService("updateWorkEffort", serviceMap, context); return storePartyAssignments(workEffortId, component, context); } protected static ResponseProperties toCalendarComponent(ComponentList components, GenericValue workEffort, Map<String, Object> context) throws GenericEntityException { Delegator delegator = workEffort.getDelegator(); String workEffortId = workEffort.getString("workEffortId"); String workEffortUid = workEffort.getString("universalId"); String workEffortTypeId = workEffort.getString("workEffortTypeId"); GenericValue typeValue = EntityQuery.use(delegator).from("WorkEffortType").where("workEffortTypeId", workEffortTypeId).cache().queryOne(); boolean isTask = false; boolean newComponent = true; ComponentList resultList = null; ComponentList alarms = null; Component result = null; if ("TASK".equals(workEffortTypeId) || (typeValue != null && "TASK".equals(typeValue.get("parentTypeId")))) { isTask = true; resultList = components.getComponents("VTODO"); } else if ("EVENT".equals(workEffortTypeId) || (typeValue != null && "EVENT".equals(typeValue.get("parentTypeId")))) { resultList = components.getComponents("VEVENT"); } else { return null; } Iterator<Component> i = UtilGenerics.cast(resultList.iterator()); while (i.hasNext()) { result = i.next(); Property xProperty = result.getProperty(workEffortIdXPropName); if (xProperty != null && workEffortId.equals(xProperty.getValue())) { newComponent = false; break; } Property uid = result.getProperty(Uid.UID); if (uid != null && uid.getValue().equals(workEffortUid)) { newComponent = false; break; } } if (isTask) { VToDo toDo = null; if (newComponent) { toDo = new VToDo(); result = toDo; } else { toDo = (VToDo) result; } alarms = toDo.getAlarms(); } else { VEvent event = null; if (newComponent) { event = new VEvent(); result = event; } else { event = (VEvent) result; } alarms = event.getAlarms(); } if (newComponent) { components.add(result); } PropertyList componentProps = result.getProperties(); loadWorkEffort(componentProps, workEffort); if (isTask) { replaceProperty(componentProps, toCompleted(workEffort.getTimestamp("actualCompletionDate"))); replaceProperty(componentProps, toPercentComplete(workEffort.getLong("percentComplete"))); } else { replaceProperty(componentProps, toDtEnd(workEffort.getTimestamp("estimatedCompletionDate"))); } if (workEffort.get("estimatedCompletionDate") == null) { replaceProperty(componentProps, toDuration(workEffort.getDouble("estimatedMilliSeconds"))); } List<GenericValue> relatedParties = EntityQuery.use(delegator).from("WorkEffortPartyAssignView").where("workEffortId", workEffortId).cache(true).filterByDate().queryList(); if (relatedParties.size() > 0) { loadRelatedParties(relatedParties, componentProps, context); } if (newComponent) { if (UtilValidate.isNotEmpty(workEffort.getString("tempExprId"))) { TemporalExpression tempExpr = TemporalExpressionWorker.getTemporalExpression(delegator, workEffort.getString("tempExprId")); if (tempExpr != null) { try { ICalRecurConverter.convert(tempExpr, componentProps); } catch (Exception e) { replaceProperty(componentProps, new Description("Error while converting recurrence: " + e)); } } } getAlarms(workEffort, alarms); } if (Debug.verboseOn()) { try { result.validate(true); Debug.logVerbose("iCalendar component passes validation", module); } catch (ValidationException e) { Debug.logVerbose(e, "iCalendar component fails validation: ", module); } } return null; } protected static Clazz toClazz(String javaObj) { if (javaObj == null) { return null; } return new Clazz(javaObj.replace("WES_", "")); } protected static Completed toCompleted(Timestamp javaObj) { if (javaObj == null) { return null; } return new Completed(new DateTime(javaObj)); } protected static Created toCreated(Timestamp javaObj) { if (javaObj == null) { return null; } return new Created(new DateTime(javaObj)); } protected static Description toDescription(String javaObj) { if (javaObj == null) { return null; } return new Description(javaObj); } protected static DtEnd toDtEnd(Timestamp javaObj) { if (javaObj == null) { return null; } return new DtEnd(new DateTime(javaObj)); } protected static DtStart toDtStart(Timestamp javaObj) { if (javaObj == null) { return null; } return new DtStart(new DateTime(javaObj)); } protected static Duration toDuration(Double javaObj) { if (javaObj == null) { return null; } TimeDuration duration = TimeDuration.fromNumber(javaObj); return new Duration(new Dur(duration.days(), duration.hours(), duration.minutes(), duration.seconds())); } protected static LastModified toLastModified(Timestamp javaObj) { if (javaObj == null) { return null; } return new LastModified(new DateTime(javaObj)); } protected static Location toLocation(String javaObj) { if (javaObj == null) { return null; } return new Location(javaObj); } protected static PartStat toParticipationStatus(String statusId) { if (statusId == null) { return null; } return toPartStatusMap.get(statusId); } protected static PercentComplete toPercentComplete(Long javaObj) { if (javaObj == null) { return null; } return new PercentComplete(javaObj.intValue()); } protected static Priority toPriority(Long javaObj) { if (javaObj == null) { return null; } return new Priority(javaObj.intValue()); } protected static Status toStatus(String javaObj) { if (javaObj == null) { return null; } return toStatusMap.get(javaObj); } protected static Summary toSummary(String javaObj) { if (javaObj == null) { return null; } return new Summary(javaObj); } protected static Uid toUid(String javaObj) { if (javaObj == null) { return null; } return new Uid(uidPrefix.concat(javaObj)); } protected static XParameter toXParameter(String name, String value) { if (name == null || value == null) { return null; } return new XParameter(name, value); } protected static XProperty toXProperty(String name, String value) { if (name == null || value == null) { return null; } return new XProperty(name, value); } }
/* * 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.cassandra.db; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.TreeSet; import com.google.common.collect.Lists; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.cache.RowCacheKey; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.Schema; import org.apache.cassandra.db.rows.*; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.filter.ColumnFilter; import org.apache.cassandra.db.marshal.IntegerType; import org.apache.cassandra.db.partitions.CachedPartition; import org.apache.cassandra.dht.Bounds; import org.apache.cassandra.dht.Token; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.dht.ByteOrderedPartitioner.BytesToken; import org.apache.cassandra.locator.TokenMetadata; import org.apache.cassandra.metrics.ClearableHistogram; import org.apache.cassandra.schema.CachingParams; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.service.CacheService; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.ByteBufferUtil; import static org.junit.Assert.*; public class RowCacheTest { private static final String KEYSPACE_CACHED = "RowCacheTest"; private static final String CF_CACHED = "CachedCF"; private static final String CF_CACHEDINT = "CachedIntCF"; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.prepareServer(); SchemaLoader.createKeyspace(KEYSPACE_CACHED, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE_CACHED, CF_CACHED).caching(CachingParams.CACHE_EVERYTHING), SchemaLoader.standardCFMD(KEYSPACE_CACHED, CF_CACHEDINT, 1, IntegerType.instance) .caching(new CachingParams(true, 100))); } @AfterClass public static void cleanup() { SchemaLoader.cleanupSavedCaches(); } @Test public void testRoundTrip() throws Exception { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE_CACHED); String cf = "CachedIntCF"; ColumnFamilyStore cachedStore = keyspace.getColumnFamilyStore(cf); long startRowCacheHits = cachedStore.metric.rowCacheHit.getCount(); long startRowCacheOutOfRange = cachedStore.metric.rowCacheHitOutOfRange.getCount(); // empty the row cache CacheService.instance.invalidateRowCache(); // set global row cache size to 1 MB CacheService.instance.setRowCacheCapacityInMB(1); ByteBuffer key = ByteBufferUtil.bytes("rowcachekey"); DecoratedKey dk = cachedStore.decorateKey(key); RowCacheKey rck = new RowCacheKey(cachedStore.metadata.ksAndCFName, dk); RowUpdateBuilder rub = new RowUpdateBuilder(cachedStore.metadata, System.currentTimeMillis(), key); rub.clustering(String.valueOf(0)); rub.add("val", ByteBufferUtil.bytes("val" + 0)); rub.build().applyUnsafe(); // populate row cache, we should not get a row cache hit; Util.getAll(Util.cmd(cachedStore, dk).withLimit(1).build()); assertEquals(startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); // do another query, limit is 20, which is < 100 that we cache, we should get a hit and it should be in range Util.getAll(Util.cmd(cachedStore, dk).withLimit(1).build()); assertEquals(++startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); assertEquals(startRowCacheOutOfRange, cachedStore.metric.rowCacheHitOutOfRange.getCount()); CachedPartition cachedCf = (CachedPartition)CacheService.instance.rowCache.get(rck); assertEquals(1, cachedCf.rowCount()); for (Unfiltered unfiltered : Util.once(cachedCf.unfilteredIterator(ColumnFilter.selection(cachedCf.columns()), Slices.ALL, false))) { Row r = (Row) unfiltered; for (ColumnData c : r) { assertEquals(((Cell)c).value(), ByteBufferUtil.bytes("val" + 0)); } } cachedStore.truncateBlocking(); } @Test public void testRowCache() throws Exception { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE_CACHED); ColumnFamilyStore cachedStore = keyspace.getColumnFamilyStore(CF_CACHED); // empty the row cache CacheService.instance.invalidateRowCache(); // set global row cache size to 1 MB CacheService.instance.setRowCacheCapacityInMB(1); // inserting 100 rows into both column families SchemaLoader.insertData(KEYSPACE_CACHED, CF_CACHED, 0, 100); // now reading rows one by one and checking if row change grows for (int i = 0; i < 100; i++) { DecoratedKey key = Util.dk("key" + i); Util.getAll(Util.cmd(cachedStore, key).build()); assert CacheService.instance.rowCache.size() == i + 1; assert cachedStore.containsCachedParition(key); // current key should be stored in the cache // checking if cell is read correctly after cache CachedPartition cp = cachedStore.getRawCachedPartition(key); try (UnfilteredRowIterator ai = cp.unfilteredIterator(ColumnFilter.selection(cp.columns()), Slices.ALL, false)) { assert ai.hasNext(); Row r = (Row)ai.next(); assertFalse(ai.hasNext()); Iterator<Cell> ci = r.cells().iterator(); assert(ci.hasNext()); Cell cell = ci.next(); assert cell.column().name.bytes.equals(ByteBufferUtil.bytes("val")); assert cell.value().equals(ByteBufferUtil.bytes("val" + i)); } } // insert 10 more keys SchemaLoader.insertData(KEYSPACE_CACHED, CF_CACHED, 100, 10); for (int i = 100; i < 110; i++) { DecoratedKey key = Util.dk("key" + i); Util.getAll(Util.cmd(cachedStore, key).build()); assert cachedStore.containsCachedParition(key); // cache should be populated with the latest rows read (old ones should be popped) // checking if cell is read correctly after cache CachedPartition cp = cachedStore.getRawCachedPartition(key); try (UnfilteredRowIterator ai = cp.unfilteredIterator(ColumnFilter.selection(cp.columns()), Slices.ALL, false)) { assert ai.hasNext(); Row r = (Row)ai.next(); assertFalse(ai.hasNext()); Iterator<Cell> ci = r.cells().iterator(); assert(ci.hasNext()); Cell cell = ci.next(); assert cell.column().name.bytes.equals(ByteBufferUtil.bytes("val")); assert cell.value().equals(ByteBufferUtil.bytes("val" + i)); } } // clear 100 rows from the cache int keysLeft = 109; for (int i = 109; i >= 10; i--) { cachedStore.invalidateCachedPartition(Util.dk("key" + i)); assert CacheService.instance.rowCache.size() == keysLeft; keysLeft--; } CacheService.instance.setRowCacheCapacityInMB(0); } @Test public void testRowCacheLoad() throws Exception { CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, Integer.MAX_VALUE, 0); CacheService.instance.setRowCacheCapacityInMB(0); } @Test public void testRowCacheCleanup() throws Exception { StorageService.instance.initServer(0); CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, Integer.MAX_VALUE, 1000); ColumnFamilyStore store = Keyspace.open(KEYSPACE_CACHED).getColumnFamilyStore(CF_CACHED); assertEquals(CacheService.instance.rowCache.size(), 100); store.cleanupCache(); assertEquals(CacheService.instance.rowCache.size(), 100); TokenMetadata tmd = StorageService.instance.getTokenMetadata(); byte[] tk1, tk2; tk1 = "key1000".getBytes(); tk2 = "key1050".getBytes(); tmd.updateNormalToken(new BytesToken(tk1), InetAddress.getByName("127.0.0.1")); tmd.updateNormalToken(new BytesToken(tk2), InetAddress.getByName("127.0.0.2")); store.cleanupCache(); assertEquals(50, CacheService.instance.rowCache.size()); CacheService.instance.setRowCacheCapacityInMB(0); } @Test public void testInvalidateRowCache() throws Exception { StorageService.instance.initServer(0); CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, Integer.MAX_VALUE, 1000); ColumnFamilyStore store = Keyspace.open(KEYSPACE_CACHED).getColumnFamilyStore(CF_CACHED); assertEquals(CacheService.instance.rowCache.size(), 100); //construct 5 bounds of 20 elements each ArrayList<Bounds<Token>> subranges = getBounds(20); //invalidate 3 of the 5 bounds ArrayList<Bounds<Token>> boundsToInvalidate = Lists.newArrayList(subranges.get(0), subranges.get(2), subranges.get(4)); int invalidatedKeys = store.invalidateRowCache(boundsToInvalidate); assertEquals(60, invalidatedKeys); //now there should be only 40 cached entries left assertEquals(CacheService.instance.rowCache.size(), 40); CacheService.instance.setRowCacheCapacityInMB(0); } private ArrayList<Bounds<Token>> getBounds(int nElements) { ColumnFamilyStore store = Keyspace.open(KEYSPACE_CACHED).getColumnFamilyStore(CF_CACHED); TreeSet<DecoratedKey> orderedKeys = new TreeSet<>(); for(Iterator<RowCacheKey> it = CacheService.instance.rowCache.keyIterator();it.hasNext();) orderedKeys.add(store.decorateKey(ByteBuffer.wrap(it.next().key))); ArrayList<Bounds<Token>> boundsToInvalidate = new ArrayList<>(); Iterator<DecoratedKey> iterator = orderedKeys.iterator(); while (iterator.hasNext()) { Token startRange = iterator.next().getToken(); for (int i = 0; i < nElements-2; i++) iterator.next(); Token endRange = iterator.next().getToken(); boundsToInvalidate.add(new Bounds<>(startRange, endRange)); } return boundsToInvalidate; } @Test public void testRowCachePartialLoad() throws Exception { CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, 50, 0); CacheService.instance.setRowCacheCapacityInMB(0); } @Test public void testRowCacheDropSaveLoad() throws Exception { CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, 50, 0); CacheService.instance.rowCache.submitWrite(Integer.MAX_VALUE).get(); Keyspace instance = Schema.instance.removeKeyspaceInstance(KEYSPACE_CACHED); try { CacheService.instance.rowCache.size(); CacheService.instance.rowCache.clear(); CacheService.instance.rowCache.loadSaved(); int after = CacheService.instance.rowCache.size(); assertEquals(0, after); } finally { Schema.instance.storeKeyspaceInstance(instance); } } @Test public void testRowCacheDisabled() throws Exception { CacheService.instance.setRowCacheCapacityInMB(1); rowCacheLoad(100, 50, 0); CacheService.instance.rowCache.submitWrite(Integer.MAX_VALUE).get(); CacheService.instance.setRowCacheCapacityInMB(0); CacheService.instance.rowCache.size(); CacheService.instance.rowCache.clear(); CacheService.instance.rowCache.loadSaved(); int after = CacheService.instance.rowCache.size(); assertEquals(0, after); } @Test public void testRowCacheRange() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE_CACHED); String cf = "CachedIntCF"; ColumnFamilyStore cachedStore = keyspace.getColumnFamilyStore(cf); long startRowCacheHits = cachedStore.metric.rowCacheHit.getCount(); long startRowCacheOutOfRange = cachedStore.metric.rowCacheHitOutOfRange.getCount(); // empty the row cache CacheService.instance.invalidateRowCache(); // set global row cache size to 1 MB CacheService.instance.setRowCacheCapacityInMB(1); ByteBuffer key = ByteBufferUtil.bytes("rowcachekey"); DecoratedKey dk = cachedStore.decorateKey(key); RowCacheKey rck = new RowCacheKey(cachedStore.metadata.ksAndCFName, dk); String values[] = new String[200]; for (int i = 0; i < 200; i++) { RowUpdateBuilder rub = new RowUpdateBuilder(cachedStore.metadata, System.currentTimeMillis(), key); rub.clustering(String.valueOf(i)); values[i] = "val" + i; rub.add("val", ByteBufferUtil.bytes(values[i])); rub.build().applyUnsafe(); } Arrays.sort(values); // populate row cache, we should not get a row cache hit; Util.getAll(Util.cmd(cachedStore, dk).withLimit(10).build()); assertEquals(startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); // do another query, limit is 20, which is < 100 that we cache, we should get a hit and it should be in range Util.getAll(Util.cmd(cachedStore, dk).withLimit(10).build()); assertEquals(++startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); assertEquals(startRowCacheOutOfRange, cachedStore.metric.rowCacheHitOutOfRange.getCount()); // get a slice from 95 to 105, 95->99 are in cache, we should not get a hit and then row cache is out of range Util.getAll(Util.cmd(cachedStore, dk).fromIncl(String.valueOf(210)).toExcl(String.valueOf(215)).build()); assertEquals(startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); assertEquals(++startRowCacheOutOfRange, cachedStore.metric.rowCacheHitOutOfRange.getCount()); // get a slice with limit > 100, we should get a hit out of range. Util.getAll(Util.cmd(cachedStore, dk).withLimit(101).build()); assertEquals(startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); assertEquals(++startRowCacheOutOfRange, cachedStore.metric.rowCacheHitOutOfRange.getCount()); CacheService.instance.invalidateRowCache(); // try to populate row cache with a limit > rows to cache, we should still populate row cache; Util.getAll(Util.cmd(cachedStore, dk).withLimit(105).build()); assertEquals(startRowCacheHits, cachedStore.metric.rowCacheHit.getCount()); // validate the stuff in cache; CachedPartition cachedCf = (CachedPartition)CacheService.instance.rowCache.get(rck); assertEquals(cachedCf.rowCount(), 100); int i = 0; for (Unfiltered unfiltered : Util.once(cachedCf.unfilteredIterator(ColumnFilter.selection(cachedCf.columns()), Slices.ALL, false))) { Row r = (Row) unfiltered; assertEquals(r.clustering().get(0), ByteBufferUtil.bytes(values[i].substring(3))); for (ColumnData c : r) { assertEquals(((Cell)c).value(), ByteBufferUtil.bytes(values[i])); } i++; } cachedStore.truncateBlocking(); } @Test public void testSSTablesPerReadHistogramWhenRowCache() { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE_CACHED); ColumnFamilyStore cachedStore = keyspace.getColumnFamilyStore(CF_CACHED); // empty the row cache CacheService.instance.invalidateRowCache(); // set global row cache size to 1 MB CacheService.instance.setRowCacheCapacityInMB(1); // inserting 100 rows into both column families SchemaLoader.insertData(KEYSPACE_CACHED, CF_CACHED, 0, 100); //force flush for confidence that SSTables exists cachedStore.forceBlockingFlush(); ((ClearableHistogram)cachedStore.metric.sstablesPerReadHistogram.cf).clear(); for (int i = 0; i < 100; i++) { DecoratedKey key = Util.dk("key" + i); Util.getAll(Util.cmd(cachedStore, key).build()); long count_before = cachedStore.metric.sstablesPerReadHistogram.cf.getCount(); Util.getAll(Util.cmd(cachedStore, key).build()); // check that SSTablePerReadHistogram has been updated by zero, // so count has been increased and in a 1/2 of requests there were zero read SSTables long count_after = cachedStore.metric.sstablesPerReadHistogram.cf.getCount(); double belowMedian = cachedStore.metric.sstablesPerReadHistogram.cf.getSnapshot().getValue(0.49D); double mean_after = cachedStore.metric.sstablesPerReadHistogram.cf.getSnapshot().getMean(); assertEquals("SSTablePerReadHistogram should be updated even key found in row cache", count_before + 1, count_after); assertTrue("In half of requests we have not touched SSTables, " + "so 49 percentile (" + belowMedian + ") must be strongly less than 0.9", belowMedian < 0.9D); assertTrue("In half of requests we have not touched SSTables, " + "so mean value (" + mean_after + ") must be strongly less than 1, but greater than 0", mean_after < 0.999D && mean_after > 0.001D); } assertEquals("Min value of SSTablesPerRead should be zero", 0, cachedStore.metric.sstablesPerReadHistogram.cf.getSnapshot().getMin()); CacheService.instance.setRowCacheCapacityInMB(0); } public void rowCacheLoad(int totalKeys, int keysToSave, int offset) throws Exception { CompactionManager.instance.disableAutoCompaction(); ColumnFamilyStore store = Keyspace.open(KEYSPACE_CACHED).getColumnFamilyStore(CF_CACHED); // empty the cache CacheService.instance.invalidateRowCache(); assertEquals(0, CacheService.instance.rowCache.size()); // insert data and fill the cache SchemaLoader.insertData(KEYSPACE_CACHED, CF_CACHED, offset, totalKeys); readData(KEYSPACE_CACHED, CF_CACHED, offset, totalKeys); assertEquals(totalKeys, CacheService.instance.rowCache.size()); // force the cache to disk CacheService.instance.rowCache.submitWrite(keysToSave).get(); // empty the cache again to make sure values came from disk CacheService.instance.invalidateRowCache(); assertEquals(0, CacheService.instance.rowCache.size()); assertEquals(keysToSave == Integer.MAX_VALUE ? totalKeys : keysToSave, CacheService.instance.rowCache.loadSaved()); } private static void readData(String keyspace, String columnFamily, int offset, int numberOfRows) { ColumnFamilyStore store = Keyspace.open(keyspace).getColumnFamilyStore(columnFamily); CFMetaData cfm = Schema.instance.getCFMetaData(keyspace, columnFamily); for (int i = offset; i < offset + numberOfRows; i++) { DecoratedKey key = Util.dk("key" + i); Clustering cl = Clustering.make(ByteBufferUtil.bytes("col" + i)); Util.getAll(Util.cmd(store, key).build()); } } }
/* * The MIT License (MIT) Copyright (c) 2014 Hayda Almeida Marie-Jean Meurs Concordia University Tsang Lab Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package triage.analyse; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import triage.filter.NaiveFilter; import triage.configure.ConfigConstants; /** * This class extracts and parses n-grams * from XML doc instances. * * @author Hayda Almeida * @since 2014 * */ public class NgramExtractor extends Extractor{ public NgramExtractor(){ //defining relevant paper text fields this.id = "PMID"; this.openJournal = "Title"; this.openAbst = "AbstractText"; this.openEC = "RegistryNumber"; this.classTag = "TRIAGE"; this.openTitle = "ArticleTitle"; } public static void main(String[] args) { ConfigConstants pathVars = new ConfigConstants(); boolean verbose = false; String AnCorpus = pathVars.HOME_DIR + pathVars.CORPUS_DIR + "L" + pathVars.TARGET_LEVEL + "/" + pathVars.TRAINING_FILE; NgramExtractor nextrac = new NgramExtractor(); NaiveFilter featFilter = new NaiveFilter(); File featureDir = new File(pathVars.HOME_DIR + pathVars.FEATURE_DIR + "/"); featFilter.loadStopWords(pathVars.HOME_DIR + pathVars.STOP_LIST); //store abstract ngrams and its count HashMap<String,Integer> ngram_count = new HashMap<String,Integer>(); //store abstract ngrams, count and "relevance(TBD)" HashMap<Map<String,String>,Integer> ngrams = new HashMap<Map<String,String>,Integer>(); //store title ngrams and its count HashMap<String,Integer> ngram_title_count = new HashMap<String,Integer>(); //store title ngrams, count and "relevance(TBD)" HashMap<Map<String,String>,Integer> ngram_title = new HashMap<Map<String,String>,Integer>(); //store ID and label of documents HashMap<String,String> PMIDs = new HashMap<String,String>(); nextrac.initialize(featureDir, pathVars); try { //Loading file File input = new File(AnCorpus); //Jsoup parse Document doc = Jsoup.parse(input, "UTF-8"); Elements corpus = doc.body().getElementsByTag("pubmedarticle"); //Fetching elements for(Element paper : corpus ){ //Fetching elements Elements journalTitle = paper.getElementsByTag(nextrac.getOpenJournal()); Elements title = paper.getElementsByTag(nextrac.getOpenTitle()); Elements abstractC = paper.getElementsByTag(nextrac.getopenAbst()); Elements ECnumber = paper.getElementsByTag(nextrac.getOpenEC()); Elements classDoc = paper.getElementsByTag(nextrac.getClassTag()); String journal = ""; String docID = ""; String label = ""; int jTitle = 0; //fetching the paper ID - //for all items in a paper, retrieve only PMIDs for(Element e : paper.select(nextrac.getId())){ //only consider the ID if the parent is medline citation if(e.parentNode().nodeName().contains("medline")){ docID = e.text(); } } //fetch the doc label as well if(classDoc.hasText()){ label = classDoc.text(); } PMIDs.put(docID, label); //Extracting the Journal Title if(journalTitle.hasText()){ jTitle++; journal = journalTitle.toString(); journal = nextrac.removeSpecialChar(journal); journal = nextrac.removeTags(journal); } String tit_content = ""; //Extracting the Paper Title if(title.hasText()){ tit_content = title.toString(); tit_content = nextrac.removeSpecialChar(tit_content); tit_content = nextrac.removeTags(tit_content); ArrayList<String> title_c = nextrac.nGrams(tit_content, featFilter, pathVars); nextrac.addNGram(title_c, ngram_title_count, pathVars); } String abstrac = ""; //Extracting the Paper abstract if(abstractC.hasText()){ abstrac = abstractC.toString(); abstrac = nextrac.removeSpecialChar(abstrac); abstrac = nextrac.removeAbstractTags(abstrac); ArrayList<String> abstract_c = nextrac.nGrams(abstrac, featFilter, pathVars); nextrac.addNGram(abstract_c, ngram_count, pathVars); } } }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(verbose){ //print list of extracted n-grams nextrac.displayList(PMIDs); System.out.println("\n========ABSTRACT==NGRAMS============="); nextrac.displayList(ngram_count); nextrac.displayList(ngram_title); System.out.println("\n===========TITLE==NGRAMS============="); nextrac.displayList(ngram_title_count); } //filter features by occurrence featFilter.considerOccurence(ngram_count, pathVars); featFilter.considerOccurence(ngram_title_count, pathVars); System.out.println("\n===========NGRAMS==EXPORT===============\n"); nextrac.exportFile(featureDir + "/" + pathVars.DOC_IDS, PMIDs); System.out.println("..."+ PMIDs.size()+" document IDs listed."); nextrac.exportFile(featureDir + "/" + pathVars.NGRAM_FEATURES, ngram_count); System.out.println("..."+ ngram_count.size()+" unique Abstract ngrams saved."); nextrac.exportFile(featureDir + "/" + pathVars.TITLE_NGRAMS, ngram_title_count); System.out.println("... "+ ngram_title_count.size() +" unique Title ngrams saved."); System.out.println("\n========================================\n"); } /** * Inserts ngrams into list of features * with a mapping for ngram count * @param str relation of ngrams extracted * @param list_count mapping for ngram counts * @param pathVars */ private void addNGram(ArrayList<String> str, HashMap<String,Integer> list_count, ConfigConstants pathVars){ //iterating over ngram list for(int i = 0; i < str.size(); i++){ String currentNGram = str.get(i); //checking existence of current ngram on list mapping if(list_count.containsKey(currentNGram)){ //retrieve the amount of current ngrams on mapping int count = list_count.get(currentNGram); //insert the updated count of ngrams list_count.put(currentNGram, count+1); } else { //insert ngram on mapping list if(currentNGram.length() >= Integer.parseInt(pathVars.FEATURE_MIN_LENGTH)){ list_count.put(currentNGram, 1); } } } } /** * Extracts n-grams from a given content field * * @param str text to extract ngrams * @return list of extracted grams */ public ArrayList<String> nGrams(String str, NaiveFilter filter, ConfigConstants pathVar){ //removing ASCII special characters str = str.replace("/", ""); str = str.replace("\\", ""); str = str.replace(" ", "-"); str = str.replaceAll("\\s+"," "); str = str.replace(" ", "-"); //Tokenizing the sentence String[] words = StringUtils.split(str,"-"); ArrayList<String> ngramList = new ArrayList<String>(); int ngram =Integer.parseInt(pathVar.NGRAM_SIZE); //Stop-words removal if(Boolean.valueOf(pathVar.NGRAM_STOP)){ words = StringUtils.split(filter.removeStopList(words)," "); } //extracting ngrams according to gram size (1, 2, 3) for(int i=0; i < words.length - (ngram - 1); i++){ switch(pathVar.NGRAM_SIZE){ case "1": ngramList.add(words[i].toLowerCase()); break; case "2": ngramList.add(words[i].toLowerCase()+" "+words[i+1].toLowerCase()); break; case "3": ngramList.add(words[i].toLowerCase()+" "+words[i+1].toLowerCase()+" "+words[i+2].toLowerCase()); break; } } return ngramList; } @Override public void initialize(File featureDir, ConfigConstants pathVars){ try{ featureDir.mkdir(); File ngrams = new File(featureDir + "/" + pathVars.NGRAM_FEATURES); ngrams.createNewFile(); File titlengrams = new File(featureDir + "/" + pathVars.TITLE_NGRAMS); titlengrams.createNewFile(); }catch(Exception e){ System.out.println("Error creating features folder."); System.exit(0); } } /** * Displays the keys and values of the * maps created with n-grams and counts. * @param hash HashMap containing n-grams */ @Override public void displayList(HashMap hash){ super.displayList(hash); //sum = sum + hash.get(str); System.out.println("\n=======================================\n"); System.out.println("Number of unique n-grams: "+hash.size()); System.out.println("\n=======================================\n"); } }
/** * Copyright 2007-2016, Kaazing Corporation. 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 org.kaazing.gateway.transport.http.connector.specification.rfc7232; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertTrue; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.session.IoSessionInitializer; import org.jmock.Expectations; import org.jmock.api.Invocation; import org.jmock.integration.junit4.JUnitRuleMockery; import org.jmock.lib.action.CustomAction; import org.jmock.lib.concurrent.Synchroniser; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.kaazing.gateway.transport.http.HttpConnectSession; import org.kaazing.gateway.transport.http.HttpConnectorRule; import org.kaazing.gateway.transport.http.HttpHeaders; import org.kaazing.gateway.transport.http.HttpMethod; import org.kaazing.k3po.junit.annotation.Specification; import org.kaazing.k3po.junit.rules.K3poRule; import org.kaazing.mina.core.session.IoSessionEx; import org.kaazing.test.util.ITUtil; import org.kaazing.test.util.MethodExecutionTrace; public class ValidatorsIT { private final HttpConnectorRule connector = new HttpConnectorRule(); private JUnitRuleMockery context = new JUnitRuleMockery() { { setThreadingPolicy(new Synchroniser()); } }; private final TestRule trace = new MethodExecutionTrace(); private TestRule contextRule = ITUtil.toTestRule(context); private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/http/rfc7232/validators"); private final TestRule timeoutRule = new DisableOnDebug(new Timeout(5, SECONDS)); @Rule public TestRule chain = RuleChain.outerRule(trace).around(timeoutRule).around(contextRule).around(connector).around(k3po); @Test @Specification({"last.modified.in.get/response"}) public void shouldReceiveLastModifiedInGetResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializer()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.in.head/response"}) public void shouldReceiveLastModifiedInHeadResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerHead()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } private static class ConnectSessionInitializerHead implements IoSessionInitializer<ConnectFuture> { @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setMethod(HttpMethod.HEAD); connectSession.addWriteHeader(HttpHeaders.HEADER_HOST, "localhost:8000"); } } @Test @Specification({"last.modified.in.post/response"}) public void shouldReceiveLastModifiedInPostResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPost()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } private static class ConnectSessionInitializerPost implements IoSessionInitializer<ConnectFuture> { @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setMethod(HttpMethod.POST); connectSession.addWriteHeader(HttpHeaders.HEADER_HOST, "localhost:8000"); connectSession.addWriteHeader(HttpHeaders.HEADER_CONTENT_LENGTH, String.valueOf(7)); ByteBuffer bytes = ByteBuffer.wrap("content".getBytes()); connectSession.write(connectSession.getBufferAllocator().wrap(bytes)); } } @Test @Specification({"last.modified.in.put/response"}) public void shouldReceiveLastModifiedInPutResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPut()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } private static class ConnectSessionInitializerPut implements IoSessionInitializer<ConnectFuture> { @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setMethod(HttpMethod.PUT); connectSession.addWriteHeader(HttpHeaders.HEADER_HOST, "localhost:8000"); connectSession.addWriteHeader(HttpHeaders.HEADER_CONTENT_LENGTH, String.valueOf(7)); ByteBuffer bytes = ByteBuffer.wrap("content".getBytes()); connectSession.write(connectSession.getBufferAllocator().wrap(bytes)); } } @Test @Specification({"last.modified.with.strong.etag.in.get/response"}) public void shouldReceiveLastModifiedAndStrongETagInGetResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializer()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.strong.etag.in.head/response"}) public void shouldReceiveLastModifiedAndStrongETagInHeadResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerHead()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.strong.etag.in.post/response"}) public void shouldReceiveLastModifiedAndStrongETagInPostResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPost()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.strong.etag.in.put/response"}) public void shouldReceiveLastModifiedAndStrongETagInPutResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPut()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.weak.etag.in.get/response"}) public void shouldReceiveLastModifiedAndWeakETagInGetResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializer()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.weak.etag.in.head/response"}) public void shouldReceiveLastModifiedAndWeakETagInHeadResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerHead()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.weak.etag.in.post/response"}) public void shouldReceiveLastModifiedAndWeakETagInPostResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPost()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"last.modified.with.weak.etag.in.put/response"}) public void shouldReceiveLastModifiedAndWeakETagInPutResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPut()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"strong.etag.in.get/response"}) public void shouldReceiveStrongETagInGetResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializer()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"strong.etag.in.head/response"}) public void shouldReceiveStrongETagInHeadResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerHead()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"strong.etag.in.post/response"}) public void shouldReceiveStrongETagInPostResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPost()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"strong.etag.in.put/response"}) public void shouldReceiveStrongETagInPutResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPut()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"weak.etag.in.get/response"}) public void shouldReceiveWeakETagInGetResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializer()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"weak.etag.in.head/response"}) public void shouldReceiveWeakETagInHeadResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerHead()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"weak.etag.in.post/response"}) public void shouldReceiveWeakETagInPostResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPost()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } @Test @Specification({"weak.etag.in.put/response"}) public void shouldReceiveWeakETagInPutResponse() throws Exception { final IoHandler handler = context.mock(IoHandler.class); final CountDownLatch closed = new CountDownLatch(1); context.checking(new Expectations() { { oneOf(handler).sessionCreated(with(any(IoSessionEx.class))); oneOf(handler).sessionOpened(with(any(IoSessionEx.class))); oneOf(handler).sessionClosed(with(any(IoSessionEx.class))); will(new CustomAction("Latch countdown") { @Override public Object invoke(Invocation invocation) throws Throwable { closed.countDown(); return null; } }); } }); connector.connect("http://localhost:8000/index.html/", handler, new ConnectSessionInitializerPut()); assertTrue(closed.await(2, SECONDS)); k3po.finish(); } private static class ConnectSessionInitializer implements IoSessionInitializer<ConnectFuture> { @Override public void initializeSession(IoSession session, ConnectFuture future) { HttpConnectSession connectSession = (HttpConnectSession) session; connectSession.setMethod(HttpMethod.GET); connectSession.addWriteHeader(HttpHeaders.HEADER_HOST, "localhost:8000"); } } }
package org.umlg.sqlg.test.gremlincompile; import org.apache.commons.collections4.set.ListOrderedSet; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.Pop; import org.apache.tinkerpop.gremlin.process.traversal.Scope; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.DefaultGraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; import org.apache.tinkerpop.gremlin.process.traversal.step.util.MapHelper; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.umlg.sqlg.structure.*; import org.umlg.sqlg.test.BaseTest; import java.util.*; import java.util.stream.Collectors; /** * Date: 2015/01/19 * Time: 6:22 AM */ public class TestGremlinCompileWithHas extends BaseTest { @BeforeClass public static void beforeClass() { BaseTest.beforeClass(); if (isPostgres()) { configuration.addProperty("distributed", true); } } @Test public void testMultipleHasWithinUserSuppliedIds() { this.sqlgGraph.getTopology().getPublicSchema().ensureVertexLabelExist( "TestHierarchy", new LinkedHashMap<String, PropertyType>() {{ put("column1", PropertyType.varChar(100)); put("column2", PropertyType.varChar(100)); put("name", PropertyType.STRING); }}, ListOrderedSet.listOrderedSet(Arrays.asList("column1", "column2")) ); this.sqlgGraph.tx().commit(); this.sqlgGraph.addVertex(T.label, "TestHierarchy", "column1", "a1", "column2", "a2", "name", "name1"); this.sqlgGraph.addVertex(T.label, "TestHierarchy", "column1", "b1", "column2", "b2", "name", "name1"); this.sqlgGraph.addVertex(T.label, "TestHierarchy", "column1", "c1", "column2", "c2", "name", "name1"); this.sqlgGraph.addVertex(T.label, "TestHierarchy", "column1", "d1", "column2", "d2", "name", "name1"); this.sqlgGraph.tx().commit(); List<String> values1 = Collections.singletonList(""); List<String> values2 = Collections.singletonList(""); List<Vertex> vertexList = this.sqlgGraph.traversal().V() .hasLabel("TestHierarchy") .has("column1", P.within(values1)) .has("column2", P.within(values2)) .toList(); Assert.assertEquals(0, vertexList.size()); values1 = Arrays.asList("a1", "b1", "c1"); values2 = Arrays.asList("a2", "b2", "c2"); vertexList = this.sqlgGraph.traversal().V() .hasLabel("TestHierarchy") .has("column1", P.within(values1)) .has("column2", P.within(values2)) .toList(); Assert.assertEquals(3, vertexList.size()); values1 = Arrays.asList("a1"); values2 = Arrays.asList("a2", "b2", "c2"); vertexList = this.sqlgGraph.traversal().V() .hasLabel("TestHierarchy") .has("column1", P.within(values1)) .has("column2", P.within(values2)) .toList(); Assert.assertEquals(1, vertexList.size()); } @Test public void testHasPropertyWithLabel() { this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); this.sqlgGraph.addVertex(T.label, "A", "name", "a2"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V().hasLabel("A").has("name").as("a").<Vertex>select("a").toList(); Assert.assertEquals(2, vertices.size()); vertices = this.sqlgGraph.traversal().V().hasLabel("A").hasNot("name").as("a").<Vertex>select("a").toList(); Assert.assertEquals(2, vertices.size()); } @Test public void testHasIdRecompilation() throws InterruptedException { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.tx().commit(); testHasIdRecompilation_assert(this.sqlgGraph, a1); if (this.sqlgGraph1 != null) { Thread.sleep(SLEEP_TIME); testHasIdRecompilation_assert(this.sqlgGraph1, a1); } } private void testHasIdRecompilation_assert(SqlgGraph sqlgGraph, Vertex a1) { DefaultGraphTraversal<Vertex, Vertex> gt1 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(a1.id()); Assert.assertEquals(1, gt1.getSteps().size()); DefaultGraphTraversal<Vertex, Vertex> gt2 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V().hasId(a1.id()); Assert.assertEquals(2, gt2.getSteps().size()); List<Vertex> vertices1 = gt1.toList(); Assert.assertEquals(1, gt1.getSteps().size()); Assert.assertEquals(1, vertices1.size()); Assert.assertEquals(a1, vertices1.get(0)); List<Vertex> vertices2 = gt2.toList(); Assert.assertEquals(1, gt2.getSteps().size()); Assert.assertEquals(1, vertices2.size()); Assert.assertEquals(a1, vertices2.get(0)); Assert.assertEquals(gt1, gt2); } @Test public void testHasIdIn() throws InterruptedException { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b4 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c3 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c4 = this.sqlgGraph.addVertex(T.label, "C"); b1.addEdge("ab", a1); b2.addEdge("ab", a1); b3.addEdge("ab", a1); b4.addEdge("ab", a1); c1.addEdge("ac", a1); c2.addEdge("ac", a1); c3.addEdge("ac", a1); c4.addEdge("ac", a1); this.sqlgGraph.tx().commit(); testHasIdIn_assert(this.sqlgGraph); if (this.sqlgGraph1 != null) { Thread.sleep(SLEEP_TIME); testHasIdIn_assert(this.sqlgGraph1); } } private void testHasIdIn_assert(SqlgGraph sqlgGraph) { long start = sqlgGraph.getSqlDialect().getPrimaryKeyStartValue(); RecordId recordIda1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start); RecordId recordIda2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 1L); RecordId recordIda3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 3L); RecordId recordIdb1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start); RecordId recordIdb2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 1L); RecordId recordIdb3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 3L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start); RecordId recordIdc2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 1L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 3L); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).hasLabel("A"); Assert.assertEquals(2, traversal.getSteps().size()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).has(T.id, P.within(recordIda2, recordIdb1)); Assert.assertEquals(2, traversal1.getSteps().size()); vertices = traversal1.toList(); Assert.assertEquals(1, traversal1.getSteps().size()); Assert.assertEquals(0, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal2 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V().has(T.id, P.within(recordIda1, recordIda2, recordIdb1)); Assert.assertEquals(2, traversal2.getSteps().size()); vertices = traversal2.toList(); Assert.assertEquals(1, traversal2.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3, recordIdb1); Assert.assertEquals(1, traversal3.getSteps().size()); vertices = traversal3.toList(); Assert.assertEquals(1, traversal3.getSteps().size()); Assert.assertEquals(4, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal4 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V().has(T.id, P.within(recordIda1)); Assert.assertEquals(2, traversal4.getSteps().size()); vertices = traversal4.toList(); Assert.assertEquals(1, traversal4.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal5 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1); Assert.assertEquals(3, traversal5.getSteps().size()); vertices = traversal5.toList(); Assert.assertEquals(1, traversal5.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal6 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3).in().hasId(recordIdb1, recordIdb2, recordIdb3); Assert.assertEquals(3, traversal6.getSteps().size()); vertices = traversal6.toList(); Assert.assertEquals(1, traversal6.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal7 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIda1); Assert.assertEquals(3, traversal7.getSteps().size()); vertices = traversal7.toList(); Assert.assertEquals(1, traversal7.getSteps().size()); Assert.assertEquals(0, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal8 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1); Assert.assertEquals(3, traversal8.getSteps().size()); vertices = traversal8.toList(); Assert.assertEquals(1, traversal8.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal9 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1, recordIdb2); Assert.assertEquals(3, traversal9.getSteps().size()); vertices = traversal9.toList(); Assert.assertEquals(1, traversal9.getSteps().size()); Assert.assertEquals(2, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal10 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1.toString()); Assert.assertEquals(3, traversal10.getSteps().size()); vertices = traversal10.toList(); Assert.assertEquals(1, traversal10.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal11 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1.toString(), recordIdb2.toString()); Assert.assertEquals(3, traversal11.getSteps().size()); vertices = traversal11.toList(); Assert.assertEquals(1, traversal11.getSteps().size()); Assert.assertEquals(2, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal12 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).in().hasId(recordIdb1.toString(), recordIdc2.toString()); Assert.assertEquals(3, traversal12.getSteps().size()); vertices = traversal12.toList(); Assert.assertEquals(1, traversal12.getSteps().size()); Assert.assertEquals(2, vertices.size()); } @Test public void testHasIdInJoin() throws InterruptedException { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a3 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a4 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b4 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c3 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c4 = this.sqlgGraph.addVertex(T.label, "C"); Vertex d1 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d2 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d3 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d4 = this.sqlgGraph.addVertex(T.label, "D"); b1.addEdge("ab", a1); b2.addEdge("ab", a2); b3.addEdge("ab", a3); b4.addEdge("ab", a4); c1.addEdge("ac", b1); c1.addEdge("ac", b2); c1.addEdge("ac", b3); c1.addEdge("ac", b4); d1.addEdge("ac", c1); d2.addEdge("ac", c2); d3.addEdge("ac", c3); d4.addEdge("ac", c4); this.sqlgGraph.tx().commit(); testHasIdInJoin_assert(this.sqlgGraph, a1, a2, a3, a4); if (this.sqlgGraph1 != null) { Thread.sleep(SLEEP_TIME); testHasIdInJoin_assert(this.sqlgGraph, a1, a2, a3, a4); } } private void testHasIdInJoin_assert(SqlgGraph sqlgGraph, Vertex a1, Vertex a2, Vertex a3, Vertex a4) { long start = sqlgGraph.getSqlDialect().getPrimaryKeyStartValue(); RecordId recordIda1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start); RecordId recordIda2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 1L); RecordId recordIda3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 2L); RecordId recordIda4 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 3L); RecordId recordIdb1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start); RecordId recordIdb2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 1L); RecordId recordIdb3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 3L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 1L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 3L); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3, recordIda4).in().hasId(recordIdb1, recordIdb2, recordIdb3); Assert.assertEquals(3, traversal.getSteps().size()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1.toString(), recordIda2.toString(), recordIda3.toString(), recordIda4.toString()).in() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal1.getSteps().size()); vertices = traversal1.toList(); Assert.assertEquals(1, traversal1.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal2 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(a1, a2, a3, a4).in() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal2.getSteps().size()); vertices = traversal2.toList(); Assert.assertEquals(1, traversal2.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(a1, a2, a3, a4).in() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal3.getSteps().size()); vertices = traversal3.toList(); Assert.assertEquals(1, traversal3.getSteps().size()); Assert.assertEquals(3, vertices.size()); } @Test public void testHasIdOutJoin() throws InterruptedException { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a3 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a4 = this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b4 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c3 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c4 = this.sqlgGraph.addVertex(T.label, "C"); Vertex d1 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d2 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d3 = this.sqlgGraph.addVertex(T.label, "D"); Vertex d4 = this.sqlgGraph.addVertex(T.label, "D"); a1.addEdge("ab", b1); a2.addEdge("ab", b2); a3.addEdge("ab", b3); a4.addEdge("ab", b4); a1.addEdge("ac", c1); a1.addEdge("ac", c2); a1.addEdge("ac", c3); a1.addEdge("ac", c4); c1.addEdge("ac", d1); c2.addEdge("ac", d2); c3.addEdge("ac", d3); c4.addEdge("ac", d4); this.sqlgGraph.tx().commit(); testHasIdOutJoin_assert(this.sqlgGraph, a1, a2, a3, a4); if (this.sqlgGraph1 != null) { Thread.sleep(SLEEP_TIME); testHasIdOutJoin_assert(this.sqlgGraph1, a1, a2, a3, a4); } } private void testHasIdOutJoin_assert(SqlgGraph sqlgGraph, Vertex a1, Vertex a2, Vertex a3, Vertex a4) { long start = sqlgGraph.getSqlDialect().getPrimaryKeyStartValue(); RecordId recordIda1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start); RecordId recordIda2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 1L); RecordId recordIda3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 2L); RecordId recordIda4 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 3L); RecordId recordIdb1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start); RecordId recordIdb2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 1L); RecordId recordIdb3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 3L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 1L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 3L); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3, recordIda4).out().hasId(recordIdb1, recordIdb2, recordIdb3); Assert.assertEquals(3, traversal.getSteps().size()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1.toString(), recordIda2.toString(), recordIda3.toString(), recordIda4.toString()).out() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal1.getSteps().size()); vertices = traversal1.toList(); Assert.assertEquals(1, traversal1.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal2 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(a1, a2, a3, a4).out() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal2.getSteps().size()); vertices = traversal2.toList(); Assert.assertEquals(1, traversal2.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(a1, a2, a3, a4).out() .hasId(recordIdb1.toString(), recordIdb2.toString(), recordIdb3.toString()); Assert.assertEquals(3, traversal3.getSteps().size()); vertices = traversal3.toList(); Assert.assertEquals(1, traversal3.getSteps().size()); Assert.assertEquals(3, vertices.size()); } @Test public void testHasIdOut() throws InterruptedException { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.addVertex(T.label, "A"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B"); Vertex b4 = this.sqlgGraph.addVertex(T.label, "B"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c2 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c3 = this.sqlgGraph.addVertex(T.label, "C"); Vertex c4 = this.sqlgGraph.addVertex(T.label, "C"); a1.addEdge("ab", b1); a1.addEdge("ab", b2); a1.addEdge("ab", b3); a1.addEdge("ab", b4); a1.addEdge("ac", c1); a1.addEdge("ac", c2); a1.addEdge("ac", c3); a1.addEdge("ac", c4); this.sqlgGraph.tx().commit(); testHasIdOut_assert(this.sqlgGraph); if (this.sqlgGraph1 != null) { Thread.sleep(SLEEP_TIME); testHasIdOut_assert(this.sqlgGraph1); } } private void testHasIdOut_assert(SqlgGraph sqlgGraph) { long start = sqlgGraph.getSqlDialect().getPrimaryKeyStartValue(); RecordId recordIda1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start); RecordId recordIda2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 1L); RecordId recordIda3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "A"), start + 3L); RecordId recordIdb1 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start); RecordId recordIdb2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 1L); RecordId recordIdb3 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "B"), start + 3L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start); RecordId recordIdc2 = RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 1L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 2L); RecordId.from(SchemaTable.of(sqlgGraph.getSqlDialect().getPublicSchema(), "C"), start + 3L); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).hasLabel("A"); Assert.assertEquals(2, traversal.getSteps().size()); List<Vertex> vertices = traversal.toList(); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).has(T.id, P.within(recordIda2, recordIdb1)); Assert.assertEquals(2, traversal1.getSteps().size()); vertices = traversal1.toList(); Assert.assertEquals(1, traversal1.getSteps().size()); Assert.assertEquals(0, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal2 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V().has(T.id, P.within(recordIda1, recordIda2, recordIdb1)); Assert.assertEquals(2, traversal2.getSteps().size()); vertices = traversal2.toList(); Assert.assertEquals(1, traversal2.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3, recordIdb1); Assert.assertEquals(1, traversal3.getSteps().size()); vertices = traversal3.toList(); Assert.assertEquals(1, traversal3.getSteps().size()); Assert.assertEquals(4, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal4 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V().has(T.id, P.within(recordIda1)); Assert.assertEquals(2, traversal4.getSteps().size()); vertices = traversal4.toList(); Assert.assertEquals(1, traversal4.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal5 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1); Assert.assertEquals(3, traversal5.getSteps().size()); vertices = traversal5.toList(); Assert.assertEquals(1, traversal5.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal6 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1, recordIda2, recordIda3).out().hasId(recordIdb1, recordIdb2, recordIdb3); Assert.assertEquals(3, traversal6.getSteps().size()); vertices = traversal6.toList(); Assert.assertEquals(1, traversal6.getSteps().size()); Assert.assertEquals(3, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal7 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIda1); Assert.assertEquals(3, traversal7.getSteps().size()); vertices = traversal7.toList(); Assert.assertEquals(1, traversal7.getSteps().size()); Assert.assertEquals(0, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal8 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1); Assert.assertEquals(3, traversal8.getSteps().size()); vertices = traversal8.toList(); Assert.assertEquals(1, traversal8.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal9 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1, recordIdb2); Assert.assertEquals(3, traversal9.getSteps().size()); vertices = traversal9.toList(); Assert.assertEquals(1, traversal9.getSteps().size()); Assert.assertEquals(2, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal10 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1.toString()); Assert.assertEquals(3, traversal10.getSteps().size()); vertices = traversal10.toList(); Assert.assertEquals(1, traversal10.getSteps().size()); Assert.assertEquals(1, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal11 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1.toString(), recordIdb2.toString()); Assert.assertEquals(3, traversal11.getSteps().size()); vertices = traversal11.toList(); Assert.assertEquals(1, traversal11.getSteps().size()); Assert.assertEquals(2, vertices.size()); DefaultGraphTraversal<Vertex, Vertex> traversal12 = (DefaultGraphTraversal<Vertex, Vertex>) sqlgGraph.traversal().V(recordIda1).out().hasId(recordIdb1.toString(), recordIdc2.toString()); Assert.assertEquals(3, traversal12.getSteps().size()); vertices = traversal12.toList(); Assert.assertEquals(1, traversal12.getSteps().size()); Assert.assertEquals(2, vertices.size()); } @Test public void g_V_asXaX_out_asXbX_selectXa_bX_byXnameX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, Map<String, String>> traversal = (DefaultGraphTraversal<Vertex, Map<String, String>>) g.traversal() .V().as("a").out().aggregate("x").as("b").<String>select("a", "b").by("name"); Assert.assertEquals(4, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(3, traversal.getSteps().size()); final List<Map<String, String>> expected = makeMapList(2, "a", "marko", "b", "lop", "a", "marko", "b", "vadas", "a", "marko", "b", "josh", "a", "josh", "b", "ripple", "a", "josh", "b", "lop", "a", "peter", "b", "lop"); checkResults(expected, traversal); } @Test public void g_VX1AsStringX_out_hasXid_2AsStringX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal().V(convertToVertexId("marko")).out().hasId(convertToVertexId("vadas")); Assert.assertEquals(3, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertThat(traversal.hasNext(), CoreMatchers.is(true)); Assert.assertEquals(convertToVertexId("vadas"), traversal.next().id()); Assert.assertThat(traversal.hasNext(), CoreMatchers.is(false)); } @Test public void g_VX4X_out_asXhereX_hasXlang_javaX_selectXhereX_name() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); Object vertexId = convertToVertexId("josh"); DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) g.traversal().V(vertexId) .out().as("here") .has("lang", "java") .select("here").<String>values("name"); Assert.assertEquals(5, traversal.getSteps().size()); printTraversalForm(traversal); if (traversal.getSteps().size() != 3 && traversal.getSteps().size() != 4) { Assert.fail("expected 3 or 4 found " + traversal.getSteps().size()); } int counter = 0; final Set<String> names = new HashSet<>(); while (traversal.hasNext()) { counter++; names.add(traversal.next()); } Assert.assertEquals(2, counter); Assert.assertEquals(2, names.size()); Assert.assertTrue(names.contains("ripple")); Assert.assertTrue(names.contains("lop")); } @Test public void g_V_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_bothXknowsX_bothXknowsX_asXdX_whereXc__notXeqXaX_orXeqXdXXXX_selectXa_b_c_dX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, Map<String, Object>> traversal = (DefaultGraphTraversal<Vertex, Map<String, Object>>) this.sqlgGraph.traversal() .V().as("a") .out("created").as("b") .in("created").as("c") .both("knows") .both("knows").as("d") .where("c", P.not(P.eq("a").or(P.eq("d")))) .select("a", "b", "c", "d"); Assert.assertEquals(7, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(3, traversal.getSteps().size()); checkResults(makeMapList(4, "a", convertToVertex(this.sqlgGraph, "marko"), "b", convertToVertex(this.sqlgGraph, "lop"), "c", convertToVertex(this.sqlgGraph, "josh"), "d", convertToVertex(this.sqlgGraph, "vadas"), "a", convertToVertex(this.sqlgGraph, "peter"), "b", convertToVertex(this.sqlgGraph, "lop"), "c", convertToVertex(this.sqlgGraph, "josh"), "d", convertToVertex(this.sqlgGraph, "vadas")), traversal); } @SuppressWarnings("unchecked") protected static <T> void checkResults(final List<T> expectedResults, final Traversal<?, T> traversal) { final List<T> results = traversal.toList(); Assert.assertFalse(traversal.hasNext()); if (expectedResults.size() != results.size()) { System.err.println("Expected results: " + expectedResults); System.err.println("Actual results: " + results); Assert.assertEquals("Checking result size", expectedResults.size(), results.size()); } for (T t : results) { if (t instanceof Map) { Assert.assertTrue("Checking map result existence: " + t, expectedResults.stream().filter(e -> e instanceof Map).anyMatch(e -> checkMap((Map) e, (Map) t))); } else { Assert.assertTrue("Checking result existence: " + t, expectedResults.contains(t)); } } final Map<T, Long> expectedResultsCount = new HashMap<>(); final Map<T, Long> resultsCount = new HashMap<>(); Assert.assertEquals("Checking indexing is equivalent", expectedResultsCount.size(), resultsCount.size()); expectedResults.forEach(t -> MapHelper.incr(expectedResultsCount, t, 1L)); results.forEach(t -> MapHelper.incr(resultsCount, t, 1L)); expectedResultsCount.forEach((k, v) -> Assert.assertEquals("Checking result group counts", v, resultsCount.get(k))); Assert.assertFalse(traversal.hasNext()); } @SuppressWarnings("Duplicates") private static <A, B> boolean checkMap(final Map<A, B> expectedMap, final Map<A, B> actualMap) { final List<Map.Entry<A, B>> actualList = actualMap.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey().toString())).collect(Collectors.toList()); final List<Map.Entry<A, B>> expectedList = expectedMap.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey().toString())).collect(Collectors.toList()); if (expectedList.size() > actualList.size()) { return false; } else if (actualList.size() > expectedList.size()) { return false; } for (int i = 0; i < actualList.size(); i++) { if (!actualList.get(i).getKey().equals(expectedList.get(i).getKey())) { return false; } if (!actualList.get(i).getValue().equals(expectedList.get(i).getValue())) { return false; } } return true; } @Test public void g_V_asXaX_out_asXaX_out_asXaX_selectXaX_byXunfold_valuesXnameX_foldX_rangeXlocal_1_2X() { loadModern(); Graph g = this.sqlgGraph; assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) g.traversal() .V().as("a") .out().as("a") .out().as("a") .<List<String>>select(Pop.all, "a") .by(__.unfold().values("name").fold()) .<String>range(Scope.local, 1, 2); Assert.assertEquals(5, traversal.getSteps().size()); int counter = 0; while (traversal.hasNext()) { final String s = traversal.next(); Assert.assertEquals("josh", s); counter++; } Assert.assertEquals(2, counter); Assert.assertEquals(3, traversal.getSteps().size()); } @Test public void g_V_asXaX_out_asXaX_out_asXaX_selectXaX_byXunfold_valuesXnameX_foldX_rangeXlocal_1_2X_Simple() { loadModern(); Graph g = this.sqlgGraph; assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, List<Vertex>> traversal = (DefaultGraphTraversal<Vertex, List<Vertex>>) g.traversal() .V().as("a") .out().as("a") .out().as("a") .<List<Vertex>>select(Pop.all, "a"); Assert.assertEquals(4, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(2, traversal.getSteps().size()); int counter = 0; while (traversal.hasNext()) { final List<Vertex> s = traversal.next(); Assert.assertEquals(3, s.size()); System.out.println(s); counter++; } Assert.assertEquals(2, counter); } @Test public void g_V_hasXinXcreatedX_count_isXgte_2XX_valuesXnameX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) this.sqlgGraph.traversal() .V() .where( __.in("created") .count() .is( P.gte(2L) ) ) .<String>values("name"); Assert.assertEquals(3, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(3, traversal.getSteps().size()); Assert.assertTrue(traversal.hasNext()); Assert.assertEquals("lop", traversal.next()); Assert.assertFalse(traversal.hasNext()); } @Test public void g_VX1X_out_hasXid_2X() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); Object marko = convertToVertexId("marko"); Object vadas = convertToVertexId("vadas"); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal().V(marko).out().hasId(vadas); Assert.assertEquals(3, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertThat(traversal.hasNext(), CoreMatchers.is(true)); Assert.assertEquals(convertToVertexId("vadas"), traversal.next().id()); Assert.assertThat(traversal.hasNext(), CoreMatchers.is(false)); } @Test public void testHasLabelOut() { SqlgVertex a1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "A"); SqlgVertex b1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); a1.addEdge("outB", b1); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) this.sqlgGraph.traversal().V().both().has(T.label, "B"); Assert.assertEquals(3, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); List<Vertex> softwares = traversal.toList(); Assert.assertEquals(1, softwares.size()); for (Vertex software : softwares) { if (!software.label().equals("B")) { Assert.fail("expected label B found " + software.label()); } } } @Test public void testSingleCompileWithHasLabelIn() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a2"); Vertex a3 = this.sqlgGraph.addVertex(T.label, "A", "name", "a3"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); Vertex b4 = this.sqlgGraph.addVertex(T.label, "B", "name", "b4"); Vertex d1 = this.sqlgGraph.addVertex(T.label, "D", "name", "d1"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C", "name", "c1"); a1.addEdge("outB", b1); b1.addEdge("outC", c1); a2.addEdge("outB", b2); b2.addEdge("outC", c1); a3.addEdge("outB", b3); b3.addEdge("outC", c1); d1.addEdge("outB", b4); b4.addEdge("outC", c1); this.sqlgGraph.tx().commit(); Assert.assertEquals(4, vertexTraversal(this.sqlgGraph, c1).in().in().count().next().intValue()); Assert.assertEquals(3, vertexTraversal(this.sqlgGraph, c1).in().in().has(T.label, "A").count().next().intValue()); } @Test public void testOutHasOutHas() { SqlgVertex a1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "A"); SqlgVertex b1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); SqlgVertex b2 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); SqlgVertex b3 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); a1.addEdge("outB", b1); a1.addEdge("outB", b2); a1.addEdge("outB", b3); SqlgVertex c1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c1"); SqlgVertex c2 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c2"); SqlgVertex c3 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c3"); SqlgVertex c4 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c4"); SqlgVertex c5 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c5"); SqlgVertex c6 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c6"); SqlgVertex c7 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c7"); SqlgVertex c8 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c8"); SqlgVertex c9 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c9"); b1.addEdge("outC", c1); b1.addEdge("outC", c2); b1.addEdge("outC", c3); b2.addEdge("outC", c4); b2.addEdge("outC", c5); b2.addEdge("outC", c6); b3.addEdge("outC", c7); b3.addEdge("outC", c8); b3.addEdge("outC", c9); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Long> traversal = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b1").out().has("name", "c1").count(); Assert.assertEquals(6, traversal.getSteps().size()); Assert.assertEquals(1, traversal.next().intValue()); Assert.assertEquals(2, traversal.getSteps().size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b1").out().has("name", "c1"); Assert.assertEquals(5, traversal1.getSteps().size()); Assert.assertEquals(c1, traversal1.next()); Assert.assertEquals(1, traversal1.getSteps().size()); DefaultGraphTraversal<Vertex, Long> traversal2 = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b2").out().has("name", "c5").count(); Assert.assertEquals(6, traversal2.getSteps().size()); Assert.assertEquals(1, traversal2.next().intValue()); Assert.assertEquals(2, traversal2.getSteps().size()); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b2").out().has("name", "c5"); Assert.assertEquals(5, traversal3.getSteps().size()); Assert.assertEquals(c5, traversal3.next()); Assert.assertEquals(1, traversal3.getSteps().size()); } @Test public void testOutHasOutHasNotParsed() { SqlgVertex a1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "A"); SqlgVertex b1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); SqlgVertex b2 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); SqlgVertex b3 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); a1.addEdge("outB", b1); a1.addEdge("outB", b2); a1.addEdge("outB", b3); SqlgVertex c1 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c1"); SqlgVertex c2 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c2"); SqlgVertex c3 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c3"); SqlgVertex c4 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c4"); SqlgVertex c5 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c5"); SqlgVertex c6 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c6"); SqlgVertex c7 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c7"); SqlgVertex c8 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c8"); SqlgVertex c9 = (SqlgVertex) this.sqlgGraph.addVertex(T.label, "C", "name", "c9"); b1.addEdge("outC", c1); b1.addEdge("outC", c2); b1.addEdge("outC", c3); b2.addEdge("outC", c4); b2.addEdge("outC", c5); b2.addEdge("outC", c6); b3.addEdge("outC", c7); b3.addEdge("outC", c8); b3.addEdge("outC", c9); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Long> traversal = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b1").out().has("name", "c1").count(); Assert.assertEquals(6, traversal.getSteps().size()); Assert.assertEquals(1, traversal.next().intValue()); Assert.assertEquals(2, traversal.getSteps().size()); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b1").out().has("name", "c1"); Assert.assertEquals(5, traversal1.getSteps().size()); Assert.assertEquals(c1, traversal1.next()); Assert.assertEquals(1, traversal1.getSteps().size()); DefaultGraphTraversal<Vertex, Long> traversal2 = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b2").out().has("name", "c5").count(); Assert.assertEquals(6, traversal2.getSteps().size()); Assert.assertEquals(1, traversal2.next().intValue()); Assert.assertEquals(2, traversal2.getSteps().size()); DefaultGraphTraversal<Vertex, Long> traversal3 = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b2").has("name", "b2").out().has("name", P.within(Arrays.asList("c5", "c6"))).count(); Assert.assertEquals(6, traversal3.getSteps().size()); Assert.assertEquals(2, traversal3.next().intValue()); Assert.assertEquals(2, traversal3.getSteps().size()); DefaultGraphTraversal<Vertex, Long> traversal4 = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, a1) .out().has("name", "b2").has("name", "b2").out().has("name", P.eq("c5")).count(); Assert.assertEquals(6, traversal4.getSteps().size()); Assert.assertEquals(1, traversal4.next().intValue()); Assert.assertEquals(2, traversal4.getSteps().size()); } @Test public void testInOut() { Vertex v1 = sqlgGraph.addVertex(); Vertex v2 = sqlgGraph.addVertex(); Vertex v3 = sqlgGraph.addVertex(); Vertex v4 = sqlgGraph.addVertex(); sqlgGraph.addVertex(); Edge e1 = v1.addEdge("label1", v2); Edge e2 = v2.addEdge("label2", v3); v3.addEdge("label3", v4); sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Long> traversal = (DefaultGraphTraversal<Vertex, Long>) vertexTraversal(this.sqlgGraph, v2).inE().count(); Assert.assertEquals(3, traversal.getSteps().size()); Assert.assertEquals(1, traversal.next(), 1); Assert.assertEquals(2, traversal.getSteps().size()); DefaultGraphTraversal<Vertex, Edge> traversal1 = (DefaultGraphTraversal<Vertex, Edge>) vertexTraversal(this.sqlgGraph, v2).inE(); Assert.assertEquals(2, traversal1.getSteps().size()); Assert.assertEquals(e1, traversal1.next()); Assert.assertEquals(1, traversal1.getSteps().size()); DefaultGraphTraversal<Edge, Long> traversal2 = (DefaultGraphTraversal<Edge, Long>) edgeTraversal(this.sqlgGraph, e1).inV().count(); Assert.assertEquals(3, traversal2.getSteps().size()); Assert.assertEquals(1L, traversal2.next(), 0); Assert.assertEquals(2, traversal2.getSteps().size()); DefaultGraphTraversal<Edge, Vertex> traversal3 = (DefaultGraphTraversal<Edge, Vertex>) edgeTraversal(this.sqlgGraph, e1).inV(); Assert.assertEquals(2, traversal3.getSteps().size()); Assert.assertEquals(v2, traversal3.next()); Assert.assertEquals(1, traversal3.getSteps().size()); DefaultGraphTraversal<Edge, Long> traversal4 = (DefaultGraphTraversal<Edge, Long>) edgeTraversal(this.sqlgGraph, e1).outV().count(); Assert.assertEquals(3, traversal4.getSteps().size()); Assert.assertEquals(1L, traversal4.next(), 0); Assert.assertEquals(2, traversal4.getSteps().size()); DefaultGraphTraversal<Edge, Long> traversal5 = (DefaultGraphTraversal<Edge, Long>) edgeTraversal(this.sqlgGraph, e1).outV().inE().count(); Assert.assertEquals(4, traversal5.getSteps().size()); Assert.assertEquals(0L, traversal5.next(), 0); Assert.assertEquals(2, traversal5.getSteps().size()); DefaultGraphTraversal<Edge, Long> traversal6 = (DefaultGraphTraversal<Edge, Long>) edgeTraversal(this.sqlgGraph, e2).inV().count(); Assert.assertEquals(3, traversal6.getSteps().size()); Assert.assertEquals(1L, traversal6.next(), 0); Assert.assertEquals(2, traversal6.getSteps().size()); DefaultGraphTraversal<Edge, Vertex> traversal7 = (DefaultGraphTraversal<Edge, Vertex>) edgeTraversal(this.sqlgGraph, e2).inV(); Assert.assertEquals(2, traversal7.getSteps().size()); Assert.assertEquals(v3, traversal7.next()); Assert.assertEquals(1, traversal7.getSteps().size()); } @Test public void testVertexOutWithHas() { Vertex marko = this.sqlgGraph.addVertex(T.label, "Person", "name", "marko"); Vertex bmw1 = this.sqlgGraph.addVertex(T.label, "Car", "name", "bmw", "cc", 600); Vertex bmw2 = this.sqlgGraph.addVertex(T.label, "Car", "name", "bmw", "cc", 800); Vertex ktm1 = this.sqlgGraph.addVertex(T.label, "Bike", "name", "ktm", "cc", 200); Vertex ktm2 = this.sqlgGraph.addVertex(T.label, "Bike", "name", "ktm", "cc", 200); Vertex ktm3 = this.sqlgGraph.addVertex(T.label, "Bike", "name", "ktm", "cc", 400); marko.addEdge("drives", bmw1); marko.addEdge("drives", bmw2); marko.addEdge("drives", ktm1); marko.addEdge("drives", ktm2); marko.addEdge("drives", ktm3); this.sqlgGraph.tx().commit(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("name", "bmw"); Assert.assertEquals(3, traversal.getSteps().size()); List<Vertex> drivesBmw = traversal.toList(); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertEquals(2L, drivesBmw.size(), 0); DefaultGraphTraversal<Vertex, Vertex> traversal1 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("name", "ktm"); Assert.assertEquals(3, traversal1.getSteps().size()); List<Vertex> drivesKtm = traversal1.toList(); Assert.assertEquals(1, traversal1.getSteps().size()); Assert.assertEquals(3L, drivesKtm.size(), 0); DefaultGraphTraversal<Vertex, Vertex> traversal2 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("cc", 600); Assert.assertEquals(3, traversal2.getSteps().size()); List<Vertex> cc600 = traversal2.toList(); Assert.assertEquals(1, traversal2.getSteps().size()); Assert.assertEquals(1L, cc600.size(), 0); DefaultGraphTraversal<Vertex, Vertex> traversal3 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("cc", 800); Assert.assertEquals(3, traversal3.getSteps().size()); List<Vertex> cc800 = traversal3.toList(); Assert.assertEquals(1, traversal3.getSteps().size()); Assert.assertEquals(1L, cc800.size(), 0); DefaultGraphTraversal<Vertex, Vertex> traversal4 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("cc", 200); Assert.assertEquals(3, traversal4.getSteps().size()); List<Vertex> cc200 = traversal4.toList(); Assert.assertEquals(1, traversal4.getSteps().size()); Assert.assertEquals(2L, cc200.size(), 0); DefaultGraphTraversal<Vertex, Vertex> traversal5 = (DefaultGraphTraversal<Vertex, Vertex>) vertexTraversal(this.sqlgGraph, marko) .out("drives").<Vertex>has("cc", 400); Assert.assertEquals(3, traversal5.getSteps().size()); List<Vertex> cc400 = traversal5.toList(); Assert.assertEquals(1, traversal5.getSteps().size()); Assert.assertEquals(1L, cc400.size(), 0); } @Test public void testg_EX11X_outV_outE_hasXid_10AsStringX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); final Object edgeId11 = convertToEdgeId(this.sqlgGraph, "josh", "created", "lop"); final Object edgeId10 = convertToEdgeId(this.sqlgGraph, "josh", "created", "ripple"); DefaultGraphTraversal<Edge, Edge> traversal = (DefaultGraphTraversal<Edge, Edge>) g.traversal().E(edgeId11.toString()) .outV().outE().has(T.id, edgeId10.toString()); Assert.assertEquals(4, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertTrue(traversal.hasNext()); final Edge e = traversal.next(); Assert.assertEquals(edgeId10.toString(), e.id().toString()); Assert.assertFalse(traversal.hasNext()); } @Test public void g_V_out_outE_inV_inE_inV_both_name() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); Object id = convertToVertexId(g, "marko"); DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) g.traversal().V(id).out().outE().inV().inE().inV().both().<String>values("name"); Assert.assertEquals(8, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(2, traversal.getSteps().size()); int counter = 0; final Map<String, Integer> counts = new HashMap<>(); while (traversal.hasNext()) { final String key = traversal.next(); final int previousCount = counts.getOrDefault(key, 0); counts.put(key, previousCount + 1); counter++; } Assert.assertEquals(3, counts.size()); Assert.assertEquals(4, counts.get("josh").intValue()); Assert.assertEquals(3, counts.get("marko").intValue()); Assert.assertEquals(3, counts.get("peter").intValue()); Assert.assertEquals(10, counter); Assert.assertFalse(traversal.hasNext()); } @Test public void testHasWithStringIds() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); String marko = convertToVertexId("marko").toString(); String vadas = convertToVertexId("vadas").toString(); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) g.traversal().V(marko).out().hasId(vadas); Assert.assertEquals(3, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); Assert.assertTrue(traversal.hasNext()); Assert.assertEquals(convertToVertexId("vadas"), traversal.next().id()); } @SuppressWarnings("Duplicates") @Test public void testHas() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); final Object id2 = convertToVertexId("vadas"); final Object id3 = convertToVertexId("lop"); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) get_g_VX1X_out_hasIdX2_3X(g.traversal(), convertToVertexId("marko"), id2.toString(), id3.toString()); Assert.assertEquals(3, traversal.getSteps().size()); assert_g_VX1X_out_hasXid_2_3X(id2, id3, traversal); Assert.assertEquals(1, traversal.getSteps().size()); } @SuppressWarnings("Duplicates") @Test public void g_VX1X_out_hasXid_2AsString_3AsStringX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); final Object id2 = convertToVertexId("vadas"); final Object id3 = convertToVertexId("lop"); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) get_g_VX1X_out_hasIdX2_3X(g.traversal(), convertToVertexId("marko"), id2.toString(), id3.toString()); Assert.assertEquals(3, traversal.getSteps().size()); assert_g_VX1X_out_hasXid_2_3X(id2, id3, traversal); Assert.assertEquals(1, traversal.getSteps().size()); } @Test public void testX() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); final Object marko = convertToVertexId("marko"); DefaultGraphTraversal<Vertex, Edge> traversal = (DefaultGraphTraversal<Vertex, Edge>) g.traversal().V(marko) .outE("knows").has("weight", 1.0d).as("here").inV().has("name", "josh").<Edge>select("here"); Assert.assertEquals(6, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(3, traversal.getSteps().size()); Assert.assertTrue(traversal.hasNext()); Assert.assertTrue(traversal.hasNext()); final Edge edge = traversal.next(); Assert.assertEquals("knows", edge.label()); Assert.assertEquals(1.0d, edge.<Double>value("weight"), 0.00001d); Assert.assertFalse(traversal.hasNext()); Assert.assertFalse(traversal.hasNext()); } @Test public void g_VX1X_outE_hasXweight_inside_0_06X_inV() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); DefaultGraphTraversal<Vertex, Vertex> traversal = (DefaultGraphTraversal<Vertex, Vertex>) get_g_VX1X_outE_hasXweight_inside_0_06X_inV(g.traversal(), convertToVertexId("marko")); Assert.assertEquals(4, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(1, traversal.getSteps().size()); while (traversal.hasNext()) { Vertex vertex = traversal.next(); Assert.assertTrue(vertex.value("name").equals("vadas") || vertex.value("name").equals("lop")); } Assert.assertFalse(traversal.hasNext()); } @Test public void testY() { Graph g = this.sqlgGraph; loadModern(this.sqlgGraph); assertModernGraph(g, true, false); Object marko = convertToVertexId(g, "marko"); DefaultGraphTraversal<Vertex, String> traversal = (DefaultGraphTraversal<Vertex, String>) g.traversal().V(marko).outE("knows").bothV().<String>values("name"); Assert.assertEquals(4, traversal.getSteps().size()); printTraversalForm(traversal); Assert.assertEquals(2, traversal.getSteps().size()); final List<String> names = traversal.toList(); Assert.assertEquals(4, names.size()); Assert.assertTrue(names.contains("marko")); Assert.assertTrue(names.contains("josh")); Assert.assertTrue(names.contains("vadas")); names.remove("marko"); Assert.assertEquals(3, names.size()); names.remove("marko"); Assert.assertEquals(2, names.size()); names.remove("josh"); Assert.assertEquals(1, names.size()); names.remove("vadas"); Assert.assertEquals(0, names.size()); } private Traversal<Vertex, Vertex> get_g_VX1X_outE_hasXweight_inside_0_06X_inV(GraphTraversalSource g, final Object v1Id) { return g.V(v1Id).outE().has("weight", P.inside(0.0d, 0.6d)).inV(); } private Traversal<Vertex, Vertex> get_g_VX1X_out_hasIdX2_3X(GraphTraversalSource g, final Object v1Id, final Object v2Id, final Object v3Id) { return g.V(v1Id).out().hasId(v2Id, v3Id); } private void assert_g_VX1X_out_hasXid_2_3X(Object id2, Object id3, Traversal<Vertex, Vertex> traversal) { printTraversalForm(traversal); Assert.assertTrue(traversal.hasNext()); Assert.assertThat(traversal.next().id(), CoreMatchers.anyOf(CoreMatchers.is(id2), CoreMatchers.is(id3))); Assert.assertThat(traversal.next().id(), CoreMatchers.anyOf(CoreMatchers.is(id2), CoreMatchers.is(id3))); Assert.assertFalse(traversal.hasNext()); } public Object convertToEdgeId(final Graph graph, final String outVertexName, String edgeLabel, final String inVertexName) { return graph.traversal().V().has("name", outVertexName).outE(edgeLabel).as("e").inV().has("name", inVertexName).<Edge>select("e").next().id(); } }
/* * The MIT License (MIT) * * Copyright (c) 2015-2016, Max Roncace <me@caseif.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.caseif.flint.common.util.agent.rollback; import net.caseif.flint.arena.Arena; import net.caseif.flint.common.CommonCore; import net.caseif.flint.common.arena.CommonArena; import net.caseif.flint.common.util.file.CommonDataFiles; import net.caseif.flint.minigame.Minigame; import net.caseif.flint.util.physical.Location3D; import com.google.common.base.Preconditions; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; public abstract class CommonRollbackAgent implements IRollbackAgent { private static final String SQLITE_PROTOCOL = "jdbc:sqlite:"; private static final Properties SQL_QUERIES = new Properties(); private final CommonArena arena; private final File rollbackStore; private final File stateStore; protected CommonRollbackAgent(CommonArena arena) { this.arena = arena; rollbackStore = CommonDataFiles.ROLLBACK_STORE.getFile(getArena().getMinigame()); stateStore = CommonDataFiles.ROLLBACK_STATE_STORE.getFile(getArena().getMinigame()); initializeStateStore(); } static { try (InputStream is = CommonRollbackAgent.class.getResourceAsStream("/sql-queries.properties")) { SQL_QUERIES.load(is); } catch (IOException ex) { throw new RuntimeException("Failed to load SQL query strings", ex); } } /** * Returns the {@link CommonArena} associated with this * {@link CommonRollbackAgent}. * * @return The {@link CommonArena} associated with this * {@link CommonRollbackAgent}. */ public CommonArena getArena() { return arena; } /** * Creates a rollback database for the arena backing this * {@link CommonRollbackAgent}. * * @throws IOException If an exception occurs while creating the database * file * @throws SQLException If an exception occurs while manipulating the * database */ @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void createRollbackDatabase() throws IOException, SQLException { if (!rollbackStore.exists()) { rollbackStore.createNewFile(); } if (!stateStore.exists()) { stateStore.createNewFile(); } try (Connection conn = DriverManager.getConnection(SQLITE_PROTOCOL + rollbackStore.getAbsolutePath())) { try (PreparedStatement st = conn.prepareStatement(SQL_QUERIES.getProperty("create-rollback-table") .replace("{table}", getArena().getId())) ) { st.executeUpdate(); } } } @Override public Map<Integer, String> loadStateMap() throws IOException { Map<Integer, String> stateMap = new HashMap<>(); JsonObject json = new JsonParser().parse(new FileReader(stateStore)).getAsJsonObject(); if (!json.has(getArena().getId()) || !json.get(getArena().getId()).isJsonObject()) { throw new IOException("Cannot load rollback states for arena " + getArena().getId()); } JsonObject arena = json.getAsJsonObject(getArena().getId()); for (Map.Entry<String, JsonElement> entry : arena.entrySet()) { int id = -1; try { id = Integer.parseInt(entry.getKey()); } catch (NumberFormatException ex) { CommonCore.logWarning("Cannot load rollback state with ID " + entry.getKey() + " - key is not an int"); } if (!entry.getValue().isJsonPrimitive() || !entry.getValue().getAsJsonPrimitive().isString()) { CommonCore.logWarning("Cannot load rollback state with ID " + id + " - not a string"); continue; } stateMap.put(id, entry.getValue().getAsString()); } return stateMap; } @Override public void logChange(RollbackRecord record) throws IOException, SQLException { String world = record.getLocation().getWorld().isPresent() ? record.getLocation().getWorld().get() : arena.getWorld(); Preconditions.checkNotNull(record.getLocation(), "Location required for all record types"); switch (record.getType()) { case BLOCK_CHANGE: Preconditions.checkNotNull(record.getTypeData(), "Type required for BLOCK_CHANGED record type"); break; case ENTITY_CREATION: Preconditions.checkNotNull(record.getUuid(), "UUID required for ENTITY_CREATED record type"); break; case ENTITY_CHANGE: Preconditions.checkNotNull(record.getTypeData(), "Type required for ENTITY_CHANGED record type"); Preconditions.checkNotNull(record.getStateSerial(), "State required for ENTITY_CHANGED record type"); break; default: throw new AssertionError("Undefined record type"); } if (!rollbackStore.exists()) { //noinspection ResultOfMethodCallIgnored rollbackStore.createNewFile(); } try (Connection conn = DriverManager.getConnection("jdbc:sqlite:" + rollbackStore.getPath())) { String querySql; switch (record.getType()) { case BLOCK_CHANGE: querySql = SQL_QUERIES.getProperty("query-by-location") .replace("{world}", world) .replace("{x}", "" + record.getLocation().getX()) .replace("{y}", "" + record.getLocation().getY()) .replace("{z}", "" + record.getLocation().getZ()); break; case ENTITY_CHANGE: querySql = SQL_QUERIES.getProperty("query-by-uuid") .replace("{uuid}", record.getUuid().toString()); break; default: querySql = null; break; } if (querySql != null) { querySql = querySql.replace("{table}", getArena().getId()); try ( PreparedStatement query = conn.prepareStatement(querySql); ResultSet queryResults = query.executeQuery(); ) { if (queryResults.next()) { return; // subject has already been modified; no need to re-record } } } String updateSql; switch (record.getType()) { case BLOCK_CHANGE: updateSql = SQL_QUERIES.getProperty("insert-block-rollback-record") .replace("{world}", world) .replace("{x}", "" + record.getLocation().getX()) .replace("{y}", "" + record.getLocation().getY()) .replace("{z}", "" + record.getLocation().getZ()) .replace("{type}", record.getTypeData()) .replace("{data}", "" + record.getData()); break; case ENTITY_CREATION: updateSql = SQL_QUERIES.getProperty("insert-entity-created-rollback-record") .replace("{world}", world) .replace("{uuid}", record.getUuid().toString()); break; case ENTITY_CHANGE: updateSql = SQL_QUERIES.getProperty("insert-entity-changed-rollback-record") .replace("{world}", world) .replace("{x}", "" + record.getLocation().getX()) .replace("{y}", "" + record.getLocation().getY()) .replace("{z}", "" + record.getLocation().getZ()) .replace("{uuid}", record.getUuid().toString()) .replace("{type}", record.getTypeData()); break; default: throw new AssertionError("Inconsistency detected in method: recordType is in an illegal state. " + "Report this immediately."); } if (updateSql != null) { // replace non-negotiable values updateSql = updateSql .replace("{table}", getArena().getId()) .replace("{state}", "" + (record.getStateSerial() != null ? 1 : 0)) .replace("{record_type}", "" + record.getType().ordinal()); } int id; try (PreparedStatement ps = conn.prepareStatement(updateSql, Statement.RETURN_GENERATED_KEYS)) { ps.executeUpdate(); try (ResultSet gen = ps.getGeneratedKeys()) { if (gen.next()) { id = gen.getInt(1); } else { throw new SQLException("Failed to get generated key from update query"); } } } if (record.getStateSerial() != null) { saveStateSerial(id, record.getStateSerial()); } } } @Override @SuppressWarnings("deprecation") public void popRollbacks() throws IOException, SQLException { final Set<RollbackRecord> blockChangeRecords = new HashSet<>(); final Set<RollbackRecord> entityCreateRecords = new HashSet<>(); final Set<RollbackRecord> entityChangeRecords = new HashSet<>(); if (rollbackStore.exists()) { Map<Integer, String> stateMap = loadStateMap(); try ( Connection conn = DriverManager.getConnection(SQLITE_PROTOCOL + rollbackStore.getAbsolutePath()); PreparedStatement query = conn.prepareStatement(SQL_QUERIES.getProperty("get-all-records") .replace("{table}", getArena().getId())); PreparedStatement drop = conn.prepareStatement(SQL_QUERIES.getProperty("drop-table") .replace("{table}", getArena().getId())); ResultSet rs = query.executeQuery(); ) { cacheEntities(); while (rs.next()) { try { int id = rs.getInt("id"); String world = rs.getString("world"); int x = rs.getInt("x"); int y = rs.getInt("y"); int z = rs.getInt("z"); UUID uuid = rs.getString("uuid") != null ? UUID.fromString(rs.getString("uuid")) : null; String type = rs.getString("type"); int data = rs.getInt("data"); boolean state = rs.getBoolean("state"); RollbackRecord.Type recordType = RollbackRecord.Type.values()[rs.getInt("record_type")]; if (world.equals(getArena().getWorld())) { String stateSerial = stateMap.get(id); if (state && stateSerial == null) { CommonCore.logVerbose("Rollback record with ID " + id + " was marked as having " + "state, but no corresponding serial was found"); } switch (recordType) { case BLOCK_CHANGE: blockChangeRecords.add(RollbackRecord.createBlockRecord(id, new Location3D(world, x, y, z), type, data, stateSerial)); break; case ENTITY_CREATION: entityCreateRecords.add(RollbackRecord.createEntityCreationRecord(id, uuid, world)); break; case ENTITY_CHANGE: entityChangeRecords.add(RollbackRecord.createEntityChangeRecord(id, uuid, new Location3D(world, x, y, z), type, stateSerial)); break; default: CommonCore.logWarning("Invalid rollback record type at ID " + id); } } else { CommonCore.logVerbose("Rollback record with ID " + id + " in arena " + getArena().getId() + " has a mismtching world name - refusing to roll back"); } } catch (SQLException ex) { CommonCore.logSevere("Failed to read rollback record in arena " + getArena().getId()); ex.printStackTrace(); } } for (RollbackRecord record : blockChangeRecords) { assert record.getType() == RollbackRecord.Type.BLOCK_CHANGE; rollbackBlock(record); } for (RollbackRecord record : entityCreateRecords) { assert record.getType() == RollbackRecord.Type.BLOCK_CHANGE; rollbackEntityCreation(record); } // entity change rollbacks need to be delayed by one tick to avoid conflict with block changes or any // entities which might have been created in the same location delay(new Runnable() { @Override public void run() { try { for (RollbackRecord record : entityChangeRecords) { assert record.getType() == RollbackRecord.Type.BLOCK_CHANGE; rollbackEntityChange(record); } } catch (IOException ex) { // } } }); drop.executeUpdate(); } clearStateStore(); } else { throw new IllegalArgumentException("Rollback store does not exist"); } } @Override public void clearStateStore() throws IOException { JsonObject json = new JsonParser().parse(new FileReader(stateStore)).getAsJsonObject(); if (!json.has(getArena().getId()) || !json.get(getArena().getId()).isJsonObject()) { CommonCore.logWarning("State store clear requested, but arena was not present"); return; } json.remove(getArena().getId()); json.add(getArena().getId(), new JsonObject()); saveState(json); } @Override public void initializeStateStore() { try { if (!stateStore.exists()) { //noinspection ResultOfMethodCallIgnored stateStore.createNewFile(); } JsonElement json = new JsonParser().parse(new FileReader(stateStore)); if (json.isJsonNull()) { json = new JsonObject(); } json.getAsJsonObject().add(getArena().getId(), new JsonObject()); saveState(json.getAsJsonObject()); } catch (IOException ex) { throw new RuntimeException("Failed to intialize state store for arena " + arena.getId(), ex); } } @Override public void saveStateSerial(int id, String serial) throws IOException { JsonObject json = new JsonParser().parse(new FileReader(stateStore)).getAsJsonObject(); if (!json.has(getArena().getId())) { initializeStateStore(); saveStateSerial(id, serial); // i'm a bad person return; } json.get(getArena().getId()).getAsJsonObject().addProperty(id + "", serial); saveState(json); } private void saveState(JsonObject json) throws IOException { try (FileWriter writer = new FileWriter(stateStore)) { writer.write(new Gson().toJson(json)); } } protected static List<Arena> checkChangeAtLocation(Location3D location) { List<Arena> arenas = new ArrayList<>(); for (Minigame mg : CommonCore.getMinigames().values()) { for (Arena arena : mg.getArenas()) { if (arena.getRound().isPresent() && arena.getBoundary().contains(location)) { arenas.add(arena); } } } return arenas; } protected abstract void delay(Runnable runnable); }
/* * MyWindow.java * * Created on April 14, 2003, 10:25 AM */ package xal.app.mtv; import javax.swing.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.Timer; import xal.extension.application.*; import xal.extension.application.smf.*; import xal.smf.*; import xal.smf.impl.*; import xal.ca.*; /** * The window representation / view of an xiodiag document * * @author jdg */ public class MagnetPanel extends JPanel implements ItemListener { /** serialization identifier */ private static final long serialVersionUID = 1L; private MTVDocument theDoc; private ArrayList <String> magTypes, selectedMagTypes; private ArrayList <JCheckBox> magCheckBoxes; protected ArrayList <String> magnetNames; protected ArrayList <PVTableCell> B_Sets, B_RBs, B_Trim_Sets, B_Books; private JPanel magCheckBoxPanel; private JButton updateTableButton; private JTable magnetTable; protected MagnetTableModel magnetTableModel; private JScrollPane tableScrollPane; protected javax.swing.Timer timer; /** Creates a new instance of MainWindow */ public MagnetPanel(MTVDocument aDocument) { super(new BorderLayout()); theDoc = aDocument; selectedMagTypes = new ArrayList<String>(); magTypes = new ArrayList<String>(); magCheckBoxes = new ArrayList<JCheckBox>(); magnetNames = new ArrayList<String>(); B_Sets = new ArrayList<PVTableCell> (); B_RBs = new ArrayList<PVTableCell> (); B_Trim_Sets = new ArrayList<PVTableCell> (); B_Books = new ArrayList<PVTableCell> (); magCheckBoxPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); updateTableButton = new JButton("Make Table"); updateTableButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateMagnetTable(); } }); makeMagnetTable(); magnetTable.setCellSelectionEnabled(true); tableScrollPane = new JScrollPane(magnetTable); ActionListener taskPerformer = new ActionListener() { public void actionPerformed(ActionEvent evt) { tableTask(); } }; timer = new javax.swing.Timer(1500, taskPerformer); timer.start(); final TableCellRenderer defaultRenderer = magnetTable.getDefaultRenderer(String.class); TableCellRenderer newRenderer = new TableCellRenderer(){ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){ Component component = defaultRenderer.getTableCellRendererComponent(table,value,isSelected, hasFocus,row,column); if(column != 0){ PVTableCell cell = (PVTableCell) magnetTableModel.getValueAt(row,column); if(cell.isValueChanged()){ component.setForeground(Color.blue); } else{ component.setForeground(Color.black); } } else{ component.setForeground(Color.black); } return component; } }; magnetTable.setDefaultRenderer(String.class,newRenderer); magnetTable.setDefaultRenderer(PVTableCell.class,newRenderer); //make all JPanels JPanel commandPanel = new JPanel(new GridLayout(2,1)); JPanel tableButtonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); tableButtonPanel.add(updateTableButton); commandPanel.add(magCheckBoxPanel); commandPanel.add(tableButtonPanel); add(commandPanel,BorderLayout.NORTH); add(tableScrollPane,BorderLayout.CENTER); } public ArrayList <String> getSelectedTypes() { return selectedMagTypes;} /** the action to perform when the tables need updating */ protected void tableTask() { magnetTableModel.fireTableRowsUpdated(0, magnetTableModel.getRowCount()); } /** find the magnet types in the selcted accelerator sequence */ protected void updateMagnetTypes() { magTypes.clear(); selectedMagTypes.clear(); magCheckBoxes.clear(); magTypes.add("all"); JCheckBox magBox = new JCheckBox("magnet"); magBox.addItemListener(this); magCheckBoxes.add(magBox); java.util.List <AcceleratorNode> magNodes = theDoc.getSelectedSequence().getNodesOfType("magnet"); for (AcceleratorNode mag : magNodes) { String type = mag.getType(); if(!magTypes.contains(type)){ magTypes.add(type); magBox = new JCheckBox(type); magBox.setSelected(false); magBox.addItemListener(this); magCheckBoxes.add(magBox); //System.out.println(type); } } } public void itemStateChanged(ItemEvent e) { JCheckBox source = (JCheckBox) e.getItemSelectable(); String type = source.getText(); if (e.getStateChange() == ItemEvent.DESELECTED) { int index = selectedMagTypes.indexOf(type); if (index >= 0) selectedMagTypes.remove(index); } if (e.getStateChange() == ItemEvent.SELECTED) { int index = selectedMagTypes.indexOf(type); if (index < 0) selectedMagTypes.add(type); } } /** update the magnet table with type options for the selected sequence */ protected void updateMagnetPanel(){ magCheckBoxPanel.removeAll(); for (JCheckBox box : magCheckBoxes) { magCheckBoxPanel.add(box); } this.validate(); } /** update the magnet table for the selected types */ private void makeMagnetTable() { magnetTableModel = new MagnetTableModel(this); magnetTable = new JTable(magnetTableModel); //magnetTable.setDefaultRenderer(Integer.class, new IntegerRenderer()); magnetTable.setRowSelectionAllowed(true); magnetTable.addMouseListener( new MouseAdapter() { public void mouseClicked( final MouseEvent event ) { int col = magnetTable.columnAtPoint(event.getPoint()); int row = magnetTable.getSelectedRow(); //System.out.println("row = " + row + " col = " + col); if(col == 1) { theDoc.myWindow().wheelPanel.setPVTableCell(B_Sets.get(row)); return; } if(col == 2) { theDoc.myWindow().wheelPanel.setPVTableCell(B_Trim_Sets.get(row)); return; } if(col == 4) { theDoc.myWindow().wheelPanel.setPVTableCell(B_Books.get(row)); return; } theDoc.myWindow().wheelPanel.setPVTableCell(null); } }); } /** update the magnet table based on the selected magnet types */ protected void updateMagnetTable() { magnetNames.clear(); B_Sets.clear(); B_RBs.clear(); B_Trim_Sets.clear(); B_Books.clear(); java.util.List <AcceleratorNode> nodes = theDoc.getSelectedSequence().getAllNodes(); for (AcceleratorNode node : nodes) { boolean useIt = false; for (String type : selectedMagTypes) { if (node.isKindOf(type)) { useIt = true; break; } } if(!node.getStatus()){ useIt = false; } if(useIt && !node.isKindOf("pmag")) { magnetNames.add(node.getId()); Channel bRB = ((Electromagnet) node).getChannel( Electromagnet.FIELD_RB_HANDLE); MagnetMainSupply mms = ((Electromagnet) node).getMainSupply(); Channel bSet = mms.getChannel(MagnetMainSupply.FIELD_SET_HANDLE); PVTableCell pvrb = null; if(bRB != null) pvrb = getNewCell(bRB); else pvrb = getNewCell(); B_RBs.add(pvrb); PVTableCell pvsp = null; if(bSet != null) pvsp = getNewCell(bSet); else pvsp = getNewCell(); B_Sets.add(pvsp); PVTableCell pvBook = null; try { Channel bBookSet = mms.getChannel(MagnetMainSupply.FIELD_BOOK_HANDLE); pvBook = getNewCell(bBookSet); if(pvsp.getChannel() != null){ pvsp.setBBookCell(pvBook); } } catch (Exception ex) { pvBook = getNewCell(); } B_Books.add(pvBook); PVTableCell pvtsp; if(node.isKindOf("trimmedquad")) { MagnetTrimSupply mts = ((TrimmedQuadrupole) node).getTrimSupply(); Channel btSet = mts.getChannel(MagnetTrimSupply.FIELD_SET_HANDLE); if(btSet != null) pvtsp = getNewCell(btSet); else pvtsp = getNewCell(); B_Trim_Sets.add(pvtsp); } else { pvtsp = getNewCell(); B_Trim_Sets.add(pvtsp); } } } magnetTableModel.fireTableDataChanged(); } private PVTableCell getNewCell(Channel chan){ String pvName = chan.getId(); Hashtable<String,PVTableCell> hash = theDoc.getCellHashtable(); if(hash.containsKey(pvName)){ return hash.get(pvName); } PVTableCell newCell = new PVTableCell(pvName); hash.put(pvName,newCell); return newCell; } private PVTableCell getNewCell(){ String pvName = "null"; Hashtable<String,PVTableCell> hash = theDoc.getCellHashtable(); if(hash.containsKey(pvName)){ return hash.get(pvName); } PVTableCell newCell = new PVTableCell(); hash.put(pvName,newCell); return newCell; } }
/****************************************************************************** * Copyright (c) 2013-2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.alljoyn.about.test; import java.util.Timer; import java.util.TimerTask; import org.alljoyn.about.test.AboutApplication.IconDetails; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; /** * The IconActivity displays all the icon data of the * device (the icon version, icon mimetype, icon url, icon size and of course the icon itself.). */ public class IconActivity extends Activity{ //General protected static final String TAG = AboutApplication.TAG; private AboutApplication m_application; private BroadcastReceiver m_receiver; private SoftAPDetails m_device; private Timer m_timer; private int m_tasksToPerform = 0; private ProgressDialog m_loadingPopup; //Current Network private TextView m_currentNetwork; //Icon version private TextView m_iconVersion; //Icon data private TextView m_iconMimeType; private TextView m_iconSize; private TextView m_iconUrl; private ImageView m_iconContent; //==================================================================== /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //General setContentView(R.layout.icon_layout); String deviceId = getIntent().getStringExtra(Keys.Extras.EXTRA_DEVICE_ID); m_application = (AboutApplication)getApplication(); m_device = m_application.getDevice(deviceId); if(m_device == null){ closeScreen(); return; } startIconSession(); m_loadingPopup = new ProgressDialog(this); //Current Network m_currentNetwork = (TextView) findViewById(R.id.current_network_name); String ssid = m_application.getCurrentSSID(); m_currentNetwork.setText(getString(R.string.current_network, ssid)); //Icon version m_iconVersion = (TextView)findViewById(R.id.icon_version_value); //Icon data m_iconMimeType = (TextView)findViewById(R.id.icon_mime_type_value); m_iconSize = (TextView)findViewById(R.id.icon_size_value); m_iconUrl = (TextView)findViewById(R.id.icon_url_value); m_iconContent = (ImageView)findViewById(R.id.icon_content); m_receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(Keys.Actions.ACTION_ERROR.equals(intent.getAction())){ String error = intent.getStringExtra(Keys.Extras.EXTRA_ERROR); m_application.showAlert(IconActivity.this, error); } else if(Keys.Actions.ACTION_CONNECTED_TO_NETWORK.equals(intent.getAction())){ String ssid = intent.getStringExtra(Keys.Extras.EXTRA_NETWORK_SSID); m_currentNetwork.setText(getString(R.string.current_network, ssid)); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(Keys.Actions.ACTION_ERROR); filter.addAction(Keys.Actions.ACTION_CONNECTED_TO_NETWORK); registerReceiver(m_receiver, filter); m_tasksToPerform = 2; getVersion(); getIconDetails(); } //==================================================================== private void startIconSession() { final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){ @Override protected void onPreExecute() { Log.d(TAG, "startSession: onPreExecute"); } @Override protected Void doInBackground(Void... params) { m_application.startIconSession(m_device); return null; } @Override protected void onPostExecute(Void result) { Log.d(TAG, "startSession: onPostExecute"); } }; task.execute(); } //==================================================================== // Gets the device icon version and put it on the screen private void getVersion() { final AsyncTask<Void, Void, Short> task = new AsyncTask<Void, Void, Short>(){ @Override protected void onPreExecute() { Log.d(TAG, "setIconVersion: onPreExecute"); showLoadingPopup("getting icon version"); } @Override protected Short doInBackground(Void... params){ return m_application.getIconVersion(); } @Override protected void onPostExecute(Short result){ short version = result.shortValue(); m_iconVersion.setText(String.valueOf(version)); Log.d(TAG, "setIconVersion: onPostExecute"); m_tasksToPerform--; dismissLoadingPopup(); } }; task.execute(); } //==================================================================== // Gets all the icon data put it on the screen (icon mimetype, url, size and content) private void getIconDetails() { final AsyncTask<Void, Void, IconDetails> task = new AsyncTask<Void, Void, IconDetails>(){ @Override protected void onPreExecute() { Log.d(TAG, "getIconDetails: onPreExecute"); showLoadingPopup("getting icon detilas"); } @Override protected IconDetails doInBackground(Void... params){ return m_application.getIconDetails(); } @Override protected void onPostExecute(IconDetails result){ String url = result.url; int size = result.size; byte[] content = result.content; String mimeType = result.mimeType; m_iconMimeType.setText(mimeType+""); m_iconSize.setText(size+""); m_iconUrl.setText(url); if(size == content.length){ Bitmap aboutIcon = BitmapFactory.decodeByteArray(content, 0, content.length); m_iconContent.setImageBitmap(aboutIcon); } m_application.makeToast("Get icon done"); Log.d(TAG, "getIconDetails: onPostExecute"); m_tasksToPerform--; dismissLoadingPopup(); } }; task.execute(); } //==================================================================== /* (non-Javadoc) * @see android.app.Activity#onDestroy() */ @Override protected void onDestroy() { super.onDestroy(); m_application.stopIconSession(); if(m_receiver != null){ try{ unregisterReceiver(m_receiver); } catch (IllegalArgumentException e) {} } } //==================================================================== /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.icon_menu, menu); return true; } //==================================================================== /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_icon_refresh: m_tasksToPerform = 2; getVersion(); getIconDetails(); break; } return true; } //==================================================================== /* (non-Javadoc) * @see android.app.Activity#onConfigurationChanged(android.content.res.Configuration) */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } //==================================================================== //Let the user know the device not found and we cannot move to the About screen private void closeScreen() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Error"); alert.setMessage("Device was not found"); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); finish(); } }); alert.show(); } //==================================================================== // Display a progress dialog with the given msg. // If the dialog is already showing - it will update its message to the given msg. // The dialog will dismiss after 30 seconds if no response has returned. private void showLoadingPopup(String msg) { if (m_loadingPopup !=null){ if(!m_loadingPopup.isShowing()){ m_loadingPopup = ProgressDialog.show(this, "", msg, true); Log.d(TAG, "showLoadingPopup with msg = "+msg); } else{ m_loadingPopup.setMessage(msg); Log.d(TAG, "setMessage with msg = "+msg); } } m_timer = new Timer(); m_timer.schedule(new TimerTask() { public void run() { if (m_loadingPopup !=null && m_loadingPopup.isShowing()){ Log.d(TAG, "showLoadingPopup dismissed the popup"); m_loadingPopup.dismiss(); }; } },30*1000); } //==================================================================== // Dismiss the progress dialog (only if it is showing). private void dismissLoadingPopup() { if(m_tasksToPerform == 0){ if (m_loadingPopup != null){ Log.d(TAG, "dismissLoadingPopup dismissed the popup"); m_loadingPopup.dismiss(); if(m_timer != null){ m_timer.cancel(); } } } } //==================================================================== }
/** * 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.yarn.server.resourcemanager; import static org.mockito.Matchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.metrics2.MetricsSystem; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerState; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase; import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.UnRegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.records.NodeAction; import org.apache.hadoop.yarn.server.api.records.NodeStatus; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NodeLabelsUtils; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.YarnVersionInfo; import org.junit.After; import org.junit.Assert; import org.junit.Test; public class TestResourceTrackerService extends NodeLabelTestBase { private final static File TEMP_DIR = new File(System.getProperty( "test.build.data", "/tmp"), "decommision"); private final File hostFile = new File(TEMP_DIR + File.separator + "hostFile.txt"); private MockRM rm; /** * Test RM read NM next heartBeat Interval correctly from Configuration file, * and NM get next heartBeat Interval from RM correctly */ @Test (timeout = 50000) public void testGetNextHeartBeatInterval() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NM_HEARTBEAT_INTERVAL_MS, "4000"); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals(4000, nodeHeartbeat.getNextHeartBeatInterval()); NodeHeartbeatResponse nodeHeartbeat2 = nm2.nodeHeartbeat(true); Assert.assertEquals(4000, nodeHeartbeat2.getNextHeartBeatInterval()); } /** * Decommissioning using a pre-configured include hosts file */ @Test public void testDecommissionWithIncludeHosts() throws Exception { writeToHostsFile("localhost", "host1", "host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int metricCount = metrics.getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); // To test that IPs also work String ip = NetUtils.normalizeHostName("localhost"); writeToHostsFile("host1", ip); rm.getNodesListManager().refreshNodes(conf); checkShutdownNMCount(rm, ++metricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); Assert .assertEquals(1, ClusterMetrics.getMetrics().getNumShutdownNMs()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue("Node is not decommisioned.", NodeAction.SHUTDOWN .equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); Assert.assertEquals(metricCount, ClusterMetrics.getMetrics() .getNumShutdownNMs()); rm.stop(); } /** * Decommissioning using a pre-configured exclude hosts file */ @Test public void testDecommissionWithExcludeHosts() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); int metricCount = ClusterMetrics.getMetrics().getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); rm.drainEvents(); // To test that IPs also work String ip = NetUtils.normalizeHostName("localhost"); writeToHostsFile("host2", ip); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, metricCount + 2); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue("The decommisioned metrics are not updated", NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue("The decommisioned metrics are not updated", NodeAction.SHUTDOWN.equals(nodeHeartbeat.getNodeAction())); rm.drainEvents(); writeToHostsFile(""); rm.getNodesListManager().refreshNodes(conf); nm3 = rm.registerNode("localhost:4433", 1024); nodeHeartbeat = nm3.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); // decommissined node is 1 since 1 node is rejoined after updating exclude // file checkDecommissionedNMCount(rm, metricCount + 1); } /** * Graceful decommission node with no running application. */ @Test public void testGracefulDecommissionNoApp() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("host3:4433", 5120); int metricCount = ClusterMetrics.getMetrics().getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat1 = nm1.nodeHeartbeat(true); NodeHeartbeatResponse nodeHeartbeat2 = nm2.nodeHeartbeat(true); NodeHeartbeatResponse nodeHeartbeat3 = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat1.getNodeAction())); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat2.getNodeAction())); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat3.getNodeAction())); rm.waitForState(nm2.getNodeId(), NodeState.RUNNING); rm.waitForState(nm3.getNodeId(), NodeState.RUNNING); // Graceful decommission both host2 and host3. writeToHostsFile("host2", "host3"); rm.getNodesListManager().refreshNodesGracefully(conf); rm.waitForState(nm2.getNodeId(), NodeState.DECOMMISSIONING); rm.waitForState(nm3.getNodeId(), NodeState.DECOMMISSIONING); nodeHeartbeat1 = nm1.nodeHeartbeat(true); nodeHeartbeat2 = nm2.nodeHeartbeat(true); nodeHeartbeat3 = nm3.nodeHeartbeat(true); checkDecommissionedNMCount(rm, metricCount + 2); rm.waitForState(nm2.getNodeId(), NodeState.DECOMMISSIONED); rm.waitForState(nm3.getNodeId(), NodeState.DECOMMISSIONED); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat1.getNodeAction())); nodeHeartbeat2 = nm2.nodeHeartbeat(true); nodeHeartbeat3 = nm3.nodeHeartbeat(true); Assert.assertEquals(NodeAction.SHUTDOWN, nodeHeartbeat2.getNodeAction()); Assert.assertEquals(NodeAction.SHUTDOWN, nodeHeartbeat3.getNodeAction()); } /** * Graceful decommission node with running application. */ @Test public void testGracefulDecommissionWithApp() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); writeToHostsFile(""); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 10240); MockNM nm2 = rm.registerNode("host2:5678", 20480); MockNM nm3 = rm.registerNode("host3:4433", 10240); NodeId id1 = nm1.getNodeId(); NodeId id3 = nm3.getNodeId(); rm.waitForState(id1, NodeState.RUNNING); rm.waitForState(id3, NodeState.RUNNING); // Create an app and launch two containers on host1. RMApp app = rm.submitApp(2000); MockAM am = MockRM.launchAndRegisterAM(app, rm, nm1); ApplicationAttemptId aaid = app.getCurrentAppAttempt().getAppAttemptId(); nm1.nodeHeartbeat(aaid, 2, ContainerState.RUNNING); nm3.nodeHeartbeat(true); // Graceful decommission host1 and host3 writeToHostsFile("host1", "host3"); rm.getNodesListManager().refreshNodesGracefully(conf); rm.waitForState(id1, NodeState.DECOMMISSIONING); rm.waitForState(id3, NodeState.DECOMMISSIONING); // host1 should be DECOMMISSIONING due to running containers. // host3 should become DECOMMISSIONED. nm1.nodeHeartbeat(true); nm3.nodeHeartbeat(true); rm.waitForState(id1, NodeState.DECOMMISSIONING); rm.waitForState(id3, NodeState.DECOMMISSIONED); nm1.nodeHeartbeat(aaid, 2, ContainerState.RUNNING); // Complete containers on host1. // Since the app is still RUNNING, expect NodeAction.NORMAL. NodeHeartbeatResponse nodeHeartbeat1 = nm1.nodeHeartbeat(aaid, 2, ContainerState.COMPLETE); Assert.assertEquals(NodeAction.NORMAL, nodeHeartbeat1.getNodeAction()); // Finish the app and verified DECOMMISSIONED. MockRM.finishAMAndVerifyAppState(app, rm, nm1, am); rm.waitForState(app.getApplicationId(), RMAppState.FINISHED); nodeHeartbeat1 = nm1.nodeHeartbeat(aaid, 2, ContainerState.COMPLETE); Assert.assertEquals(NodeAction.NORMAL, nodeHeartbeat1.getNodeAction()); rm.waitForState(id1, NodeState.DECOMMISSIONED); nodeHeartbeat1 = nm1.nodeHeartbeat(true); Assert.assertEquals(NodeAction.SHUTDOWN, nodeHeartbeat1.getNodeAction()); } /** * Decommissioning using a post-configured include hosts file */ @Test public void testAddNewIncludePathToConfiguration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int initialMetricCount = metrics.getNumShutdownNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); writeToHostsFile("host1"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); checkShutdownNMCount(rm, ++initialMetricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( "Node should not have been shutdown.", NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); NodeState nodeState = rm.getRMContext().getInactiveRMNodes().get(nm2.getNodeId()).getState(); Assert.assertEquals("Node should have been shutdown but is in state" + nodeState, NodeState.SHUTDOWN, nodeState); } /** * Decommissioning using a post-configured exclude hosts file */ @Test public void testAddNewExcludePathToConfiguration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert(metrics != null); int initialMetricCount = metrics.getNumDecommisionedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals( NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); writeToHostsFile("host2"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); checkDecommissionedNMCount(rm, ++initialMetricCount); nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertEquals( "Node should not have been decomissioned.", NodeAction.NORMAL, nodeHeartbeat.getNodeAction()); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertEquals("Node should have been decomissioned but is in state" + nodeHeartbeat.getNodeAction(), NodeAction.SHUTDOWN, nodeHeartbeat.getNodeAction()); } @Test public void testNodeRegistrationSuccess() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); } @Test public void testNodeRegistrationWithLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toSet(NodeLabel.newInstance("A"))); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(registerReq); Assert.assertEquals("Action should be normal on valid Node Labels", NodeAction.NORMAL, response.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), NodeLabelsUtils.convertToStringSet(registerReq.getNodeLabels())); Assert.assertTrue("Valid Node Labels were not accepted by RM", response.getAreNodeLabelsAcceptedByRM()); rm.stop(); } @Test public void testNodeRegistrationWithInvalidLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("X", "Y", "Z")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A", "B", "C")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(registerReq); Assert.assertEquals( "On Invalid Node Labels action is expected to be normal", NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert.assertNotNull(response.getDiagnosticsMessage()); Assert.assertFalse("Node Labels should not accepted by RM If Invalid", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationWithInvalidLabelsSyntax() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("X", "Y", "Z")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("#Y")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals( "On Invalid Node Labels action is expected to be normal", NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert.assertNotNull(response.getDiagnosticsMessage()); Assert.assertFalse("Node Labels should not accepted by RM If Invalid", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationWithCentralLabelConfig() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DEFAULT_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("A")); RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); // registered to RM with central label config Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); Assert .assertFalse( "Node Labels should not accepted by RM If its configured with " + "Central configuration", response.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @SuppressWarnings("unchecked") private NodeStatus getNodeStatusObject(NodeId nodeId) { NodeStatus status = Records.newRecord(NodeStatus.class); status.setNodeId(nodeId); status.setResponseId(0); status.setContainersStatuses(Collections.EMPTY_LIST); status.setKeepAliveApplications(Collections.EMPTY_LIST); return status; } @Test public void testNodeHeartBeatWithLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); // adding valid labels try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } // Registering of labels and other required info to RM ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A")); // Node register label RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(registerReq); // modification of labels during heartbeat NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B")); // Node heartbeat label update NodeStatus nodeStatusObject = getNodeStatusObject(nodeId); heartbeatReq.setNodeStatus(nodeStatusObject); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); Assert.assertEquals("InValid Node Labels were not accepted by RM", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), NodeLabelsUtils.convertToStringSet(heartbeatReq.getNodeLabels())); Assert.assertTrue("Valid Node Labels were not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); // After modification of labels next heartbeat sends null informing no update Set<String> oldLabels = nodeLabelsMgr.getNodeLabels().get(nodeId); int responseId = nodeStatusObject.getResponseId(); heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(null); // Node heartbeat label update nodeStatusObject = getNodeStatusObject(nodeId); nodeStatusObject.setResponseId(responseId+2); heartbeatReq.setNodeStatus(nodeStatusObject); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); Assert.assertEquals("InValid Node Labels were not accepted by RM", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); assertCollectionEquals(nodeLabelsMgr.getNodeLabels().get(nodeId), oldLabels); Assert.assertFalse("Node Labels should not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); rm.stop(); } @Test public void testNodeHeartBeatWithInvalidLabels() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); try { nodeLabelsMgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet("A", "B", "C")); } catch (IOException e) { Assert.fail("Caught Exception while intializing"); e.printStackTrace(); } ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest registerReq = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); registerReq.setResource(capability); registerReq.setNodeId(nodeId); registerReq.setHttpPort(1234); registerReq.setNMVersion(YarnVersionInfo.getVersion()); registerReq.setNodeLabels(toNodeLabelSet("A")); RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(registerReq); NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B", "#C")); // Invalid heart beat labels heartbeatReq.setNodeStatus(getNodeStatusObject(nodeId)); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); // response should be NORMAL when RM heartbeat labels are rejected Assert.assertEquals("Response should be NORMAL when RM heartbeat labels" + " are rejected", NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); Assert.assertFalse(nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); Assert.assertNotNull(nodeHeartbeatResponse.getDiagnosticsMessage()); rm.stop(); } @Test public void testNodeHeartbeatWithCentralLabelConfig() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, YarnConfiguration.DEFAULT_NODELABEL_CONFIGURATION_TYPE); final RMNodeLabelsManager nodeLabelsMgr = new NullRMNodeLabelsManager(); rm = new MockRM(conf) { @Override protected RMNodeLabelsManager createNodeLabelManager() { return nodeLabelsMgr; } }; rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord(RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(YarnVersionInfo.getVersion()); req.setNodeLabels(toNodeLabelSet("A", "B", "C")); RegisterNodeManagerResponse registerResponse = resourceTrackerService.registerNodeManager(req); NodeHeartbeatRequest heartbeatReq = Records.newRecord(NodeHeartbeatRequest.class); heartbeatReq.setNodeLabels(toNodeLabelSet("B")); // Valid heart beat labels heartbeatReq.setNodeStatus(getNodeStatusObject(nodeId)); heartbeatReq.setLastKnownNMTokenMasterKey(registerResponse .getNMTokenMasterKey()); heartbeatReq.setLastKnownContainerTokenMasterKey(registerResponse .getContainerTokenMasterKey()); NodeHeartbeatResponse nodeHeartbeatResponse = resourceTrackerService.nodeHeartbeat(heartbeatReq); // response should be ok but the RMacceptNodeLabelsUpdate should be false Assert.assertEquals(NodeAction.NORMAL, nodeHeartbeatResponse.getNodeAction()); // no change in the labels, Assert.assertNull(nodeLabelsMgr.getNodeLabels().get(nodeId)); // heartbeat labels rejected Assert.assertFalse("Invalid Node Labels should not accepted by RM", nodeHeartbeatResponse.getAreNodeLabelsAcceptedByRM()); if (rm != null) { rm.stop(); } } @Test public void testNodeRegistrationVersionLessThanRM() throws Exception { writeToHostsFile("host2"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); conf.set(YarnConfiguration.RM_NODEMANAGER_MINIMUM_VERSION,"EqualToRM" ); rm = new MockRM(conf); rm.start(); String nmVersion = "1.9.9"; ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); req.setNodeId(nodeId); req.setHttpPort(1234); req.setNMVersion(nmVersion); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response.getNodeAction()); Assert.assertTrue("Diagnostic message did not contain: 'Disallowed NodeManager " + "Version "+ nmVersion + ", is less than the minimum version'", response.getDiagnosticsMessage().contains("Disallowed NodeManager Version " + nmVersion + ", is less than the minimum version ")); } @Test public void testNodeRegistrationFailure() throws Exception { writeToHostsFile("host1"); Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = NodeId.newInstance("host2", 1234); req.setNodeId(nodeId); req.setHttpPort(1234); // trying to register a invalid node. RegisterNodeManagerResponse response = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response.getNodeAction()); Assert .assertEquals( "Disallowed NodeManager from host2, Sending SHUTDOWN signal to the NodeManager.", response.getDiagnosticsMessage()); } @Test public void testSetRMIdentifierInRegistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm = new MockNM("host1:1234", 5120, rm.getResourceTrackerService()); RegisterNodeManagerResponse response = nm.registerNode(); // Verify the RMIdentifier is correctly set in RegisterNodeManagerResponse Assert.assertEquals(ResourceManager.getClusterTimeStamp(), response.getRMIdentifier()); } @Test public void testNodeRegistrationWithMinimumAllocations() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, "2048"); conf.set(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, "4"); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm.getResourceTrackerService(); RegisterNodeManagerRequest req = Records.newRecord( RegisterNodeManagerRequest.class); NodeId nodeId = BuilderUtils.newNodeId("host", 1234); req.setNodeId(nodeId); Resource capability = BuilderUtils.newResource(1024, 1); req.setResource(capability); RegisterNodeManagerResponse response1 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response1.getNodeAction()); capability.setMemorySize(2048); capability.setVirtualCores(1); req.setResource(capability); RegisterNodeManagerResponse response2 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response2.getNodeAction()); capability.setMemorySize(1024); capability.setVirtualCores(4); req.setResource(capability); RegisterNodeManagerResponse response3 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.SHUTDOWN,response3.getNodeAction()); capability.setMemorySize(2048); capability.setVirtualCores(4); req.setResource(capability); RegisterNodeManagerResponse response4 = resourceTrackerService.registerNodeManager(req); Assert.assertEquals(NodeAction.NORMAL,response4.getNodeAction()); } @Test public void testReboot() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:1234", 2048); int initialMetricCount = ClusterMetrics.getMetrics().getNumRebootedNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat( new HashMap<ApplicationId, List<ContainerStatus>>(), true, -100); Assert.assertTrue(NodeAction.RESYNC.equals(nodeHeartbeat.getNodeAction())); Assert.assertEquals("Too far behind rm response id:0 nm response id:-100", nodeHeartbeat.getDiagnosticsMessage()); checkRebootedNMCount(rm, ++initialMetricCount); } private void checkRebootedNMCount(MockRM rm2, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumRebootedNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals("The rebooted metrics are not updated", count, ClusterMetrics.getMetrics().getNumRebootedNMs()); } @Test public void testUnhealthyNodeStatus() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, hostFile .getAbsolutePath()); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); Assert.assertEquals(0, ClusterMetrics.getMetrics().getUnhealthyNMs()); // node healthy nm1.nodeHeartbeat(true); // node unhealthy nm1.nodeHeartbeat(false); checkUnhealthyNMCount(rm, nm1, true, 1); // node healthy again nm1.nodeHeartbeat(true); checkUnhealthyNMCount(rm, nm1, false, 0); } private void checkUnhealthyNMCount(MockRM rm, MockNM nm1, boolean health, int count) throws Exception { int waitCount = 0; while((rm.getRMContext().getRMNodes().get(nm1.getNodeId()) .getState() != NodeState.UNHEALTHY) == health && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertFalse((rm.getRMContext().getRMNodes().get(nm1.getNodeId()) .getState() != NodeState.UNHEALTHY) == health); Assert.assertEquals("Unhealthy metrics not incremented", count, ClusterMetrics.getMetrics().getUnhealthyNMs()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testHandleContainerStatusInvalidCompletions() throws Exception { rm = new MockRM(new YarnConfiguration()); rm.start(); EventHandler handler = spy(rm.getRMContext().getDispatcher().getEventHandler()); // Case 1: Unmanaged AM RMApp app = rm.submitApp(1024, true); // Case 1.1: AppAttemptId is null NMContainerStatus report = NMContainerStatus.newInstance( ContainerId.newContainerId( ApplicationAttemptId.newInstance(app.getApplicationId(), 2), 1), 0, ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); rm.getResourceTrackerService().handleNMContainerStatus(report, null); verify(handler, never()).handle((Event) any()); // Case 1.2: Master container is null RMAppAttemptImpl currentAttempt = (RMAppAttemptImpl) app.getCurrentAppAttempt(); currentAttempt.setMasterContainer(null); report = NMContainerStatus.newInstance( ContainerId.newContainerId(currentAttempt.getAppAttemptId(), 0), 0, ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); rm.getResourceTrackerService().handleNMContainerStatus(report, null); verify(handler, never()).handle((Event)any()); // Case 2: Managed AM app = rm.submitApp(1024); // Case 2.1: AppAttemptId is null report = NMContainerStatus.newInstance( ContainerId.newContainerId( ApplicationAttemptId.newInstance(app.getApplicationId(), 2), 1), 0, ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); try { rm.getResourceTrackerService().handleNMContainerStatus(report, null); } catch (Exception e) { // expected - ignore } verify(handler, never()).handle((Event)any()); // Case 2.2: Master container is null currentAttempt = (RMAppAttemptImpl) app.getCurrentAppAttempt(); currentAttempt.setMasterContainer(null); report = NMContainerStatus.newInstance( ContainerId.newContainerId(currentAttempt.getAppAttemptId(), 0), 0, ContainerState.COMPLETE, Resource.newInstance(1024, 1), "Dummy Completed", 0, Priority.newInstance(10), 1234); try { rm.getResourceTrackerService().handleNMContainerStatus(report, null); } catch (Exception e) { // expected - ignore } verify(handler, never()).handle((Event)any()); } @Test public void testReconnectNode() throws Exception { rm = new MockRM() { @Override protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() { return new SchedulerEventDispatcher(this.scheduler) { @Override public void handle(SchedulerEvent event) { scheduler.handle(event); } }; } }; rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 5120); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(false); rm.drainEvents(); checkUnhealthyNMCount(rm, nm2, true, 1); final int expectedNMs = ClusterMetrics.getMetrics().getNumActiveNMs(); QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); // TODO Metrics incorrect in case of the FifoScheduler Assert.assertEquals(5120, metrics.getAvailableMB()); // reconnect of healthy node nm1 = rm.registerNode("host1:1234", 5120); NodeHeartbeatResponse response = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); rm.drainEvents(); Assert.assertEquals(expectedNMs, ClusterMetrics.getMetrics().getNumActiveNMs()); checkUnhealthyNMCount(rm, nm2, true, 1); // reconnect of unhealthy node nm2 = rm.registerNode("host2:5678", 5120); response = nm2.nodeHeartbeat(false); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); rm.drainEvents(); Assert.assertEquals(expectedNMs, ClusterMetrics.getMetrics().getNumActiveNMs()); checkUnhealthyNMCount(rm, nm2, true, 1); // unhealthy node changed back to healthy nm2 = rm.registerNode("host2:5678", 5120); response = nm2.nodeHeartbeat(true); response = nm2.nodeHeartbeat(true); rm.drainEvents(); Assert.assertEquals(5120 + 5120, metrics.getAvailableMB()); // reconnect of node with changed capability nm1 = rm.registerNode("host2:5678", 10240); response = nm1.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); Assert.assertEquals(5120 + 10240, metrics.getAvailableMB()); // reconnect of node with changed capability and running applications List<ApplicationId> runningApps = new ArrayList<ApplicationId>(); runningApps.add(ApplicationId.newInstance(1, 0)); nm1 = rm.registerNode("host2:5678", 15360, 2, runningApps); response = nm1.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue(NodeAction.NORMAL.equals(response.getNodeAction())); Assert.assertEquals(5120 + 15360, metrics.getAvailableMB()); // reconnect healthy node changing http port nm1 = new MockNM("host1:1234", 5120, rm.getResourceTrackerService()); nm1.setHttpPort(3); nm1.registerNode(); response = nm1.nodeHeartbeat(true); response = nm1.nodeHeartbeat(true); rm.drainEvents(); RMNode rmNode = rm.getRMContext().getRMNodes().get(nm1.getNodeId()); Assert.assertEquals(3, rmNode.getHttpPort()); Assert.assertEquals(5120, rmNode.getTotalCapability().getMemorySize()); Assert.assertEquals(5120 + 15360, metrics.getAvailableMB()); } @Test public void testNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); MockNM nm1 = rm.registerNode("host1:1234", 5120); int shutdownNMsCount = ClusterMetrics.getMetrics() .getNumShutdownNMs(); NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, ++shutdownNMsCount); // The RM should remove the node after unregistration, hence send a reboot // command. nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.RESYNC.equals(nodeHeartbeat.getNodeAction())); } @Test public void testUnhealthyNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); MockNM nm1 = rm.registerNode("host1:1234", 5120); Assert.assertEquals(0, ClusterMetrics.getMetrics().getUnhealthyNMs()); // node healthy nm1.nodeHeartbeat(true); int shutdownNMsCount = ClusterMetrics.getMetrics().getNumShutdownNMs(); // node unhealthy nm1.nodeHeartbeat(false); checkUnhealthyNMCount(rm, nm1, true, 1); UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, ++shutdownNMsCount); } @Test public void testInvalidNMUnregistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); ResourceTrackerService resourceTrackerService = rm .getResourceTrackerService(); int decommisionedNMsCount = ClusterMetrics.getMetrics() .getNumDecommisionedNMs(); // Node not found for unregister UnRegisterNodeManagerRequest request = Records .newRecord(UnRegisterNodeManagerRequest.class); request.setNodeId(BuilderUtils.newNodeId("host", 1234)); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, 0); checkDecommissionedNMCount(rm, 0); // 1. Register the Node Manager // 2. Exclude the same Node Manager host // 3. Give NM heartbeat to RM // 4. Unregister the Node Manager MockNM nm1 = new MockNM("host1:1234", 5120, resourceTrackerService); RegisterNodeManagerResponse response = nm1.registerNode(); Assert.assertEquals(NodeAction.NORMAL, response.getNodeAction()); writeToHostsFile("host2"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); NodeHeartbeatResponse heartbeatResponse = nm1.nodeHeartbeat(true); Assert.assertEquals(NodeAction.SHUTDOWN, heartbeatResponse.getNodeAction()); int shutdownNMsCount = ClusterMetrics.getMetrics().getNumShutdownNMs(); checkShutdownNMCount(rm, shutdownNMsCount); checkDecommissionedNMCount(rm, decommisionedNMsCount); request.setNodeId(nm1.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); shutdownNMsCount = ClusterMetrics.getMetrics().getNumShutdownNMs(); checkShutdownNMCount(rm, shutdownNMsCount); checkDecommissionedNMCount(rm, decommisionedNMsCount); // 1. Register the Node Manager // 2. Exclude the same Node Manager host // 3. Unregister the Node Manager MockNM nm2 = new MockNM("host2:1234", 5120, resourceTrackerService); RegisterNodeManagerResponse response2 = nm2.registerNode(); Assert.assertEquals(NodeAction.NORMAL, response2.getNodeAction()); writeToHostsFile("host1"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); request.setNodeId(nm2.getNodeId()); resourceTrackerService.unRegisterNodeManager(request); checkShutdownNMCount(rm, ++shutdownNMsCount); checkDecommissionedNMCount(rm, decommisionedNMsCount); rm.stop(); } @Test(timeout = 30000) public void testInitDecommMetric() throws Exception { testInitDecommMetricHelper(true); testInitDecommMetricHelper(false); } public void testInitDecommMetricHelper(boolean hasIncludeList) throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); writeToHostsFile(excludeHostFile, "host1"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); if (hasIncludeList) { writeToHostsFile(hostFile, "host1", "host2"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); } rm.getNodesListManager().refreshNodes(conf); rm.drainEvents(); rm.stop(); MockRM rm1 = new MockRM(conf); rm1.start(); nm1 = rm1.registerNode("host1:1234", 5120); nm2 = rm1.registerNode("host2:5678", 10240); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); rm1.drainEvents(); Assert.assertEquals("Number of Decommissioned nodes should be 1", 1, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); Assert.assertEquals("The inactiveRMNodes should contain an entry for the" + "decommissioned node", 1, rm1.getRMContext().getInactiveRMNodes().size()); excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); writeToHostsFile(excludeHostFile, ""); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); rm1.getNodesListManager().refreshNodes(conf); nm1 = rm1.registerNode("host1:1234", 5120); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); rm1.drainEvents(); Assert.assertEquals("The decommissioned nodes metric should have " + "decremented to 0", 0, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); Assert.assertEquals("The active nodes metric should be 2", 2, ClusterMetrics.getMetrics().getNumActiveNMs()); Assert.assertEquals("The inactive RMNodes entry should have been removed", 0, rm1.getRMContext().getInactiveRMNodes().size()); rm1.drainEvents(); rm1.stop(); } @Test(timeout = 30000) public void testInitDecommMetricNoRegistration() throws Exception { Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); //host3 will not register or heartbeat File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); writeToHostsFile(excludeHostFile, "host3", "host2"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); writeToHostsFile(hostFile, "host1", "host2"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); rm.getNodesListManager().refreshNodes(conf); rm.drainEvents(); Assert.assertEquals("The decommissioned nodes metric should be 1 ", 1, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); rm.stop(); MockRM rm1 = new MockRM(conf); rm1.start(); rm1.getNodesListManager().refreshNodes(conf); rm1.drainEvents(); Assert.assertEquals("The decommissioned nodes metric should be 2 ", 2, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); rm1.stop(); } @Test public void testIncorrectRecommission() throws Exception { //Check decommissioned node not get recommissioned with graceful refresh Configuration conf = new Configuration(); rm = new MockRM(conf); rm.start(); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); writeToHostsFile(excludeHostFile, "host3", "host2"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); writeToHostsFile(hostFile, "host1", "host2"); writeToHostsFile(excludeHostFile, "host1"); rm.getNodesListManager().refreshNodesGracefully(conf); rm.drainEvents(); nm1.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue("Node " + nm1.getNodeId().getHost() + " should be Decommissioned", rm.getRMContext() .getInactiveRMNodes().get(nm1.getNodeId()).getState() == NodeState .DECOMMISSIONED); writeToHostsFile(excludeHostFile, ""); rm.getNodesListManager().refreshNodesGracefully(conf); rm.drainEvents(); Assert.assertTrue("Node " + nm1.getNodeId().getHost() + " should be Decommissioned", rm.getRMContext() .getInactiveRMNodes().get(nm1.getNodeId()).getState() == NodeState .DECOMMISSIONED); rm.stop(); } /** * Remove a node from all lists and check if its forgotten */ @Test public void testNodeRemovalNormally() throws Exception { testNodeRemovalUtil(false); testNodeRemovalUtilLost(false); testNodeRemovalUtilRebooted(false); testNodeRemovalUtilUnhealthy(false); } @Test public void testNodeRemovalGracefully() throws Exception { testNodeRemovalUtil(true); testNodeRemovalUtilLost(true); testNodeRemovalUtilRebooted(true); testNodeRemovalUtilUnhealthy(true); } public void refreshNodesOption(boolean doGraceful, Configuration conf) throws Exception { if (doGraceful) { rm.getNodesListManager().refreshNodesGracefully(conf); } else { rm.getNodesListManager().refreshNodes(conf); } } public void testNodeRemovalUtil(boolean doGraceful) throws Exception { Configuration conf = new Configuration(); int timeoutValue = 500; File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, ""); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, ""); conf.setInt(YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, timeoutValue); CountDownLatch latch = new CountDownLatch(1); rm = new MockRM(conf); rm.init(conf); rm.start(); RMContext rmContext = rm.getRMContext(); refreshNodesOption(doGraceful, conf); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics metrics = ClusterMetrics.getMetrics(); assert (metrics != null); //check all 3 nodes joined in as NORMAL NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); rm.drainEvents(); Assert.assertEquals("All 3 nodes should be active", metrics.getNumActiveNMs(), 3); //Remove nm2 from include list, should now be shutdown with timer test String ip = NetUtils.normalizeHostName("localhost"); writeToHostsFile("host1", ip); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile .getAbsolutePath()); refreshNodesOption(doGraceful, conf); nm1.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue("Node should not be in active node list", !rmContext.getRMNodes().containsKey(nm2.getNodeId())); RMNode rmNode = rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertEquals("Node should be in inactive node list", rmNode.getState(), NodeState.SHUTDOWN); Assert.assertEquals("Active nodes should be 2", metrics.getNumActiveNMs(), 2); Assert.assertEquals("Shutdown nodes should be 1", metrics.getNumShutdownNMs(), 1); int nodeRemovalTimeout = conf.getInt( YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, YarnConfiguration. DEFAULT_RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC); int nodeRemovalInterval = rmContext.getNodesListManager().getNodeRemovalCheckInterval(); long maxThreadSleeptime = nodeRemovalInterval + nodeRemovalTimeout; latch.await(maxThreadSleeptime, TimeUnit.MILLISECONDS); rmNode = rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertEquals("Node should have been forgotten!", rmNode, null); Assert.assertEquals("Shutdown nodes should be 0 now", metrics.getNumShutdownNMs(), 0); //Check node removal and re-addition before timer expires writeToHostsFile("host1", ip, "host2"); refreshNodesOption(doGraceful, conf); nm2 = rm.registerNode("host2:5678", 10240); rm.drainEvents(); writeToHostsFile("host1", ip); refreshNodesOption(doGraceful, conf); rm.drainEvents(); rmNode = rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertEquals("Node should be shutdown", rmNode.getState(), NodeState.SHUTDOWN); Assert.assertEquals("Active nodes should be 2", metrics.getNumActiveNMs(), 2); Assert.assertEquals("Shutdown nodes should be 1", metrics.getNumShutdownNMs(), 1); //add back the node before timer expires latch.await(maxThreadSleeptime - 2000, TimeUnit.MILLISECONDS); writeToHostsFile("host1", ip, "host2"); refreshNodesOption(doGraceful, conf); nm2 = rm.registerNode("host2:5678", 10240); nodeHeartbeat = nm2.nodeHeartbeat(true); rm.drainEvents(); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); Assert.assertEquals("Shutdown nodes should be 0 now", metrics.getNumShutdownNMs(), 0); Assert.assertEquals("All 3 nodes should be active", metrics.getNumActiveNMs(), 3); //Decommission this node, check timer doesn't remove it writeToHostsFile("host1", "host2", ip); writeToHostsFile(excludeHostFile, "host2"); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile .getAbsolutePath()); refreshNodesOption(doGraceful, conf); rm.drainEvents(); rmNode = doGraceful ? rmContext.getRMNodes().get(nm2.getNodeId()) : rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertTrue("Node should be DECOMMISSIONED or DECOMMISSIONING", (rmNode.getState() == NodeState.DECOMMISSIONED) || (rmNode.getState() == NodeState.DECOMMISSIONING)); if (rmNode.getState() == NodeState.DECOMMISSIONED) { Assert.assertEquals("Decommissioned/ing nodes should be 1 now", metrics.getNumDecommisionedNMs(), 1); } latch.await(maxThreadSleeptime, TimeUnit.MILLISECONDS); rmNode = doGraceful ? rmContext.getRMNodes().get(nm2.getNodeId()) : rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertTrue("Node should be DECOMMISSIONED or DECOMMISSIONING", (rmNode.getState() == NodeState.DECOMMISSIONED) || (rmNode.getState() == NodeState.DECOMMISSIONING)); if (rmNode.getState() == NodeState.DECOMMISSIONED) { Assert.assertEquals("Decommissioned/ing nodes should be 1 now", metrics.getNumDecommisionedNMs(), 1); } //Test decommed/ing node that transitions to untracked,timer should remove writeToHostsFile("host1", ip, "host2"); writeToHostsFile(excludeHostFile, "host2"); refreshNodesOption(doGraceful, conf); nm1.nodeHeartbeat(true); //nm2.nodeHeartbeat(true); nm3.nodeHeartbeat(true); latch.await(maxThreadSleeptime, TimeUnit.MILLISECONDS); rmNode = doGraceful ? rmContext.getRMNodes().get(nm2.getNodeId()) : rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertNotEquals("Timer for this node was not canceled!", rmNode, null); Assert.assertTrue("Node should be DECOMMISSIONED or DECOMMISSIONING", (rmNode.getState() == NodeState.DECOMMISSIONED) || (rmNode.getState() == NodeState.DECOMMISSIONING)); writeToHostsFile("host1", ip); writeToHostsFile(excludeHostFile, ""); refreshNodesOption(doGraceful, conf); latch.await(maxThreadSleeptime, TimeUnit.MILLISECONDS); rmNode = doGraceful ? rmContext.getRMNodes().get(nm2.getNodeId()) : rmContext.getInactiveRMNodes().get(nm2.getNodeId()); Assert.assertEquals("Node should have been forgotten!", rmNode, null); Assert.assertEquals("Shutdown nodes should be 0 now", metrics.getNumDecommisionedNMs(), 0); Assert.assertEquals("Shutdown nodes should be 0 now", metrics.getNumShutdownNMs(), 0); Assert.assertEquals("Active nodes should be 2", metrics.getNumActiveNMs(), 2); rm.stop(); } private void testNodeRemovalUtilLost(boolean doGraceful) throws Exception { Configuration conf = new Configuration(); conf.setLong(YarnConfiguration.RM_NM_EXPIRY_INTERVAL_MS, 2000); int timeoutValue = 500; File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); writeToHostsFile(hostFile, "host1", "localhost", "host2"); writeToHostsFile(excludeHostFile, ""); conf.setInt(YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, timeoutValue); rm = new MockRM(conf); rm.init(conf); rm.start(); RMContext rmContext = rm.getRMContext(); refreshNodesOption(doGraceful, conf); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); ClusterMetrics metrics = clusterMetrics; assert (metrics != null); rm.drainEvents(); //check all 3 nodes joined in as NORMAL NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); rm.drainEvents(); Assert.assertEquals("All 3 nodes should be active", metrics.getNumActiveNMs(), 3); int waitCount = 0; while(waitCount ++<20){ synchronized (this) { wait(200); } nm3.nodeHeartbeat(true); nm1.nodeHeartbeat(true); } Assert.assertNotEquals("host2 should be a lost NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("host2 should be a lost NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()).getState(), NodeState.LOST); Assert.assertEquals("There should be 1 Lost NM!", clusterMetrics.getNumLostNMs(), 1); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); int nodeRemovalTimeout = conf.getInt( YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, YarnConfiguration. DEFAULT_RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC); int nodeRemovalInterval = rmContext.getNodesListManager().getNodeRemovalCheckInterval(); long maxThreadSleeptime = nodeRemovalInterval + nodeRemovalTimeout; writeToHostsFile(hostFile, "host1", "localhost"); writeToHostsFile(excludeHostFile, ""); refreshNodesOption(doGraceful, conf); nm1.nodeHeartbeat(true); nm3.nodeHeartbeat(true); rm.drainEvents(); waitCount = 0; while(rmContext.getInactiveRMNodes().get( nm2.getNodeId()) != null && waitCount++ < 2){ synchronized (this) { wait(maxThreadSleeptime); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); } } Assert.assertEquals("host2 should have been forgotten!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("There should be no Lost NMs!", clusterMetrics.getNumLostNMs(), 0); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); rm.stop(); } private void testNodeRemovalUtilRebooted(boolean doGraceful) throws Exception { Configuration conf = new Configuration(); int timeoutValue = 500; File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); writeToHostsFile(hostFile, "host1", "localhost", "host2"); writeToHostsFile(excludeHostFile, ""); conf.setInt(YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, timeoutValue); rm = new MockRM(conf); rm.init(conf); rm.start(); RMContext rmContext = rm.getRMContext(); refreshNodesOption(doGraceful, conf); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); ClusterMetrics metrics = clusterMetrics; assert (metrics != null); NodeHeartbeatResponse nodeHeartbeat = nm2.nodeHeartbeat( new HashMap<ApplicationId, List<ContainerStatus>>(), true, -100); rm.drainEvents(); rm.drainEvents(); Assert.assertNotEquals("host2 should be a rebooted NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("host2 should be a rebooted NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()).getState(), NodeState.REBOOTED); Assert.assertEquals("There should be 1 Rebooted NM!", clusterMetrics.getNumRebootedNMs(), 1); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); int nodeRemovalTimeout = conf.getInt( YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, YarnConfiguration. DEFAULT_RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC); int nodeRemovalInterval = rmContext.getNodesListManager().getNodeRemovalCheckInterval(); long maxThreadSleeptime = nodeRemovalInterval + nodeRemovalTimeout; writeToHostsFile(hostFile, "host1", "localhost"); writeToHostsFile(excludeHostFile, ""); refreshNodesOption(doGraceful, conf); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(true); nm3.nodeHeartbeat(true); rm.drainEvents(); int waitCount = 0; while(rmContext.getInactiveRMNodes().get( nm2.getNodeId()) != null && waitCount++ < 2){ synchronized (this) { wait(maxThreadSleeptime); } } Assert.assertEquals("host2 should have been forgotten!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("There should be no Rebooted NMs!", clusterMetrics.getNumRebootedNMs(), 0); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); rm.stop(); } private void testNodeRemovalUtilUnhealthy(boolean doGraceful) throws Exception { Configuration conf = new Configuration(); int timeoutValue = 500; File excludeHostFile = new File(TEMP_DIR + File.separator + "excludeHostFile.txt"); conf.set(YarnConfiguration.RM_NODES_INCLUDE_FILE_PATH, hostFile.getAbsolutePath()); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, excludeHostFile.getAbsolutePath()); writeToHostsFile(hostFile, "host1", "localhost", "host2"); writeToHostsFile(excludeHostFile, ""); conf.setInt(YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, timeoutValue); rm = new MockRM(conf); rm.init(conf); rm.start(); RMContext rmContext = rm.getRMContext(); refreshNodesOption(doGraceful, conf); MockNM nm1 = rm.registerNode("host1:1234", 5120); MockNM nm2 = rm.registerNode("host2:5678", 10240); MockNM nm3 = rm.registerNode("localhost:4433", 1024); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); ClusterMetrics metrics = clusterMetrics; assert (metrics != null); rm.drainEvents(); //check all 3 nodes joined in as NORMAL NodeHeartbeatResponse nodeHeartbeat = nm1.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm2.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); nodeHeartbeat = nm3.nodeHeartbeat(true); Assert.assertTrue(NodeAction.NORMAL.equals(nodeHeartbeat.getNodeAction())); rm.drainEvents(); Assert.assertEquals("All 3 nodes should be active", metrics.getNumActiveNMs(), 3); // node healthy nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(false); nm3.nodeHeartbeat(true); checkUnhealthyNMCount(rm, nm2, true, 1); writeToHostsFile(hostFile, "host1", "localhost"); writeToHostsFile(excludeHostFile, ""); refreshNodesOption(doGraceful, conf); nm1.nodeHeartbeat(true); nm2.nodeHeartbeat(false); nm3.nodeHeartbeat(true); rm.drainEvents(); Assert.assertNotEquals("host2 should be a shutdown NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("host2 should be a shutdown NM!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()).getState(), NodeState.SHUTDOWN); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); Assert.assertEquals("There should be 1 Shutdown NM!", clusterMetrics.getNumShutdownNMs(), 1); Assert.assertEquals("There should be 0 Unhealthy NM!", clusterMetrics.getUnhealthyNMs(), 0); int nodeRemovalTimeout = conf.getInt( YarnConfiguration.RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC, YarnConfiguration. DEFAULT_RM_NODEMANAGER_UNTRACKED_REMOVAL_TIMEOUT_MSEC); int nodeRemovalInterval = rmContext.getNodesListManager().getNodeRemovalCheckInterval(); long maxThreadSleeptime = nodeRemovalInterval + nodeRemovalTimeout; int waitCount = 0; while(rmContext.getInactiveRMNodes().get( nm2.getNodeId()) != null && waitCount++ < 2){ synchronized (this) { wait(maxThreadSleeptime); } } Assert.assertEquals("host2 should have been forgotten!", rmContext.getInactiveRMNodes().get(nm2.getNodeId()), null); Assert.assertEquals("There should be no Shutdown NMs!", clusterMetrics.getNumRebootedNMs(), 0); Assert.assertEquals("There should be 2 Active NM!", clusterMetrics.getNumActiveNMs(), 2); rm.stop(); } private void writeToHostsFile(String... hosts) throws IOException { writeToHostsFile(hostFile, hosts); } private void writeToHostsFile(File file, String... hosts) throws IOException { if (!file.exists()) { TEMP_DIR.mkdirs(); file.createNewFile(); } FileOutputStream fStream = null; try { fStream = new FileOutputStream(file); for (int i = 0; i < hosts.length; i++) { fStream.write(hosts[i].getBytes()); fStream.write("\n".getBytes()); } } finally { if (fStream != null) { IOUtils.closeStream(fStream); fStream = null; } } } private void checkDecommissionedNMCount(MockRM rm, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumDecommisionedNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals(count, ClusterMetrics.getMetrics() .getNumDecommisionedNMs()); Assert.assertEquals("The decommisioned metrics are not updated", count, ClusterMetrics.getMetrics().getNumDecommisionedNMs()); } private void checkShutdownNMCount(MockRM rm, int count) throws InterruptedException { int waitCount = 0; while (ClusterMetrics.getMetrics().getNumShutdownNMs() != count && waitCount++ < 20) { synchronized (this) { wait(100); } } Assert.assertEquals("The shutdown metrics are not updated", count, ClusterMetrics.getMetrics().getNumShutdownNMs()); } @After public void tearDown() { if (hostFile != null && hostFile.exists()) { hostFile.delete(); } ClusterMetrics.destroy(); if (rm != null) { rm.stop(); } MetricsSystem ms = DefaultMetricsSystem.instance(); if (ms.getSource("ClusterMetrics") != null) { DefaultMetricsSystem.shutdown(); } } }
package org.jetbrains.plugins.gradle.service; import com.intellij.openapi.externalSystem.service.project.PlatformFacade; import com.intellij.openapi.externalSystem.util.ExternalSystemConstants; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.ContainerUtilRt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleEnvironment; import org.jetbrains.plugins.gradle.util.GradleLog; import org.jetbrains.plugins.gradle.util.GradleUtil; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; /** * Encapsulates algorithm of gradle libraries discovery. * <p/> * Thread-safe. * * @author Denis Zhdanov * @since 8/4/11 11:06 AM */ @SuppressWarnings("MethodMayBeStatic") public class GradleInstallationManager { public static final Pattern GRADLE_JAR_FILE_PATTERN; public static final Pattern ANY_GRADLE_JAR_FILE_PATTERN; private static final String[] GRADLE_START_FILE_NAMES; @NonNls private static final String GRADLE_ENV_PROPERTY_NAME; static { // Init static data with ability to redefine it locally. GRADLE_JAR_FILE_PATTERN = Pattern.compile(System.getProperty("gradle.pattern.core.jar", "gradle-(core-)?(\\d.*)\\.jar")); ANY_GRADLE_JAR_FILE_PATTERN = Pattern.compile(System.getProperty("gradle.pattern.core.jar", "gradle-(.*)\\.jar")); GRADLE_START_FILE_NAMES = System.getProperty("gradle.start.file.names", "gradle:gradle.cmd:gradle.sh").split(":"); GRADLE_ENV_PROPERTY_NAME = System.getProperty("gradle.home.env.key", "GRADLE_HOME"); } @NotNull private final PlatformFacade myPlatformFacade; @Nullable private Ref<File> myCachedGradleHomeFromPath; public GradleInstallationManager(@NotNull PlatformFacade facade) { myPlatformFacade = facade; } /** * Allows to get file handles for the gradle binaries to use. * * @param project target project * @param linkedProjectPath path to the target external project's config * @return file handles for the gradle binaries; <code>null</code> if gradle is not discovered */ @Nullable public Collection<File> getAllLibraries(@Nullable Project project, @NotNull String linkedProjectPath) { // Manually defined gradle home File gradleHome = getGradleHome(project, linkedProjectPath); if (gradleHome == null || !gradleHome.isDirectory()) { return null; } List<File> result = ContainerUtilRt.newArrayList(); File libs = new File(gradleHome, "lib"); File[] files = libs.listFiles(); if (files != null) { for (File file : files) { if (file.getName().endsWith(".jar")) { result.add(file); } } } File plugins = new File(libs, "plugins"); files = plugins.listFiles(); if (files != null) { for (File file : files) { if (file.getName().endsWith(".jar")) { result.add(file); } } } return result.isEmpty() ? null : result; } /** * Tries to return file handle that points to the gradle installation home. * * @param project target project (if any) * @param linkedProjectPath path to the target linked project config * @return file handle that points to the gradle installation home (if any) */ @Nullable public File getGradleHome(@Nullable Project project, @NotNull String linkedProjectPath) { File result = getWrapperHome(project, linkedProjectPath); if (result != null) { return result; } result = getManuallyDefinedGradleHome(project, linkedProjectPath); if (result != null) { return result; } return getAutodetectedGradleHome(); } /** * Tries to deduce gradle location from current environment. * * @return gradle home deduced from the current environment (if any); <code>null</code> otherwise */ @Nullable public File getAutodetectedGradleHome() { File result = getGradleHomeFromPath(); return result == null ? getGradleHomeFromEnvProperty() : result; } /** * Tries to return gradle home that is defined as a dependency to the given module. * * @param module target module * @return file handle that points to the gradle installation home defined as a dependency of the given module (if any) */ @Nullable public VirtualFile getGradleHome(@Nullable Module module) { if (module == null) { return null; } final VirtualFile[] roots = OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots(); if (roots == null) { return null; } for (VirtualFile root : roots) { if (root != null && isGradleSdkHome(root)) { return root; } } return null; } /** * Tries to return gradle home defined as a dependency of the given module; falls back to the project-wide settings otherwise. * * @param module target module that can have gradle home as a dependency * @param project target project which gradle home setting should be used if module-specific gradle location is not defined * @return gradle home derived from the settings of the given entities (if any); <code>null</code> otherwise */ @Nullable public VirtualFile getGradleHome(@Nullable Module module, @Nullable Project project, @NotNull String linkedProjectPath) { final VirtualFile result = getGradleHome(module); if (result != null) { return result; } final File home = getGradleHome(project, linkedProjectPath); return home == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(home); } @Nullable public File getWrapperHome(@Nullable Project project, @NotNull String linkedProjectPath) { if (project == null) { return null; } GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath); if (settings == null) { return null; } if (settings.isPreferLocalInstallationToWrapper()) { return null; } String distribution = GradleUtil.getWrapperDistribution(linkedProjectPath); if (distribution == null) { return null; } File gradleSystemDir = new File(System.getProperty("user.home"), ".gradle"); if (!gradleSystemDir.isDirectory()) { return null; } File gradleWrapperDistributionsHome = new File(gradleSystemDir, "wrapper/dists"); if (!gradleWrapperDistributionsHome.isDirectory()) { return null; } File targetDistributionHome = new File(gradleWrapperDistributionsHome, distribution); if (!targetDistributionHome.isDirectory()) { return null; } File[] files = targetDistributionHome.listFiles(); if (files == null || files.length != 1) { // Gradle keeps wrapper at a directory which name is a hash value like '35oej0jnbfh6of4dd05531edaj' return null; } File[] distFiles = files[0].listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } }); if (distFiles == null || distFiles.length != 1) { // There should exist only the gradle directory in the distribution directory return null; } return distFiles[0].isDirectory() ? distFiles[0] : null; } /** * Allows to ask for user-defined path to gradle. * * @param project target project to use (if any) * @return path to the gradle distribution (if the one is explicitly configured) */ @Nullable public File getManuallyDefinedGradleHome(@Nullable Project project, @NotNull String linkedProjectPath) { if (project == null) { return null; } GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath); if (settings == null) { return null; } String path = settings.getGradleHome(); if (path == null) { return null; } File candidate = new File(path); return isGradleSdkHome(candidate) ? candidate : null; } /** * Tries to discover gradle installation path from the configured system path * * @return file handle for the gradle directory if it's possible to deduce from the system path; <code>null</code> otherwise */ @Nullable public File getGradleHomeFromPath() { Ref<File> ref = myCachedGradleHomeFromPath; if (ref != null) { return ref.get(); } String path = System.getenv("PATH"); if (path == null) { return null; } for (String pathEntry : path.split(File.pathSeparator)) { File dir = new File(pathEntry); if (!dir.isDirectory()) { continue; } for (String fileName : GRADLE_START_FILE_NAMES) { File startFile = new File(dir, fileName); if (startFile.isFile()) { File candidate = dir.getParentFile(); if (isGradleSdkHome(candidate)) { myCachedGradleHomeFromPath = new Ref<File>(candidate); return candidate; } } } } return null; } /** * Tries to discover gradle installation via environment property. * * @return file handle for the gradle directory deduced from the system property (if any) */ @Nullable public File getGradleHomeFromEnvProperty() { String path = System.getenv(GRADLE_ENV_PROPERTY_NAME); if (path == null) { return null; } File candidate = new File(path); return isGradleSdkHome(candidate) ? candidate : null; } /** * Does the same job as {@link #isGradleSdkHome(File)} for the given virtual file. * * @param file gradle installation home candidate * @return <code>true</code> if given file points to the gradle installation; <code>false</code> otherwise */ public boolean isGradleSdkHome(@Nullable VirtualFile file) { if (file == null) { return false; } return isGradleSdkHome(new File(file.getPath())); } /** * Allows to answer if given virtual file points to the gradle installation root. * * @param file gradle installation root candidate * @return <code>true</code> if we consider that given file actually points to the gradle installation root; * <code>false</code> otherwise */ public boolean isGradleSdkHome(@Nullable File file) { if (file == null) { return false; } final File libs = new File(file, "lib"); if (!libs.isDirectory()) { if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) { GradleLog.LOG.info(String.format( "Gradle sdk check failed for the path '%s'. Reason: it doesn't have a child directory named 'lib'", file.getAbsolutePath() )); } return false; } final boolean found = isGradleSdk(libs.listFiles()); if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) { GradleLog.LOG.info(String.format("Gradle home check %s for the path '%s'", found ? "passed" : "failed", file.getAbsolutePath())); } return found; } /** * Allows to answer if given files contain the one from gradle installation. * * @param files files to process * @return <code>true</code> if one of the given files is from the gradle installation; <code>false</code> otherwise */ public boolean isGradleSdk(@Nullable VirtualFile... files) { if (files == null) { return false; } File[] arg = new File[files.length]; for (int i = 0; i < files.length; i++) { arg[i] = new File(files[i].getPath()); } return isGradleSdk(arg); } private boolean isGradleSdk(@Nullable File ... files) { return findGradleJar(files) != null; } @Nullable private File findGradleJar(@Nullable File ... files) { if (files == null) { return null; } for (File file : files) { if (GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches()) { return file; } } if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) { StringBuilder filesInfo = new StringBuilder(); for (File file : files) { filesInfo.append(file.getAbsolutePath()).append(';'); } if (filesInfo.length() > 0) { filesInfo.setLength(filesInfo.length() - 1); } GradleLog.LOG.info(String.format( "Gradle sdk check fails. Reason: no one of the given files matches gradle jar pattern (%s). Files: %s", GRADLE_JAR_FILE_PATTERN.toString(), filesInfo )); } return null; } /** * Allows to ask for the classpath roots of the classes that are additionally provided by the gradle integration (e.g. gradle class * files, bundled groovy-all jar etc). * * @param project target project to use for gradle home retrieval * @return classpath roots of the classes that are additionally provided by the gradle integration (if any); * <code>null</code> otherwise */ @Nullable public List<VirtualFile> getClassRoots(@Nullable Project project) { if (project == null) { project = ProjectManager.getInstance().getDefaultProject(); } for (Module module : myPlatformFacade.getModules(project)) { String path = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY); if (StringUtil.isEmpty(path)) { continue; } assert path != null; final Collection<File> libraries = getAllLibraries(project, path); if (libraries == null) { continue; } final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); final JarFileSystem jarFileSystem = JarFileSystem.getInstance(); List<VirtualFile> result = new ArrayList<VirtualFile>(); for (File file : libraries) { if (ANY_GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches() || GroovyConfigUtils.matchesGroovyAll(file.getName())) { final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file); if (virtualFile != null) { ContainerUtil.addIfNotNull(result, jarFileSystem.getJarRootForLocalFile(virtualFile)); } } } return result; } return null; } }
/*- * ========================LICENSE_START================================= * Bucket4j * %% * Copyright (C) 2015 - 2020 Vladimir Bukhtoyarov * %% * 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. * =========================LICENSE_END================================== */ package io.github.bucket4j; import java.text.MessageFormat; import java.time.Duration; import java.time.Instant; public final class BucketExceptions { // ------------------- construction time exceptions -------------------------------- public static IllegalArgumentException nonPositiveCapacity(long capacity) { String pattern = "{0} is wrong value for capacity, because capacity should be positive"; String msg = MessageFormat.format(pattern, capacity); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveInitialTokens(long initialTokens) { String pattern = "{0} is wrong value for initial capacity, because initial tokens count should be positive"; String msg = MessageFormat.format(pattern, initialTokens); return new IllegalArgumentException(msg); } public static IllegalArgumentException nullBandwidth() { String msg = "Bandwidth can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullBandwidthRefill() { String msg = "Bandwidth refill can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullTimeMeter() { String msg = "Time meter can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullSynchronizationStrategy() { String msg = "Synchronization strategy can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullListener() { String msg = "listener can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullRefillPeriod() { String msg = "Refill period can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullFixedRefillInterval() { String msg = "Fixed refill interval can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullScheduler() { String msg = "Scheduler can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullConfiguration() { String msg = "Configuration can not be null"; return new IllegalArgumentException(msg); } public static Throwable nullConfigurationFuture() { String msg = "Configuration future can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullConfigurationSupplier() { String msg = "Configuration supplier can not be null"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositivePeriod(long period) { String pattern = "{0} is wrong value for period of bandwidth, because period should be positive"; String msg = MessageFormat.format(pattern, period); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveLimitToSync(long unsynchronizedPeriod) { String pattern = "{0} is wrong value for limit to sync, because period should be positive"; String msg = MessageFormat.format(pattern, unsynchronizedPeriod); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveFixedRefillInterval(Duration fixedRefillInterval) { String pattern = "{0} is wrong value for fixed refill interval, because period should be positive"; String msg = MessageFormat.format(pattern, fixedRefillInterval); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositivePeriodTokens(long tokens) { String pattern = "{0} is wrong value for period tokens, because tokens should be positive"; String msg = MessageFormat.format(pattern, tokens); return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException nonPositiveTokensForDelayParameters(long maxUnsynchronizedTokens) { String pattern = "{0} is wrong value for maxUnsynchronizedTokens, because tokens should be positive"; String msg = MessageFormat.format(pattern, maxUnsynchronizedTokens); return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException nullMaxTimeoutBetweenSynchronizationForDelayParameters() { String msg = "maxTimeoutBetweenSynchronization can not be null"; return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException nonPositiveMaxTimeoutBetweenSynchronizationForDelayParameters(Duration maxTimeoutBetweenSynchronization) { String pattern = "maxTimeoutBetweenSynchronization = {0}, maxTimeoutBetweenSynchronization can not be negative"; String msg = MessageFormat.format(pattern, maxTimeoutBetweenSynchronization); return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException wrongValueOfMinSamplesForPredictionParameters(int minSamples) { String pattern = "minSamples = {0}, minSamples must be >= 2"; String msg = MessageFormat.format(pattern, minSamples); return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException maxSamplesForPredictionParametersCanNotBeLessThanMinSamples(int minSamples, int maxSamples) { String pattern = "minSamples = {0}, maxSamples = {1}, maxSamples must be >= minSamples"; String msg = MessageFormat.format(pattern, minSamples, maxSamples); return new IllegalArgumentException(msg); } // TODO add test public static IllegalArgumentException nonPositiveSampleMaxAgeForPredictionParameters(long maxUnsynchronizedTimeoutNanos) { String pattern = "maxUnsynchronizedTimeoutNanos = {0}, maxUnsynchronizedTimeoutNanos must be positive"; String msg = MessageFormat.format(pattern, maxUnsynchronizedTimeoutNanos); return new IllegalArgumentException(msg); } public static IllegalArgumentException restrictionsNotSpecified() { String msg = "At list one limited bandwidth should be specified"; return new IllegalArgumentException(msg); } public static IllegalArgumentException tooHighRefillRate(long periodNanos, long tokens) { double actualRate = (double) tokens / (double) periodNanos; String pattern = "{0} token/nanosecond is not permitted refill rate" + ", because highest supported rate is 1 token/nanosecond"; String msg = MessageFormat.format(pattern, actualRate); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveTimeOfFirstRefill(Instant timeOfFirstRefill) { String pattern = "{0} is wrong value for timeOfFirstRefill, because timeOfFirstRefill should be a positive date"; String msg = MessageFormat.format(pattern, timeOfFirstRefill); return new IllegalArgumentException(msg); } public static IllegalArgumentException intervallyAlignedRefillWithAdaptiveInitialTokensIncompatipleWithManualSpecifiedInitialTokens() { String msg = "Intervally aligned Refill With adaptive initial tokens incompatiple with maanual specified initial tokens"; return new IllegalArgumentException(msg); } public static IllegalArgumentException intervallyAlignedRefillCompatibleOnlyWithWallClock() { String msg = "intervally aligned refill is compatible only with wall-clock style TimeMeter"; return new IllegalArgumentException(msg); } public static IllegalArgumentException foundTwoBandwidthsWithSameId(int firstIndex, int secondIndex, String id) { String pattern = "All identifiers must unique. Id: {0}, first index: {1}, second index: {2}"; String msg = MessageFormat.format(pattern, id, firstIndex, secondIndex); return new IllegalArgumentException(msg); } // ------------------- end of construction time exceptions -------------------------------- // ------------------- usage time exceptions --------------------------------------------- public static IllegalArgumentException nonPositiveNanosToWait(long waitIfBusyNanos) { String pattern = "Waiting value should be positive, {0} is wrong waiting period"; String msg = MessageFormat.format(pattern, waitIfBusyNanos); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveTokensToConsume(long tokens) { String pattern = "Unable to consume {0} tokens, due to number of tokens to consume should be positive"; String msg = MessageFormat.format(pattern, tokens); return new IllegalArgumentException(msg); } public static IllegalArgumentException nonPositiveTokensLimitToSync(long tokens) { String pattern = "Sync threshold tokens should be positive, {0} is wrong waiting period"; String msg = MessageFormat.format(pattern, tokens); return new IllegalArgumentException(msg); } public static IllegalArgumentException reservationOverflow() { String msg = "Existed hardware is unable to service the reservation of so many tokens"; return new IllegalArgumentException(msg); } public static IllegalArgumentException nullTokensInheritanceStrategy() { String msg = "Tokens migration mode must not be null"; return new IllegalArgumentException(msg); } public static BucketExecutionException executionException(Throwable cause) { return new BucketExecutionException(cause); } public static UnsupportedOperationException asyncModeIsNotSupported() { String msg = "Asynchronous mode is not supported"; return new UnsupportedOperationException(msg); } public static class BucketExecutionException extends RuntimeException { public BucketExecutionException(Throwable cause) { super(cause); } public BucketExecutionException(String message) { super(message); } } private BucketExceptions() { // private constructor for utility class } }
/** * 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.cassandra.serializers; import org.junit.Test; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; public class TimeSerializerTest { @Test public void testSerializerFromString() { // nano long expected = 5; Long time = TimeSerializer.timeStringToLong("00:00:00.000000005"); assert time == expected : String.format("Failed nano conversion. Expected %s, got %s", expected, time); // usec expected = TimeUnit.MICROSECONDS.toNanos(123); time = TimeSerializer.timeStringToLong("00:00:00.000123000"); assert time == expected : String.format("Failed usec conversion. Expected %s, got %s", expected, time); // milli expected = TimeUnit.MILLISECONDS.toNanos(123); time = TimeSerializer.timeStringToLong("00:00:00.123000"); assert time == expected : String.format("Failed milli conversion. Expected %s, got %s", expected, time); // sec expected = TimeUnit.SECONDS.toNanos(15); time = TimeSerializer.timeStringToLong("00:00:15.000"); assert time == expected : String.format("Failed sec conversion. Expected %s, got %s", expected, time); // min expected = TimeUnit.MINUTES.toNanos(13); time = TimeSerializer.timeStringToLong("00:13:00.000"); assert time == expected : String.format("Failed min conversion. Expected %s, got %s", expected, time); // hour expected = TimeUnit.HOURS.toNanos(2); time = TimeSerializer.timeStringToLong("02:0:00.000"); assert time == expected : String.format("Failed min conversion. Expected %s, got %s", expected, time); // complex expected = buildExpected(4, 31, 12, 123, 456, 789); time = TimeSerializer.timeStringToLong("4:31:12.123456789"); assert time == expected : String.format("Failed complex conversion. Expected %s, got %s", expected, time); // upper bound expected = buildExpected(23, 59, 59, 999, 999, 999); time = TimeSerializer.timeStringToLong("23:59:59.999999999"); assert time == expected : String.format("Failed upper bounds conversion. Expected %s, got %s", expected, time); // Test partial nano expected = buildExpected(12, 13, 14, 123, 654, 120); time = TimeSerializer.timeStringToLong("12:13:14.12365412"); assert time == expected : String.format("Failed partial nano timestring. Expected %s, got %s", expected, time); // Test raw long value expected = 10; time = TimeSerializer.timeStringToLong("10"); assert time == expected : String.format("Failed long conversion. Expected %s, got %s", expected, time); // Test 0 long expected = 0; time = TimeSerializer.timeStringToLong("0"); assert time == expected : String.format("Failed long conversion. Expected %s, got %s", expected, time); } private long buildExpected(int hour, int minute, int second, int milli, int micro, int nano) { return TimeUnit.HOURS.toNanos(hour) + TimeUnit.MINUTES.toNanos(minute) + TimeUnit.SECONDS.toNanos(second) + TimeUnit.MILLISECONDS.toNanos(milli) + TimeUnit.MICROSECONDS.toNanos(micro) + nano; } @Test public void testSerializerToString() { String source = "00:00:00.000000011"; Long time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "00:00:00.000012311"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "00:00:00.123000000"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "00:00:12.123450000"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "00:34:12.123450000"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "15:00:12.123450000"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); // boundaries source = "00:00:00.000000000"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); source = "23:59:59.999999999"; time = TimeSerializer.timeStringToLong(source); assert(source.equals(TimeSerializer.instance.toString(time))); // truncated source = "01:14:18.12"; time = TimeSerializer.timeStringToLong(source); String result = TimeSerializer.instance.toString(time); assert(result.equals("01:14:18.120000000")); source = "01:14:18.1201"; time = TimeSerializer.timeStringToLong(source); result = TimeSerializer.instance.toString(time); assert(result.equals("01:14:18.120100000")); source = "01:14:18.1201098"; time = TimeSerializer.timeStringToLong(source); result = TimeSerializer.instance.toString(time); assert(result.equals("01:14:18.120109800")); } @Test public void testSerialization() { String source = "01:01:01.123123123"; Long nt = TimeSerializer.timeStringToLong(source); ByteBuffer buf = TimeSerializer.instance.serialize(nt); TimeSerializer.instance.validate(buf); Long result = TimeSerializer.instance.deserialize(buf); String strResult = TimeSerializer.instance.toString(result); assert(strResult.equals(source)); } @Test (expected=MarshalException.class) public void testBadHourLow() { Long time = TimeSerializer.timeStringToLong("-1:0:0.123456789"); } @Test (expected=MarshalException.class) public void testBadHourHigh() { Long time = TimeSerializer.timeStringToLong("24:0:0.123456789"); } @Test (expected=MarshalException.class) public void testBadMinuteLow() { Long time = TimeSerializer.timeStringToLong("23:-1:0.123456789"); } @Test (expected=MarshalException.class) public void testBadMinuteHigh() { Long time = TimeSerializer.timeStringToLong("23:60:0.123456789"); } @Test (expected=MarshalException.class) public void testEmpty() { Long time = TimeSerializer.timeStringToLong(""); } @Test (expected=MarshalException.class) public void testBadSecondLow() { Long time = TimeSerializer.timeStringToLong("23:59:-1.123456789"); } @Test (expected=MarshalException.class) public void testBadSecondHigh() { Long time = TimeSerializer.timeStringToLong("23:59:60.123456789"); } @Test (expected=MarshalException.class) public void testBadSecondHighNoMilli() { Long time = TimeSerializer.timeStringToLong("23:59:60"); } @Test (expected=MarshalException.class) public void testBadNanoLow() { Long time = TimeSerializer.timeStringToLong("23:59:59.-123456789"); } @Test (expected=MarshalException.class) public void testBadNanoHigh() { Long time = TimeSerializer.timeStringToLong("23:59:59.1234567899"); } @Test (expected=MarshalException.class) public void testBadNanoCharacter() { Long time = TimeSerializer.timeStringToLong("23:59:59.12345A789"); } @Test (expected=MarshalException.class) public void testNegativeLongTime() { Long time = TimeSerializer.timeStringToLong("-10"); } @Test (expected=MarshalException.class) public void testRawLongOverflow() { Long input = TimeUnit.DAYS.toNanos(1) + 1; Long time = TimeSerializer.timeStringToLong(input.toString()); } }
/* * 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.drill.test.rowSet.test; import static org.apache.drill.test.rowSet.RowSetUtilities.dec; import static org.apache.drill.test.rowSet.RowSetUtilities.strArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.util.Arrays; import org.apache.drill.categories.RowSetTests; import org.apache.drill.common.exceptions.UserException; import org.apache.drill.common.types.TypeProtos.DataMode; import org.apache.drill.common.types.TypeProtos.MajorType; import org.apache.drill.common.types.TypeProtos.MinorType; import org.apache.drill.exec.record.SimpleVectorWrapper; import org.apache.drill.exec.record.metadata.SchemaBuilder; import org.apache.drill.exec.record.metadata.TupleMetadata; import org.apache.drill.exec.vector.DateUtilities; import org.apache.drill.exec.vector.NullableVarCharVector; import org.apache.drill.exec.vector.ValueVector; import org.apache.drill.exec.vector.accessor.ArrayReader; import org.apache.drill.exec.vector.accessor.ArrayWriter; import org.apache.drill.exec.vector.accessor.ScalarReader; import org.apache.drill.exec.vector.accessor.ScalarWriter; import org.apache.drill.exec.vector.accessor.ValueType; import org.apache.drill.shaded.guava.com.google.common.collect.Lists; import org.apache.drill.test.SubOperatorTest; import org.apache.drill.exec.physical.rowSet.DirectRowSet; import org.apache.drill.exec.physical.rowSet.RowSet; import org.apache.drill.exec.physical.rowSet.RowSet.SingleRowSet; import org.apache.drill.exec.physical.rowSet.RowSetBuilder; import org.apache.drill.exec.physical.rowSet.RowSetReader; import org.apache.drill.test.rowSet.RowSetUtilities; import org.apache.drill.exec.physical.rowSet.RowSetWriter; import org.joda.time.DateTimeZone; import org.joda.time.Instant; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.joda.time.Period; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Verify that simple scalar (non-repeated) column readers * and writers work as expected. The focus is on the generated * and type-specific functions for each type. */ // The following types are not fully supported in Drill // TODO: Var16Char // TODO: Bit @Category(RowSetTests.class) public class TestScalarAccessors extends SubOperatorTest { @Test public void testUInt1RW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.UINT1) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0) .addRow(0x7F) .addRow(0xFF) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(0x7F, colReader.getInt()); assertEquals(0x7F, colReader.getObject()); assertEquals(Integer.toString(0x7F), colReader.getAsString()); assertTrue(reader.next()); assertEquals(0xFF, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } @Test public void testUInt2RW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.UINT2) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0) .addRow(0x7FFF) .addRow(0xFFFF) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(0x7FFF, colReader.getInt()); assertEquals(0x7FFF, colReader.getObject()); assertEquals(Integer.toString(0x7FFF), colReader.getAsString()); assertTrue(reader.next()); assertEquals(0xFFFF, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } @Test public void testTinyIntRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.TINYINT) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0) .addRow(Byte.MAX_VALUE) .addRow(Byte.MIN_VALUE) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(Byte.MAX_VALUE, colReader.getInt()); assertEquals((int) Byte.MAX_VALUE, colReader.getObject()); assertEquals(Byte.toString(Byte.MAX_VALUE), colReader.getAsString()); assertTrue(reader.next()); assertEquals(Byte.MIN_VALUE, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } private void nullableIntTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addNullable("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(10) .addSingleCol(null) .addRow(30) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(10, colReader.getInt()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); // Data value is undefined, may be garbage assertTrue(reader.next()); assertEquals(30, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableTinyInt() { nullableIntTester(MinorType.TINYINT); } private void intArrayTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addArray("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new int[] {}) .addSingleCol(new int[] {0, 20, 30}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getInt()); assertEquals(0, colReader.getObject()); assertEquals("0", colReader.getAsString()); assertTrue(arrayReader.next()); assertFalse(colReader.isNull()); assertEquals(20, colReader.getInt()); assertEquals(20, colReader.getObject()); assertEquals("20", colReader.getAsString()); assertTrue(arrayReader.next()); assertFalse(colReader.isNull()); assertEquals(30, colReader.getInt()); assertEquals(30, colReader.getObject()); assertEquals("30", colReader.getAsString()); assertFalse(arrayReader.next()); assertEquals("[0, 20, 30]", arrayReader.getAsString()); assertEquals(Lists.newArrayList(0, 20, 30), arrayReader.getObject()); assertFalse(reader.next()); rs.clear(); } @Test public void testTinyIntArray() { intArrayTester(MinorType.TINYINT); } @Test public void testSmallIntRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.SMALLINT) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0) .addRow(Short.MAX_VALUE) .addRow(Short.MIN_VALUE) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(Short.MAX_VALUE, colReader.getInt()); assertEquals((int) Short.MAX_VALUE, colReader.getObject()); assertEquals(Short.toString(Short.MAX_VALUE), colReader.getAsString()); assertTrue(reader.next()); assertEquals(Short.MIN_VALUE, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableSmallInt() { nullableIntTester(MinorType.SMALLINT); } @Test public void testSmallArray() { intArrayTester(MinorType.SMALLINT); } @Test public void testIntRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.INT) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0) .addRow(Integer.MAX_VALUE) .addRow(Integer.MIN_VALUE) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.INTEGER, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, reader.scalar(0).getInt()); assertTrue(reader.next()); assertEquals(Integer.MAX_VALUE, colReader.getInt()); assertEquals(Integer.MAX_VALUE, colReader.getObject()); assertEquals(Integer.toString(Integer.MAX_VALUE), colReader.getAsString()); assertTrue(reader.next()); assertEquals(Integer.MIN_VALUE, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableInt() { nullableIntTester(MinorType.INT); } @Test public void testIntArray() { intArrayTester(MinorType.INT); } private void longRWTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .add("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0L) .addRow(Long.MAX_VALUE) .addRow(Long.MIN_VALUE) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.LONG, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getLong()); assertTrue(reader.next()); assertEquals(Long.MAX_VALUE, colReader.getLong()); if (colReader.extendedType() == ValueType.LONG) { assertEquals(Long.MAX_VALUE, colReader.getObject()); assertEquals(Long.toString(Long.MAX_VALUE), colReader.getAsString()); } assertTrue(reader.next()); assertEquals(Long.MIN_VALUE, colReader.getLong()); assertFalse(reader.next()); rs.clear(); } @Test public void testLongRW() { longRWTester(MinorType.BIGINT); } private void nullableLongTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addNullable("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(10L) .addSingleCol(null) .addRow(30L) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(10, colReader.getLong()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); // Data value is undefined, may be garbage assertTrue(reader.next()); assertEquals(30, colReader.getLong()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableLong() { nullableLongTester(MinorType.BIGINT); } private void longArrayTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addArray("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new long[] {}) .addSingleCol(new long[] {0, 20, 30}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.LONG, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(0, colReader.getLong()); if (colReader.extendedType() == ValueType.LONG) { assertEquals(0L, colReader.getObject()); assertEquals("0", colReader.getAsString()); } assertTrue(arrayReader.next()); assertEquals(20, colReader.getLong()); if (colReader.extendedType() == ValueType.LONG) { assertEquals(20L, colReader.getObject()); assertEquals("20", colReader.getAsString()); } assertTrue(arrayReader.next()); assertEquals(30, colReader.getLong()); if (colReader.extendedType() == ValueType.LONG) { assertEquals(30L, colReader.getObject()); assertEquals("30", colReader.getAsString()); } assertFalse(arrayReader.next()); if (colReader.extendedType() == ValueType.LONG) { assertEquals("[0, 20, 30]", arrayReader.getAsString()); assertEquals(Lists.newArrayList(0L, 20L, 30L), arrayReader.getObject()); } assertFalse(reader.next()); rs.clear(); } @Test public void testLongArray() { longArrayTester(MinorType.BIGINT); } @Test public void testFloatRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.FLOAT4) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0F) .addRow(Float.MAX_VALUE) .addRow(Float.MIN_VALUE) .addRow(100F) .build(); assertEquals(4, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DOUBLE, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getDouble(), 0.000001); assertTrue(reader.next()); assertEquals(Float.MAX_VALUE, colReader.getDouble(), 0.000001); assertEquals(Float.MAX_VALUE, (double) colReader.getObject(), 0.000001); assertTrue(reader.next()); assertEquals(Float.MIN_VALUE, colReader.getDouble(), 0.000001); assertTrue(reader.next()); assertEquals(100, colReader.getDouble(), 0.000001); assertEquals("100.0", colReader.getAsString()); assertFalse(reader.next()); rs.clear(); } private void nullableDoubleTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addNullable("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(10F) .addSingleCol(null) .addRow(30F) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(10, colReader.getDouble(), 0.000001); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); // Data value is undefined, may be garbage assertTrue(reader.next()); assertEquals(30, colReader.getDouble(), 0.000001); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableFloat() { nullableDoubleTester(MinorType.FLOAT4); } private void doubleArrayTester(MinorType type) { TupleMetadata schema = new SchemaBuilder() .addArray("col", type) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new double[] {}) .addSingleCol(new double[] {0, 20.5, 30.0}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.DOUBLE, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(0, colReader.getDouble(), 0.00001); assertEquals(0, (double) colReader.getObject(), 0.00001); assertEquals("0.0", colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(20.5, colReader.getDouble(), 0.00001); assertEquals(20.5, (double) colReader.getObject(), 0.00001); assertEquals("20.5", colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(30.0, colReader.getDouble(), 0.00001); assertEquals(30.0, (double) colReader.getObject(), 0.00001); assertEquals("30.0", colReader.getAsString()); assertFalse(arrayReader.next()); assertEquals("[0.0, 20.5, 30.0]", arrayReader.getAsString()); assertEquals(Lists.newArrayList(0.0D, 20.5D, 30D), arrayReader.getObject()); assertFalse(reader.next()); rs.clear(); } @Test public void testFloatArray() { doubleArrayTester(MinorType.FLOAT4); } @Test public void testDoubleRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.FLOAT8) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(0D) .addRow(Double.MAX_VALUE) .addRow(Double.MIN_VALUE) .addRow(100D) .build(); assertEquals(4, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DOUBLE, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, colReader.getDouble(), 0.000001); assertTrue(reader.next()); assertEquals(Double.MAX_VALUE, colReader.getDouble(), 0.000001); assertEquals(Double.MAX_VALUE, (double) colReader.getObject(), 0.000001); assertTrue(reader.next()); assertEquals(Double.MIN_VALUE, colReader.getDouble(), 0.000001); assertTrue(reader.next()); assertEquals(100, colReader.getDouble(), 0.000001); assertEquals("100.0", colReader.getAsString()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableDouble() { nullableDoubleTester(MinorType.FLOAT8); } @Test public void testDoubleArray() { doubleArrayTester(MinorType.FLOAT8); } @Test public void testVarcharRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.VARCHAR) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow("") .addRow("fred") .addRow("barney") .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.STRING, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals("", colReader.getString()); assertTrue(reader.next()); assertEquals("fred", colReader.getString()); assertEquals("fred", colReader.getObject()); assertEquals("\"fred\"", colReader.getAsString()); assertTrue(reader.next()); assertEquals("barney", colReader.getString()); assertEquals("barney", colReader.getObject()); assertEquals("\"barney\"", colReader.getAsString()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableVarchar() { TupleMetadata schema = new SchemaBuilder() .addNullable("col", MinorType.VARCHAR) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow("") .addSingleCol(null) .addRow("abcd") .build(); assertEquals(3, rs.rowCount()); SimpleVectorWrapper<?> vw = (SimpleVectorWrapper<?>) rs.container().getValueVector(0); NullableVarCharVector v = (NullableVarCharVector) vw.getValueVector(); assertEquals(3, v.getMutator().getLastSet()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals("", colReader.getString()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertEquals("abcd", colReader.getString()); assertEquals("abcd", colReader.getObject()); assertEquals("\"abcd\"", colReader.getAsString()); assertFalse(reader.next()); rs.clear(); } @Test public void testVarcharArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.VARCHAR) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new String[] {}) .addSingleCol(new String[] {"fred", "", "wilma"}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.STRING, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals("fred", colReader.getString()); assertEquals("fred", colReader.getObject()); assertEquals("\"fred\"", colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals("", colReader.getString()); assertEquals("", colReader.getObject()); assertEquals("\"\"", colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals("wilma", colReader.getString()); assertEquals("wilma", colReader.getObject()); assertEquals("\"wilma\"", colReader.getAsString()); assertFalse(arrayReader.next()); assertEquals("[\"fred\", \"\", \"wilma\"]", arrayReader.getAsString()); assertEquals(Lists.newArrayList("fred", "", "wilma"), arrayReader.getObject()); assertFalse(reader.next()); rs.clear(); } /** * Test the low-level interval-year utilities used by the column accessors. */ @Test public void testIntervalYearUtils() { { Period expected = Period.months(0); Period actual = DateUtilities.fromIntervalYear(0); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalYearStringBuilder(expected).toString(); assertEquals("0 years 0 months", fmt); } { Period expected = Period.years(1).plusMonths(2); Period actual = DateUtilities.fromIntervalYear(DateUtilities.periodToMonths(expected)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalYearStringBuilder(expected).toString(); assertEquals("1 year 2 months", fmt); } { Period expected = Period.years(6).plusMonths(1); Period actual = DateUtilities.fromIntervalYear(DateUtilities.periodToMonths(expected)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalYearStringBuilder(expected).toString(); assertEquals("6 years 1 month", fmt); } } @Test public void testIntervalYearRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.INTERVALYEAR) .buildSchema(); Period p1 = Period.years(0); Period p2 = Period.years(2).plusMonths(3); Period p3 = Period.years(1234).plusMonths(11); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addRow(p2) .addRow(p3) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(p1, colReader.getPeriod()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod()); assertEquals(p2, colReader.getObject()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(reader.next()); assertEquals(p3, colReader.getPeriod()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableIntervalYear() { TupleMetadata schema = new SchemaBuilder() .addNullable("col", MinorType.INTERVALYEAR) .buildSchema(); Period p1 = Period.years(0); Period p2 = Period.years(2).plusMonths(3); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addSingleCol(null) .addRow(p2) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(p1, colReader.getPeriod()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod()); assertFalse(reader.next()); rs.clear(); } @Test public void testIntervalYearArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.INTERVALYEAR) .buildSchema(); Period p1 = Period.years(0); Period p2 = Period.years(2).plusMonths(3); Period p3 = Period.years(1234).plusMonths(11); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new Period[] {}) .addSingleCol(new Period[] {p1, p2, p3}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(p1, colReader.getPeriod()); assertTrue(arrayReader.next()); assertEquals(p2, colReader.getPeriod()); assertEquals(p2, colReader.getObject()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(p3, colReader.getPeriod()); assertFalse(arrayReader.next()); assertFalse(reader.next()); rs.clear(); } /** * Test the low-level interval-day utilities used by the column accessors. */ @Test public void testIntervalDayUtils() { { Period expected = Period.days(0); Period actual = DateUtilities.fromIntervalDay(0, 0); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalDayStringBuilder(expected).toString(); assertEquals("0 days 0:00:00", fmt); } { Period expected = Period.days(1).plusHours(5).plusMinutes(6).plusSeconds(7); Period actual = DateUtilities.fromIntervalDay(1, DateUtilities.timeToMillis(5, 6, 7, 0)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalDayStringBuilder(expected).toString(); assertEquals("1 day 5:06:07", fmt); } { Period expected = Period.days(2).plusHours(12).plusMinutes(23).plusSeconds(34).plusMillis(567); Period actual = DateUtilities.fromIntervalDay(2, DateUtilities.timeToMillis(12, 23, 34, 567)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalDayStringBuilder(expected).toString(); assertEquals("2 days 12:23:34.567", fmt); } } @Test public void testIntervalDayRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.INTERVALDAY) .buildSchema(); Period p1 = Period.days(0); Period p2 = Period.days(3).plusHours(4).plusMinutes(5).plusSeconds(23); Period p3 = Period.days(999).plusHours(23).plusMinutes(59).plusSeconds(59); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addRow(p2) .addRow(p3) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); // The normalizedStandard() call is a hack. See DRILL-5689. assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertEquals(p2, ((Period) colReader.getObject()).normalizedStandard()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(reader.next()); assertEquals(p3.normalizedStandard(), colReader.getPeriod().normalizedStandard()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableIntervalDay() { TupleMetadata schema = new SchemaBuilder() .addNullable("col", MinorType.INTERVALDAY) .buildSchema(); Period p1 = Period.years(0); Period p2 = Period.days(3).plusHours(4).plusMinutes(5).plusSeconds(23); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addSingleCol(null) .addRow(p2) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertFalse(reader.next()); rs.clear(); } @Test public void testIntervalDayArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.INTERVALDAY) .buildSchema(); Period p1 = Period.days(0); Period p2 = Period.days(3).plusHours(4).plusMinutes(5).plusSeconds(23); Period p3 = Period.days(999).plusHours(23).plusMinutes(59).plusSeconds(59); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new Period[] {}) .addSingleCol(new Period[] {p1, p2, p3}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(arrayReader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertEquals(p2, ((Period) colReader.getObject()).normalizedStandard()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(p3.normalizedStandard(), colReader.getPeriod().normalizedStandard()); assertFalse(arrayReader.next()); assertFalse(reader.next()); rs.clear(); } /** * Test the low-level interval utilities used by the column accessors. */ @Test public void testIntervalUtils() { { Period expected = Period.months(0); Period actual = DateUtilities.fromInterval(0, 0, 0); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalStringBuilder(expected).toString(); assertEquals("0 years 0 months 0 days 0:00:00", fmt); } { Period expected = Period.years(1).plusMonths(2).plusDays(3) .plusHours(5).plusMinutes(6).plusSeconds(7); Period actual = DateUtilities.fromInterval(DateUtilities.periodToMonths(expected), 3, DateUtilities.periodToMillis(expected)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalStringBuilder(expected).toString(); assertEquals("1 year 2 months 3 days 5:06:07", fmt); } { Period expected = Period.years(2).plusMonths(1).plusDays(3) .plusHours(12).plusMinutes(23).plusSeconds(34) .plusMillis(456); Period actual = DateUtilities.fromInterval(DateUtilities.periodToMonths(expected), 3, DateUtilities.periodToMillis(expected)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalStringBuilder(expected).toString(); assertEquals("2 years 1 month 3 days 12:23:34.456", fmt); } { Period expected = Period.years(2).plusMonths(3).plusDays(1) .plusHours(12).plusMinutes(23).plusSeconds(34); Period actual = DateUtilities.fromInterval(DateUtilities.periodToMonths(expected), 1, DateUtilities.periodToMillis(expected)); assertEquals(expected, actual.normalizedStandard()); String fmt = DateUtilities.intervalStringBuilder(expected).toString(); assertEquals("2 years 3 months 1 day 12:23:34", fmt); } } @Test public void testIntervalRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.INTERVAL) .buildSchema(); Period p1 = Period.days(0); Period p2 = Period.years(7).plusMonths(8) .plusDays(3).plusHours(4) .plusMinutes(5).plusSeconds(23); Period p3 = Period.years(9999).plusMonths(11) .plusDays(365).plusHours(23) .plusMinutes(59).plusSeconds(59); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addRow(p2) .addRow(p3) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); // The normalizedStandard() call is a hack. See DRILL-5689. assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertEquals(p2, ((Period) colReader.getObject()).normalizedStandard()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(reader.next()); assertEquals(p3.normalizedStandard(), colReader.getPeriod().normalizedStandard()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableInterval() { TupleMetadata schema = new SchemaBuilder() .addNullable("col", MinorType.INTERVAL) .buildSchema(); Period p1 = Period.years(0); Period p2 = Period.years(7).plusMonths(8) .plusDays(3).plusHours(4) .plusMinutes(5).plusSeconds(23); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(p1) .addSingleCol(null) .addRow(p2) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertFalse(reader.next()); rs.clear(); } @Test public void testIntervalArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.INTERVAL) .buildSchema(); Period p1 = Period.days(0); Period p2 = Period.years(7).plusMonths(8) .plusDays(3).plusHours(4) .plusMinutes(5).plusSeconds(23); Period p3 = Period.years(9999).plusMonths(11) .plusDays(365).plusHours(23) .plusMinutes(59).plusSeconds(59); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new Period[] {}) .addSingleCol(new Period[] {p1, p2, p3}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.PERIOD, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(p1, colReader.getPeriod().normalizedStandard()); assertTrue(arrayReader.next()); assertEquals(p2, colReader.getPeriod().normalizedStandard()); assertEquals(p2, ((Period) colReader.getObject()).normalizedStandard()); assertEquals(p2.toString(), colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(p3.normalizedStandard(), colReader.getPeriod().normalizedStandard()); assertFalse(arrayReader.next()); assertFalse(reader.next()); rs.clear(); } @Test public void testDecimal9RW() { MajorType type = MajorType.newBuilder() .setMinorType(MinorType.DECIMAL9) .setScale(3) .setPrecision(9) .setMode(DataMode.REQUIRED) .build(); TupleMetadata schema = new SchemaBuilder() .add("col", type) .buildSchema(); BigDecimal v1 = BigDecimal.ZERO; BigDecimal v2 = BigDecimal.valueOf(123_456_789, 3); BigDecimal v3 = BigDecimal.valueOf(999_999_999, 3); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(v1) .addRow(v2) .addRow(v3) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DECIMAL, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, v1.compareTo(colReader.getDecimal())); assertTrue(reader.next()); assertEquals(0, v2.compareTo(colReader.getDecimal())); assertEquals(0, v2.compareTo((BigDecimal) colReader.getObject())); assertEquals(v2.toString(), colReader.getAsString()); assertTrue(reader.next()); assertEquals(0, v3.compareTo(colReader.getDecimal())); assertFalse(reader.next()); rs.clear(); } private void nullableDecimalTester(MinorType type, int precision) { MajorType majorType = MajorType.newBuilder() .setMinorType(type) .setScale(3) .setPrecision(precision) .setMode(DataMode.OPTIONAL) .build(); TupleMetadata schema = new SchemaBuilder() .add("col", majorType) .buildSchema(); BigDecimal v1 = BigDecimal.ZERO; BigDecimal v2 = BigDecimal.valueOf(123_456_789, 3); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(v1) .addSingleCol(null) .addRow(v2) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DECIMAL, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, v1.compareTo(colReader.getDecimal())); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertEquals(0, v2.compareTo(colReader.getDecimal())); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableDecimal9() { nullableDecimalTester(MinorType.DECIMAL9, 9); } private void decimalArrayTester(MinorType type, int precision) { MajorType majorType = MajorType.newBuilder() .setMinorType(type) .setScale(3) .setPrecision(precision) .setMode(DataMode.REPEATED) .build(); TupleMetadata schema = new SchemaBuilder() .add("col", majorType) .buildSchema(); BigDecimal v1 = BigDecimal.ZERO; BigDecimal v2 = BigDecimal.valueOf(123_456_789, 3); BigDecimal v3 = BigDecimal.TEN; SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new BigDecimal[] {}) .addSingleCol(new BigDecimal[] {v1, v2, v3}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.DECIMAL, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertEquals(0, v1.compareTo(colReader.getDecimal())); assertTrue(arrayReader.next()); assertEquals(0, v2.compareTo(colReader.getDecimal())); assertEquals(0, v2.compareTo((BigDecimal) colReader.getObject())); assertEquals(v2.toString(), colReader.getAsString()); assertTrue(arrayReader.next()); assertEquals(0, v3.compareTo(colReader.getDecimal())); assertFalse(arrayReader.next()); assertFalse(reader.next()); rs.clear(); } @Test public void testDecimal9Array() { decimalArrayTester(MinorType.DECIMAL9, 9); } @Test public void testDecimal18RW() { MajorType type = MajorType.newBuilder() .setMinorType(MinorType.DECIMAL18) .setScale(3) .setPrecision(9) .setMode(DataMode.REQUIRED) .build(); TupleMetadata schema = new SchemaBuilder() .add("col", type) .buildSchema(); BigDecimal v1 = BigDecimal.ZERO; BigDecimal v2 = BigDecimal.valueOf(123_456_789_123_456_789L, 3); BigDecimal v3 = BigDecimal.valueOf(999_999_999_999_999_999L, 3); SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(v1) .addRow(v2) .addRow(v3) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DECIMAL, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertEquals(0, v1.compareTo(colReader.getDecimal())); assertTrue(reader.next()); assertEquals(0, v2.compareTo(colReader.getDecimal())); assertEquals(0, v2.compareTo((BigDecimal) colReader.getObject())); assertEquals(v2.toString(), colReader.getAsString()); assertTrue(reader.next()); assertEquals(0, v3.compareTo(colReader.getDecimal())); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableDecimal18() { nullableDecimalTester(MinorType.DECIMAL18, 9); } @Test public void testDecimal18Array() { decimalArrayTester(MinorType.DECIMAL18, 9); } // From the perspective of the vector, a date vector is just a long. @Test public void testDateRW() { longRWTester(MinorType.DATE); } @Test public void testNullableDate() { nullableLongTester(MinorType.DATE); } @Test public void testDateArray() { longArrayTester(MinorType.DATE); } // From the perspective of the vector, a timestamp vector is just a long. @Test public void testTimestampRW() { longRWTester(MinorType.TIMESTAMP); } @Test public void testNullableTimestamp() { nullableLongTester(MinorType.TIMESTAMP); } @Test public void testTimestampArray() { longArrayTester(MinorType.TIMESTAMP); } @Test public void testVarBinaryRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.VARBINARY) .buildSchema(); byte v1[] = new byte[] {}; byte v2[] = new byte[] { (byte) 0x00, (byte) 0x7f, (byte) 0x80, (byte) 0xFF}; SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(v1) .addRow(v2) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.BYTES, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertTrue(Arrays.equals(v1, colReader.getBytes())); assertTrue(reader.next()); assertTrue(Arrays.equals(v2, colReader.getBytes())); assertTrue(Arrays.equals(v2, (byte[]) colReader.getObject())); assertEquals("[00, 7f, 80, ff]", colReader.getAsString()); assertFalse(reader.next()); rs.clear(); } @Test public void testNullableVarBinary() { TupleMetadata schema = new SchemaBuilder() .addNullable("col", MinorType.VARBINARY) .buildSchema(); byte v1[] = new byte[] {}; byte v2[] = new byte[] { (byte) 0x00, (byte) 0x7f, (byte) 0x80, (byte) 0xFF}; SingleRowSet rs = fixture.rowSetBuilder(schema) .addRow(v1) .addSingleCol(null) .addRow(v2) .build(); assertEquals(3, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.BYTES, colReader.valueType()); assertTrue(reader.next()); assertFalse(colReader.isNull()); assertTrue(Arrays.equals(v1, colReader.getBytes())); assertTrue(reader.next()); assertTrue(colReader.isNull()); assertNull(colReader.getObject()); assertEquals("null", colReader.getAsString()); assertTrue(reader.next()); assertTrue(Arrays.equals(v2, colReader.getBytes())); assertFalse(reader.next()); rs.clear(); } @Test public void testVarBinaryArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.VARBINARY) .buildSchema(); byte v1[] = new byte[] {}; byte v2[] = new byte[] { (byte) 0x00, (byte) 0x7f, (byte) 0x80, (byte) 0xFF}; byte v3[] = new byte[] { (byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xAF}; SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(new byte[][] {}) .addSingleCol(new byte[][] {v1, v2, v3}) .build(); assertEquals(2, rs.rowCount()); RowSetReader reader = rs.reader(); ArrayReader arrayReader = reader.array(0); ScalarReader colReader = arrayReader.scalar(); assertEquals(ValueType.BYTES, colReader.valueType()); assertTrue(reader.next()); assertEquals(0, arrayReader.size()); assertTrue(reader.next()); assertEquals(3, arrayReader.size()); assertTrue(arrayReader.next()); assertTrue(Arrays.equals(v1, colReader.getBytes())); assertTrue(arrayReader.next()); assertTrue(Arrays.equals(v2, colReader.getBytes())); assertTrue(Arrays.equals(v2, (byte[]) colReader.getObject())); assertEquals("[00, 7f, 80, ff]", colReader.getAsString()); assertTrue(arrayReader.next()); assertTrue(Arrays.equals(v3, colReader.getBytes())); assertFalse(arrayReader.next()); assertFalse(reader.next()); rs.clear(); } // Test the convenience objects for DATE, TIME and TIMESTAMP @Test public void testDateObjectRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.DATE) .buildSchema(); LocalDate v1 = new LocalDate(2019, 3, 24); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(v1) .build(); assertEquals(1, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.DATE, colReader.extendedType()); assertTrue(reader.next()); assertEquals(v1, colReader.getDate()); assertFalse(reader.next()); rs.clear(); } @Test public void testTimeObjectRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.TIME) .buildSchema(); LocalTime v1 = new LocalTime(12, 13, 14); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(v1) .build(); assertEquals(1, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.TIME, colReader.extendedType()); assertTrue(reader.next()); assertEquals(v1, colReader.getTime()); assertFalse(reader.next()); rs.clear(); } @Test public void testTimeStampObjectRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.TIMESTAMP) .buildSchema(); LocalDate dt = new LocalDate(2019, 3, 24); LocalTime lt = new LocalTime(12, 13, 14); Instant v1 = dt.toDateTime(lt, DateTimeZone.UTC).toInstant(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(v1) .build(); assertEquals(1, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertEquals(ValueType.TIMESTAMP, colReader.extendedType()); assertTrue(reader.next()); assertEquals(v1, colReader.getTimestamp()); assertFalse(reader.next()); rs.clear(); } @Test public void testBitRW() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.BIT) .buildSchema(); SingleRowSet rs = fixture.rowSetBuilder(schema) .addSingleCol(true) .addSingleCol(false) .addSingleCol(0) .addSingleCol(1) .addSingleCol(2) .addSingleCol(3) .build(); assertEquals(6, rs.rowCount()); RowSetReader reader = rs.reader(); ScalarReader colReader = reader.scalar(0); assertTrue(reader.next()); assertEquals(true, colReader.getBoolean()); assertEquals(1, colReader.getInt()); assertTrue(reader.next()); assertEquals(false, colReader.getBoolean()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(false, colReader.getBoolean()); assertEquals(0, colReader.getInt()); assertTrue(reader.next()); assertEquals(true, colReader.getBoolean()); assertEquals(1, colReader.getInt()); assertTrue(reader.next()); assertEquals(true, colReader.getBoolean()); assertEquals(1, colReader.getInt()); assertTrue(reader.next()); assertEquals(true, colReader.getBoolean()); assertEquals(1, colReader.getInt()); assertFalse(reader.next()); rs.clear(); } /** * The bit reader/writer are special and use the BitVector directly. * Ensure that resize works in this special case. */ @Test public void testBitResize() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.BIT) .buildSchema(); RowSetBuilder rsb = new RowSetBuilder(fixture.allocator(), schema, 100); ScalarWriter bitWriter = rsb.writer().scalar(0); for (int i = 0; i < ValueVector.MAX_ROW_COUNT; i++) { bitWriter.setBoolean((i % 5) == 0); rsb.writer().save(); } SingleRowSet rs = rsb.build(); RowSetReader reader = rs.reader(); ScalarReader bitReader = reader.scalar(0); for (int i = 0; i < ValueVector.MAX_ROW_COUNT; i++) { reader.next(); assertEquals((i % 5) == 0, bitReader.getBoolean()); } rs.clear(); } private static String repeat(String str, int n) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < n; i++) { buf.append(str); } return str.toString(); } @Test public void testVarDecimalRange() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.VARDECIMAL, 38, 4) .buildSchema(); String big = repeat("9", 34) + ".9999"; SingleRowSet rs = new RowSetBuilder(fixture.allocator(), schema) .addSingleCol(dec("0")) .addSingleCol(dec("-0.0000")) .addSingleCol(dec("0.0001")) .addSingleCol(dec("-0.0001")) .addSingleCol(dec(big)) .addSingleCol(dec("-" + big)) .addSingleCol(dec("1234.56789")) .build(); RowSetReader reader = rs.reader(); ScalarReader decReader = reader.scalar(0); assertTrue(reader.next()); assertEquals(dec("0.0000"), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec("0.0000"), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec("0.0001"), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec("-0.0001"), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec(big), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec("-" + big), decReader.getDecimal()); assertTrue(reader.next()); assertEquals(dec("1234.5679"), decReader.getDecimal()); assertFalse(reader.next()); rs.clear(); } @Test public void testVarDecimalOverflow() { TupleMetadata schema = new SchemaBuilder() .add("col", MinorType.VARDECIMAL, 8, 4) .buildSchema(); RowSetBuilder rsb = new RowSetBuilder(fixture.allocator(), schema, 100); try { // With rounding due to scale, value exceeds allowed precision. rsb.addSingleCol(dec("9999.99999")); fail(); } catch (UserException e) { // Expected } rsb.build().clear(); } /** * Test the ability to append bytes to a VarChar column. Should work for * Var16Char, but that type is not yet supported in Drill. */ @Test public void testAppend() { doTestAppend(new SchemaBuilder() .add("col", MinorType.VARCHAR) .buildSchema()); doTestAppend(new SchemaBuilder() .addNullable("col", MinorType.VARCHAR) .buildSchema()); } private void doTestAppend(TupleMetadata schema) { DirectRowSet rs = DirectRowSet.fromSchema(fixture.allocator(), schema); RowSetWriter writer = rs.writer(100); ScalarWriter colWriter = writer.scalar("col"); byte first[] = "abc".getBytes(); byte second[] = "12345".getBytes(); colWriter.setBytes(first, first.length); colWriter.appendBytes(second, second.length); writer.save(); colWriter.setBytes(second, second.length); colWriter.appendBytes(first, first.length); writer.save(); colWriter.setBytes(first, first.length); colWriter.appendBytes(second, second.length); writer.save(); RowSet actual = writer.done(); RowSet expected = new RowSetBuilder(fixture.allocator(), schema) .addSingleCol("abc12345") .addSingleCol("12345abc") .addSingleCol("abc12345") .build(); RowSetUtilities.verify(expected, actual); } /** * Test the ability to append bytes to a VarChar column. Should work for * Var16Char, but that type is not yet supported in Drill. */ @Test public void testAppendWithArray() { TupleMetadata schema = new SchemaBuilder() .addArray("col", MinorType.VARCHAR) .buildSchema(); DirectRowSet rs = DirectRowSet.fromSchema(fixture.allocator(), schema); RowSetWriter writer = rs.writer(100); ArrayWriter arrayWriter = writer.array("col"); ScalarWriter colWriter = arrayWriter.scalar(); byte first[] = "abc".getBytes(); byte second[] = "12345".getBytes(); for (int i = 0; i < 3; i++) { colWriter.setBytes(first, first.length); colWriter.appendBytes(second, second.length); arrayWriter.save(); colWriter.setBytes(second, second.length); colWriter.appendBytes(first, first.length); arrayWriter.save(); colWriter.setBytes(first, first.length); colWriter.appendBytes(second, second.length); arrayWriter.save(); writer.save(); } RowSet actual = writer.done(); RowSet expected = new RowSetBuilder(fixture.allocator(), schema) .addSingleCol(strArray("abc12345", "12345abc", "abc12345")) .addSingleCol(strArray("abc12345", "12345abc", "abc12345")) .addSingleCol(strArray("abc12345", "12345abc", "abc12345")) .build(); RowSetUtilities.verify(expected, actual); } }
/* * Copyright 2000-2016 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.openapi.vcs.changes; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.ui.PlusMinusModify; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.BeforeAfter; import com.intellij.util.ObjectUtils; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FactoryMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.containers.OpenTHashSet; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; /** should work under _external_ lock * just logic here: do modifications to group of change lists */ public class ChangeListWorker { private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.ChangeListWorker"); @NotNull private final Project myProject; @NotNull private final DelayedNotificator myDelayedNotificator; private final boolean myMainWorker; private final Set<ListData> myLists = new HashSet<>(); private ListData myDefault; private final Map<Change, ListData> myChangeMappings = new HashMap<>(); private final Map<FilePath, PartialChangeTracker> myPartialChangeTrackers = new HashMap<>(); private final ChangeListsIndexes myIdx; @Nullable private Map<ListData, Set<Change>> myReadOnlyChangesCache = null; private final AtomicBoolean myReadOnlyChangesCacheInvalidated = new AtomicBoolean(false); public ChangeListWorker(@NotNull Project project, @NotNull DelayedNotificator delayedNotificator) { myProject = project; myDelayedNotificator = delayedNotificator; myMainWorker = true; myIdx = new ChangeListsIndexes(); ensureDefaultListExists(); } private ChangeListWorker(@NotNull ChangeListWorker worker) { myProject = worker.myProject; myDelayedNotificator = worker.myDelayedNotificator; myMainWorker = false; myIdx = new ChangeListsIndexes(worker.myIdx); Map<ListData, ListData> listMapping = copyListsDataFrom(worker.myLists); worker.myChangeMappings.forEach((change, oldList) -> { ListData newList = notNullList(listMapping.get(oldList)); myChangeMappings.put(change, newList); }); myPartialChangeTrackers.putAll(worker.myPartialChangeTrackers); } @NotNull private Map<ListData, ListData> copyListsDataFrom(@NotNull Collection<ListData> lists) { ListData oldDefault = myDefault; List<String> oldIds = ContainerUtil.map(myLists, list -> list.id); myLists.clear(); myDefault = null; Map<ListData, ListData> listMapping = new HashMap<>(); for (ListData oldList : lists) { ListData newList = new ListData(oldList); if (newList.isDefault && myDefault != null) { LOG.error("multiple default lists found when copy"); newList.isDefault = false; } newList = putNewListData(newList); if (newList.isDefault) myDefault = newList; listMapping.put(oldList, newList); } ensureDefaultListExists(); if (myMainWorker) { if (!oldDefault.id.equals(myDefault.id)) { fireDefaultListChanged(oldDefault.id, myDefault.id); } HashSet<String> removedListIds = new HashSet<>(oldIds); for (ListData list : myLists) { removedListIds.remove(list.id); } for (String listId : removedListIds) { fireChangeListRemoved(listId); } } myReadOnlyChangesCache = null; return listMapping; } private void ensureDefaultListExists() { if (myDefault != null) return; if (myLists.isEmpty()) { putNewListData(new ListData(null, LocalChangeList.DEFAULT_NAME)); } myDefault = myLists.iterator().next(); myDefault.isDefault = true; } public ChangeListWorker copy() { return new ChangeListWorker(this); } public void registerChangeTracker(@NotNull FilePath filePath, @NotNull PartialChangeTracker tracker) { if (myPartialChangeTrackers.containsKey(filePath)) { LOG.error(String.format("Attempt to register duplicate trackers: %s; old: %s; new: %s", filePath, myPartialChangeTrackers.get(filePath), tracker)); return; } myPartialChangeTrackers.put(filePath, tracker); tracker.initChangeTracking(myDefault.id, ContainerUtil.map(myLists, list -> list.id)); Change change = getChangeForAfterPath(filePath); if (change != null) { removeChangeMapping(change); } } public void unregisterChangeTracker(@NotNull FilePath filePath, @NotNull PartialChangeTracker tracker) { PartialChangeTracker oldTracker = myPartialChangeTrackers.remove(filePath); if (!Comparing.equal(oldTracker, tracker)) { LOG.error(String.format("Wrong tracker removed: %s; expected: %s; passed: %s", filePath, oldTracker, tracker)); } Change change = getChangeForAfterPath(filePath); if (change != null) { putChangeMapping(change, getMainList(oldTracker)); } } @NotNull private ListData getMainList(@Nullable PartialChangeTracker oldTracker) { if (oldTracker == null) return myDefault; List<String> changelistIds = oldTracker.getAffectedChangeListsIds(); if (changelistIds.size() == 1) { ListData list = getDataByIdVerify(changelistIds.get(0)); if (list != null) return list; } return myDefault; } @NotNull public Project getProject() { return myProject; } @NotNull public LocalChangeList getDefaultList() { return toChangeList(myDefault); } @Nullable public LocalChangeList getChangeListByName(@Nullable String name) { if (name == null) return null; return toChangeList(getDataByName(name)); } @Nullable public LocalChangeList getChangeListById(@Nullable String id) { if (id == null) return null; return toChangeList(getDataById(id)); } @NotNull public List<LocalChangeList> getChangeLists() { return ContainerUtil.map(myLists, this::toChangeList); } public int getChangeListsNumber() { return myLists.size(); } @Nullable public Change getChangeForPath(@Nullable FilePath filePath) { if (filePath == null) return null; for (Change change : myIdx.getChanges()) { ContentRevision before = change.getBeforeRevision(); ContentRevision after = change.getAfterRevision(); if (before != null && before.getFile().equals(filePath) || after != null && after.getFile().equals(filePath)) { return change; } } return null; } @Nullable private Change getChangeForAfterPath(@Nullable FilePath filePath) { if (filePath == null) return null; for (Change change : myIdx.getChanges()) { ContentRevision after = change.getAfterRevision(); if (after != null && after.getFile().equals(filePath)) { return change; } } return null; } @NotNull public Collection<Change> getAllChanges() { return new ArrayList<>(myIdx.getChanges()); } @NotNull public List<LocalChangeList> getAffectedLists(@NotNull Collection<Change> changes) { return ContainerUtil.map(getAffectedListsData(changes), this::toChangeList); } @NotNull public List<LocalChangeList> getAffectedLists(@NotNull Change change) { return getAffectedLists(Collections.singletonList(change)); } @NotNull private List<ListData> getAffectedListsData(@NotNull Collection<Change> changes) { Set<ListData> result = new HashSet<>(); for (Change change : changes) { ListData list = myChangeMappings.get(change); if (list != null) { result.add(list); } else { PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker != null) { Set<ListData> affectedLists = getAffectedLists(tracker); if (change instanceof ChangeListChange) { String changeListId = ((ChangeListChange)change).getChangeListId(); ContainerUtil.addIfNotNull(result, ContainerUtil.find(affectedLists, partialList -> partialList.id.equals(changeListId))); } else { result.addAll(affectedLists); } } } } return new ArrayList<>(result); } @NotNull private List<Change> getChangesIn(@NotNull ListData data) { List<Change> changes = new ArrayList<>(); for (Change change : myIdx.getChanges()) { ListData list = myChangeMappings.get(change); if (list != null) { if (list == data) { changes.add(change); } } else { PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker != null && tracker.getAffectedChangeListsIds().contains(data.id)) { changes.add(change); } } } return changes; } @NotNull private Map<ListData, Set<Change>> getChangesMapping() { Map<ListData, Set<Change>> map = new HashMap<>(); for (Change change : myIdx.getChanges()) { ListData list = myChangeMappings.get(change); if (list != null) { Set<Change> listChanges = map.computeIfAbsent(list, key -> new HashSet<>()); listChanges.add(change); } else { PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker != null) { Set<ListData> lists = getAffectedLists(tracker); for (ListData partialList : lists) { Set<Change> listChanges = map.computeIfAbsent(partialList, key -> new HashSet<>()); listChanges.add(toChangeListChange(change, partialList)); } } } } return map; } @NotNull public List<File> getAffectedPaths() { return ContainerUtil.map(myIdx.getAffectedPaths(), FilePath::getIOFile); } @NotNull public List<VirtualFile> getAffectedFiles() { return ContainerUtil.mapNotNull(myIdx.getAffectedPaths(), FilePath::getVirtualFile); } public ThreeState haveChangesUnder(@NotNull VirtualFile virtualFile) { FilePath dir = VcsUtil.getFilePath(virtualFile); return myIdx.haveChangesUnder(dir); } @NotNull public List<Change> getChangesUnder(@NotNull FilePath dirPath) { List<Change> changes = new ArrayList<>(); for (Change change : myIdx.getChanges()) { ContentRevision after = change.getAfterRevision(); ContentRevision before = change.getBeforeRevision(); if (after != null && after.getFile().isUnder(dirPath, false) || before != null && before.getFile().isUnder(dirPath, false)) { changes.add(change); } } return changes; } @Nullable public VcsKey getVcsFor(@NotNull Change change) { return myIdx.getVcsFor(change); } @Nullable public FileStatus getStatus(@NotNull VirtualFile file) { return myIdx.getStatus(file); } @Nullable public FileStatus getStatus(@NotNull FilePath file) { return myIdx.getStatus(file); } public boolean setDefaultList(String name) { ListData newDefault = getDataByName(name); if (newDefault == null || newDefault.isDefault) return false; ListData oldDefault = myDefault; myDefault.isDefault = false; newDefault.isDefault = true; myDefault = newDefault; fireDefaultListChanged(oldDefault.id, newDefault.id); fireChangeListsChanged(); return true; } public boolean setReadOnly(String name, boolean value) { ListData list = getDataByName(name); if (list == null || list.isReadOnly) return false; list.isReadOnly = value; fireChangeListsChanged(); return true; } public boolean editName(@NotNull String fromName, @NotNull String toName) { if (fromName.equals(toName)) return false; if (getDataByName(toName) != null) return false; final ListData list = getDataByName(fromName); if (list == null || list.isReadOnly) return false; list.name = toName; fireChangeListsChanged(); return true; } @Nullable public String editComment(@NotNull String name, @NotNull String newComment) { final ListData list = getDataByName(name); if (list == null) return null; final String oldComment = list.comment; if (!Comparing.equal(oldComment, newComment)) { list.comment = newComment; } fireChangeListsChanged(); return oldComment; } @NotNull public LocalChangeList addChangeList(@NotNull String name, @Nullable String description, @Nullable String id, @Nullable ChangeListData data) { LocalChangeList existingList = getChangeListByName(name); if (existingList != null) { LOG.error("Attempt to create duplicate changelist " + name); return existingList; } ListData list = new ListData(id, name); list.comment = StringUtil.notNullize(description); list.data = data; list = putNewListData(list); fireChangeListsChanged(); return toChangeList(list); } public boolean removeChangeList(@NotNull String name) { ListData removedList = getDataByName(name); if (removedList == null) return false; if (removedList.isDefault) { LOG.error("Cannot remove default changelist"); return false; } myChangeMappings.replaceAll((change, list) -> { if (list == removedList) return myDefault; return list; }); myLists.remove(removedList); fireChangeListRemoved(removedList.id); fireChangeListsChanged(); myReadOnlyChangesCache = null; return true; } @Nullable public MultiMap<LocalChangeList, Change> moveChangesTo(@NotNull String name, @NotNull Change[] changes) { final ListData targetList = getDataByName(name); if (targetList == null) return null; final MultiMap<ListData, Change> result = new MultiMap<>(); for (Change change : changes) { ListData list = myChangeMappings.get(change); if (list != null) { if (list != targetList) { myChangeMappings.replace(change, targetList); result.putValue(list, change); } } else { PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker != null) { if (change instanceof ChangeListChange) { String fromListId = ((ChangeListChange)change).getChangeListId(); ListData fromList = getDataById(fromListId); if (fromList != null && fromList != targetList) { if (myMainWorker) { tracker.moveChanges(fromList.id, targetList.id); } result.putValue(fromList, change); } } else { HashSet<ListData> fromLists = getAffectedLists(tracker); fromLists.remove(targetList); if (!fromLists.isEmpty()) { if (myMainWorker) { tracker.moveChangesTo(targetList.id); } for (ListData fromList : fromLists) { result.putValue(fromList, change); } } } } } } fireChangeListsChanged(); myReadOnlyChangesCache = null; MultiMap<LocalChangeList, Change> notifications = new MultiMap<>(); for (Map.Entry<ListData, Collection<Change>> entry : result.entrySet()) { notifications.put(toChangeList(entry.getKey()), entry.getValue()); } return notifications; } /** * Called without external lock */ public void notifyChangelistsChanged() { if (myReadOnlyChangesCacheInvalidated.compareAndSet(false, true)) { fireChangeListsChanged(); } } public void applyChangesFromUpdate(@NotNull ChangeListWorker updatedWorker, @NotNull PlusMinusModify<BaseRevision> deltaListener) { boolean somethingChanged = notifyPathsChanged(myIdx, updatedWorker.myIdx, deltaListener); myIdx.copyFrom(updatedWorker.myIdx); myChangeMappings.clear(); Map<ListData, ListData> listMapping = copyListsDataFrom(updatedWorker.myLists); for (Change change : myIdx.getChanges()) { PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker == null) { ListData oldList = updatedWorker.myChangeMappings.get(change); ListData newList = notNullList(listMapping.get(oldList)); myChangeMappings.put(change, newList); } } if (somethingChanged) { FileStatusManager.getInstance(myProject).fileStatusesChanged(); } fireChangeListsChanged(); } private static boolean notifyPathsChanged(@NotNull ChangeListsIndexes was, @NotNull ChangeListsIndexes became, @NotNull PlusMinusModify<BaseRevision> deltaListener) { final Set<BaseRevision> toRemove = new HashSet<>(); final Set<BaseRevision> toAdd = new HashSet<>(); final Set<BeforeAfter<BaseRevision>> toModify = new HashSet<>(); was.getDelta(became, toRemove, toAdd, toModify); for (BaseRevision pair : toRemove) { deltaListener.minus(pair); } for (BaseRevision pair : toAdd) { deltaListener.plus(pair); } for (BeforeAfter<BaseRevision> beforeAfter : toModify) { deltaListener.modify(beforeAfter.getBefore(), beforeAfter.getAfter()); } return !toRemove.isEmpty() || !toAdd.isEmpty(); } void setChangeLists(@NotNull Collection<LocalChangeListImpl> lists) { myIdx.clear(); myChangeMappings.clear(); copyListsDataFrom(ContainerUtil.map(lists, ListData::new)); for (LocalChangeListImpl list : lists) { ListData listData = notNullList(getDataByIdVerify(list.getId())); for (Change change : list.getChanges()) { if (myIdx.getChanges().contains(change)) continue; myIdx.changeAdded(change, null); PartialChangeTracker tracker = getChangeTrackerFor(change); if (tracker == null) { myChangeMappings.put(change, listData); } } } fireChangeListsChanged(); } private void fireDefaultListChanged(@NotNull String oldDefaultId, @NotNull String newDefaultId) { if (myMainWorker) { for (PartialChangeTracker tracker : myPartialChangeTrackers.values()) { tracker.defaultListChanged(oldDefaultId, newDefaultId); } } } private void fireChangeListRemoved(@NotNull String listId) { if (myMainWorker) { for (PartialChangeTracker tracker : myPartialChangeTrackers.values()) { tracker.changeListRemoved(listId); } } } private void fireChangeListsChanged() { if (myMainWorker) { myDelayedNotificator.changeListsChanged(); } } @Nullable private ListData removeChangeMapping(@NotNull Change change) { ListData oldList = myChangeMappings.remove(change); fireChangeListsChanged(); myReadOnlyChangesCache = null; return oldList; } private void putChangeMapping(@NotNull Change change, @NotNull ListData list) { myChangeMappings.put(change, list); fireChangeListsChanged(); myReadOnlyChangesCache = null; } @NotNull private ListData putNewListData(@NotNull ListData list) { ListData listWithSameName = getDataByName(list.name); if (listWithSameName != null) { LOG.error(String.format("Attempt to create changelist with same name: %s - %s", list.name, list.id)); return listWithSameName; } ListData listWithSameId = getDataById(list.id); if (listWithSameId != null) { LOG.error(String.format("Attempt to create changelist with same id: %s - %s", list.name, list.id)); return listWithSameId; } myLists.add(list); return list; } @NotNull private ListData notNullList(@Nullable ListData listData) { if (listData == null) LOG.error("ListData not found"); return ObjectUtils.notNull(listData, myDefault); } @Nullable private ListData getDataById(@NotNull String id) { return ContainerUtil.find(myLists, list -> list.id.equals(id)); } @Nullable private ListData getDataByName(@NotNull String name) { return ContainerUtil.find(myLists, list -> list.name.equals(name)); } @Nullable private ListData getDataByIdVerify(@NotNull String id) { ListData list = getDataById(id); if (myMainWorker && list == null) LOG.error(String.format("Unknown changelist %s", id)); return list; } @Nullable private PartialChangeTracker getChangeTrackerFor(@NotNull Change change) { if (myPartialChangeTrackers.isEmpty()) return null; if (!myIdx.getChanges().contains(change)) return null; ContentRevision revision = change.getAfterRevision(); if (revision == null) return null; return myPartialChangeTrackers.get(revision.getFile()); } @NotNull private HashSet<ListData> getAffectedLists(@NotNull PartialChangeTracker tracker) { HashSet<ListData> data = new HashSet<>(); for (String listId : tracker.getAffectedChangeListsIds()) { ListData partialList = getDataByIdVerify(listId); data.add(partialList != null ? partialList : myDefault); } return data; } @Contract("!null -> !null; null -> null") private LocalChangeListImpl toChangeList(@Nullable ListData data) { if (data == null) return null; if (myReadOnlyChangesCache == null || myReadOnlyChangesCacheInvalidated.get()) { myReadOnlyChangesCacheInvalidated.set(false); myReadOnlyChangesCache = getChangesMapping(); } Set<Change> cachedChanges = myReadOnlyChangesCache.get(data); Set<Change> changes = cachedChanges != null ? Collections.unmodifiableSet(cachedChanges) : Collections.emptySet(); return new LocalChangeListImpl.Builder(myProject, data.name) .setId(data.id) .setComment(data.comment) .setChangesCollection(changes) .setData(data.data) .setDefault(data.isDefault) .setReadOnly(data.isReadOnly) .build(); } @NotNull private static Change toChangeListChange(@NotNull Change change, @NotNull ListData list) { if (change.getClass() == Change.class) { return new ChangeListChange(change, list.name, list.id); } return change; } private static class ListData { @NotNull public final String id; @NotNull public String name; @NotNull public String comment = ""; @Nullable public ChangeListData data; public boolean isDefault = false; public boolean isReadOnly = false; // read-only lists cannot be removed or renamed public ListData(@Nullable String id, @NotNull String name) { this.id = id != null ? id : LocalChangeListImpl.generateChangelistId(); this.name = name; } public ListData(@NotNull LocalChangeListImpl list) { this.id = list.getId(); this.name = list.getName(); this.comment = list.getComment(); this.data = list.getData(); this.isDefault = list.isDefault(); this.isReadOnly = list.isReadOnly(); } public ListData(@NotNull ListData list) { this.id = list.id; this.name = list.name; this.comment = list.comment; this.data = list.data; this.isDefault = list.isDefault; this.isReadOnly = list.isReadOnly; } } @Override public String toString() { return String.format("ChangeListWorker{myMap=%s}", StringUtil.join(myLists, list -> { return String.format("list: %s changes: %s", list.name, StringUtil.join(getChangesIn(list), ", ")); }, "\n")); } public static class ChangeListUpdater implements ChangeListManagerGate { private final ChangeListWorker myWorker; private final Map<String, OpenTHashSet<Change>> myChangesBeforeUpdateMap = FactoryMap.create(it -> new OpenTHashSet<>()); private final Set<String> myListsToDisappear = new HashSet<>(); public ChangeListUpdater(@NotNull ChangeListWorker worker) { myWorker = worker.copy(); } @NotNull public Project getProject() { return myWorker.getProject(); } public void notifyStartProcessingChanges(@Nullable VcsModifiableDirtyScope scope) { myWorker.myChangeMappings.forEach((change, list) -> { OpenTHashSet<Change> changes = myChangesBeforeUpdateMap.get(list.id); changes.add(change); }); List<Change> removedChanges = removeChangesUnderScope(scope); // scope should be modified for correct moves tracking if (scope != null) { for (Change change : removedChanges) { if (change.isMoved() || change.isRenamed()) { scope.addDirtyFile(change.getBeforeRevision().getFile()); scope.addDirtyFile(change.getAfterRevision().getFile()); } } } } @NotNull private List<Change> removeChangesUnderScope(@Nullable VcsModifiableDirtyScope scope) { List<Change> removed = new ArrayList<>(); for (Change change : myWorker.myIdx.getChanges()) { ContentRevision before = change.getBeforeRevision(); ContentRevision after = change.getAfterRevision(); boolean isUnderScope = scope == null || before != null && scope.belongsTo(before.getFile()) || after != null && scope.belongsTo(after.getFile()) || isIgnoredChange(before, after, getProject()); if (isUnderScope) { removed.add(change); } } for (Change change : removed) { myWorker.myIdx.changeRemoved(change); myWorker.removeChangeMapping(change); } return removed; } private static boolean isIgnoredChange(@Nullable ContentRevision before, @Nullable ContentRevision after, @NotNull Project project) { return isIgnoredRevision(before, project) && isIgnoredRevision(after, project); } private static boolean isIgnoredRevision(@Nullable ContentRevision revision, final @NotNull Project project) { if (revision == null) return true; return ReadAction.compute(() -> { if (project.isDisposed()) return false; VirtualFile vFile = revision.getFile().getVirtualFile(); return vFile != null && ProjectLevelVcsManager.getInstance(project).isIgnored(vFile); }); } public void notifyDoneProcessingChanges(@NotNull DelayedNotificator dispatcher) { List<ChangeList> changedLists = new ArrayList<>(); final Map<LocalChangeListImpl, List<Change>> removedChanges = new HashMap<>(); final Map<LocalChangeListImpl, List<Change>> addedChanges = new HashMap<>(); for (ChangeListWorker.ListData list : myWorker.myLists) { final List<Change> removed = new ArrayList<>(); final List<Change> added = new ArrayList<>(); boolean wasChanged = doneProcessingChanges(list, removed, added); LocalChangeListImpl changeList = myWorker.toChangeList(list); if (wasChanged) { changedLists.add(changeList); } if (!removed.isEmpty()) { removedChanges.put(changeList, removed); } if (!added.isEmpty()) { addedChanges.put(changeList, added); } } removedChanges.forEach((changeList, changes) -> { dispatcher.changesRemoved(changes, changeList); }); addedChanges.forEach((changeList, changes) -> { dispatcher.changesAdded(changes, changeList); }); for (ChangeList changeList : changedLists) { dispatcher.changeListChanged(changeList); } for (String name : myListsToDisappear) { final ChangeListWorker.ListData list = myWorker.getDataByName(name); if (list != null && myWorker.getChangesIn(list).isEmpty() && !list.isReadOnly && !list.isDefault) { myWorker.removeChangeList(name); } } myListsToDisappear.clear(); myChangesBeforeUpdateMap.clear(); } private boolean doneProcessingChanges(@NotNull ChangeListWorker.ListData list, @NotNull List<Change> removedChanges, @NotNull List<Change> addedChanges) { OpenTHashSet<Change> changesBeforeUpdate = myChangesBeforeUpdateMap.get(list.id); Set<Change> listChanges = new HashSet<>(); myWorker.myChangeMappings.forEach((change, mappedList) -> { if (mappedList == list) listChanges.add(change); }); for (Change newChange : listChanges) { Change oldChange = findOldChange(changesBeforeUpdate, newChange); if (oldChange == null) { addedChanges.add(newChange); } } removedChanges.addAll(changesBeforeUpdate); removedChanges.removeAll(listChanges); return listChanges.size() != changesBeforeUpdate.size() || !addedChanges.isEmpty() || !removedChanges.isEmpty(); } @Nullable private static Change findOldChange(@NotNull OpenTHashSet<Change> changesBeforeUpdate, @NotNull Change newChange) { Change oldChange = changesBeforeUpdate.get(newChange); if (oldChange != null && sameBeforeRevision(oldChange, newChange) && newChange.getFileStatus().equals(oldChange.getFileStatus())) { return oldChange; } return null; } private static boolean sameBeforeRevision(@NotNull Change change1, @NotNull Change change2) { final ContentRevision b1 = change1.getBeforeRevision(); final ContentRevision b2 = change2.getBeforeRevision(); if (b1 != null && b2 != null) { final VcsRevisionNumber rn1 = b1.getRevisionNumber(); final VcsRevisionNumber rn2 = b2.getRevisionNumber(); final boolean isBinary1 = (b1 instanceof BinaryContentRevision); final boolean isBinary2 = (b2 instanceof BinaryContentRevision); return rn1 != VcsRevisionNumber.NULL && rn2 != VcsRevisionNumber.NULL && rn1.compareTo(rn2) == 0 && isBinary1 == isBinary2; } return b1 == null && b2 == null; } @NotNull public ChangeListWorker finish() { checkForMultipleCopiesNotMove(); return myWorker; } private void checkForMultipleCopiesNotMove() { final MultiMap<FilePath, Change> moves = new MultiMap<>(); for (Change change : myWorker.myIdx.getChanges()) { if (change.isMoved() || change.isRenamed()) { moves.putValue(change.getBeforeRevision().getFile(), change); } } for (FilePath filePath : moves.keySet()) { final List<Change> copies = (List<Change>)moves.get(filePath); if (copies.size() == 1) continue; copies.sort(CHANGES_AFTER_REVISION_COMPARATOR); for (int i = 0; i < (copies.size() - 1); i++) { final Change oldChange = copies.get(i); final Change newChange = new Change(null, oldChange.getAfterRevision()); final VcsKey key = myWorker.myIdx.getVcsFor(oldChange); myWorker.myIdx.changeRemoved(oldChange); myWorker.myIdx.changeAdded(newChange, key); ListData list = myWorker.removeChangeMapping(oldChange); myWorker.putChangeMapping(newChange, myWorker.notNullList(list)); } } } private final Comparator<Change> CHANGES_AFTER_REVISION_COMPARATOR = (o1, o2) -> { String s1 = o1.getAfterRevision().getFile().getPresentableUrl(); String s2 = o2.getAfterRevision().getFile().getPresentableUrl(); return SystemInfo.isFileSystemCaseSensitive ? s1.compareTo(s2) : s1.compareToIgnoreCase(s2); }; public void addChangeToList(@NotNull String name, @NotNull Change change, VcsKey vcsKey) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("[addChangeToList] name: %s change: %s vcs: %s", name, ChangesUtil.getFilePath(change).getPath(), vcsKey == null ? null : vcsKey.getName())); } ListData list = myWorker.getDataByName(name); if (list == null) return; addChangeToList(list, change, vcsKey); } public void addChangeToCorrespondingList(@NotNull Change change, VcsKey vcsKey) { if (LOG.isDebugEnabled()) { final String path = ChangesUtil.getFilePath(change).getPath(); LOG.debug("[addChangeToCorrespondingList] for change " + path + " type: " + change.getType() + " have before revision: " + (change.getBeforeRevision() != null)); } for (ChangeListWorker.ListData list : myWorker.myLists) { Set<Change> changesBeforeUpdate = myChangesBeforeUpdateMap.get(list.id); if (changesBeforeUpdate.contains(change)) { if (LOG.isDebugEnabled()) { LOG.debug("[addChangeToCorrespondingList] matched: " + list.name); } addChangeToList(list, change, vcsKey); return; } } if (LOG.isDebugEnabled()) { LOG.debug("[addChangeToCorrespondingList] added to default list"); } addChangeToList(myWorker.myDefault, change, vcsKey); } private void addChangeToList(@NotNull ListData list, @NotNull Change change, VcsKey vcsKey) { if (myWorker.myIdx.getChanges().contains(change)) { LOG.warn(String.format("Multiple equal changes added: %s", change)); return; } myWorker.myIdx.changeAdded(change, vcsKey); myWorker.putChangeMapping(change, list); } public void removeRegisteredChangeFor(@Nullable FilePath filePath) { Change change = myWorker.getChangeForPath(filePath); if (change == null) return; myWorker.myIdx.changeRemoved(change); myWorker.removeChangeMapping(change); } @NotNull @Override public List<LocalChangeList> getListsCopy() { return myWorker.getChangeLists(); } @Nullable @Override public LocalChangeList findChangeList(final String name) { return myWorker.getChangeListByName(name); } @NotNull @Override public LocalChangeList addChangeList(@NotNull String name, @Nullable String comment) { return myWorker.addChangeList(name, comment, null, null); } @NotNull @Override public LocalChangeList findOrCreateList(@NotNull final String name, final String comment) { LocalChangeList list = myWorker.getChangeListByName(name); if (list != null) return list; return addChangeList(name, comment); } @Override public void editComment(@NotNull final String name, final String comment) { myWorker.editComment(name, StringUtil.notNullize(comment)); } @Override public void editName(@NotNull String oldName, @NotNull String newName) { myWorker.editName(oldName, newName); } @Override public void setListsToDisappear(@NotNull Collection<String> names) { myListsToDisappear.addAll(names); } @Override public FileStatus getStatus(@NotNull VirtualFile file) { return myWorker.getStatus(file); } @Deprecated @Override public FileStatus getStatus(@NotNull File file) { return myWorker.getStatus(VcsUtil.getFilePath(file)); } @Override public FileStatus getStatus(@NotNull FilePath filePath) { return myWorker.getStatus(filePath); } @Override public void setDefaultChangeList(@NotNull String list) { myWorker.setDefaultList(list); } } public interface PartialChangeTracker { @NotNull List<String> getAffectedChangeListsIds(); void initChangeTracking(@NotNull String defaultId, @NotNull List<String> changelistsIds); void defaultListChanged(@NotNull String oldListId, @NotNull String newListId); void changeListRemoved(@NotNull String listId); void moveChanges(@NotNull String fromListId, @NotNull String toListId); void moveChangesTo(@NotNull String toListId); } }
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util.cache.impl; import com.facebook.buck.core.io.ArchiveMemberPath; import com.facebook.buck.event.AbstractBuckEvent; import com.facebook.buck.util.cache.FileHashCacheEngine; import com.facebook.buck.util.cache.HashCodeAndFileType; import com.facebook.buck.util.cache.JarHashCodeAndFileType; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.hash.HashCode; import java.io.IOException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.Collections; 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.ConcurrentMap; import java.util.concurrent.ExecutionException; class LoadingCacheFileHashCache implements FileHashCacheEngine { private final LoadingCache<Path, HashCodeAndFileType> loadingCache; private final LoadingCache<Path, Long> sizeCache; private final Map<Path, Set<Path>> parentToChildCache = new ConcurrentHashMap<>(); private LoadingCacheFileHashCache( ValueLoader<HashCodeAndFileType> hashLoader, ValueLoader<Long> sizeLoader) { loadingCache = CacheBuilder.newBuilder() .build( new CacheLoader<Path, HashCodeAndFileType>() { @Override public HashCodeAndFileType load(Path path) { HashCodeAndFileType hashCodeAndFileType = hashLoader.load(path); updateParent(path); return hashCodeAndFileType; } }); sizeCache = CacheBuilder.newBuilder() .build( new CacheLoader<Path, Long>() { @Override public Long load(Path path) { long size = sizeLoader.load(path); updateParent(path); return size; } }); } private void updateParent(Path path) { Path parent = path.getParent(); if (parent != null) { Set<Path> children = parentToChildCache.computeIfAbsent(parent, key -> Sets.newConcurrentHashSet()); children.add(path); } } public static FileHashCacheEngine createWithStats( ValueLoader<HashCodeAndFileType> hashLoader, ValueLoader<Long> sizeLoader) { return new StatsTrackingFileHashCacheEngine( new LoadingCacheFileHashCache(hashLoader, sizeLoader), "old"); } @Override public void put(Path path, HashCodeAndFileType value) { loadingCache.put(path, value); updateParent(path); } @Override public void putSize(Path path, long value) { sizeCache.put(path, value); updateParent(path); } @Override public void invalidateWithParents(Path path) { Iterable<Path> pathsToInvalidate = Maps.filterEntries( loadingCache.asMap(), entry -> { Objects.requireNonNull(entry); // If we get a invalidation for a file which is a prefix of our current one, this // means the invalidation is of a symlink which points to a directory (since // events // won't be triggered for directories). We don't fully support symlinks, however, // we do support some limited flows that use them to point to read-only storage // (e.g. the `project.read_only_paths`). For these limited flows to work // correctly, // we invalidate. if (entry.getKey().startsWith(path)) { return true; } // Otherwise, we want to invalidate the entry if the path matches it. We also // invalidate any directories that contain this entry, so use the following // comparison to capture both these scenarios. return path.startsWith(entry.getKey()); }) .keySet(); for (Path pathToInvalidate : pathsToInvalidate) { invalidate(pathToInvalidate); } } @Override public void invalidate(Path path) { loadingCache.invalidate(path); sizeCache.invalidate(path); Set<Path> children = parentToChildCache.remove(path); // recursively invalidate all recorded children (underlying files and subfolders) if (children != null) { children.forEach(this::invalidate); } Path parent = path.getParent(); if (parent != null) { Set<Path> siblings = parentToChildCache.get(parent); if (siblings != null) { siblings.remove(path); } } } @Override public HashCode get(Path path) throws IOException { HashCode sha1; try { sha1 = loadingCache.get(path.normalize()).getHashCode(); } catch (ExecutionException e) { Throwables.throwIfInstanceOf(e.getCause(), IOException.class); throw new RuntimeException(e.getCause()); } return Preconditions.checkNotNull(sha1, "Failed to find a HashCode for %s.", path); } @Override public HashCode get(ArchiveMemberPath archiveMemberPath) throws IOException { Path relativeFilePath = archiveMemberPath.getArchivePath().normalize(); try { JarHashCodeAndFileType fileHashCodeAndFileType = (JarHashCodeAndFileType) loadingCache.get(relativeFilePath); Path memberPath = archiveMemberPath.getMemberPath(); HashCodeAndFileType memberHashCodeAndFileType = fileHashCodeAndFileType.getContents().get(memberPath); if (memberHashCodeAndFileType == null) { throw new NoSuchFileException(archiveMemberPath.toString()); } return memberHashCodeAndFileType.getHashCode(); } catch (ExecutionException e) { Throwables.throwIfInstanceOf(e.getCause(), IOException.class); throw new RuntimeException(e.getCause()); } } @Override public long getSize(Path relativePath) throws IOException { try { return sizeCache.get(relativePath.normalize()); } catch (ExecutionException e) { Throwables.throwIfInstanceOf(e.getCause(), IOException.class); throw new RuntimeException(e.getCause()); } } @Override public void invalidateAll() { loadingCache.invalidateAll(); sizeCache.invalidateAll(); parentToChildCache.clear(); } @Override public ConcurrentMap<Path, HashCodeAndFileType> asMap() { return loadingCache.asMap(); } @Override public HashCodeAndFileType getIfPresent(Path path) { return loadingCache.getIfPresent(path); } @Override public Long getSizeIfPresent(Path path) { return sizeCache.getIfPresent(path); } @Override public List<AbstractBuckEvent> getStatsEvents() { return Collections.emptyList(); } }
package com.bbn.openmap.event; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.text.DecimalFormat; import java.text.Format; import java.util.Properties; import com.bbn.openmap.MapBean; import com.bbn.openmap.omGraphics.OMCircle; import com.bbn.openmap.omGraphics.OMPoint; import com.bbn.openmap.omGraphics.OMText; import com.bbn.openmap.proj.GreatCircle; import com.bbn.openmap.proj.ProjMath; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.proj.coords.LatLonPoint; import com.bbn.openmap.util.PropUtils; /** * Mouse mode for drawing temporary range rings on a map bean.<br> * The whole map bean is repainted each time the range rings needs to be * repainted. The map bean needs to use a mouseDelegator to repaint properly.<br> * * @author Stephane Wasserhardt * */ public class RangeRingsMouseMode extends CoordMouseMode { private static final long serialVersionUID = 6208201699394207932L; public final static transient String modeID = "RangeRings"; /** * The property string used to set the numRings member variable. */ public static final String NUM_RINGS_PROPERTY = "numRings"; public transient DecimalFormat df = new DecimalFormat("0.###"); /** * Format used to draw distances. */ protected Format distanceFormat; /** * Number of rings to draw. Must be a positive integer, or else the value 1 * will be used. Default value is 3.<br> */ protected int numRings = 3; /** * Origin point of the range rings to be drawn. */ protected LatLonPoint origin = null; /** * Temporary destination point of the range rings to be drawn. */ protected LatLonPoint intermediateDest = null; /** * Destination point of the range rings to be drawn. */ protected LatLonPoint destination = null; /** * Active MapBean. */ protected MapBean mapBean; public RangeRingsMouseMode() { this(true); } public RangeRingsMouseMode(boolean shouldConsumeEvents) { super(modeID, shouldConsumeEvents); init(); } public RangeRingsMouseMode(String name, boolean shouldConsumeEvents) { super(name, shouldConsumeEvents); init(); } protected void init() { setModeCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); } /** * Return the map bean. * * @return The map bean. */ public MapBean getMapBean() { return mapBean; } /** * Set the map bean. * * @param aMap a map bean */ public void setMapBean(MapBean aMap) { mapBean = aMap; } /** * Give the Format object used to display distances. * * @return Format. */ public Format getDistanceFormat() { return distanceFormat; } /** * Sets the Format object used to display distances. * * @param distanceFormat Format. */ public void setDistanceFormat(Format distanceFormat) { this.distanceFormat = distanceFormat; redraw(); } /** * Returns the number of rings to display. * * @return the number of rings to display. */ public int getNumRings() { return numRings; } /** * Sets the number of rings to display. * * @param numRings the number of rings to display. */ public void setNumRings(int numRings) { this.numRings = numRings; redraw(); } public void mouseClicked(MouseEvent e) { if (e.getSource() instanceof MapBean) { setMapBean((MapBean) e.getSource()); // if double (or more) mouse clicked if (e.getClickCount() >= 2) { // Clean the range rings cleanUp(); redraw(); } } } public void mousePressed(MouseEvent e) { e.getComponent().requestFocus(); } public void mouseReleased(MouseEvent e) { if ((e.getComponent().hasFocus()) && (e.getSource() instanceof MapBean)) { setMapBean((MapBean) e.getSource()); LatLonPoint pt = (LatLonPoint) getMapBean().getProjection().inverse(e.getPoint(), new LatLonPoint.Double()); // If this is the first click (real first click or click after // "finished" rangeRings) if ((origin == null) || ((origin != null) && (destination != null))) { // First, we clear up the map (erase any previous rangeRings) cleanUp(); redraw(); origin = pt; // Just to be sure destination = null; startUp(); } // This case is when only the origin is known else { // The click then corresponds to the selection of a destination destination = pt; finished(); } redraw(); } } public void mouseMoved(MouseEvent e) { if (e.getSource() instanceof MapBean) { setMapBean((MapBean) (e.getSource())); if (origin != null) { intermediateDest = (LatLonPoint) getMapBean().getProjection().inverse(e.getPoint(), new LatLonPoint.Double()); fireMouseLocation(e); update(); redraw(); } else { fireMouseLocation(e); } } } public void mouseEntered(MouseEvent e) { if (e.getSource() instanceof MapBean) { setMapBean((MapBean) e.getSource()); } } /** * Repaints the map bean. When this mouse mode is active, it is registered * as a <code>paintListener</code> for the mapBean by the mouseDelegator, so * the <code>listenerPaint</code> method can draw the range rings on the map * bean. */ public void redraw() { MapBean mb = getMapBean(); if (mb != null) { mb.repaint(); } } public void listenerPaint(Graphics g) { // We paint only if we know the origin ... if (origin != null) { paintOrigin(g); // ... and we paint the rings if we know either of destination or // intermediateDest if (destination != null) { paintRangeRings(destination, g); } else if (intermediateDest != null) { paintRangeRings(intermediateDest, g); } } } /** * Paints the origin point of the range rings and its label on the map bean. */ protected void paintOrigin() { MapBean mb = getMapBean(); if (mb != null) { Graphics g = mb.getGraphics(true); paintOrigin(g); } } /** * Paints the origin point of the range rings and its label on the given * Graphics. * * @param graphics The Graphics to paint on. */ protected void paintOrigin(Graphics graphics) { MapBean mb = getMapBean(); if (mb == null) { return; } paintOriginPoint(graphics); paintOriginLabel(graphics); } /** * Paints the origin point of the range rings on the given Graphics. * * @param graphics The Graphics to paint on. */ protected void paintOriginPoint(Graphics graphics) { MapBean mb = getMapBean(); Projection proj = mb.getProjection(); OMPoint pt = new OMPoint((float) origin.getY(), (float) origin.getX()); Graphics2D g = (Graphics2D) graphics; g.setPaintMode(); g.setColor(Color.BLACK); preparePoint(pt); pt.generate(proj); pt.render(g); } /** * Paints the origin label of the range rings on the given Graphics. * * @param graphics The Graphics to paint on. */ protected void paintOriginLabel(Graphics graphics) { MapBean mb = getMapBean(); Projection proj = mb.getProjection(); Point2D pt = proj.forward(origin); String infoText = getOriginLabel(); Graphics2D g = (Graphics2D) graphics; Rectangle2D r = g.getFontMetrics().getStringBounds(infoText, graphics); pt.setLocation(pt.getX() - (r.getWidth() / 2d), pt.getY() - (r.getHeight() / 2d)); OMText text = new OMText((int) pt.getX(), (int) pt.getY(), infoText, OMText.JUSTIFY_LEFT); g.setPaintMode(); g.setColor(Color.BLACK); prepareLabel(text); text.generate(proj); text.render(g); } /** * Paints the circles and their labels on the map bean. * * @param dest The destination point, used with the <code>origin</code> * member variable to compute the rings. */ protected void paintRangeRings(LatLonPoint dest) { MapBean mb = getMapBean(); if (mb != null) { Graphics g = mb.getGraphics(true); paintRangeRings(dest, g); } } /** * Paints the circles and their labels on the given Graphics. * * @param dest The destination point, used with the <code>origin</code> * member variable to compute the rings. * @param graphics The Graphics to paint on. */ protected void paintRangeRings(LatLonPoint dest, Graphics graphics) { MapBean mb = getMapBean(); if (mb == null) { return; } Projection proj = mb.getProjection(); AffineTransform xyTranslation = getTranslation(origin, dest, proj); LatLonPoint p = null; for (int i = 0; i < Math.max(1, numRings); i++) { if (p == null) { p = dest; } else { p = translate(p, xyTranslation, proj); } paintCircle(p, graphics); paintLabel(p, graphics); } } /** * Paints a unique circle centered on <code>origin</code> and which crosses * <code>dest</code> on the map bean. * * @param dest A point on the circle. */ protected void paintCircle(LatLonPoint dest) { MapBean mb = getMapBean(); if (mb != null) { Graphics g = mb.getGraphics(true); paintCircle(dest, g); } } /** * Paints a unique circle centered on <code>origin</code> and which crosses * <code>dest</code> on the given Graphics. * * @param dest A point on the circle. * @param graphics The Graphics to paint on. */ protected void paintCircle(LatLonPoint dest, Graphics graphics) { double oLat = origin.getY(); double oLon = origin.getX(); double radphi1 = ProjMath.degToRad(oLat); double radlambda0 = ProjMath.degToRad(oLon); double radphi = ProjMath.degToRad(dest.getY()); double radlambda = ProjMath.degToRad(dest.getX()); // calculate the circle radius double dRad = GreatCircle.sphericalDistance(radphi1, radlambda0, radphi, radlambda); // convert into decimal degrees float rad = (float) ProjMath.radToDeg(dRad); // make the circle OMCircle circle = new OMCircle((float) oLat, (float) oLon, rad); prepareCircle(circle); // get the map projection Projection proj = getMapBean().getProjection(); // prepare the circle for rendering circle.generate(proj); // render the circle graphic circle.render(graphics); } /** * Paints a label for the circle drawn using <code>dest</code> on the map * bean. * * @param dest A point on the circle. */ protected void paintLabel(LatLonPoint dest) { MapBean mb = getMapBean(); if (mb != null) { Graphics g = mb.getGraphics(true); paintLabel(dest, g); } } /** * Paints a label for the circle drawn using <code>dest</code> on the given * Graphics. * * @param dest A point on the circle. * @param graphics The Graphics to paint on. */ protected void paintLabel(LatLonPoint dest, Graphics graphics) { String infoText = getLabelFor(dest); Graphics2D g = (Graphics2D) graphics; Rectangle2D r = g.getFontMetrics().getStringBounds(infoText, graphics); double th = r.getHeight(); LatLonPoint llp = new LatLonPoint.Double(origin); double distance = llp.distance(dest); if (llp.getLatitude() > 0) { llp.setLatLon(Math.toRadians(llp.getLatitude()) - distance, Math.toRadians(llp.getLongitude()), true); } else { llp.setLatLon(Math.toRadians(llp.getLatitude()) + distance, Math.toRadians(llp.getLongitude()), true); th = -th / 2d; } Projection proj = getMapBean().getProjection(); Point2D pt = proj.forward(llp); pt.setLocation(pt.getX() - (r.getWidth() / 2d), pt.getY() - th); OMText text = new OMText((int) pt.getX(), (int) pt.getY(), infoText, OMText.JUSTIFY_LEFT); g.setPaintMode(); g.setColor(Color.BLACK); prepareLabel(text); text.generate(proj); text.render(g); } /** * Customizes the given OMPoint before it is rendered. * * @param point OMPoint. */ protected void preparePoint(OMPoint point) { } /** * Customizes the given OMCicle before it is rendered. * * @param circle OMCircle. */ protected void prepareCircle(OMCircle circle) { } /** * Customizes the given OMText before it is rendered. * * @param text OMText. */ protected void prepareLabel(OMText text) { text.setLinePaint(Color.BLACK); text.setTextMatteColor(getMapBean().getBackground()); text.setTextMatteStroke(new BasicStroke(4)); } /** * Returns the String to be used as a labeler for the origin point of the * range rings. * * @return label String. */ protected String getOriginLabel() { return "(" + df.format(origin.getY()) + ", " + df.format(origin.getX()) + ")"; } /** * Returns the String to be used as a labeler for the circle drawn using * <code>dest</code>. * * @param dest A point on a circle. * @return label String. */ protected String getLabelFor(LatLonPoint dest) { Format distFormat = getDistanceFormat(); double distance = origin.distance(dest); if (distFormat == null) { return Double.toString(distance); } return distFormat.format(new Double(distance)); } /** * Called when the origin point of the range rings has been selected, before * painting on the map. */ protected void startUp() { } /** * Called when the origin point of the range is is known, and the mouse is * moving on the map, but before painting on the map. */ protected void update() { } /** * Called when the end point of the range rings has been selected, before * painting on the map. */ protected void finished() { } /** * Called when the range rings must be cleared, before repainting a clean * map. */ protected void cleanUp() { origin = null; intermediateDest = null; destination = null; } private AffineTransform getTranslation(LatLonPoint pt1, LatLonPoint pt2, Projection proj) { Point2D p1 = proj.forward(pt1); Point2D p2 = proj.forward(pt2); return AffineTransform.getTranslateInstance(p2.getX() - p1.getX(), p2.getY() - p1.getY()); } private LatLonPoint translate(LatLonPoint pt, AffineTransform xyTranslation, Projection proj) { Point2D p = proj.forward(pt); xyTranslation.transform(p, p); return (LatLonPoint) proj.inverse(p, new LatLonPoint.Double()); } public void setProperties(String prefix, Properties props) { super.setProperties(prefix, props); prefix = PropUtils.getScopedPropertyPrefix(prefix); numRings = PropUtils.intFromProperties(props, prefix + NUM_RINGS_PROPERTY, numRings); } public Properties getProperties(Properties props) { props = super.getProperties(props); String prefix = PropUtils.getScopedPropertyPrefix(getPropertyPrefix()); props.setProperty(prefix + NUM_RINGS_PROPERTY, Integer.toString(numRings)); return props; } public Properties getPropertyInfo(Properties list) { list = super.getPropertyInfo(list); list.setProperty(NUM_RINGS_PROPERTY, "Number of range rings to be drawn (minimum=1; default=3)."); return list; } }
/* * 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.facebook.presto.raptor.storage; import com.facebook.presto.raptor.metadata.ColumnInfo; import com.facebook.presto.raptor.metadata.ForMetadata; import com.facebook.presto.raptor.metadata.MetadataDao; import com.facebook.presto.raptor.metadata.ShardInfo; import com.facebook.presto.raptor.metadata.ShardManager; import com.facebook.presto.raptor.metadata.ShardMetadata; import com.facebook.presto.raptor.metadata.TableColumn; import com.facebook.presto.raptor.metadata.TableMetadata; import com.facebook.presto.spi.NodeManager; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.type.Type; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import io.airlift.log.Logger; import io.airlift.stats.CounterStat; import io.airlift.units.DataSize; import io.airlift.units.Duration; import org.skife.jdbi.v2.IDBI; import org.weakref.jmx.Managed; import org.weakref.jmx.Nested; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.facebook.presto.raptor.RaptorErrorCode.RAPTOR_ERROR; import static com.facebook.presto.raptor.metadata.DatabaseShardManager.maxColumn; import static com.facebook.presto.raptor.metadata.DatabaseShardManager.minColumn; import static com.facebook.presto.raptor.metadata.DatabaseShardManager.shardIndexTable; import static com.facebook.presto.spi.block.SortOrder.ASC_NULLS_FIRST; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Iterables.partition; import static com.google.common.collect.Sets.newConcurrentHashSet; import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static java.lang.String.format; import static java.util.Collections.nCopies; import static java.util.Objects.requireNonNull; import static java.util.concurrent.CompletableFuture.runAsync; import static java.util.concurrent.Executors.newFixedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; public class ShardCompactionManager { private static final double FILL_FACTOR = 0.75; private static final Logger log = Logger.get(ShardCompactionManager.class); private static final int MAX_PENDING_COMPACTIONS = 500; private final ScheduledExecutorService compactionDiscoveryService = newScheduledThreadPool(1, daemonThreadsNamed("shard-compaction-discovery")); private final ExecutorService compactionDriverService = newFixedThreadPool(1, daemonThreadsNamed("shard-compaction-driver")); private final ExecutorService compactionService; private final AtomicBoolean discoveryStarted = new AtomicBoolean(); private final AtomicBoolean compactionStarted = new AtomicBoolean(); private final AtomicBoolean shutdown = new AtomicBoolean(); // Tracks shards that are scheduled for compaction so that we do not schedule them more than once private final Set<Long> shardsInProgress = newConcurrentHashSet(); private final BlockingQueue<CompactionSet> compactionQueue = new LinkedBlockingQueue<>(); private final MetadataDao metadataDao; private final ShardCompactor compactor; private final ShardManager shardManager; private final String currentNodeIdentifier; private final boolean compactionEnabled; private final Duration compactionDiscoveryInterval; private final DataSize maxShardSize; private final long maxShardRows; private final IDBI dbi; private final CounterStat compactionSuccessCount = new CounterStat(); private final CounterStat compactionFailureCount = new CounterStat(); @Inject public ShardCompactionManager(@ForMetadata IDBI dbi, NodeManager nodeManager, ShardManager shardManager, ShardCompactor compactor, StorageManagerConfig config) { this(dbi, nodeManager.getCurrentNode().getNodeIdentifier(), shardManager, compactor, config.getCompactionInterval(), config.getMaxShardSize(), config.getMaxShardRows(), config.getCompactionThreads(), config.isCompactionEnabled()); } public ShardCompactionManager( IDBI dbi, String currentNodeIdentifier, ShardManager shardManager, ShardCompactor compactor, Duration compactionDiscoveryInterval, DataSize maxShardSize, long maxShardRows, int compactionThreads, boolean compactionEnabled) { this.dbi = requireNonNull(dbi, "dbi is null"); this.metadataDao = dbi.onDemand(MetadataDao.class); this.currentNodeIdentifier = requireNonNull(currentNodeIdentifier, "currentNodeIdentifier is null"); this.shardManager = requireNonNull(shardManager, "shardManager is null"); this.compactor = requireNonNull(compactor, "compactor is null"); this.compactionDiscoveryInterval = requireNonNull(compactionDiscoveryInterval, "compactionDiscoveryInterval is null"); checkArgument(maxShardSize.toBytes() > 0, "maxShardSize must be > 0"); this.maxShardSize = requireNonNull(maxShardSize, "maxShardSize is null"); checkArgument(maxShardRows > 0, "maxShardRows must be > 0"); this.maxShardRows = maxShardRows; this.compactionEnabled = compactionEnabled; if (compactionEnabled) { checkArgument(compactionThreads > 0, "compactionThreads must be > 0"); this.compactionService = newFixedThreadPool(compactionThreads, daemonThreadsNamed("shard-compactor-%s")); } else { this.compactionService = null; } } @PostConstruct public void start() { if (!compactionEnabled) { return; } if (!discoveryStarted.getAndSet(true)) { startDiscovery(); } if (!compactionStarted.getAndSet(true)) { compactionDriverService.submit(new ShardCompactionDriver()); } } @PreDestroy public void shutdown() { if (!compactionEnabled) { return; } shutdown.set(true); compactionDiscoveryService.shutdown(); compactionDriverService.shutdown(); compactionService.shutdown(); } private void startDiscovery() { compactionDiscoveryService.scheduleWithFixedDelay(() -> { try { // jitter to avoid overloading database long interval = (long) compactionDiscoveryInterval.convertTo(SECONDS).getValue(); SECONDS.sleep(ThreadLocalRandom.current().nextLong(1, interval)); discoverShards(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Throwable t) { log.error(t, "Error discovering shards to compact"); } }, 0, compactionDiscoveryInterval.toMillis(), TimeUnit.MILLISECONDS); } private void discoverShards() { if (shardsInProgress.size() >= MAX_PENDING_COMPACTIONS) { return; } for (long tableId : metadataDao.listTableIds()) { Set<ShardMetadata> shardMetadata = shardManager.getNodeTableShards(currentNodeIdentifier, tableId); Set<ShardMetadata> shards = shardMetadata.stream() .filter(this::needsCompaction) .filter(shard -> !shardsInProgress.contains(shard.getShardId())) .collect(toSet()); if (shards.size() <= 1) { continue; } Long temporalColumnId = metadataDao.getTemporalColumnId(tableId); CompactionSetCreator compactionSetCreator; if (temporalColumnId == null) { compactionSetCreator = new FileCompactionSetCreator(maxShardSize, maxShardRows); } else { Type type = metadataDao.getTableColumn(tableId, temporalColumnId).getDataType(); compactionSetCreator = new TemporalCompactionSetCreator(maxShardSize, maxShardRows, type); shards = filterShardsWithTemporalMetadata(shardMetadata, tableId, temporalColumnId); } addToCompactionQueue(compactionSetCreator, tableId, shards); } } /** * @return shards that have temporal information */ @VisibleForTesting Set<ShardMetadata> filterShardsWithTemporalMetadata(Set<ShardMetadata> shardMetadata, long tableId, long temporalColumnId) { List<ShardMetadata> shardMetadatas = ImmutableList.copyOf(shardMetadata); Map<Long, ShardMetadata> shardsById = shardMetadatas.stream().collect(toMap(ShardMetadata::getShardId, shard -> shard)); String minColumn = minColumn(temporalColumnId); String maxColumn = maxColumn(temporalColumnId); ImmutableSet.Builder<ShardMetadata> temporalShards = ImmutableSet.builder(); try (Connection connection = dbi.open().getConnection()) { for (List<ShardMetadata> shards : partition(shardMetadatas, 1000)) { String args = Joiner.on(",").join(nCopies(shards.size(), "?")); String sql = format("SELECT shard_id, %s, %s FROM %s WHERE shard_id IN (%s)", minColumn, maxColumn, shardIndexTable(tableId), args); try (PreparedStatement statement = connection.prepareStatement(sql)) { for (int i = 0; i < shards.size(); i++) { statement.setLong(i + 1, shards.get(i).getShardId()); } try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { long rangeStart = resultSet.getLong(minColumn); if (resultSet.wasNull()) { // no temporal information for shard, skip it continue; } long rangeEnd = resultSet.getLong(maxColumn); if (resultSet.wasNull()) { // no temporal information for shard, skip it continue; } long shardId = resultSet.getLong("shard_id"); if (resultSet.wasNull()) { // shard does not exist anymore continue; } ShardMetadata shard = shardsById.get(shardId); if (shard != null) { temporalShards.add(shard.withTimeRange(rangeStart, rangeEnd)); } } } } } } catch (SQLException e) { throw new PrestoException(RAPTOR_ERROR, e); } return temporalShards.build(); } private void addToCompactionQueue(CompactionSetCreator compactionSetCreator, long tableId, Set<ShardMetadata> shardsToCompact) { for (CompactionSet compactionSet : compactionSetCreator.createCompactionSets(tableId, shardsToCompact)) { if (compactionSet.getShardsToCompact().size() <= 1) { // throw it away because there is no work to be done continue; } compactionSet.getShardsToCompact().stream() .map(ShardMetadata::getShardId) .forEach(shardsInProgress::add); compactionQueue.add(compactionSet); } } private boolean needsCompaction(ShardMetadata shard) { if (shard.getUncompressedSize() < (FILL_FACTOR * maxShardSize.toBytes())) { return true; } if (shard.getRowCount() < (FILL_FACTOR * maxShardRows)) { return true; } return false; } private class ShardCompactionDriver implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted() && !shutdown.get()) { try { CompactionSet compactionSet = compactionQueue.take(); runAsync(new CompactionJob(compactionSet), compactionService) .whenComplete((none, throwable) -> { if (throwable == null) { compactionSuccessCount.update(1); } else { log.warn(throwable, "Error in compaction"); compactionFailureCount.update(1); } }); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } private class CompactionJob implements Runnable { private final CompactionSet compactionSet; public CompactionJob(CompactionSet compactionSet) { this.compactionSet = requireNonNull(compactionSet, "compactionSet is null"); } @Override public void run() { Set<UUID> shardUuids = compactionSet.getShardsToCompact().stream().map(ShardMetadata::getShardUuid).collect(toSet()); Set<Long> shardIds = compactionSet.getShardsToCompact().stream().map(ShardMetadata::getShardId).collect(toSet()); try { TableMetadata tableMetadata = getTableMetadata(compactionSet.getTableId()); List<ShardInfo> newShards = performCompaction(shardUuids, tableMetadata); shardManager.replaceShardIds(tableMetadata.getTableId(), tableMetadata.getColumns(), shardIds, newShards); } catch (IOException e) { throw Throwables.propagate(e); } finally { shardsInProgress.removeAll(shardIds); } } private List<ShardInfo> performCompaction(Set<UUID> shardUuids, TableMetadata tableMetadata) throws IOException { if (tableMetadata.getSortColumnIds().isEmpty()) { return compactor.compact(shardUuids, tableMetadata.getColumns()); } return compactor.compactSorted( shardUuids, tableMetadata.getColumns(), tableMetadata.getSortColumnIds(), nCopies(tableMetadata.getSortColumnIds().size(), ASC_NULLS_FIRST)); } } private TableMetadata getTableMetadata(long tableId) { List<TableColumn> sortColumns = metadataDao.listSortColumns(tableId); List<Long> sortColumnIds = sortColumns.stream().map(TableColumn::getColumnId).collect(toList()); List<ColumnInfo> columns = metadataDao.listTableColumns(tableId).stream() .map(TableColumn::toColumnInfo) .collect(toList()); return new TableMetadata(tableId, columns, sortColumnIds); } @Managed public int getShardsInProgress() { return shardsInProgress.size(); } @Managed @Nested public CounterStat getCompactionSuccessCount() { return compactionSuccessCount; } @Managed @Nested public CounterStat getCompactionFailureCount() { return compactionFailureCount; } }
/** * 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.kerby.has.server; import org.apache.commons.dbutils.DbUtils; import org.apache.hadoop.http.HttpConfig; import org.apache.kerby.has.common.HasConfig; import org.apache.kerby.has.common.HasException; import org.apache.kerby.has.common.util.HasUtil; import org.apache.kerby.has.server.web.WebConfigKey; import org.apache.kerby.has.server.web.WebServer; import org.apache.kerby.kerberos.kdc.impl.NettyKdcServerImpl; import org.apache.kerby.kerberos.kerb.KrbException; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadmin; import org.apache.kerby.kerberos.kerb.admin.kadmin.local.LocalKadminImpl; import org.apache.kerby.kerberos.kerb.client.ClientUtil; import org.apache.kerby.kerberos.kerb.client.KrbConfig; import org.apache.kerby.kerberos.kerb.client.KrbSetting; import org.apache.kerby.kerberos.kerb.identity.backend.BackendConfig; import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend; import org.apache.kerby.kerberos.kerb.server.KdcServer; import org.apache.kerby.kerberos.kerb.server.KdcUtil; import org.apache.kerby.util.IOUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * The HAS KDC server implementation. */ public class HasServer { public static final Logger LOG = LoggerFactory.getLogger(HasServer.class); private static HasServer server = null; private KrbSetting krbSetting; private KdcServer kdcServer; private WebServer webServer; private File confDir; private File workDir; private String kdcHost; private HasConfig hasConfig; public HasServer(File confDir) throws KrbException { this.confDir = confDir; } private void setConfDir(File confDir) { this.confDir = confDir; } public File getConfDir() { return confDir; } public File getWorkDir() { return workDir; } public void setWorkDir(File workDir) { this.workDir = workDir; } public void setKdcHost(String host) { this.kdcHost = host; } public String getKdcHost() { return kdcHost; } public KrbSetting getKrbSetting() { return krbSetting; } public KdcServer getKdcServer() { return kdcServer; } public WebServer getWebServer() { return webServer; } public void setWebServer(WebServer webServer) { this.webServer = webServer; } public void startKdcServer() throws HasException { BackendConfig backendConfig; try { backendConfig = KdcUtil.getBackendConfig(getConfDir()); } catch (KrbException e) { throw new HasException("Failed to get backend config. " + e); } String backendJar = backendConfig.getString("kdc_identity_backend"); if (backendJar.equals("org.apache.kerby.kerberos.kdc.identitybackend.MySQLIdentityBackend")) { updateKdcConf(); } try { kdcServer = new KdcServer(confDir); } catch (KrbException e) { throw new HasException("Failed to create KdcServer. " + e.getMessage()); } kdcServer.setWorkDir(workDir); kdcServer.setInnerKdcImpl(new NettyKdcServerImpl(kdcServer.getKdcSetting())); try { kdcServer.init(); } catch (KrbException e) { LOG.error("Errors occurred when init has kdc server: " + e.getMessage()); throw new HasException("Errors occurred when init has kdc server: " + e.getMessage()); } KrbConfig krbConfig; try { krbConfig = ClientUtil.getConfig(confDir); } catch (KrbException e) { throw new HasException("Errors occurred when getting the config from conf dir. " + e.getMessage()); } if (krbConfig == null) { krbConfig = new KrbConfig(); } this.krbSetting = new KrbSetting(krbConfig); try { kdcServer.start(); } catch (KrbException e) { throw new HasException("Failed to start kdc server. " + e.getMessage()); } try { HasUtil.setEnableConf(new File(confDir, "has-server.conf"), "false"); } catch (Exception e) { throw new HasException("Failed to enable conf. " + e.getMessage()); } setHttpFilter(); } public File initKdcServer() throws KrbException { File adminKeytabFile = new File(workDir, "admin.keytab"); if (kdcServer == null) { throw new KrbException("Please start KDC server first."); } LocalKadmin kadmin = new LocalKadminImpl(kdcServer.getKdcSetting(), kdcServer.getIdentityService()); if (adminKeytabFile.exists()) { throw new KrbException("KDC Server is already inited."); } kadmin.createBuiltinPrincipals(); kadmin.exportKeytab(adminKeytabFile, kadmin.getKadminPrincipal()); System.out.println("The keytab for kadmin principal " + "has been exported to the specified file " + adminKeytabFile.getAbsolutePath() + ", please keep it safe, " + "in order to use kadmin tool later"); return adminKeytabFile; } private void setHttpFilter() throws HasException { File httpKeytabFile = new File(workDir, "http.keytab"); LocalKadmin kadmin = new LocalKadminImpl(kdcServer.getKdcSetting(), kdcServer.getIdentityService()); createHttpPrincipal(kadmin); try { kadmin.exportKeytab(httpKeytabFile, getHttpPrincipal()); } catch (KrbException e) { throw new HasException("Failed to export keytab: " + e.getMessage()); } webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_FILTER_AUTH_TYPE, hasConfig.getFilterAuthType()); webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, getHttpPrincipal()); webServer.getConf().setString(WebConfigKey.HAS_AUTHENTICATION_KERBEROS_KEYTAB_KEY, httpKeytabFile.getPath()); webServer.defineFilter(); } public void createHttpPrincipal(LocalKadmin kadmin) throws HasException { String httpPrincipal = getHttpPrincipal(); IdentityBackend backend = kdcServer.getIdentityService(); try { if (backend.getIdentity(httpPrincipal) == null) { kadmin.addPrincipal(httpPrincipal); } else { LOG.info("The http principal already exists in backend."); } } catch (KrbException e) { throw new HasException("Failed to add principal, " + e.getMessage()); } } public String getHttpPrincipal() throws HasException { String realm = kdcServer.getKdcSetting().getKdcRealm(); String nameString; try { InetAddress addr = InetAddress.getLocalHost(); String fqName = addr.getCanonicalHostName(); nameString = "HTTP/" + fqName + "@" + realm; } catch (UnknownHostException e) { throw new HasException(e); } LOG.info("The http principal name is: " + nameString); return nameString; } /** * Update conf file. * * @param confName conf file name * @param values customized values * @throws IOException throw IOException * @throws HasException e */ public void updateConfFile(String confName, Map<String, String> values) throws IOException, HasException { File confFile = new File(getConfDir().getAbsolutePath(), confName); if (confFile.exists()) { // Update conf file content InputStream templateResource; if (confName.equals("has-server.conf")) { templateResource = new FileInputStream(confFile); } else { String resourcePath = "/" + confName + ".template"; templateResource = getClass().getResourceAsStream(resourcePath); } String content; try { content = IOUtil.readInput(templateResource); } finally { templateResource.close(); } for (Map.Entry<String, String> entry : values.entrySet()) { content = content.replaceAll(Pattern.quote(entry.getKey()), entry.getValue()); } // Delete the original conf file boolean delete = confFile.delete(); if (!delete) { throw new HasException("Failed to delete conf file: " + confName); } // Save the updated conf file IOUtil.writeFile(content, confFile); } else { throw new HasException("Conf file: " + confName + " not found."); } } /** * Get KDC Config from MySQL. * * @return Kdc config * @throws HasException e */ private Map<String, String> getKdcConf() throws HasException { PreparedStatement preStm = null; ResultSet result = null; Map<String, String> kdcConf = new HashMap<>(); BackendConfig backendConfig; try { backendConfig = KdcUtil.getBackendConfig(getConfDir()); } catch (KrbException e) { throw new HasException("Getting backend config failed." + e.getMessage()); } String driver = backendConfig.getString("mysql_driver"); String url = backendConfig.getString("mysql_url"); String user = backendConfig.getString("mysql_user"); String password = backendConfig.getString("mysql_password"); Connection connection = startConnection(driver, url, user, password); try { // Get Kdc configuration from kdc_config table String stmKdc = "SELECT * FROM `kdc_config` WHERE id = 1"; preStm = connection.prepareStatement(stmKdc); result = preStm.executeQuery(); while (result.next()) { String realm = result.getString("realm"); String servers = result.getString("servers"); String port = String.valueOf(result.getInt("port")); kdcConf.put("servers", servers); kdcConf.put("_PORT_", port); kdcConf.put("_REALM_", realm); } } catch (SQLException e) { LOG.error("Error occurred while getting kdc config."); throw new HasException("Failed to get kdc config. ", e); } finally { DbUtils.closeQuietly(preStm); DbUtils.closeQuietly(result); DbUtils.closeQuietly(connection); } return kdcConf; } /** * Update KDC conf file. * * @throws HasException e */ private void updateKdcConf() throws HasException { try { Map<String, String> values = getKdcConf(); String host = getKdcHost(); if (host == null) { InetSocketAddress bind = getWebServer().getBindAddress(); if (bind != null) { host = bind.getHostName(); } } values.remove("servers"); values.put("_HOST_", host); updateConfFile("kdc.conf", values); } catch (IOException e) { throw new HasException("Failed to update kdc config. ", e); } } /** * Start the MySQL connection. * * @param url url of connection * @param user username of connection * @param password password of connection * @throws HasException e * @return MySQL JDBC connection */ private Connection startConnection(String driver, String url, String user, String password) throws HasException { Connection connection; try { Class.forName(driver); connection = DriverManager.getConnection(url, user, password); if (!connection.isClosed()) { LOG.info("Succeeded in connecting to MySQL."); } } catch (ClassNotFoundException e) { throw new HasException("JDBC Driver Class not found. ", e); } catch (SQLException e) { throw new HasException("Failed to connecting to MySQL. ", e); } return connection; } /** * Config HAS server KDC which have MySQL backend. * @param backendConfig MySQL backend config * @param realm KDC realm to set * @param port has server port * @param host KDC host to set * @param hasServer has server to get param * @throws HasException e */ public void configMySQLKdc(BackendConfig backendConfig, String realm, int port, String host, HasServer hasServer) throws HasException { // Start mysql connection String driver = backendConfig.getString("mysql_driver"); String url = backendConfig.getString("mysql_url"); String user = backendConfig.getString("mysql_user"); String password = backendConfig.getString("mysql_password"); Connection connection = startConnection(driver, url, user, password); ResultSet resConfig = null; PreparedStatement preStm = null; try { createKdcTable(connection); // Create kdc_config table if not exists String stm = "SELECT * FROM `kdc_config` WHERE id = 1"; preStm = connection.prepareStatement(stm); resConfig = preStm.executeQuery(); if (!resConfig.next()) { addKdcConfig(connection, realm, port, host); } else { String oldHost = hasServer.getKdcHost(); String servers = resConfig.getString("servers"); String[] serverArray = servers.split(","); List<String> serverList = new ArrayList<>(); Collections.addAll(serverList, serverArray); if (serverList.contains(oldHost)) { servers = servers.replaceAll(oldHost, host); } else { servers = servers + "," + host; } boolean initialized = resConfig.getBoolean("initialized"); updateKdcConfig(connection, initialized, port, realm, servers); } hasServer.setKdcHost(host); } catch (SQLException e) { throw new HasException("Failed to config HAS KDC. ", e); } finally { DbUtils.closeQuietly(preStm); DbUtils.closeQuietly(resConfig); DbUtils.closeQuietly(connection); } } /** * Create kdc_config table in database. * @param conn database connection * @throws HasException e */ private void createKdcTable(final Connection conn) throws HasException { PreparedStatement preStm = null; try { String stm = "CREATE TABLE IF NOT EXISTS `kdc_config` (" + "port INTEGER DEFAULT 88, servers VARCHAR(255) NOT NULL, " + "initialized bool DEFAULT FALSE, realm VARCHAR(255) " + "DEFAULT NULL, id INTEGER DEFAULT 1, CHECK (id=1), PRIMARY KEY (id)) " + "ENGINE=INNODB;"; preStm = conn.prepareStatement(stm); preStm.executeUpdate(); } catch (SQLException e) { throw new HasException("Failed to create kdc_config table. ", e); } finally { DbUtils.closeQuietly(preStm); } } /** * Add KDC Config information in database. * @param conn database connection * @param realm realm to add * @param port port to add * @param host host to add */ private void addKdcConfig(Connection conn, String realm, int port, String host) throws HasException { PreparedStatement preStm = null; try { String stm = "INSERT INTO `kdc_config` (port, servers, realm)" + " VALUES(?, ?, ?)"; preStm = conn.prepareStatement(stm); preStm.setInt(1, port); preStm.setString(2, host); preStm.setString(3, realm); preStm.executeUpdate(); } catch (SQLException e) { throw new HasException("Failed to insert into kdc_config table. ", e); } finally { DbUtils.closeQuietly(preStm); } } /** * Update KDC Config record in database. * @param conn database connection * @param realm realm to update * @param port port to update * @param servers servers to update * @param initialized initial state of KDC Config */ private void updateKdcConfig(Connection conn, boolean initialized, int port, String realm, String servers) throws HasException { PreparedStatement preStm = null; try { if (initialized) { String stmUpdate = "UPDATE `kdc_config` SET servers = ? WHERE id = 1"; preStm = conn.prepareStatement(stmUpdate); preStm.setString(1, servers); preStm.executeUpdate(); } else { String stmUpdate = "UPDATE `kdc_config` SET port = ?, realm = ?, servers = ? WHERE id = 1"; preStm = conn.prepareStatement(stmUpdate); preStm.setInt(1, port); preStm.setString(2, realm); preStm.setString(3, servers); preStm.executeUpdate(); } } catch (SQLException e) { throw new HasException("Failed to update KDC Config. ", e); } finally { DbUtils.closeQuietly(preStm); } } /** * Read in krb5-template.conf and substitute in the correct port. * * @return krb5 conf file * @throws HasException e */ public File generateKrb5Conf() throws HasException { Map<String, String> kdcConf = getKdcConf(); String[] servers = kdcConf.get("servers").split(","); int kdcPort = Integer.parseInt(kdcConf.get("_PORT_")); String kdcRealm = kdcConf.get("_REALM_"); StringBuilder kdcBuilder = new StringBuilder(); for (String server : servers) { String append = "\t\tkdc = " + server.trim() + ":" + kdcPort + "\n"; kdcBuilder.append(append); } String kdc = kdcBuilder.toString(); kdc = kdc.substring(0, kdc.length() - 1); String resourcePath = "/krb5.conf.template"; String content; try (InputStream templateResource = getClass().getResourceAsStream(resourcePath)) { content = IOUtil.readInput(templateResource); } catch (IOException e) { throw new HasException("Read template resource failed. " + e.getMessage()); } content = content.replaceAll("_REALM_", kdcRealm); content = content.replaceAll("_PORT_", String.valueOf(kdcPort)); content = content.replaceAll("_UDP_LIMIT_", "4096"); content = content.replaceAll("_KDCS_", kdc); File confFile = new File(confDir, "krb5.conf"); if (confFile.exists()) { boolean delete = confFile.delete(); if (!delete) { throw new HasException("File delete error!"); } } try { IOUtil.writeFile(content, confFile); } catch (IOException e) { throw new HasException("Write content to conf file failed. " + e.getMessage()); } return confFile; } /** * Read in has-server.conf and create has-client.conf. * * @return has conf file * @throws IOException e * @throws HasException e */ public File generateHasConf() throws HasException, IOException { Map<String, String> kdcConf = getKdcConf(); String servers = kdcConf.get("servers"); File confFile = new File(getConfDir().getAbsolutePath(), "has-server.conf"); HasConfig hasConfig = HasUtil.getHasConfig(confFile); if (hasConfig != null) { String defaultValue = hasConfig.getHttpsHost(); String content; try (InputStream templateResource = new FileInputStream(confFile)) { content = IOUtil.readInput(templateResource); } content = content.replaceFirst(Pattern.quote(defaultValue), servers); File hasFile = new File(confDir, "has-client.conf"); IOUtil.writeFile(content, hasFile); return hasFile; } else { throw new HasException("has-server.conf not found. "); } } public void stopKdcServer() { try { kdcServer.stop(); } catch (KrbException e) { LOG.error("Fail to stop has kdc server"); } } public void startWebServer() throws HasException { if (webServer == null) { HasConfig conf = new HasConfig(); // Parse has-server.conf to get http_host and http_port File confFile = new File(confDir, "has-server.conf"); hasConfig = HasUtil.getHasConfig(confFile); hasConfig.setConfDir(getConfDir().getAbsoluteFile()); try { String httpHost; String httpPort; String httpsHost; String httpsPort; if (hasConfig.getHttpHost() != null) { httpHost = hasConfig.getHttpHost(); } else { LOG.info("Cannot get the http_host from has-server.conf, using the default http host."); httpHost = WebConfigKey.HAS_HTTP_HOST_DEFAULT; } if (hasConfig.getHttpPort() != null) { httpPort = hasConfig.getHttpPort(); } else { LOG.info("Cannot get the http_port from has-server.conf, using the default http port."); httpPort = String.valueOf(WebConfigKey.HAS_HTTP_PORT_DEFAULT); } if (hasConfig.getHttpsHost() != null) { httpsHost = hasConfig.getHttpsHost(); } else { LOG.info("Cannot get the https_host from has-server.conf, using the default https host."); httpsHost = WebConfigKey.HAS_HTTPS_HOST_DEFAULT; } if (hasConfig.getHttpsPort() != null) { httpsPort = hasConfig.getHttpsPort(); } else { LOG.info("Cannot get the https_port from has-server.conf , using the default https port."); httpsPort = String.valueOf(WebConfigKey.HAS_HTTPS_PORT_DEFAULT); } String hasHttpAddress = httpHost + ":" + httpPort; String hasHttpsAddress = httpsHost + ":" + httpsPort; LOG.info("The web server http address: " + hasHttpAddress); LOG.info("The web server https address: " + hasHttpsAddress); conf.setString(WebConfigKey.HAS_HTTP_ADDRESS_KEY, hasHttpAddress); conf.setString(WebConfigKey.HAS_HTTPS_ADDRESS_KEY, hasHttpsAddress); conf.setString(WebConfigKey.HAS_HTTP_POLICY_KEY, HttpConfig.Policy.HTTP_AND_HTTPS.name()); conf.setString(WebConfigKey.HAS_SERVER_HTTPS_KEYSTORE_RESOURCE_KEY, hasConfig.getSslServerConf()); webServer = new WebServer(conf); } catch (NumberFormatException e) { throw new IllegalArgumentException("https_port should be a number. " + e.getMessage()); } } else { hasConfig = webServer.getConf(); } webServer.start(); webServer.defineConfFilter(); try { HasUtil.setEnableConf(new File(confDir, "has-server.conf"), "true"); } catch (IOException e) { throw new HasException("Errors occurred when enable conf. " + e.getMessage()); } webServer.setWebServerAttribute(this); } public void stopWebServer() { if (webServer != null) { try { webServer.stop(); } catch (Exception e) { LOG.error("Failed to stop http server. " + e.getMessage()); } } } public static void main(String[] args) { if (args[0].equals("-start")) { String confDirPath = args[1]; String workDirPath = args[2]; File confDir = new File(confDirPath); if (!confDir.exists()) { System.err.println("The conf-dir is invalid or does not exist"); System.exit(3); } File workDir = new File(workDirPath); if (!workDir.exists()) { System.err.println("The work-dir is invalid or does not exist"); System.exit(3); } try { server = new HasServer(confDir); } catch (KrbException e) { LOG.error("Errors occurred when create kdc server: " + e.getMessage()); System.exit(4); } server.setConfDir(confDir); server.setWorkDir(workDir); //Only start the webserver, the kdcserver could be started after setting the realm try { server.startWebServer(); } catch (HasException e) { LOG.error("Errors occurred when start has http server: " + e.getMessage()); System.exit(6); } if (server.getWebServer().getHttpAddress() != null) { LOG.info("HAS http server started."); LOG.info("host: " + server.getWebServer().getHttpAddress().getHostName()); LOG.info("port: " + server.getWebServer().getHttpAddress().getPort()); } if (server.getWebServer().getHttpsAddress() != null) { LOG.info("HAS https server started."); LOG.info("host: " + server.getWebServer().getHttpsAddress().getHostName()); LOG.info("port: " + server.getWebServer().getHttpsAddress().getPort()); } } else if (args[0].equals("-stop")) { if (server != null) { server.stopWebServer(); server.stopKdcServer(); } } else { System.exit(2); } } }
package net.querz.nbt.io; import net.querz.io.ExceptionBiFunction; import net.querz.io.MaxDepthIO; import net.querz.nbt.tag.ByteArrayTag; import net.querz.nbt.tag.ByteTag; import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.DoubleTag; import net.querz.nbt.tag.EndTag; import net.querz.nbt.tag.FloatTag; import net.querz.nbt.tag.IntArrayTag; import net.querz.nbt.tag.IntTag; import net.querz.nbt.tag.ListTag; import net.querz.nbt.tag.LongArrayTag; import net.querz.nbt.tag.LongTag; import net.querz.nbt.tag.ShortTag; import net.querz.nbt.tag.StringTag; import net.querz.nbt.tag.Tag; import java.io.Closeable; import java.io.DataInput; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class LittleEndianNBTInputStream implements DataInput, NBTInput, MaxDepthIO, Closeable { private final DataInputStream input; private static Map<Byte, ExceptionBiFunction<LittleEndianNBTInputStream, Integer, ? extends Tag<?>, IOException>> readers = new HashMap<>(); private static Map<Byte, Class<?>> idClassMapping = new HashMap<>(); static { put(EndTag.ID, (i, d) -> EndTag.INSTANCE, EndTag.class); put(ByteTag.ID, (i, d) -> readByte(i), ByteTag.class); put(ShortTag.ID, (i, d) -> readShort(i), ShortTag.class); put(IntTag.ID, (i, d) -> readInt(i), IntTag.class); put(LongTag.ID, (i, d) -> readLong(i), LongTag.class); put(FloatTag.ID, (i, d) -> readFloat(i), FloatTag.class); put(DoubleTag.ID, (i, d) -> readDouble(i), DoubleTag.class); put(ByteArrayTag.ID, (i, d) -> readByteArray(i), ByteArrayTag.class); put(StringTag.ID, (i, d) -> readString(i), StringTag.class); put(ListTag.ID, LittleEndianNBTInputStream::readListTag, ListTag.class); put(CompoundTag.ID, LittleEndianNBTInputStream::readCompound, CompoundTag.class); put(IntArrayTag.ID, (i, d) -> readIntArray(i), IntArrayTag.class); put(LongArrayTag.ID, (i, d) -> readLongArray(i), LongArrayTag.class); } private static void put(byte id, ExceptionBiFunction<LittleEndianNBTInputStream, Integer, ? extends Tag<?>, IOException> reader, Class<?> clazz) { readers.put(id, reader); idClassMapping.put(id, clazz); } public LittleEndianNBTInputStream(InputStream in) { input = new DataInputStream(in); } public LittleEndianNBTInputStream(DataInputStream in) { input = in; } public NamedTag readTag(int maxDepth) throws IOException { byte id = readByte(); return new NamedTag(readUTF(), readTag(id, maxDepth)); } public Tag<?> readRawTag(int maxDepth) throws IOException { byte id = readByte(); return readTag(id, maxDepth); } private Tag<?> readTag(byte type, int maxDepth) throws IOException { ExceptionBiFunction<LittleEndianNBTInputStream, Integer, ? extends Tag<?>, IOException> f; if ((f = readers.get(type)) == null) { throw new IOException("invalid tag id \"" + type + "\""); } return f.accept(this, maxDepth); } private static ByteTag readByte(LittleEndianNBTInputStream in) throws IOException { return new ByteTag(in.readByte()); } private static ShortTag readShort(LittleEndianNBTInputStream in) throws IOException { return new ShortTag(in.readShort()); } private static IntTag readInt(LittleEndianNBTInputStream in) throws IOException { return new IntTag(in.readInt()); } private static LongTag readLong(LittleEndianNBTInputStream in) throws IOException { return new LongTag(in.readLong()); } private static FloatTag readFloat(LittleEndianNBTInputStream in) throws IOException { return new FloatTag(in.readFloat()); } private static DoubleTag readDouble(LittleEndianNBTInputStream in) throws IOException { return new DoubleTag(in.readDouble()); } private static StringTag readString(LittleEndianNBTInputStream in) throws IOException { return new StringTag(in.readUTF()); } private static ByteArrayTag readByteArray(LittleEndianNBTInputStream in) throws IOException { ByteArrayTag bat = new ByteArrayTag(new byte[in.readInt()]); in.readFully(bat.getValue()); return bat; } private static IntArrayTag readIntArray(LittleEndianNBTInputStream in) throws IOException { int l = in.readInt(); int[] data = new int[l]; IntArrayTag iat = new IntArrayTag(data); for (int i = 0; i < l; i++) { data[i] = in.readInt(); } return iat; } private static LongArrayTag readLongArray(LittleEndianNBTInputStream in) throws IOException { int l = in.readInt(); long[] data = new long[l]; LongArrayTag iat = new LongArrayTag(data); for (int i = 0; i < l; i++) { data[i] = in.readLong(); } return iat; } private static ListTag<?> readListTag(LittleEndianNBTInputStream in, int maxDepth) throws IOException { byte listType = in.readByte(); ListTag<?> list = ListTag.createUnchecked(idClassMapping.get(listType)); int length = in.readInt(); if (length < 0) { length = 0; } for (int i = 0; i < length; i++) { list.addUnchecked(in.readTag(listType, in.decrementMaxDepth(maxDepth))); } return list; } private static CompoundTag readCompound(LittleEndianNBTInputStream in, int maxDepth) throws IOException { CompoundTag comp = new CompoundTag(); for (int id = in.readByte() & 0xFF; id != 0; id = in.readByte() & 0xFF) { String key = in.readUTF(); Tag<?> element = in.readTag((byte) id, in.decrementMaxDepth(maxDepth)); comp.put(key, element); } return comp; } @Override public void readFully(byte[] b) throws IOException { input.readFully(b); } @Override public void readFully(byte[] b, int off, int len) throws IOException { input.readFully(b, off, len); } @Override public int skipBytes(int n) throws IOException { return input.skipBytes(n); } @Override public boolean readBoolean() throws IOException { return input.readBoolean(); } @Override public byte readByte() throws IOException { return input.readByte(); } @Override public int readUnsignedByte() throws IOException { return input.readUnsignedByte(); } @Override public short readShort() throws IOException { return Short.reverseBytes(input.readShort()); } public int readUnsignedShort() throws IOException { return Short.toUnsignedInt(Short.reverseBytes(input.readShort())); } @Override public char readChar() throws IOException { return Character.reverseBytes(input.readChar()); } @Override public int readInt() throws IOException { return Integer.reverseBytes(input.readInt()); } @Override public long readLong() throws IOException { return Long.reverseBytes(input.readLong()); } @Override public float readFloat() throws IOException { return Float.intBitsToFloat(Integer.reverseBytes(input.readInt())); } @Override public double readDouble() throws IOException { return Double.longBitsToDouble(Long.reverseBytes(input.readLong())); } @Override @Deprecated public String readLine() throws IOException { return input.readLine(); } @Override public void close() throws IOException { input.close(); } @Override public String readUTF() throws IOException { byte[] bytes = new byte[readUnsignedShort()]; readFully(bytes); return new String(bytes, StandardCharsets.UTF_8); } }
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.io; import java.io.IOException; /* ------------------------------------------------------------ */ /** ByteArrayEndPoint. * * */ public class ByteArrayEndPoint implements ConnectedEndPoint { protected byte[] _inBytes; protected ByteArrayBuffer _in; protected ByteArrayBuffer _out; protected boolean _closed; protected boolean _nonBlocking; protected boolean _growOutput; protected Connection _connection; protected int _maxIdleTime; /* ------------------------------------------------------------ */ /** * */ public ByteArrayEndPoint() { } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.io.ConnectedEndPoint#getConnection() */ public Connection getConnection() { return _connection; } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.io.ConnectedEndPoint#setConnection(org.eclipse.jetty.io.Connection) */ public void setConnection(Connection connection) { _connection=connection; } /* ------------------------------------------------------------ */ /** * @return the nonBlocking */ public boolean isNonBlocking() { return _nonBlocking; } /* ------------------------------------------------------------ */ /** * @param nonBlocking the nonBlocking to set */ public void setNonBlocking(boolean nonBlocking) { _nonBlocking=nonBlocking; } /* ------------------------------------------------------------ */ /** * */ public ByteArrayEndPoint(byte[] input, int outputSize) { _inBytes=input; _in=new ByteArrayBuffer(input); _out=new ByteArrayBuffer(outputSize); } /* ------------------------------------------------------------ */ /** * @return Returns the in. */ public ByteArrayBuffer getIn() { return _in; } /* ------------------------------------------------------------ */ /** * @param in The in to set. */ public void setIn(ByteArrayBuffer in) { _in = in; } /* ------------------------------------------------------------ */ /** * @return Returns the out. */ public ByteArrayBuffer getOut() { return _out; } /* ------------------------------------------------------------ */ /** * @param out The out to set. */ public void setOut(ByteArrayBuffer out) { _out = out; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#isOpen() */ public boolean isOpen() { return !_closed; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.io.EndPoint#isInputShutdown() */ public boolean isInputShutdown() { return _closed; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.io.EndPoint#isOutputShutdown() */ public boolean isOutputShutdown() { return _closed; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#isBlocking() */ public boolean isBlocking() { return !_nonBlocking; } /* ------------------------------------------------------------ */ public boolean blockReadable(long millisecs) { return true; } /* ------------------------------------------------------------ */ public boolean blockWritable(long millisecs) { return true; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#shutdownOutput() */ public void shutdownOutput() throws IOException { close(); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#shutdownInput() */ public void shutdownInput() throws IOException { close(); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#close() */ public void close() throws IOException { _closed=true; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#fill(org.eclipse.io.Buffer) */ public int fill(Buffer buffer) throws IOException { if (_closed) throw new IOException("CLOSED"); if (_in!=null && _in.length()>0) { int len = buffer.put(_in); _in.skip(len); return len; } if (_in!=null && _in.length()==0 && _nonBlocking) return 0; close(); return -1; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer) */ public int flush(Buffer buffer) throws IOException { if (_closed) throw new IOException("CLOSED"); if (_growOutput && buffer.length()>_out.space()) { _out.compact(); if (buffer.length()>_out.space()) { ByteArrayBuffer n = new ByteArrayBuffer(_out.putIndex()+buffer.length()); n.put(_out.peek(0,_out.putIndex())); if (_out.getIndex()>0) { n.mark(); n.setGetIndex(_out.getIndex()); } _out=n; } } int len = _out.put(buffer); if (!buffer.isImmutable()) buffer.skip(len); return len; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#flush(org.eclipse.io.Buffer, org.eclipse.io.Buffer, org.eclipse.io.Buffer) */ public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException { if (_closed) throw new IOException("CLOSED"); int flushed=0; if (header!=null && header.length()>0) flushed=flush(header); if (header==null || header.length()==0) { if (buffer!=null && buffer.length()>0) flushed+=flush(buffer); if (buffer==null || buffer.length()==0) { if (trailer!=null && trailer.length()>0) { flushed+=flush(trailer); } } } return flushed; } /* ------------------------------------------------------------ */ /** * */ public void reset() { _closed=false; _in.clear(); _out.clear(); if (_inBytes!=null) _in.setPutIndex(_inBytes.length); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getLocalAddr() */ public String getLocalAddr() { return null; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getLocalHost() */ public String getLocalHost() { return null; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getLocalPort() */ public int getLocalPort() { return 0; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getRemoteAddr() */ public String getRemoteAddr() { return null; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getRemoteHost() */ public String getRemoteHost() { return null; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getRemotePort() */ public int getRemotePort() { return 0; } /* ------------------------------------------------------------ */ /* * @see org.eclipse.io.EndPoint#getConnection() */ public Object getTransport() { return _inBytes; } /* ------------------------------------------------------------ */ public void flush() throws IOException { } /* ------------------------------------------------------------ */ /** * @return the growOutput */ public boolean isGrowOutput() { return _growOutput; } /* ------------------------------------------------------------ */ /** * @param growOutput the growOutput to set */ public void setGrowOutput(boolean growOutput) { _growOutput=growOutput; } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.io.EndPoint#getMaxIdleTime() */ public int getMaxIdleTime() { return _maxIdleTime; } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.io.EndPoint#setMaxIdleTime(int) */ public void setMaxIdleTime(int timeMs) throws IOException { _maxIdleTime=timeMs; } }
/******************************************************************************* * Copyright 2019 Tremolo Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.tremolosecurity.proxy.auth; import static org.apache.directory.ldap.client.api.search.FilterBuilder.equal; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.joda.time.DateTime; import org.jose4j.jws.JsonWebSignature; import org.jose4j.lang.JoseException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.novell.ldap.LDAPAttribute; import com.novell.ldap.LDAPEntry; import com.novell.ldap.LDAPException; import com.novell.ldap.LDAPSearchResults; import com.tremolosecurity.config.util.ConfigManager; import com.tremolosecurity.config.util.UrlHolder; import com.tremolosecurity.config.xml.AuthChainType; import com.tremolosecurity.provisioning.util.HttpCon; import com.tremolosecurity.proxy.auth.AuthController; import com.tremolosecurity.proxy.auth.AuthInfo; import com.tremolosecurity.proxy.auth.RequestHolder; import com.tremolosecurity.proxy.auth.oauth2.OAuth2Bearer; import com.tremolosecurity.proxy.auth.util.AuthStep; import com.tremolosecurity.proxy.myvd.MyVDConnection; import com.tremolosecurity.proxy.util.ProxyConstants; import com.tremolosecurity.saml.Attribute; import com.tremolosecurity.server.GlobalEntries; import com.tremolosecurity.unison.openshiftv3.OpenShiftTarget; public class OAuth2K8sServiceAccount extends OAuth2Bearer { static org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(OAuth2K8sServiceAccount.class.getName()); @Override public void processToken(HttpServletRequest request, HttpServletResponse response, AuthStep as, HttpSession session, HashMap<String, Attribute> authParams, AuthChainType act, String realmName, String scope, ConfigManager cfg, String lmToken) throws ServletException, IOException { String k8sTarget = authParams.get("k8sTarget").getValues().get(0); boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0)); String noMatchOU = authParams.get("noMatchOU").getValues().get(0); String uidAttr = authParams.get("uidAttr").getValues().get(0); String lookupFilter = authParams.get("lookupFilter").getValues().get(0); String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0); UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); JSONObject root = new JSONObject(); root.put("kind", "TokenReview"); root.put("apiVersion","authentication.k8s.io/v1"); root.put("spec", new JSONObject()); ((JSONObject) root.get("spec")).put("token", lmToken); String json = root.toJSONString(); OpenShiftTarget target = null; HttpCon con = null; try { target = (OpenShiftTarget) cfg.getProvisioningEngine().getTarget(k8sTarget).getProvider(); con = target.createClient(); String respJSON = target.callWSPost(target.getAuthToken(), con, "/apis/authentication.k8s.io/v1/tokenreviews", json); if (logger.isDebugEnabled()) { logger.debug("JSON - " + respJSON); } JSONParser parser = new JSONParser(); JSONObject resp = (JSONObject) parser.parse(respJSON); JSONObject status = (JSONObject) resp.get("status"); if (status.get("error") != null) { logger.error("Could not validate token : " + status.get("error")); as.setExecuted(true); as.setSuccess(false); cfg.getAuthManager().nextAuth(request, response,request.getSession(),false); super.sendFail(response, realmName, scope, null, null); return; } else { Boolean authenticated = (Boolean) status.get("authenticated"); if (authenticated != null && authenticated) { JSONObject user = (JSONObject) status.get("user"); if (! linkToDirectory) { loadUnlinkedUser(session, noMatchOU, uidAttr, act, user,defaultObjectClass); as.setSuccess(true); } else { lookupUser(as, session, cfg.getMyVD(), noMatchOU, uidAttr, lookupFilter, act, user,defaultObjectClass); } String redirectToURL = request.getParameter("target"); if (redirectToURL != null && ! redirectToURL.isEmpty()) { reqHolder.setURL(redirectToURL); } as.setExecuted(true); as.setSuccess(true); cfg.getAuthManager().nextAuth(request, response,request.getSession(),false); } else { as.setExecuted(true); as.setSuccess(false); cfg.getAuthManager().nextAuth(request, response,request.getSession(),false); super.sendFail(response, realmName, scope, null, null); return; } } } catch (Exception e) { throw new ServletException("Could not validate token",e); } finally { con.getHttp().close(); con.getBcm().close(); } } public static void lookupUser(AuthStep as, HttpSession session, MyVDConnection myvd, String noMatchOU, String uidAttr, String lookupFilter, AuthChainType act, Map jwtNVP,String defaultObjectClass) { boolean uidIsFilter = ! lookupFilter.isEmpty(); String filter = ""; if (uidIsFilter) { StringBuffer b = new StringBuffer(); int lastIndex = 0; int index = lookupFilter.indexOf('$'); while (index >= 0) { b.append(lookupFilter.substring(lastIndex,index)); lastIndex = lookupFilter.indexOf('}',index) + 1; String reqName = lookupFilter.substring(index + 2,lastIndex - 1); b.append(jwtNVP.get(reqName).toString()); index = lookupFilter.indexOf('$',index+1); } b.append(lookupFilter.substring(lastIndex)); filter = b.toString(); if (logger.isDebugEnabled()) { logger.debug("Filter : '" + filter + "'"); } } else { StringBuffer b = new StringBuffer(); String userParam = (String) jwtNVP.get(uidAttr); b.append('(').append(uidAttr).append('=').append(userParam).append(')'); if (userParam == null) { filter = "(!(objectClass=*))"; } else { filter = equal(uidAttr,userParam).toString(); } } try { String root = act.getRoot(); if (root == null || root.trim().isEmpty()) { root = GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(); } LDAPSearchResults res = myvd.search(root, 2, filter, new ArrayList<String>()); if (res.hasMore()) { LDAPEntry entry = res.next(); Iterator<LDAPAttribute> it = entry.getAttributeSet().iterator(); AuthInfo authInfo = new AuthInfo(entry.getDN(),(String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME),act.getName(),act.getLevel()); ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo); while (it.hasNext()) { LDAPAttribute attrib = it.next(); Attribute attr = new Attribute(attrib.getName()); String[] vals = attrib.getStringValueArray(); for (int i=0;i<vals.length;i++) { attr.getValues().add(vals[i]); } authInfo.getAttribs().put(attr.getName(), attr); } for (Object o : jwtNVP.keySet()) { String s = (String) o; Object v = jwtNVP.get(s); Attribute attr = authInfo.getAttribs().get(s); if (attr == null) { attr = new Attribute(s); authInfo.getAttribs().put(attr.getName(), attr); } if (v instanceof String) { String val = (String) v; if (! attr.getValues().contains(val)) { attr.getValues().add(val); } } else if (v instanceof Object[]) { for (Object vo : ((Object[])v)) { String vv = (String) vo; if (vv != null && ! attr.getValues().contains(vv)) { attr.getValues().add(vv); } } } } as.setSuccess(true); } else { loadUnlinkedUser(session, noMatchOU, uidAttr, act, jwtNVP,defaultObjectClass); as.setSuccess(true); } } catch (LDAPException e) { if (e.getResultCode() != LDAPException.INVALID_CREDENTIALS) { logger.error("Could not authenticate user",e); } as.setSuccess(false); } } public static void loadUnlinkedUser(HttpSession session, String noMatchOU, String uidAttr, AuthChainType act, Map jwtNVP,String defaultObjectClass) { String uid = (String) jwtNVP.get(uidAttr); StringBuffer dn = new StringBuffer(); dn.append(uidAttr).append('=').append(uid).append(",ou=").append(noMatchOU).append(",").append(GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot()); AuthInfo authInfo = new AuthInfo(dn.toString(),(String) session.getAttribute(ProxyConstants.AUTH_MECH_NAME),act.getName(),act.getLevel()); ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).setAuthInfo(authInfo); for (Object o : jwtNVP.keySet()) { String s = (String) o; Attribute attr; Object oAttr = jwtNVP.get(s); if (logger.isDebugEnabled()) { logger.debug(s + " type - '" + oAttr.getClass().getName() + "'"); } if (oAttr instanceof JSONArray) { attr = new Attribute(s); for (Object ox : ((JSONArray) oAttr)) { attr.getValues().add((String) ox); } } else { attr = new Attribute(s,oAttr.toString()); } authInfo.getAttribs().put(attr.getName(), attr); } authInfo.getAttribs().put("sub", new Attribute("sub",uid)); authInfo.getAttribs().put("objectClass", new Attribute("objectClass",defaultObjectClass)); } }