answer
stringlengths
17
10.2M
package mondrian.rolap; import mondrian.olap.*; import mondrian.olap.Level; import mondrian.rolap.RolapConnection.NonEmptyResult; import mondrian.rolap.RolapNative.*; import mondrian.rolap.cache.HardSmartCache; import mondrian.rolap.sql.MemberChildrenConstraint; import mondrian.rolap.sql.TupleConstraint; import mondrian.spi.Dialect; import mondrian.spi.Dialect.DatabaseProduct; import mondrian.test.SqlPattern; import mondrian.test.TestContext; import mondrian.util.Bug; import mondrian.util.Pair; import junit.framework.Assert; import org.apache.log4j.*; import org.apache.log4j.spi.LoggingEvent; import org.eigenbase.util.property.BooleanProperty; import org.eigenbase.util.property.StringProperty; import java.util.ArrayList; import java.util.List; /** * Tests for NON EMPTY Optimization, includes SqlConstraint type hierarchy and * RolapNative classes. * * @author av * @since Nov 21, 2005 */ public class NonEmptyTest extends BatchTestCase { private static Logger logger = Logger.getLogger(NonEmptyTest.class); SqlConstraintFactory scf = SqlConstraintFactory.instance(); TestContext localTestContext; private static final String STORE_TYPE_LEVEL = TestContext.levelName("Store Type", "Store Type", "Store Type"); private static final String EDUCATION_LEVEL_LEVEL = TestContext.levelName( "Education Level", "Education Level", "Education Level"); public NonEmptyTest() { super(); } public NonEmptyTest(String name) { super(name); } @Override protected void setUp() throws Exception { super.setUp(); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); propSaver.set( MondrianProperties.instance().EnableNativeNonEmpty, true); } @Override protected void tearDown() throws Exception { super.tearDown(); localTestContext = null; // allow gc } @Override public TestContext getTestContext() { return localTestContext != null ? localTestContext : super.getTestContext(); } public void setTestContext(TestContext testContext) { localTestContext = testContext; } public void testBugMondrian584EnumOrder() { // The interpreter results include males before females, which is // correct because it is consistent with the explicit order present // in the query. Native evaluation returns the females before males, // which is probably a reflection of the database ordering. if (Bug.BugMondrian584Fixed) { checkNative( 4, 4, "SELECT non empty { CrossJoin( " + " {Gender.M, Gender.F}, " + " { [Marital Status].[Marital Status].members } " + ") } on 0 from sales"); } } public void testBugCantRestrictSlicerToCalcMember() throws Exception { TestContext ctx = getTestContext(); ctx.assertQueryReturns( "WITH Member [Time].[Time].[Aggr] AS 'Aggregate({[Time].[1998].[Q1], [Time].[1998].[Q2]})' " + "SELECT {[Measures].[Store Sales]} ON COLUMNS, " + "NON EMPTY Order(TopCount([Customers].[Name].Members,3,[Measures].[Store Sales]),[Measures].[Store Sales],BASC) ON ROWS " + "FROM [Sales] " + "WHERE ([Time].[Aggr])", "Axis + "{[Time].[Aggr]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis } /** * Test case for an issue where mondrian failed to use native evaluation * for evaluating crossjoin. With the issue, performance is poor because * mondrian is doing crossjoins in memory; and the test case throws because * the result limit is exceeded. */ public void testAnalyzerPerformanceIssue() { final MondrianProperties mondrianProperties = MondrianProperties.instance(); propSaver.set(mondrianProperties.EnableNativeCrossJoin, true); propSaver.set(mondrianProperties.EnableNativeTopCount, false); propSaver.set(mondrianProperties.EnableNativeFilter, true); propSaver.set(mondrianProperties.EnableNativeNonEmpty, false); propSaver.set(mondrianProperties.ResultLimit, 5000000); assertQueryReturns( "with set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Education Level], NonEmptyCrossJoin([*BASE_MEMBERS_Product], NonEmptyCrossJoin([*BASE_MEMBERS_Customers], [*BASE_MEMBERS_Time])))' " + "set [*METRIC_CJ_SET] as 'Filter([*NATIVE_CJ_SET], ([Measures].[*TOP_Unit Sales_SEL~SUM] <= 2.0))' " + "set [*SORTED_ROW_AXIS] as 'Order([*CJ_ROW_AXIS], [Product].CurrentMember.OrderKey, BASC, Ancestor([Product].CurrentMember, [Product].[Brand Name]).OrderKey, BASC, [Customers].CurrentMember.OrderKey, BASC, Ancestor([Customers].CurrentMember, [Customers].[City]).OrderKey, BASC)' " + "set [*SORTED_COL_AXIS] as 'Order([*CJ_COL_AXIS], [Education Level].CurrentMember.OrderKey, BASC)' " + "set [*BASE_MEMBERS_Time] as '{[Time].[1997].[Q1]}' " + "set [*NATIVE_MEMBERS_Customers] as 'Generate([*NATIVE_CJ_SET], {[Customers].CurrentMember})' " + "set [*TOP_SET] as 'Order(Generate([*NATIVE_CJ_SET], {[Product].CurrentMember}), ([Measures].[Unit Sales], [Customers].[*CTX_MEMBER_SEL~SUM], [Education Level].[*CTX_MEMBER_SEL~SUM], [Time].[*CTX_MEMBER_SEL~AGG]), BDESC)' " + "set [*BASE_MEMBERS_Education Level] as '[Education Level].[Education Level].Members' " + "set [*NATIVE_MEMBERS_Education Level] as 'Generate([*NATIVE_CJ_SET], {[Education Level].CurrentMember})' " + "set [*METRIC_MEMBERS_Time] as 'Generate([*METRIC_CJ_SET], {[Time].[Time].CurrentMember})' " + "set [*NATIVE_MEMBERS_Time] as 'Generate([*NATIVE_CJ_SET], {[Time].[Time].CurrentMember})' " + "set [*BASE_MEMBERS_Customers] as '[Customers].[Name].Members' " + "set [*BASE_MEMBERS_Product] as '[Product].[Product Name].Members' " + "set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}' " + "set [*CJ_COL_AXIS] as 'Generate([*METRIC_CJ_SET], {[Education Level].CurrentMember})' " + "set [*CJ_ROW_AXIS] as 'Generate([*METRIC_CJ_SET], {([Product].CurrentMember, [Customers].CurrentMember)})' " + "member [Customers].[*DEFAULT_MEMBER] as '[Customers].DefaultMember', SOLVE_ORDER = (- 500.0) " + "member [Product].[*TOTAL_MEMBER_SEL~SUM] as 'Sum(Generate([*METRIC_CJ_SET], {([Product].CurrentMember, [Customers].CurrentMember)}))', SOLVE_ORDER = (- 100.0) " + "member [Customers].[*TOTAL_MEMBER_SEL~SUM] as 'Sum(Generate(Exists([*METRIC_CJ_SET], {[Product].CurrentMember}), {([Product].CurrentMember, [Customers].CurrentMember)}))', SOLVE_ORDER = (- 101.0) " + "member [Measures].[*TOP_Unit Sales_SEL~SUM] as 'Rank([Product].CurrentMember, [*TOP_SET])', SOLVE_ORDER = 300.0 " + "member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = \"Standard\", SOLVE_ORDER = 400.0 " + "member [Customers].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Customers].[All Customers]})', SOLVE_ORDER = (- 101.0) " + "member [Education Level].[*TOTAL_MEMBER_SEL~SUM] as 'Sum(Generate([*METRIC_CJ_SET], {[Education Level].CurrentMember}))', SOLVE_ORDER = (- 102.0) " + "member [Education Level].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Education Level].[All Education Levels]})', SOLVE_ORDER = (- 102.0) " + "member [Time].[Time].[*CTX_MEMBER_SEL~AGG] as 'Aggregate([*NATIVE_MEMBERS_Time])', SOLVE_ORDER = (- 402.0) " + "member [Time].[Time].[*SLICER_MEMBER] as 'Aggregate([*METRIC_MEMBERS_Time])', SOLVE_ORDER = (- 400.0) " + "select Union(Crossjoin({[Education Level].[*TOTAL_MEMBER_SEL~SUM]}, [*BASE_MEMBERS_Measures]), Crossjoin([*SORTED_COL_AXIS], [*BASE_MEMBERS_Measures])) ON COLUMNS, " + "NON EMPTY Union(Crossjoin({[Product].[*TOTAL_MEMBER_SEL~SUM]}, {[Customers].[*DEFAULT_MEMBER]}), Union(Crossjoin(Generate([*METRIC_CJ_SET], {[Product].CurrentMember}), {[Customers].[*TOTAL_MEMBER_SEL~SUM]}), [*SORTED_ROW_AXIS])) ON ROWS " + "from [Sales] " + "where [Time].[*SLICER_MEMBER] ", "Axis + "{[Time].[*SLICER_MEMBER]}\n" + "Axis + "{[Education Level].[*TOTAL_MEMBER_SEL~SUM], [Measures].[*FORMATTED_MEASURE_0]}\n" + "{[Education Level].[Bachelors Degree], [Measures].[*FORMATTED_MEASURE_0]}\n" + "{[Education Level].[Graduate Degree], [Measures].[*FORMATTED_MEASURE_0]}\n" + "{[Education Level].[High School Degree], [Measures].[*FORMATTED_MEASURE_0]}\n" + "{[Education Level].[Partial College], [Measures].[*FORMATTED_MEASURE_0]}\n" + "{[Education Level].[Partial High School], [Measures].[*FORMATTED_MEASURE_0]}\n" + "Axis + "{[Product].[*TOTAL_MEMBER_SEL~SUM], [Customers].[*DEFAULT_MEMBER]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[*TOTAL_MEMBER_SEL~SUM]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[*TOTAL_MEMBER_SEL~SUM]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Puyallup].[Cheryl Herring]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[OR].[Salem].[Robert Ahlering]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Port Orchard].[Judy Zugelder]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Marysville].[Brian Johnston]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[OR].[Corvallis].[Judy Doolittle]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Spokane].[Greg Morgan]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[West Covina].[Sandra Young]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[Long Beach].[Dana Chappell]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[La Mesa].[Georgia Thompson]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Tacoma].[Jessica Dugan]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[OR].[Milwaukie].[Adrian Torrez]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Spokane].[Grace McLaughlin]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Bremerton].[Julia Stewart]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Port Orchard].[Maureen Overholser]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Yakima].[Mary Craig]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[Spring Valley].[Deborah Adams]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[Woodland Hills].[Warren Kaufman]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[OR].[Woodburn].[David Moss]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[Newport Beach].[Michael Sample]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[OR].[Portland].[Ofelia Trembath]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Bremerton].[Alexander Case]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Bremerton].[Gloria Duncan]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[WA].[Olympia].[Jeanette Foster]}\n" + "{[Product].[Food].[Baking Goods].[Baking Goods].[Spices].[BBB Best].[BBB Best Pepper], [Customers].[USA].[CA].[Lakewood].[Shyla Bettis]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[OR].[Portland].[Tomas Manzanares]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Bremerton].[Kerry Westgaard]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Yakima].[Beatrice Barney]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Seattle].[James La Monica]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Spokane].[Martha Griego]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Bremerton].[Michelle Neri]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Spokane].[Herman Webb]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Spokane].[Bob Alexander]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Issaquah].[Gery Scott]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Spokane].[Grace McLaughlin]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Kirkland].[Brandon Rohlke]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Port Orchard].[Elwood Carter]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[CA].[Beverly Hills].[Samuel Arden]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[OR].[Woodburn].[Ida Cezar]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Olympia].[Barbara Smith]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Spokane].[Matt Bellah]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Sedro Woolley].[William Akin]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[OR].[Albany].[Karie Taylor]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[OR].[Milwaukie].[Bertie Wherrett]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[CA].[Lincoln Acres].[L. Troy Barnes]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Tacoma].[Patricia Martin]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Bremerton].[Martha Clifton]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Garlic], [Customers].[USA].[WA].[Bremerton].[Marla Bell]}\n" + "Row #0: 170\n" + "Row #0: 45\n" + "Row #0: 7\n" + "Row #0: 47\n" + "Row #0: 16\n" + "Row #0: 55\n" + "Row #1: 87\n" + "Row #1: 25\n" + "Row #1: 5\n" + "Row #1: 21\n" + "Row #1: 8\n" + "Row #1: 28\n" + "Row #2: 83\n" + "Row #2: 20\n" + "Row #2: 2\n" + "Row #2: 26\n" + "Row #2: 8\n" + "Row #2: 27\n" + "Row #3: 4\n" + "Row #3: \n" + "Row #3: \n" + "Row #3: \n" + "Row #3: 4\n" + "Row #3: \n" + "Row #4: 4\n" + "Row #4: \n" + "Row #4: \n" + "Row #4: \n" + "Row #4: 4\n" + "Row #4: \n" + "Row #5: 3\n" + "Row #5: 3\n" + "Row #5: \n" + "Row #5: \n" + "Row #5: \n" + "Row #5: \n" + "Row #6: 4\n" + "Row #6: 4\n" + "Row #6: \n" + "Row #6: \n" + "Row #6: \n" + "Row #6: \n" + "Row #7: 4\n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #7: \n" + "Row #7: 4\n" + "Row #8: 4\n" + "Row #8: 4\n" + "Row #8: \n" + "Row #8: \n" + "Row #8: \n" + "Row #8: \n" + "Row #9: 3\n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #9: \n" + "Row #9: 3\n" + "Row #10: 2\n" + "Row #10: 2\n" + "Row #10: \n" + "Row #10: \n" + "Row #10: \n" + "Row #10: \n" + "Row #11: 3\n" + "Row #11: \n" + "Row #11: \n" + "Row #11: \n" + "Row #11: \n" + "Row #11: 3\n" + "Row #12: 3\n" + "Row #12: \n" + "Row #12: \n" + "Row #12: 3\n" + "Row #12: \n" + "Row #12: \n" + "Row #13: 4\n" + "Row #13: 4\n" + "Row #13: \n" + "Row #13: \n" + "Row #13: \n" + "Row #13: \n" + "Row #14: 4\n" + "Row #14: \n" + "Row #14: \n" + "Row #14: 4\n" + "Row #14: \n" + "Row #14: \n" + "Row #15: 3\n" + "Row #15: \n" + "Row #15: \n" + "Row #15: \n" + "Row #15: \n" + "Row #15: 3\n" + "Row #16: 4\n" + "Row #16: \n" + "Row #16: \n" + "Row #16: 4\n" + "Row #16: \n" + "Row #16: \n" + "Row #17: 5\n" + "Row #17: \n" + "Row #17: 5\n" + "Row #17: \n" + "Row #17: \n" + "Row #17: \n" + "Row #18: 4\n" + "Row #18: \n" + "Row #18: \n" + "Row #18: \n" + "Row #18: \n" + "Row #18: 4\n" + "Row #19: 3\n" + "Row #19: \n" + "Row #19: \n" + "Row #19: 3\n" + "Row #19: \n" + "Row #19: \n" + "Row #20: 3\n" + "Row #20: \n" + "Row #20: \n" + "Row #20: 3\n" + "Row #20: \n" + "Row #20: \n" + "Row #21: 4\n" + "Row #21: \n" + "Row #21: \n" + "Row #21: 4\n" + "Row #21: \n" + "Row #21: \n" + "Row #22: 4\n" + "Row #22: 4\n" + "Row #22: \n" + "Row #22: \n" + "Row #22: \n" + "Row #22: \n" + "Row #23: 4\n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: \n" + "Row #23: 4\n" + "Row #24: 4\n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: \n" + "Row #24: 4\n" + "Row #25: 3\n" + "Row #25: \n" + "Row #25: \n" + "Row #25: \n" + "Row #25: \n" + "Row #25: 3\n" + "Row #26: 4\n" + "Row #26: 4\n" + "Row #26: \n" + "Row #26: \n" + "Row #26: \n" + "Row #26: \n" + "Row #27: 4\n" + "Row #27: 4\n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #27: \n" + "Row #28: 4\n" + "Row #28: 4\n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #28: \n" + "Row #29: 3\n" + "Row #29: \n" + "Row #29: \n" + "Row #29: 3\n" + "Row #29: \n" + "Row #29: \n" + "Row #30: 2\n" + "Row #30: \n" + "Row #30: \n" + "Row #30: \n" + "Row #30: \n" + "Row #30: 2\n" + "Row #31: 4\n" + "Row #31: \n" + "Row #31: \n" + "Row #31: \n" + "Row #31: 4\n" + "Row #31: \n" + "Row #32: 5\n" + "Row #32: \n" + "Row #32: \n" + "Row #32: 5\n" + "Row #32: \n" + "Row #32: \n" + "Row #33: 3\n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #33: \n" + "Row #33: 3\n" + "Row #34: 4\n" + "Row #34: 4\n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #34: \n" + "Row #35: 3\n" + "Row #35: 3\n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #35: \n" + "Row #36: 4\n" + "Row #36: \n" + "Row #36: \n" + "Row #36: 4\n" + "Row #36: \n" + "Row #36: \n" + "Row #37: 4\n" + "Row #37: \n" + "Row #37: \n" + "Row #37: 4\n" + "Row #37: \n" + "Row #37: \n" + "Row #38: 3\n" + "Row #38: \n" + "Row #38: \n" + "Row #38: 3\n" + "Row #38: \n" + "Row #38: \n" + "Row #39: 3\n" + "Row #39: 3\n" + "Row #39: \n" + "Row #39: \n" + "Row #39: \n" + "Row #39: \n" + "Row #40: 2\n" + "Row #40: \n" + "Row #40: 2\n" + "Row #40: \n" + "Row #40: \n" + "Row #40: \n" + "Row #41: 4\n" + "Row #41: \n" + "Row #41: \n" + "Row #41: \n" + "Row #41: 4\n" + "Row #41: \n" + "Row #42: 4\n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: \n" + "Row #42: 4\n" + "Row #43: 2\n" + "Row #43: 2\n" + "Row #43: \n" + "Row #43: \n" + "Row #43: \n" + "Row #43: \n" + "Row #44: 3\n" + "Row #44: \n" + "Row #44: \n" + "Row #44: 3\n" + "Row #44: \n" + "Row #44: \n" + "Row #45: 4\n" + "Row #45: \n" + "Row #45: \n" + "Row #45: 4\n" + "Row #45: \n" + "Row #45: \n" + "Row #46: 4\n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: \n" + "Row #46: 4\n" + "Row #47: 3\n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: \n" + "Row #47: 3\n" + "Row #48: 4\n" + "Row #48: \n" + "Row #48: \n" + "Row #48: \n" + "Row #48: \n" + "Row #48: 4\n" + "Row #49: 7\n" + "Row #49: \n" + "Row #49: \n" + "Row #49: \n" + "Row #49: \n" + "Row #49: 7\n"); } public void testBug1961163() throws Exception { assertQueryReturns( "with member [Measures].[AvgRevenue] as 'Avg([Store].[Store Name].Members, [Measures].[Store Sales])' " + "select NON EMPTY {[Measures].[Store Sales], [Measures].[AvgRevenue]} ON COLUMNS, " + "NON EMPTY Filter([Store].[Store Name].Members, ([Measures].[AvgRevenue] < [Measures].[Store Sales])) ON ROWS " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "{[Measures].[AvgRevenue]}\n" + "Axis + "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17]}\n" + "Row #0: 45,750.24\n" + "Row #0: 43,479.86\n" + "Row #1: 54,545.28\n" + "Row #1: 43,479.86\n" + "Row #2: 54,431.14\n" + "Row #2: 43,479.86\n" + "Row #3: 55,058.79\n" + "Row #3: 43,479.86\n" + "Row #4: 87,218.28\n" + "Row #4: 43,479.86\n" + "Row #5: 52,896.30\n" + "Row #5: 43,479.86\n" + "Row #6: 52,644.07\n" + "Row #6: 43,479.86\n" + "Row #7: 49,634.46\n" + "Row #7: 43,479.86\n" + "Row #8: 74,843.96\n" + "Row #8: 43,479.86\n"); } public void testTopCountWithCalcMemberInSlicer() { // Internal error: can not restrict SQL to calculated Members TestContext ctx = getTestContext(); ctx.assertQueryReturns( "with member [Time].[Time].[First Term] as 'Aggregate({[Time].[1997].[Q1], [Time].[1997].[Q2]})' " + "select {[Measures].[Unit Sales]} ON COLUMNS, " + "TopCount([Product].[Product Subcategory].Members, 3, [Measures].[Unit Sales]) ON ROWS " + "from [Sales] " + "where ([Time].[First Term]) ", "Axis + "{[Time].[First Term]}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n" + "{[Product].[Food].[Produce].[Fruit].[Fresh Fruit]}\n" + "{[Product].[Food].[Canned Foods].[Canned Soup].[Soup]}\n" + "Row #0: 10,215\n" + "Row #1: 5,711\n" + "Row #2: 3,926\n"); } public void testTopCountCacheKeyMustIncludeCount() { /** * When caching topcount results, the number of elements must * be part of the cache key */ TestContext ctx = getTestContext(); // fill cache ctx.assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "TopCount([Product].[Product Subcategory].Members, 2, [Measures].[Unit Sales]) ON ROWS " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n" + "{[Product].[Food].[Produce].[Fruit].[Fresh Fruit]}\n" + "Row #0: 20,739\n" + "Row #1: 11,767\n"); // run again with different count ctx.assertQueryReturns( "select {[Measures].[Unit Sales]} ON COLUMNS, " + "TopCount([Product].[Product Subcategory].Members, 3, [Measures].[Unit Sales]) ON ROWS " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables]}\n" + "{[Product].[Food].[Produce].[Fruit].[Fresh Fruit]}\n" + "{[Product].[Food].[Canned Foods].[Canned Soup].[Soup]}\n" + "Row #0: 20,739\n" + "Row #1: 11,767\n" + "Row #2: 8,006\n"); } public void testStrMeasure() { TestContext ctx = TestContext.instance().create( null, "<Cube name=\"StrMeasure\"> \n" + " <Table name=\"promotion\"/> \n" + " <Dimension name=\"Promotions\"> \n" + " <Hierarchy hasAll=\"true\" > \n" + " <Level name=\"Promotion Name\" column=\"promotion_name\" uniqueMembers=\"true\"/> \n" + " </Hierarchy> \n" + " </Dimension> \n" + " <Measure name=\"Media\" column=\"media_type\" aggregator=\"max\" datatype=\"String\"/> \n" + "</Cube> \n", null, null, null, null); ctx.assertQueryReturns( "select {[Measures].[Media]} on columns " + "from [StrMeasure]", "Axis + "{}\n" + "Axis + "{[Measures].[Media]}\n" + "Row #0: TV\n"); } public void testBug1515302() { TestContext ctx = TestContext.instance().create( null, "<Cube name=\"Bug1515302\"> \n" + " <Table name=\"sales_fact_1997\"/> \n" + " <Dimension name=\"Promotions\" foreignKey=\"promotion_id\"> \n" + " <Hierarchy hasAll=\"false\" primaryKey=\"promotion_id\"> \n" + " <Table name=\"promotion\"/> \n" + " <Level name=\"Promotion Name\" column=\"promotion_name\" uniqueMembers=\"true\"/> \n" + " </Hierarchy> \n" + " </Dimension> \n" + " <Dimension name=\"Customers\" foreignKey=\"customer_id\"> \n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Customers\" primaryKey=\"customer_id\"> \n" + " <Table name=\"customer\"/> \n" + " <Level name=\"Country\" column=\"country\" uniqueMembers=\"true\"/> \n" + " <Level name=\"State Province\" column=\"state_province\" uniqueMembers=\"true\"/> \n" + " <Level name=\"City\" column=\"city\" uniqueMembers=\"false\"/> \n" + " <Level name=\"Name\" column=\"customer_id\" type=\"Numeric\" uniqueMembers=\"true\"/> \n" + " </Hierarchy> \n" + " </Dimension> \n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"/> \n" + "</Cube> \n", null, null, null, null); ctx.assertQueryReturns( "select {[Measures].[Unit Sales]} on columns, " + "non empty crossjoin({[Promotions].[Big Promo]}, " + "Descendants([Customers].[USA], [City], " + "SELF_AND_BEFORE)) on rows " + "from [Bug1515302]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Promotions].[Big Promo], [Customers].[USA]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Anacortes]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Ballard]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Bellingham]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Burien]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Everett]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Issaquah]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Kirkland]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Lynnwood]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Marysville]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Olympia]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Puyallup]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Redmond]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Renton]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Seattle]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Sedro Woolley]}\n" + "{[Promotions].[Big Promo], [Customers].[USA].[WA].[Tacoma]}\n" + "Row #0: 1,789\n" + "Row #1: 1,789\n" + "Row #2: 20\n" + "Row #3: 35\n" + "Row #4: 15\n" + "Row #5: 18\n" + "Row #6: 60\n" + "Row #7: 42\n" + "Row #8: 36\n" + "Row #9: 79\n" + "Row #10: 58\n" + "Row #11: 520\n" + "Row #12: 438\n" + "Row #13: 14\n" + "Row #14: 20\n" + "Row #15: 65\n" + "Row #16: 3\n" + "Row #17: 366\n"); } /** * Must not use native sql optimization because it chooses the wrong * RolapStar in SqlContextConstraint/SqlConstraintUtils. Test ensures that * no exception is thrown. */ public void testVirtualCube() { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } TestCase c = new TestCase( 99, 3, "select NON EMPTY {[Measures].[Unit Sales], [Measures].[Warehouse Sales]} ON COLUMNS, " + "NON EMPTY [Product].[All Products].Children ON ROWS " + "from [Warehouse and Sales]"); c.run(); } public void testVirtualCubeMembers() throws Exception { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } // ok to use native sql optimization for members on a virtual cube TestCase c = new TestCase( 6, 3, "select NON EMPTY {[Measures].[Unit Sales], [Measures].[Warehouse Sales]} ON COLUMNS, " + "NON EMPTY {[Product].[Product Family].Members} ON ROWS " + "from [Warehouse and Sales]"); c.run(); } /** * verifies that redundant set braces do not prevent native evaluation * for example, {[Store].[Store Name].members} and * {{[Store Type].[Store Type].members}} */ public void testNativeCJWithRedundantSetBraces() { propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative( 0, 20, "select non empty {CrossJoin({[Store].[Store Name].members}, " + " {{" + STORE_TYPE_LEVEL + ".members}})}" + " on rows, " + "{[Measures].[Store Sqft]} on columns " + "from [Store]", null, requestFreshConnection); } /** * Verifies that CrossJoins with two non native inputs can be natively * evaluated. */ public void testExpandAllNonNativeInputs() { // This query will not run natively unless the <Dimension>.Children // expression is expanded to a member list. // Note: Both dimensions only have one hierarchy, which has the All // member. <Dimension>.Children is interpreted as the children of // the All member. propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative( 0, 2, "select " + "NonEmptyCrossJoin([Gender].Children, [Store].Children) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Gender].[F], [Store].[USA]}\n" + "{[Gender].[M], [Store].[USA]}\n" + "Row #0: 131,558\n" + "Row #0: 135,215\n", requestFreshConnection); } /** * Verifies that CrossJoins with one non native inputs can be natively * evaluated. */ public void testExpandOneNonNativeInput() { // This query will not be evaluated natively unless the Filter // expression is expanded to a member list. propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative( 0, 1, "With " + "Set [*Filtered_Set] as Filter([Product].[Product Name].Members, [Product].CurrentMember IS [Product].[Product Name].[Fast Raisins]) " + "Set [*NECJ_Set] as NonEmptyCrossJoin([Store].[Store Country].Members, [*Filtered_Set]) " + "select [*NECJ_Set] on columns " + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Store].[USA], [Product].[Food].[Snack Foods].[Snack Foods].[Dried Fruit].[Fast].[Fast Raisins]}\n" + "Row #0: 152\n", requestFreshConnection); } /** * Check that the ExpandNonNative does not create Joins with input lists * containing large number of members. */ public void testExpandNonNativeResourceLimitFailure() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); propSaver.set(MondrianProperties.instance().ResultLimit, 2); try { executeQuery( "select " + "NonEmptyCrossJoin({[Gender].Children, [Gender].[F]}, {[Store].Children, [Store].[Mexico]}) on columns " + "from [Sales]"); fail("Expected error did not occur"); } catch (Throwable e) { String expectedErrorMsg = "Mondrian Error:Size of CrossJoin result (3) exceeded limit (2)"; assertEquals(expectedErrorMsg, e.getMessage()); } } /** * Verify that the presence of All member in all the inputs disables native * evaluation, even when ExpandNonNative is true. */ public void testExpandAllMembersInAllInputs() { // This query will not be evaluated natively, even if the Hierarchize // expression is expanded to a member list. The reason is that the // expanded list contains ALL members. propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); checkNotNative( 1, "select NON EMPTY {[Time].[1997]} ON COLUMNS,\n" + " NON EMPTY Crossjoin(Hierarchize(Union({[Store].[All Stores]},\n" + " [Store].[USA].[CA].[San Francisco].[Store 14].Children)), {[Product].[All Products]}) \n" + " ON ROWS\n" + " from [Sales]\n" + " where [Measures].[Unit Sales]", "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Time].[1997]}\n" + "Axis + "{[Store].[All Stores], [Product].[All Products]}\n" + "Row #0: 266,773\n"); } /** * Verifies that the presence of calculated member in all the inputs * disables native evaluation, even when ExpandNonNative is true. */ public void testExpandCalcMembersInAllInputs() { // This query will not be evaluated natively, even if the Hierarchize // expression is expanded to a member list. The reason is that the // expanded list contains ALL members. propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); checkNotNative( 1, "With " + "Member [Product].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Product].[Product Family].Members})' " + "Member [Gender].[*CTX_MEMBER_SEL~SUM] as 'Sum({[Gender].[All Gender]})' " + "Select " + "NonEmptyCrossJoin({[Gender].[*CTX_MEMBER_SEL~SUM]},{[Product].[*CTX_MEMBER_SEL~SUM]}) " + "on columns " + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Gender].[*CTX_MEMBER_SEL~SUM], [Product].[*CTX_MEMBER_SEL~SUM]}\n" + "Row #0: 266,773\n"); } /** * Check that if both inputs to NECJ are either * AllMember(currentMember, defaultMember are also AllMember) * or Calcculated member * native CJ is not used. */ public void testExpandCalcMemberInputNECJ() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 1, "With \n" + "Member [Product].[All Products].[Food].[CalcSum] as \n" + "'Sum({[Product].[All Products].[Food]})', SOLVE_ORDER=-100\n" + "Select\n" + "{[Measures].[Store Cost]} on columns,\n" + "NonEmptyCrossJoin({[Product].[All Products].[Food].[CalcSum]},\n" + " {[Education Level].DefaultMember}) on rows\n" + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Store Cost]}\n" + "Axis + "{[Product].[Food].[CalcSum], [Education Level].[All Education Levels]}\n" + "Row #0: 163,270.72\n"); } /** * Native evaluation is no longer possible after the fix to * {@link #testCjEnumCalcMembersBug()} test. */ public void testExpandCalcMembers() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 9, "with " + "member [Store Type].[All Store Types].[S] as sum({[Store Type].[All Store Types]}) " + "set [Enum Store Types] as {" + " [Store Type].[All Store Types].[Small Grocery], " + " [Store Type].[All Store Types].[Supermarket], " + " [Store Type].[All Store Types].[HeadQuarters], " + " [Store Type].[All Store Types].[S]} " + "set [Filtered Enum Store Types] as Filter([Enum Store Types], [Measures].[Unit Sales] > 0)" + "select NonEmptyCrossJoin([Product].[All Products].Children, [Filtered Enum Store Types]) on columns from [Sales]", "Axis + "{}\n" + "Axis + "{[Product].[Drink], [Store Type].[Small Grocery]}\n" + "{[Product].[Drink], [Store Type].[Supermarket]}\n" + "{[Product].[Drink], [Store Type].[All Store Types].[S]}\n" + "{[Product].[Food], [Store Type].[Small Grocery]}\n" + "{[Product].[Food], [Store Type].[Supermarket]}\n" + "{[Product].[Food], [Store Type].[All Store Types].[S]}\n" + "{[Product].[Non-Consumable], [Store Type].[Small Grocery]}\n" + "{[Product].[Non-Consumable], [Store Type].[Supermarket]}\n" + "{[Product].[Non-Consumable], [Store Type].[All Store Types].[S]}\n" + "Row #0: 574\n" + "Row #0: 14,092\n" + "Row #0: 24,597\n" + "Row #0: 4,764\n" + "Row #0: 108,188\n" + "Row #0: 191,940\n" + "Row #0: 1,219\n" + "Row #0: 28,275\n" + "Row #0: 50,236\n"); } /** * Verify that evaluation is native for expressions with nested non native * inputs that preduce MemberList results. */ public void testExpandNestedNonNativeInputs() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative( 0, 6, "select " + "NonEmptyCrossJoin(" + " NonEmptyCrossJoin([Gender].Children, [Store].Children), " + " [Product].Children) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Gender].[F], [Store].[USA], [Product].[Drink]}\n" + "{[Gender].[F], [Store].[USA], [Product].[Food]}\n" + "{[Gender].[F], [Store].[USA], [Product].[Non-Consumable]}\n" + "{[Gender].[M], [Store].[USA], [Product].[Drink]}\n" + "{[Gender].[M], [Store].[USA], [Product].[Food]}\n" + "{[Gender].[M], [Store].[USA], [Product].[Non-Consumable]}\n" + "Row #0: 12,202\n" + "Row #0: 94,814\n" + "Row #0: 24,542\n" + "Row #0: 12,395\n" + "Row #0: 97,126\n" + "Row #0: 25,694\n", requestFreshConnection); } /** * Verify that a low value for maxConstraints disables native evaluation, * even when ExpandNonNative is true. */ public void testExpandLowMaxConstraints() { propSaver.set(MondrianProperties.instance().MaxConstraints, 2); propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 12, "select NonEmptyCrossJoin(" + " Filter([Store Type].Children, [Measures].[Unit Sales] > 10000), " + " [Product].Children) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Store Type].[Deluxe Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Deluxe Supermarket], [Product].[Food]}\n" + "{[Store Type].[Deluxe Supermarket], [Product].[Non-Consumable]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Food]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Non-Consumable]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Drink]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Food]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Non-Consumable]}\n" + "{[Store Type].[Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Supermarket], [Product].[Food]}\n" + "{[Store Type].[Supermarket], [Product].[Non-Consumable]}\n" + "Row #0: 6,827\n" + "Row #0: 55,358\n" + "Row #0: 14,652\n" + "Row #0: 1,945\n" + "Row #0: 15,438\n" + "Row #0: 3,950\n" + "Row #0: 1,159\n" + "Row #0: 8,192\n" + "Row #0: 2,140\n" + "Row #0: 14,092\n" + "Row #0: 108,188\n" + "Row #0: 28,275\n"); } /** * Verify that native evaluation is not enabled if expanded member list will * contain members from different levels, even if ExpandNonNative is set. */ public void testExpandDifferentLevels() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 278, "select NonEmptyCrossJoin(" + " Descendants([Customers].[All Customers].[USA].[WA].[Yakima]), " + " [Product].Children) on columns " + "from [Sales]", null); } /** * Verify that native evaluation is turned off for tuple inputs, even if * ExpandNonNative is set. */ public void testExpandTupleInputs1() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 1, "with " + "set [Tuple Set] as {([Store Type].[All Store Types].[HeadQuarters], [Product].[All Products].[Drink]), ([Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food])} " + "set [Filtered Tuple Set] as Filter([Tuple Set], 1=1) " + "set [NECJ] as NonEmptyCrossJoin([Store].Children, [Filtered Tuple Set]) " + "select [NECJ] on columns from [Sales]", "Axis + "{}\n" + "Axis + "{[Store].[USA], [Store Type].[Supermarket], [Product].[Food]}\n" + "Row #0: 108,188\n"); } /** * Verify that native evaluation is turned off for tuple inputs, even if * ExpandNonNative is set. */ public void testExpandTupleInputs2() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 1, "with " + "set [Tuple Set] as {([Store Type].[All Store Types].[HeadQuarters], [Product].[All Products].[Drink]), ([Store Type].[All Store Types].[Supermarket], [Product].[All Products].[Food])} " + "set [Filtered Tuple Set] as Filter([Tuple Set], 1=1) " + "set [NECJ] as NonEmptyCrossJoin([Filtered Tuple Set], [Store].Children) " + "select [NECJ] on columns from [Sales]", "Axis + "{}\n" + "Axis + "{[Store Type].[Supermarket], [Product].[Food], [Store].[USA]}\n" + "Row #0: 108,188\n"); } /** * Verify that native evaluation is on when ExpendNonNative is set, even if * the input list is empty. */ public void testExpandWithOneEmptyInput() { propSaver.set(MondrianProperties.instance().ExpandNonNative, true); boolean requestFreshConnection = true; // Query should return empty result. checkNative( 0, 0, "With " + "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Gender],[*BASE_MEMBERS_Product])' " + "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}' " + "Set [*BASE_MEMBERS_Gender] as 'Filter([Gender].[Gender].Members,[Gender].CurrentMember.Name Matches (\"abc\"))' " + "Set [*NATIVE_MEMBERS_Gender] as 'Generate([*NATIVE_CJ_SET], {[Gender].CurrentMember})' " + "Set [*BASE_MEMBERS_Product] as '[Product].[Product Name].Members' " + "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' " + "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,##0', SOLVE_ORDER=400 " + "Select " + "[*BASE_MEMBERS_Measures] on columns, " + "Non Empty Generate([*NATIVE_CJ_SET], {([Gender].CurrentMember,[Product].CurrentMember)}) on rows " + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[*FORMATTED_MEASURE_0]}\n" + "Axis requestFreshConnection); } public void testExpandWithTwoEmptyInputs() { getConnection().getCacheControl(null).flushSchemaCache(); propSaver.set(MondrianProperties.instance().ExpandNonNative, true); // Query should return empty result. checkNotNative( 0, "With " + "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Gender],[*BASE_MEMBERS_Product])' " + "Set [*BASE_MEMBERS_Measures] as '{[Measures].[*FORMATTED_MEASURE_0]}' " + "Set [*BASE_MEMBERS_Gender] as '{}' " + "Set [*NATIVE_MEMBERS_Gender] as 'Generate([*NATIVE_CJ_SET], {[Gender].CurrentMember})' " + "Set [*BASE_MEMBERS_Product] as '{}' " + "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' " + "Member [Measures].[*FORMATTED_MEASURE_0] as '[Measures].[Unit Sales]', FORMAT_STRING = '#,##0', SOLVE_ORDER=400 " + "Select " + "[*BASE_MEMBERS_Measures] on columns, " + "Non Empty Generate([*NATIVE_CJ_SET], {([Gender].CurrentMember,[Product].CurrentMember)}) on rows " + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[*FORMATTED_MEASURE_0]}\n" + "Axis } /** * Verify that native MemberLists inputs are subject to SQL constriant * limitation. If mondrian.rolap.maxConstraints is set too low, native * evaluations will be turned off. */ public void testEnumLowMaxConstraints() { propSaver.set(MondrianProperties.instance().MaxConstraints, 2); checkNotNative( 12, "with " + "set [All Store Types] as {" + "[Store Type].[Deluxe Supermarket], " + "[Store Type].[Gourmet Supermarket], " + "[Store Type].[Mid-Size Grocery], " + "[Store Type].[Small Grocery], " + "[Store Type].[Supermarket]} " + "set [All Products] as {" + "[Product].[Drink], " + "[Product].[Food], " + "[Product].[Non-Consumable]} " + "select " + "NonEmptyCrossJoin(" + "Filter([All Store Types], ([Measures].[Unit Sales] > 10000)), " + "[All Products]) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Store Type].[Deluxe Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Deluxe Supermarket], [Product].[Food]}\n" + "{[Store Type].[Deluxe Supermarket], [Product].[Non-Consumable]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Food]}\n" + "{[Store Type].[Gourmet Supermarket], [Product].[Non-Consumable]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Drink]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Food]}\n" + "{[Store Type].[Mid-Size Grocery], [Product].[Non-Consumable]}\n" + "{[Store Type].[Supermarket], [Product].[Drink]}\n" + "{[Store Type].[Supermarket], [Product].[Food]}\n" + "{[Store Type].[Supermarket], [Product].[Non-Consumable]}\n" + "Row #0: 6,827\n" + "Row #0: 55,358\n" + "Row #0: 14,652\n" + "Row #0: 1,945\n" + "Row #0: 15,438\n" + "Row #0: 3,950\n" + "Row #0: 1,159\n" + "Row #0: 8,192\n" + "Row #0: 2,140\n" + "Row #0: 14,092\n" + "Row #0: 108,188\n" + "Row #0: 28,275\n"); } /** * Verify that the presence of All member in all the inputs disables native * evaluation. */ public void testAllMembersNECJ1() { // This query cannot be evaluated natively because of the "All" member. propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); checkNotNative( 1, "select " + "NonEmptyCrossJoin({[Store].[All Stores]}, {[Product].[All Products]}) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Store].[All Stores], [Product].[All Products]}\n" + "Row #0: 266,773\n"); } /** * Verify that the native evaluation is possible if one input does not * contain the All member. */ public void testAllMembersNECJ2() { // This query can be evaluated natively because there is at least one // non "All" member. // It can also be rewritten to use // Filter([Product].Children, Is // NotEmpty([Measures].[Unit Sales])) // which can be natively evaluated propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative( 0, 3, "select " + "NonEmptyCrossJoin([Product].[All Products].Children, {[Store].[All Stores]}) on columns " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Product].[Drink], [Store].[All Stores]}\n" + "{[Product].[Food], [Store].[All Stores]}\n" + "{[Product].[Non-Consumable], [Store].[All Stores]}\n" + "Row #0: 24,597\n" + "Row #0: 191,940\n" + "Row #0: 50,236\n", requestFreshConnection); } /** * getMembersInLevel where Level = (All) */ public void testAllLevelMembers() { checkNative( 14, 14, "select {[Measures].[Store Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin([Product].[(All)].Members, [Promotion Media].[All Media].Children) ON ROWS " + "from [Sales]"); } /** * enum sets {} containing ALL */ public void testCjDescendantsEnumAllOnly() { checkNative( 9, 9, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin(" + " Descendants([Customers].[All Customers].[USA], [Customers].[City]), " + " {[Product].[All Products]}) ON ROWS " + "from [Sales] " + "where ([Promotions].[All Promotions].[Bag Stuffers])"); } /** * checks that crossjoin returns a modifiable copy from cache * because its modified during sort */ public void testResultIsModifyableCopy() { checkNative( 3, 3, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Order(" + " CrossJoin([Customers].[All Customers].[USA].children, [Promotions].[Promotion Name].Members), " + " [Measures].[Store Sales]) ON ROWS" + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } /** * Checks that TopCount is executed natively unless disabled. */ public void testNativeTopCount() { switch (getTestContext().getDialect().getDatabaseProduct()) { case INFOBRIGHT: // Hits same Infobright bug as NamedSetTest.testNamedSetOnMember. return; } String query = "select {[Measures].[Store Sales]} on columns," + " NON EMPTY TopCount(" + " CrossJoin([Customers].[All Customers].[USA].children, [Promotions].[Promotion Name].Members), " + " 3, (3 * [Measures].[Store Sales]) - 100) ON ROWS" + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"; propSaver.set(MondrianProperties.instance().EnableNativeTopCount, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative(3, 3, query, null, requestFreshConnection); } /** * Checks that TopCount is executed natively with calculated member. */ public void testCmNativeTopCount() { switch (getTestContext().getDialect().getDatabaseProduct()) { case INFOBRIGHT: // Hits same Infobright bug as NamedSetTest.testNamedSetOnMember. return; } String query = "with member [Measures].[Store Profit Rate] as '([Measures].[Store Sales]-[Measures].[Store Cost])/[Measures].[Store Cost]', format = ' + "select {[Measures].[Store Sales]} on columns," + " NON EMPTY TopCount(" + " [Customers].[All Customers].[USA].children, " + " 3, [Measures].[Store Profit Rate] / 2) ON ROWS" + " from [Sales]"; propSaver.set(MondrianProperties.instance().EnableNativeTopCount, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. boolean requestFreshConnection = true; checkNative(3, 3, query, null, requestFreshConnection); } public void testMeasureAndAggregateInSlicer() { assertQueryReturns( "with member [Store Type].[All Store Types].[All Types] as 'Aggregate({[Store Type].[All Store Types].[Deluxe Supermarket], " + "[Store Type].[All Store Types].[Gourmet Supermarket], " + "[Store Type].[All Store Types].[HeadQuarters], " + "[Store Type].[All Store Types].[Mid-Size Grocery], " + "[Store Type].[All Store Types].[Small Grocery], " + "[Store Type].[All Store Types].[Supermarket]})' " + "select NON EMPTY {[Time].[1997]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores].[USA].[CA].Children ON ROWS " + "from [Sales] " + "where ([Store Type].[All Store Types].[All Types], [Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink]) ", "Axis + "{[Store Type].[All Store Types].[All Types], [Measures].[Unit Sales], [Customers].[USA], [Product].[Drink]}\n" + "Axis + "{[Time].[1997]}\n" + "Axis + "{[Store].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[USA].[CA].[Los Angeles]}\n" + "{[Store].[USA].[CA].[San Diego]}\n" + "{[Store].[USA].[CA].[San Francisco]}\n" + "Row #0: 1,945\n" + "Row #1: 2,422\n" + "Row #2: 2,560\n" + "Row #3: 175\n"); } public void testMeasureInSlicer() { assertQueryReturns( "select NON EMPTY {[Time].[1997]} ON COLUMNS, " + "NON EMPTY [Store].[All Stores].[USA].[CA].Children ON ROWS " + "from [Sales] " + "where ([Measures].[Unit Sales], [Customers].[All Customers].[USA], [Product].[All Products].[Drink])", "Axis + "{[Measures].[Unit Sales], [Customers].[USA], [Product].[Drink]}\n" + "Axis + "{[Time].[1997]}\n" + "Axis + "{[Store].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[USA].[CA].[Los Angeles]}\n" + "{[Store].[USA].[CA].[San Diego]}\n" + "{[Store].[USA].[CA].[San Francisco]}\n" + "Row #0: 1,945\n" + "Row #1: 2,422\n" + "Row #2: 2,560\n" + "Row #3: 175\n"); } /** * Calc Member in TopCount: this topcount can not be calculated native * because its set contains calculated members. */ public void testCmInTopCount() { checkNotNative( 1, "with member [Time].[Time].[Jan] as " + "'Aggregate({[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]})' " + "select NON EMPTY {[Measures].[Unit Sales]} ON columns, " + "NON EMPTY TopCount({[Time].[Jan]}, 2) ON rows from [Sales] "); } /** * Calc member in slicer cannot be executed natively. */ public void testCmInSlicer() { checkNotNative( 3, "with member [Time].[Time].[Jan] as " + "'Aggregate({[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]})' " + "select NON EMPTY {[Measures].[Unit Sales]} ON columns, " + "NON EMPTY [Product].Children ON rows from [Sales] " + "where ([Time].[Jan]) "); } public void testCmInSlicerResults() { assertQueryReturns( "with member [Time].[Time].[Jan] as " + "'Aggregate({[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]})' " + "select NON EMPTY {[Measures].[Unit Sales]} ON columns, " + "NON EMPTY [Product].Children ON rows from [Sales] " + "where ([Time].[Jan]) ", "Axis + "{[Time].[Jan]}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Drink]}\n" + "{[Product].[Food]}\n" + "{[Product].[Non-Consumable]}\n" + "Row #0: 1,910\n" + "Row #1: 15,604\n" + "Row #2: 4,114\n"); } public void testSetInSlicerResults() { assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales]} ON columns, " + "NON EMPTY [Product].Children ON rows from [Sales] " + "where {[Time].[1998].[Q1].[1], [Time].[1997].[Q1].[1]} ", "Axis + "{[Time].[1998].[Q1].[1]}\n" + "{[Time].[1997].[Q1].[1]}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Drink]}\n" + "{[Product].[Food]}\n" + "{[Product].[Non-Consumable]}\n" + "Row #0: 1,910\n" + "Row #1: 15,604\n" + "Row #2: 4,114\n"); } public void testCjMembersMembersMembers() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersWithHideIfBlankLeafAndNoAll() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n" + " hideMemberIf=\"IfBlankName\"" + " />\n" + " </Hierarchy>\n" + "</Dimension>")); // No 'all' level, and ragged because [Product Name] is hidden if // blank. Native evaluation should be able to handle this query. checkNative( 9999, // Don't know why resultLimit needs to be so high. 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product Ragged].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersWithHideIfBlankLeaf() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n" + " hideMemberIf=\"IfBlankName\"" + " />\n" + " </Hierarchy>\n" + "</Dimension>")); // [Product Name] can be hidden if it is blank, but native evaluation // should be able to handle the query. checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product Ragged].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersWithHideIfParentsNameLeaf() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n" + " hideMemberIf=\"IfParentsName\"" + " />\n" + " </Hierarchy>\n" + "</Dimension>")); // [Product Name] can be hidden if it it matches its parent name, so // native evaluation can not handle this query. checkNotNative( 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product Ragged].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersWithHideIfBlankNameAncestor() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"" + " hideMemberIf=\"IfBlankName\"" + " />\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); // Since the parent of [Product Name] can be hidden, native evaluation // can't handle the query. checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product Ragged].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersWithHideIfParentsNameAncestor() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"" + " hideMemberIf=\"IfParentsName\"" + " />\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\"\n uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + "</Dimension>")); // Since the parent of [Product Name] can be hidden, native evaluation // can't handle the query. checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " [Product Ragged].[Product Name].Members), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjEnumWithHideIfBlankLeaf() { setTestContext(TestContext.instance().createSubstitutingCube( "Sales", "<Dimension name=\"Product Ragged\" foreignKey=\"product_id\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"product_id\">\n" + " <Table name=\"product\"/>\n" + " <Level name=\"Brand Name\" table=\"product\" column=\"brand_name\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Product Name\" table=\"product\" column=\"product_name\" uniqueMembers=\"true\"\n" + " hideMemberIf=\"IfBlankName\"" + " />\n" + " </Hierarchy>\n" + "</Dimension>")); // [Product Name] can be hidden if it is blank, but native evaluation // should be able to handle the query. // Note there's an existing bug with result ordering in native // non-empty evaluation of enumerations. This test intentionally // avoids this bug by explicitly lilsting [High Top Cauliflower] // before [Sphinx Bagels]. checkNative( 999, 7, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Crossjoin(" + " [Customers].[Name].Members," + " { [Product Ragged].[Kiwi].[Kiwi Scallops]," + " [Product Ragged].[Fast].[Fast Avocado Dip]," + " [Product Ragged].[High Top].[High Top Lemons]," + " [Product Ragged].[Moms].[Moms Sliced Turkey]," + " [Product Ragged].[High Top].[High Top Cauliflower]," + " [Product Ragged].[Sphinx].[Sphinx Bagels]" + " }), " + " [Promotions].[Promotion Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } /** * use SQL even when all members are known */ public void testCjEnumEnum() { // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } checkNative( 4, 4, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NonEmptyCrossjoin({[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}, {[Customers].[All Customers].[USA].[OR].[Portland], [Customers].[All Customers].[USA].[OR].[Salem]}) ON ROWS " + "from [Sales] "); } /** * Set containing only null member should not prevent usage of native. */ public void testCjNullInEnum() { propSaver.set( MondrianProperties.instance().IgnoreInvalidMembersDuringQuery, true); checkNative( 20, 0, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin({[Gender].[All Gender].[emale]}, [Customers].[All Customers].[USA].children) ON ROWS " + "from [Sales] "); } /** * enum sets {} containing members from different levels can not be computed * natively currently. */ public void testCjDescendantsEnumAll() { checkNotNative( 13, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin(" + " Descendants([Customers].[All Customers].[USA], [Customers].[City]), " + " {[Product].[All Products], [Product].[All Products].[Drink].[Dairy]}) ON ROWS " + "from [Sales] " + "where ([Promotions].[All Promotions].[Bag Stuffers])"); } public void testCjDescendantsEnum() { // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } checkNative( 11, 11, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin(" + " Descendants([Customers].[All Customers].[USA], [Customers].[City]), " + " {[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}) ON ROWS " + "from [Sales] " + "where ([Promotions].[All Promotions].[Bag Stuffers])"); } public void testCjEnumChildren() { // Make sure maxConstraint settting is high enough // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } checkNative( 3, 3, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin(" + " {[Product].[All Products].[Drink].[Beverages], [Product].[All Products].[Drink].[Dairy]}, " + " [Customers].[All Customers].[USA].[WA].Children) ON ROWS " + "from [Sales] " + "where ([Promotions].[All Promotions].[Bag Stuffers])"); } /** * {} contains members from different levels, this can not be handled by * the current native crossjoin. */ public void testCjEnumDifferentLevelsChildren() { // Don't run the test if we're testing expression dependencies. // Expression dependencies cause spurious interval calls to // 'level.getMembers()' which create false negatives in this test. if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } TestCase c = new TestCase( 8, 5, "select {[Measures].[Unit Sales]} ON COLUMNS, " + "NON EMPTY Crossjoin(" + " {[Product].[All Products].[Food], [Product].[All Products].[Drink].[Dairy]}, " + " [Customers].[All Customers].[USA].[WA].Children) ON ROWS " + "from [Sales] " + "where ([Promotions].[All Promotions].[Bag Stuffers])"); c.run(); } public void testCjDescendantsMembers() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name])," + " [Product].[Product Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersDescendants() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " [Product].[Product Name].Members," + " Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name])) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } // testcase for bug MONDRIAN-506 public void testCjMembersDescendantsWithNumericArgument() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin(" + " {[Product].[Product Name].Members}," + " {Descendants([Customers].[All Customers].[USA].[CA], 2)}) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjChildrenMembers() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin([Customers].[All Customers].[USA].[CA].children," + " [Product].[Product Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersChildren() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin([Product].[Product Name].Members," + " [Customers].[All Customers].[USA].[CA].children) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjMembersMembers() { checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin([Customers].[Name].Members," + " [Product].[Product Name].Members) ON rows " + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } public void testCjChildrenChildren() { checkNative( 3, 3, "select {[Measures].[Store Sales]} on columns, " + " NON EMPTY Crossjoin(" + " [Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Wine].children, " + " [Customers].[All Customers].[USA].[CA].CHILDREN) ON rows" + " from [Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } /** * Checks that multi-level member list generates compact form of SQL where * clause: * (1) Use IN list if possible * (2) Group members sharing the same parent * (3) Only need to compare up to the first unique parent level. */ public void testMultiLevelMemberConstraintNonNullParent() { String query = "with " + "set [Filtered Store City Set] as " + "{[Store].[USA].[OR].[Portland], " + " [Store].[USA].[OR].[Salem], " + " [Store].[USA].[CA].[San Francisco], " + " [Store].[USA].[WA].[Tacoma]} " + "set [NECJ] as NonEmptyCrossJoin([Filtered Store City Set], {[Product].[Product Family].Food}) " + "select [NECJ] on columns from [Sales]"; String necjSqlDerby = "select " + "\"store\".\"store_country\", \"store\".\"store_state\", \"store\".\"store_city\", " + "\"product_class\".\"product_family\" " + "from " + "\"store\" as \"store\", \"sales_fact_1997\" as \"sales_fact_1997\", " + "\"product\" as \"product\", \"product_class\" as \"product_class\" " + "where " + "\"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\" " + "and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" " + "and \"sales_fact_1997\".\"product_id\" = \"product\".\"product_id\" " + "and ((\"store\".\"store_state\" = 'OR' and \"store\".\"store_city\" in ('Portland', 'Salem'))" + " or (\"store\".\"store_state\" = 'CA' and \"store\".\"store_city\" = 'San Francisco')" + " or (\"store\".\"store_state\" = 'WA' and \"store\".\"store_city\" = 'Tacoma')) " + "and (\"product_class\".\"product_family\" = 'Food') " + "group by \"store\".\"store_country\", \"store\".\"store_state\", \"store\".\"store_city\", \"product_class\".\"product_family\" " + "order by CASE WHEN \"store\".\"store_country\" IS NULL THEN 1 ELSE 0 END, \"store\".\"store_country\" ASC, CASE WHEN \"store\".\"store_state\" IS NULL THEN 1 ELSE 0 END, \"store\".\"store_state\" ASC, CASE WHEN \"store\".\"store_city\" IS NULL THEN 1 ELSE 0 END, \"store\".\"store_city\" ASC, CASE WHEN \"product_class\".\"product_family\" IS NULL THEN 1 ELSE 0 END, \"product_class\".\"product_family\" ASC"; String necjSqlMySql = "select " + "`store`.`store_country` as `c0`, `store`.`store_state` as `c1`, " + "`store`.`store_city` as `c2`, `product_class`.`product_family` as `c3` " + "from " + "`store` as `store`, `sales_fact_1997` as `sales_fact_1997`, " + "`product` as `product`, `product_class` as `product_class` " + "where " + "`sales_fact_1997`.`store_id` = `store`.`store_id` " + "and `product`.`product_class_id` = `product_class`.`product_class_id` " + "and `sales_fact_1997`.`product_id` = `product`.`product_id` " + "and ((`store`.`store_city`, `store`.`store_state`) in (('Portland', 'OR'), ('Salem', 'OR'), ('San Francisco', 'CA'), ('Tacoma', 'WA'))) " + "and (`product_class`.`product_family` = 'Food') " + "group by `store`.`store_country`, `store`.`store_state`, `store`.`store_city`, `product_class`.`product_family` " + "order by ISNULL(`store`.`store_country`) ASC, `store`.`store_country` ASC, ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC, " + "ISNULL(`store`.`store_city`) ASC, `store`.`store_city` ASC, ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC"; if (MondrianProperties.instance().UseAggregates.get() && MondrianProperties.instance().ReadAggregates.get()) { // slightly different sql expected, uses agg table now for join necjSqlMySql = necjSqlMySql.replaceAll( "sales_fact_1997", "agg_c_14_sales_fact_1997"); necjSqlDerby = necjSqlDerby.replaceAll( "sales_fact_1997", "agg_c_14_sales_fact_1997"); } if (!MondrianProperties.instance().FilterChildlessSnowflakeMembers .get()) { necjSqlMySql = necjSqlMySql.replaceAll( "`product` as `product`, `product_class` as `product_class`", "`product_class` as `product_class`, `product` as `product`"); necjSqlMySql = necjSqlMySql.replaceAll( "`product`.`product_class_id` = `product_class`.`product_class_id` and " + "`sales_fact_1997`.`product_id` = `product`.`product_id` and ", "`sales_fact_1997`.`product_id` = `product`.`product_id` and " + "`product`.`product_class_id` = `product_class`.`product_class_id` and "); necjSqlDerby = necjSqlDerby.replaceAll( "\"product\" as \"product\", \"product_class\" as \"product_class\"", "\"product_class\" as \"product_class\", \"product\" as \"product\""); necjSqlDerby = necjSqlDerby.replaceAll( "\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" and " + "\"sales_fact_1997\".\"product_id\" = \"product\".\"product_id\" and ", "\"sales_fact_1997\".\"product_id\" = \"product\".\"product_id\" and " + "\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" and "); } SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby), new SqlPattern( Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql) }; assertQuerySql(query, patterns); } /** * Checks that multi-level member list generates compact form of SQL where * clause: * (1) Use IN list if possible(not possible if there are null values because * NULLs in IN lists do not match) * (2) Group members sharing the same parent, including parents with NULLs. * (3) If parent levels include NULLs, comparision includes any unique * level. */ public void testMultiLevelMemberConstraintNullParent() { if (!isDefaultNullMemberRepresentation()) { return; } if (!MondrianProperties.instance().FilterChildlessSnowflakeMembers .get()) { return; } String dimension = "<Dimension name=\"Warehouse2\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n" + " <Table name=\"warehouse\"/>\n" + " <Level name=\"address3\" column=\"wa_address3\" uniqueMembers=\"true\"/>\n" + " <Level name=\"address2\" column=\"wa_address2\" uniqueMembers=\"true\"/>\n" + " <Level name=\"address1\" column=\"wa_address1\" uniqueMembers=\"false\"/>\n" + " <Level name=\"name\" column=\"warehouse_name\" uniqueMembers=\"false\"/>\n" + " </Hierarchy>\n" + "</Dimension>\n"; String cube = "<Cube name=\"Warehouse2\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n" + " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n" + "</Cube>"; String query = "with\n" + "set [Filtered Warehouse Set] as " + "{[Warehouse2].[#null].[#null].[5617 Saclan Terrace].[Arnold and Sons]," + " [Warehouse2].[#null].[#null].[3377 Coachman Place].[Jones International]} " + "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) " + "select [NECJ] on columns from [Warehouse2]"; String necjSqlDerby = "select \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" " + "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" " + "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" " + "and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" and " + "((\"warehouse\".\"wa_address1\" = '5617 Saclan Terrace' and \"warehouse\".\"wa_address2\" is null and \"warehouse\".\"warehouse_name\" = 'Arnold and Sons') " + "or (\"warehouse\".\"wa_address1\" = '3377 Coachman Place' and \"warehouse\".\"wa_address2\" is null and \"warehouse\".\"warehouse_name\" = 'Jones International')) " + "and (\"product_class\".\"product_family\" = 'Food') group by \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"wa_address1\", " + "\"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" " + "order by CASE WHEN \"warehouse\".\"wa_address3\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address3\" ASC, CASE WHEN \"warehouse\".\"wa_address2\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address2\" ASC, CASE WHEN \"warehouse\".\"wa_address1\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address1\" ASC, CASE WHEN \"warehouse\".\"warehouse_name\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"warehouse_name\" ASC, CASE WHEN \"product_class\".\"product_family\" IS NULL THEN 1 ELSE 0 END, \"product_class\".\"product_family\" ASC"; String necjSqlMySql = "select `warehouse`.`wa_address3` as `c0`, `warehouse`.`wa_address2` as `c1`, `warehouse`.`wa_address1` as `c2`, `warehouse`.`warehouse_name` as `c3`, " + "`product_class`.`product_family` as `c4` from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, `product` as `product`, " + "`product_class` as `product_class` where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and " + "`product`.`product_class_id` = `product_class`.`product_class_id` and `inventory_fact_1997`.`product_id` = `product`.`product_id` and " + "((`warehouse`.`wa_address2` is null and (`warehouse`.`warehouse_name`, `warehouse`.`wa_address1`) in (('Arnold and Sons', '5617 Saclan Terrace'), " + "('Jones International', '3377 Coachman Place')))) and (`product_class`.`product_family` = 'Food') group by `warehouse`.`wa_address3`, " + "`warehouse`.`wa_address2`, `warehouse`.`wa_address1`, `warehouse`.`warehouse_name`, `product_class`.`product_family` " + "order by ISNULL(`warehouse`.`wa_address3`) ASC, `warehouse`.`wa_address3` ASC, ISNULL(`warehouse`.`wa_address2`) ASC, `warehouse`.`wa_address2` ASC, " + "ISNULL(`warehouse`.`wa_address1`) ASC, `warehouse`.`wa_address1` ASC, ISNULL(`warehouse`.`warehouse_name`) ASC, `warehouse`.`warehouse_name` ASC, " + "ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC"; TestContext testContext = TestContext.instance().create( dimension, cube, null, null, null, null); SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby), new SqlPattern( Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql) }; assertQuerySql(testContext, query, patterns); } /** * Check that multi-level member list generates compact form of SQL where * clause: * (1) Use IN list if possible(not possible if there are null values because * NULLs in IN lists do not match) * (2) Group members sharing the same parent, including parents with NULLs. * (3) If parent levels include NULLs, comparision includes any unique * level. * (4) Can handle predicates correctly if the member list contains both NULL * and non NULL parent levels. */ public void testMultiLevelMemberConstraintMixedNullNonNullParent() { if (!isDefaultNullMemberRepresentation()) { return; } if (!MondrianProperties.instance().FilterChildlessSnowflakeMembers .get()) { return; } String dimension = "<Dimension name=\"Warehouse2\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n" + " <Table name=\"warehouse\"/>\n" + " <Level name=\"fax\" column=\"warehouse_fax\" uniqueMembers=\"true\"/>\n" + " <Level name=\"address1\" column=\"wa_address1\" uniqueMembers=\"false\"/>\n" + " <Level name=\"name\" column=\"warehouse_name\" uniqueMembers=\"false\"/>\n" + " </Hierarchy>\n" + "</Dimension>\n"; String cube = "<Cube name=\"Warehouse2\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n" + " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n" + "</Cube>"; String query = "with\n" + "set [Filtered Warehouse Set] as " + "{[Warehouse2].[#null].[234 West Covina Pkwy].[Freeman And Co]," + " [Warehouse2].[971-555-6213].[3377 Coachman Place].[Jones International]} " + "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) " + "select [NECJ] on columns from [Warehouse2]"; String necjSqlDerby = "select \"warehouse\".\"warehouse_fax\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" " + "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" " + "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and \"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" " + "and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" and " + "((\"warehouse\".\"wa_address1\" = '234 West Covina Pkwy' and \"warehouse\".\"warehouse_fax\" is null and \"warehouse\".\"warehouse_name\" = 'Freeman And Co') " + "or (\"warehouse\".\"wa_address1\" = '3377 Coachman Place' and \"warehouse\".\"warehouse_fax\" = '971-555-6213' and \"warehouse\".\"warehouse_name\" = 'Jones International')) " + "and (\"product_class\".\"product_family\" = 'Food') " + "group by \"warehouse\".\"warehouse_fax\", \"warehouse\".\"wa_address1\", \"warehouse\".\"warehouse_name\", \"product_class\".\"product_family\" " + "order by CASE WHEN \"warehouse\".\"warehouse_fax\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"warehouse_fax\" ASC, CASE WHEN \"warehouse\".\"wa_address1\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address1\" ASC, CASE WHEN \"warehouse\".\"warehouse_name\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"warehouse_name\" ASC, CASE WHEN \"product_class\".\"product_family\" IS NULL THEN 1 ELSE 0 END, \"product_class\".\"product_family\" ASC"; String necjSqlMySql = "select `warehouse`.`warehouse_fax` as `c0`, `warehouse`.`wa_address1` as `c1`, " + "`warehouse`.`warehouse_name` as `c2`, `product_class`.`product_family` as `c3` " + "from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, " + "`product` as `product`, `product_class` as `product_class` " + "where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and " + "`product`.`product_class_id` = `product_class`.`product_class_id` and " + "`inventory_fact_1997`.`product_id` = `product`.`product_id` and " + "((`warehouse`.`warehouse_name`, `warehouse`.`wa_address1`, `warehouse`.`warehouse_fax`) in (('Jones International', '3377 Coachman Place', '971-555-6213')) " + "or (`warehouse`.`warehouse_fax` is null and " + "(`warehouse`.`warehouse_name`, `warehouse`.`wa_address1`) in (('Freeman And Co', '234 West Covina Pkwy')))) " + "and (`product_class`.`product_family` = 'Food') " + "group by `warehouse`.`warehouse_fax`, `warehouse`.`wa_address1`, `warehouse`.`warehouse_name`, `product_class`.`product_family` " + "order by ISNULL(`warehouse`.`warehouse_fax`) ASC, `warehouse`.`warehouse_fax` ASC, " + "ISNULL(`warehouse`.`wa_address1`) ASC, `warehouse`.`wa_address1` ASC, ISNULL(`warehouse`.`warehouse_name`) ASC, " + "`warehouse`.`warehouse_name` ASC, ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC"; TestContext testContext = TestContext.instance().create( dimension, cube, null, null, null, null); SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby), new SqlPattern( Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql) }; assertQuerySql(testContext, query, patterns); } /** * Check that multi-level member list generates compact form of SQL where * clause: * (1) Use IN list if possible(not possible if there are null values because * NULLs in IN lists do not match) * (2) Group members sharing the same parent * (3) Only need to compare up to the first unique parent level. * (4) Can handle predicates correctly if the member list contains both NULL * and non NULL child levels. */ public void testMultiLevelMemberConstraintWithMixedNullNonNullChild() { if (!isDefaultNullMemberRepresentation()) { return; } if (!MondrianProperties.instance().FilterChildlessSnowflakeMembers .get()) { return; } String dimension = "<Dimension name=\"Warehouse2\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"warehouse_id\">\n" + " <Table name=\"warehouse\"/>\n" + " <Level name=\"address3\" column=\"wa_address3\" uniqueMembers=\"true\"/>\n" + " <Level name=\"address2\" column=\"wa_address2\" uniqueMembers=\"false\"/>\n" + " <Level name=\"fax\" column=\"warehouse_fax\" uniqueMembers=\"false\"/>\n" + " </Hierarchy>\n" + "</Dimension>\n"; String cube = "<Cube name=\"Warehouse2\">\n" + " <Table name=\"inventory_fact_1997\"/>\n" + " <DimensionUsage name=\"Product\" source=\"Product\" foreignKey=\"product_id\"/>\n" + " <DimensionUsage name=\"Warehouse2\" source=\"Warehouse2\" foreignKey=\"warehouse_id\"/>\n" + " <Measure name=\"Warehouse Cost\" column=\"warehouse_cost\" aggregator=\"sum\"/>\n" + " <Measure name=\"Warehouse Sales\" column=\"warehouse_sales\" aggregator=\"sum\"/>\n" + "</Cube>"; String query = "with\n" + "set [Filtered Warehouse Set] as " + "{[Warehouse2].[#null].[#null].[#null]," + " [Warehouse2].[#null].[#null].[971-555-6213]} " + "set [NECJ] as NonEmptyCrossJoin([Filtered Warehouse Set], {[Product].[Product Family].Food}) " + "select [NECJ] on columns from [Warehouse2]"; String necjSqlDerby = "select \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"warehouse_fax\", \"product_class\".\"product_family\" " + "from \"warehouse\" as \"warehouse\", \"inventory_fact_1997\" as \"inventory_fact_1997\", \"product\" as \"product\", \"product_class\" as \"product_class\" " + "where \"inventory_fact_1997\".\"warehouse_id\" = \"warehouse\".\"warehouse_id\" and " + "\"product\".\"product_class_id\" = \"product_class\".\"product_class_id\" and \"inventory_fact_1997\".\"product_id\" = \"product\".\"product_id\" " + "and ((\"warehouse\".\"warehouse_fax\" = '971-555-6213' or \"warehouse\".\"warehouse_fax\" is null) and " + "\"warehouse\".\"wa_address2\" is null and \"warehouse\".\"wa_address3\" is null) and " + "(\"product_class\".\"product_family\" = 'Food') " + "group by \"warehouse\".\"wa_address3\", \"warehouse\".\"wa_address2\", \"warehouse\".\"warehouse_fax\", \"product_class\".\"product_family\" " + "order by CASE WHEN \"warehouse\".\"wa_address3\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address3\" ASC, CASE WHEN \"warehouse\".\"wa_address2\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"wa_address2\" ASC, CASE WHEN \"warehouse\".\"warehouse_fax\" IS NULL THEN 1 ELSE 0 END, \"warehouse\".\"warehouse_fax\" ASC, CASE WHEN \"product_class\".\"product_family\" IS NULL THEN 1 ELSE 0 END, \"product_class\".\"product_family\" ASC"; String necjSqlMySql = "select `warehouse`.`wa_address3` as `c0`, `warehouse`.`wa_address2` as `c1`, `warehouse`.`warehouse_fax` as `c2`, " + "`product_class`.`product_family` as `c3` from `warehouse` as `warehouse`, `inventory_fact_1997` as `inventory_fact_1997`, " + "`product` as `product`, `product_class` as `product_class` " + "where `inventory_fact_1997`.`warehouse_id` = `warehouse`.`warehouse_id` and `product`.`product_class_id` = `product_class`.`product_class_id` and " + "`inventory_fact_1997`.`product_id` = `product`.`product_id` and " + "((`warehouse`.`warehouse_fax` = '971-555-6213' or `warehouse`.`warehouse_fax` is null) and " + "`warehouse`.`wa_address2` is null and `warehouse`.`wa_address3` is null) and " + "(`product_class`.`product_family` = 'Food') " + "group by `warehouse`.`wa_address3`, `warehouse`.`wa_address2`, `warehouse`.`warehouse_fax`, " + "`product_class`.`product_family` " + "order by ISNULL(`warehouse`.`wa_address3`) ASC, `warehouse`.`wa_address3` ASC, ISNULL(`warehouse`.`wa_address2`) ASC, " + "`warehouse`.`wa_address2` ASC, ISNULL(`warehouse`.`warehouse_fax`) ASC, `warehouse`.`warehouse_fax` ASC, " + "ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC"; TestContext testContext = TestContext.instance().create( dimension, cube, null, null, null, null); SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.DERBY, necjSqlDerby, necjSqlDerby), new SqlPattern( Dialect.DatabaseProduct.MYSQL, necjSqlMySql, necjSqlMySql) }; assertQuerySql(testContext, query, patterns); } public void testNonEmptyUnionQuery() { Result result = executeQuery( "select {[Measures].[Unit Sales], [Measures].[Store Cost], [Measures].[Store Sales]} on columns,\n" + " NON EMPTY Hierarchize(\n" + " Union(\n" + " Crossjoin(\n" + " Crossjoin([Gender].[All Gender].children,\n" + " [Marital Status].[All Marital Status].children),\n" + " Crossjoin([Customers].[All Customers].children,\n" + " [Product].[All Products].children) ),\n" + " Crossjoin({([Gender].[All Gender].[M], [Marital Status].[All Marital Status].[M])},\n" + " Crossjoin(\n" + " [Customers].[All Customers].[USA].children,\n" + " [Product].[All Products].children) ) )) on rows\n" + "from Sales where ([Time].[1997])"); final Axis rowsAxis = result.getAxes()[1]; Assert.assertEquals(21, rowsAxis.getPositions().size()); } /** * when Mondrian parses a string like * "[Store].[All Stores].[USA].[CA].[San Francisco]" * it shall not lookup additional members. */ public void testLookupMemberCache() { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { // Dependency testing causes extra SQL reads, and screws up this // test. return; } // there currently isn't a cube member to children cache, only // a shared cache so use the shared smart member reader SmartMemberReader smr = getSmartMemberReader("Store"); MemberCacheHelper smrch = smr.cacheHelper; MemberCacheHelper rcsmrch = ((RolapCubeHierarchy.RolapCubeHierarchyMemberReader) smr) .getRolapCubeMemberCacheHelper(); SmartMemberReader ssmr = getSharedSmartMemberReader("Store"); MemberCacheHelper ssmrch = ssmr.cacheHelper; clearAndHardenCache(smrch); clearAndHardenCache(rcsmrch); clearAndHardenCache(ssmrch); RolapResult result = (RolapResult) executeQuery( "select {[Store].[All Stores].[USA].[CA].[San Francisco]} on columns from [Sales]"); assertTrue( "no additional members should be read:" + ssmrch.mapKeyToMember.size(), ssmrch.mapKeyToMember.size() <= 5); RolapMember sf = (RolapMember) result.getAxes()[0].getPositions().get(0).get(0); RolapMember ca = sf.getParentMember(); // convert back to shared members ca = ((RolapCubeMember) ca).getRolapMember(); sf = ((RolapCubeMember) sf).getRolapMember(); List<RolapMember> list = ssmrch.mapMemberToChildren.get( ca, scf.getMemberChildrenConstraint(null)); assertNull("children of [CA] are not in cache", list); list = ssmrch.mapMemberToChildren.get( ca, scf.getChildByNameConstraint( ca, new Id.NameSegment("San Francisco"))); assertNotNull("child [San Francisco] of [CA] is in cache", list); assertEquals("[San Francisco] expected", sf, list.get(0)); } /** * When looking for [Month] Mondrian generates SQL that tries to find * 'Month' as a member of the time dimension. This resulted in an * SQLException because the year level is numeric and the constant 'Month' * in the WHERE condition is not. Its probably a bug that Mondrian does not * take into account [Time].[1997] when looking up [Month]. */ public void testLookupMember() { // ok if no exception occurs executeQuery( "SELECT DESCENDANTS([Time].[1997], [Month]) ON COLUMNS FROM [Sales]"); } /** * Non Empty CrossJoin (A,B) gets turned into CrossJoin (Non Empty(A), Non * Empty(B)). Verify that there is no crash when the length of B could be * non-zero length before the non empty and 0 after the non empty. */ public void testNonEmptyCrossJoinList() { propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, false); boolean oldEnableNativeNonEmpty = MondrianProperties.instance().EnableNativeNonEmpty.get(); MondrianProperties.instance().EnableNativeNonEmpty.set(false); executeQuery( "select non empty CrossJoin([Customers].[Name].Members, " + "{[Promotions].[All Promotions].[Fantastic Discounts]}) " + "ON COLUMNS FROM [Sales]"); MondrianProperties.instance().EnableNativeNonEmpty.set( oldEnableNativeNonEmpty); } /** * SQL Optimization must be turned off in ragged hierarchies. */ public void testLookupMember2() { // ok if no exception occurs executeQuery( "select {[Store].[USA].[Washington]} on columns from [Sales Ragged]"); } /** * Make sure that the Crossjoin in [Measures].[CustomerCount] * is not evaluated in NON EMPTY context. */ public void testCalcMemberWithNonEmptyCrossJoin() { getConnection().getCacheControl(null).flushSchemaCache(); Result result = executeQuery( "with member [Measures].[CustomerCount] as \n" + "'Count(CrossJoin({[Product].[All Products]}, [Customers].[Name].Members))'\n" + "select \n" + "NON EMPTY{[Measures].[CustomerCount]} ON columns,\n" + "NON EMPTY{[Product].[All Products]} ON rows\n" + "from [Sales]\n" + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); Cell c = result.getCell(new int[] {0, 0}); // we expect 10281 customers, although there are only 20 non-empty ones // @see #testLevelMembers assertEquals("10,281", c.getFormattedValue()); } public void testLevelMembers() { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { // Dependency testing causes extra SQL reads, and screws up this // test. return; } SmartMemberReader smr = getSmartMemberReader("Customers"); // use the RolapCubeHierarchy's member cache for levels MemberCacheHelper smrch = ((RolapCubeHierarchy.CacheRolapCubeHierarchyMemberReader) smr) .rolapCubeCacheHelper; clearAndHardenCache(smrch); MemberCacheHelper smrich = smr.cacheHelper; clearAndHardenCache(smrich); // use the shared member cache for mapMemberToChildren SmartMemberReader ssmr = getSharedSmartMemberReader("Customers"); MemberCacheHelper ssmrch = ssmr.cacheHelper; clearAndHardenCache(ssmrch); TestCase c = new TestCase( 50, 21, "select \n" + "{[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY {[Customers].[All Customers], [Customers].[Name].Members} ON rows\n" + "from [Sales]\n" + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); Result r = c.run(); Level[] levels = smr.getHierarchy().getLevels(); Level nameLevel = levels[levels.length - 1]; // evaluator for [All Customers], [Store 14], [1/1/1997] Evaluator context = getEvaluator(r, new int[]{0, 0}); // make sure that [Customers].[Name].Members is NOT in cache TupleConstraint lmc = scf.getLevelMembersConstraint(null); assertNull(smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc)); // make sure that NON EMPTY [Customers].[Name].Members IS in cache context.setNonEmpty(true); lmc = scf.getLevelMembersConstraint(context); List<RolapMember> list = smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc); if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) { assertNotNull(list); assertEquals(20, list.size()); } // make sure that the parent/child for the context are cached // [Customers].[USA].[CA].[Burlingame].[Peggy Justice] Member member = r.getAxes()[1].getPositions().get(1).get(0); Member parent = member.getParentMember(); parent = ((RolapCubeMember) parent).getRolapMember(); member = ((RolapCubeMember) member).getRolapMember(); // lookup all children of [Burlingame] -> not in cache MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null); assertNull(ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc)); // lookup NON EMPTY children of [Burlingame] -> yes these are in cache mcc = scf.getMemberChildrenConstraint(context); list = smrich.mapMemberToChildren.get((RolapMember) parent, mcc); assertNotNull(list); assertTrue(list.contains(member)); } public void testLevelMembersWithoutNonEmpty() { SmartMemberReader smr = getSmartMemberReader("Customers"); MemberCacheHelper smrch = ((RolapCubeHierarchy.CacheRolapCubeHierarchyMemberReader) smr) .rolapCubeCacheHelper; clearAndHardenCache(smrch); MemberCacheHelper smrich = smr.cacheHelper; clearAndHardenCache(smrich); SmartMemberReader ssmr = getSharedSmartMemberReader("Customers"); MemberCacheHelper ssmrch = ssmr.cacheHelper; clearAndHardenCache(ssmrch); Result r = executeQuery( "select \n" + "{[Measures].[Unit Sales]} ON columns,\n" + "{[Customers].[All Customers], [Customers].[Name].Members} ON rows\n" + "from [Sales]\n" + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); Level[] levels = smr.getHierarchy().getLevels(); Level nameLevel = levels[levels.length - 1]; // evaluator for [All Customers], [Store 14], [1/1/1997] Evaluator context = getEvaluator(r, new int[] {0, 0}); // make sure that [Customers].[Name].Members IS in cache TupleConstraint lmc = scf.getLevelMembersConstraint(null); List<RolapMember> list = smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc); if (MondrianProperties.instance().EnableRolapCubeMemberCache.get()) { assertNotNull(list); assertEquals(10281, list.size()); } // make sure that NON EMPTY [Customers].[Name].Members is NOT in cache context.setNonEmpty(true); lmc = scf.getLevelMembersConstraint(context); assertNull(smrch.mapLevelToMembers.get((RolapLevel) nameLevel, lmc)); // make sure that the parent/child for the context are cached // [Customers].[Canada].[BC].[Burnaby] Member member = r.getAxes()[1].getPositions().get(1).get(0); Member parent = member.getParentMember(); parent = ((RolapCubeMember) parent).getRolapMember(); member = ((RolapCubeMember) member).getRolapMember(); // lookup all children of [Burnaby] -> yes, found in cache MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null); list = ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc); assertNotNull(list); assertTrue(list.contains(member)); // lookup NON EMPTY children of [Burlingame] -> not in cache mcc = scf.getMemberChildrenConstraint(context); list = ssmrch.mapMemberToChildren.get((RolapMember) parent, mcc); assertNull(list); } /** * Tests that <Dimension>.Members exploits the same optimization as * <Level>.Members. */ public void testDimensionMembers() { // No query should return more than 20 rows. (1 row at 'all' level, // 1 row at nation level, 1 at state level, 20 at city level, and 11 // at customers level = 34.) TestCase c = new TestCase( 34, 34, "select \n" + "{[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY [Customers].Members ON rows\n" + "from [Sales]\n" + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); c.run(); } /** * Tests non empty children of rolap member */ public void testMemberChildrenOfRolapMember() { TestCase c = new TestCase( 50, 4, "select \n" + "{[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY [Customers].[All Customers].[USA].[CA].[Palo Alto].Children ON rows\n" + "from [Sales]\n" + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); c.run(); } /** * Tests non empty children of All member */ public void testMemberChildrenOfAllMember() { TestCase c = new TestCase( 50, 14, "select {[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY [Promotions].[All Promotions].Children ON rows from [Sales]\n" + "where ([Time].[1997].[Q1].[1])"); c.run(); } /** * Tests non empty children of All member w/o WHERE clause */ public void testMemberChildrenNoWhere() { // The time dimension is joined because there is no (All) level in the // Time hierarchy: // select // `promotion`.`promotion_name` as `c0` // from // `time_by_day` as `time_by_day`, // `sales_fact_1997` as `sales_fact_1997`, // `promotion` as `promotion` // where `sales_fact_1997`.`time_id` = `time_by_day`.`time_id` // and `time_by_day`.`the_year` = 1997 // and `sales_fact_1997`.`promotion_id` // = `promotion`.`promotion_id` // group by // `promotion`.`promotion_name` // order by // `promotion`.`promotion_name` TestCase c = new TestCase( 50, 48, "select {[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY [Promotions].[All Promotions].Children ON rows " + "from [Sales]\n"); c.run(); } /** * Testcase for bug 1379068, which causes no children of [Time].[1997].[Q2] * to be found, because it incorrectly constrains on the level's key column * rather than name column. */ public void testMemberChildrenNameCol() { // Expression dependency testing casues false negatives. if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } TestCase c = new TestCase( 3, 1, "select " + " {[Measures].[Count]} ON columns," + " {[Time].[1997].[Q2].[April]} on rows " + "from [HR]"); c.run(); } /** * When a member is expanded in JPivot with mulitple hierarchies visible it * generates a * <code>CrossJoin({[member from left hierarchy]}, [member to * expand].Children)</code> * * <p>This should behave the same as if <code>[member from left * hierarchy]</code> was put into the slicer. */ public void testCrossjoin() { if (MondrianProperties.instance().TestExpDependencies.get() > 0) { // Dependency testing causes extra SQL reads, and makes this // test fail. return; } TestCase c = new TestCase( 45, 4, "select \n" + "{[Measures].[Unit Sales]} ON columns,\n" + "NON EMPTY Crossjoin(" + "{[Store].[USA].[CA].[San Francisco].[Store 14]}," + " [Customers].[USA].[CA].[Palo Alto].Children) ON rows\n" + "from [Sales] where ([Time].[1997].[Q1].[1])"); c.run(); } /** * Ensures that NON EMPTY Descendants is optimized. * Ensures that Descendants as a side effect collects MemberChildren that * may be looked up in the cache. */ public void testNonEmptyDescendants() { // Don't run the test if we're testing expression dependencies. // Expression dependencies cause spurious interval calls to // 'level.getMembers()' which create false negatives in this test. if (MondrianProperties.instance().TestExpDependencies.get() > 0) { return; } Connection con = getTestContext().withSchemaPool(false).getConnection(); SmartMemberReader smr = getSmartMemberReader(con, "Customers"); MemberCacheHelper smrch = smr.cacheHelper; clearAndHardenCache(smrch); SmartMemberReader ssmr = getSmartMemberReader(con, "Customers"); MemberCacheHelper ssmrch = ssmr.cacheHelper; clearAndHardenCache(ssmrch); TestCase c = new TestCase( con, 45, 21, "select \n" + "{[Measures].[Unit Sales]} ON columns, " + "NON EMPTY {[Customers].[All Customers], Descendants([Customers].[All Customers].[USA].[CA], [Customers].[Name])} on rows " + "from [Sales] " + "where ([Store].[All Stores].[USA].[CA].[San Francisco].[Store 14], [Time].[1997].[Q1].[1])"); Result result = c.run(); // [Customers].[All Customers].[USA].[CA].[Burlingame].[Peggy Justice] RolapMember peggy = (RolapMember) result.getAxes()[1].getPositions().get(1).get(0); RolapMember burlingame = peggy.getParentMember(); peggy = ((RolapCubeMember) peggy).getRolapMember(); burlingame = ((RolapCubeMember) burlingame).getRolapMember(); // all children of burlingame are not in cache MemberChildrenConstraint mcc = scf.getMemberChildrenConstraint(null); assertNull(ssmrch.mapMemberToChildren.get(burlingame, mcc)); // but non empty children is Evaluator evaluator = getEvaluator(result, new int[] {0, 0}); evaluator.setNonEmpty(true); mcc = scf.getMemberChildrenConstraint(evaluator); List<RolapMember> list = ssmrch.mapMemberToChildren.get(burlingame, mcc); assertNotNull(list); assertTrue(list.contains(peggy)); // now we run the same query again, this time everything must come out // of the cache RolapNativeRegistry reg = getRegistry(con); reg.setListener( new Listener() { public void foundEvaluator(NativeEvent e) { } public void foundInCache(TupleEvent e) { } public void executingSql(TupleEvent e) { fail("expected caching"); } }); try { c.run(); } finally { reg.setListener(null); } } public void testBug1412384() { // Bug 1412384 causes a NPE in SqlConstraintUtils. assertQueryReturns( "select NON EMPTY {[Time].[1997]} ON COLUMNS,\n" + "NON EMPTY Hierarchize(Union({[Customers].[All Customers]},\n" + "[Customers].[All Customers].Children)) ON ROWS\n" + "from [Sales]\n" + "where [Measures].[Profit]", "Axis + "{[Measures].[Profit]}\n" + "Axis + "{[Time].[1997]}\n" + "Axis + "{[Customers].[All Customers]}\n" + "{[Customers].[USA]}\n" + "Row #0: $339,610.90\n" + "Row #1: $339,610.90\n"); } public void testVirtualCubeCrossJoin() { checkNative( 18, 3, "select " + "{[Measures].[Units Ordered], [Measures].[Store Sales]} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testVirtualCubeNonEmptyCrossJoin() { checkNative( 18, 3, "select " + "{[Measures].[Units Ordered], [Measures].[Store Sales]} on columns, " + "NonEmptyCrossJoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testVirtualCubeNonEmptyCrossJoin3Args() { checkNative( 3, 3, "select " + "{[Measures].[Store Sales]} on columns, " + "nonEmptyCrossJoin([Product].[All Products].children, " + "nonEmptyCrossJoin([Customers].[All Customers].children," + "[Store].[All Stores].children)) on rows " + "from [Warehouse and Sales]"); } public void testNotNativeVirtualCubeCrossJoin1() { switch (getTestContext().getDialect().getDatabaseProduct()) { case INFOBRIGHT: // Hits same Infobright bug as NamedSetTest.testNamedSetOnMember. return; } // for this test, verify that no alert is raised even though // native evaluation isn't supported, because query // doesn't use explicit NonEmptyCrossJoin propSaver.set( MondrianProperties.instance().AlertNativeEvaluationUnsupported, "ERROR"); // native cross join cannot be used due to AllMembers checkNotNative( 3, "select " + "{[Measures].AllMembers} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testNotNativeVirtualCubeCrossJoin2() { // native cross join cannot be used due to the range operator checkNotNative( 3, "select " + "{[Measures].[Sales Count] : [Measures].[Unit Sales]} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testNotNativeVirtualCubeCrossJoinUnsupported() { switch (getTestContext().getDialect().getDatabaseProduct()) { case INFOBRIGHT: // Hits same Infobright bug as NamedSetTest.testNamedSetOnMember. return; } final BooleanProperty enableProperty = MondrianProperties.instance().EnableNativeCrossJoin; final StringProperty alertProperty = MondrianProperties.instance().AlertNativeEvaluationUnsupported; if (!enableProperty.get()) { // When native cross joins are explicitly disabled, no alerts // are supposed to be raised. return; } String mdx = "select " + "{[Measures].AllMembers} on columns, " + "NonEmptyCrossJoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"; final List<LoggingEvent> events = new ArrayList<LoggingEvent>(); // set up log4j listener to detect alerts Appender alertListener = new AppenderSkeleton() { protected void append(LoggingEvent event) { events.add(event); } public void close() { } public boolean requiresLayout() { return false; } }; final Logger rolapUtilLogger = Logger.getLogger(RolapUtil.class); propSaver.setAtLeast(rolapUtilLogger, org.apache.log4j.Level.WARN); rolapUtilLogger.addAppender(alertListener); String expectedMessage = "Unable to use native SQL evaluation for 'NonEmptyCrossJoin'"; // verify that exception is thrown if alerting is set to ERROR propSaver.set( alertProperty, org.apache.log4j.Level.ERROR.toString()); try { checkNotNative(3, mdx); fail("Expected NativeEvaluationUnsupportedException"); } catch (Exception ex) { Throwable t = ex; while (t.getCause() != null && t != t.getCause()) { t = t.getCause(); } if (!(t instanceof NativeEvaluationUnsupportedException)) { fail(); } // Expected } finally { propSaver.reset(); propSaver.setAtLeast(rolapUtilLogger, org.apache.log4j.Level.WARN); } // should have gotten one ERROR int nEvents = countFilteredEvents( events, org.apache.log4j.Level.ERROR, expectedMessage); assertEquals("logged error count check", 1, nEvents); events.clear(); // verify that exactly one warning is posted but execution succeeds // if alerting is set to WARN propSaver.set( alertProperty, org.apache.log4j.Level.WARN.toString()); try { checkNotNative(3, mdx); } finally { propSaver.reset(); propSaver.setAtLeast(rolapUtilLogger, org.apache.log4j.Level.WARN); } // should have gotten one WARN nEvents = countFilteredEvents( events, org.apache.log4j.Level.WARN, expectedMessage); assertEquals("logged warning count check", 1, nEvents); events.clear(); // verify that no warning is posted if native evaluation is // explicitly disabled propSaver.set( alertProperty, org.apache.log4j.Level.WARN.toString()); propSaver.set( enableProperty, false); try { checkNotNative(3, mdx); } finally { propSaver.reset(); propSaver.setAtLeast(rolapUtilLogger, org.apache.log4j.Level.WARN); } // should have gotten no WARN nEvents = countFilteredEvents( events, org.apache.log4j.Level.WARN, expectedMessage); assertEquals("logged warning count check", 0, nEvents); events.clear(); // no biggie if we don't get here for some reason; just being // half-heartedly clean rolapUtilLogger.removeAppender(alertListener); } private int countFilteredEvents( List<LoggingEvent> events, org.apache.log4j.Level level, String pattern) { int filteredEventCount = 0; for (LoggingEvent event : events) { if (!event.getLevel().equals(level)) { continue; } if (event.getMessage().toString().indexOf(pattern) == -1) { continue; } filteredEventCount++; } return filteredEventCount; } public void testVirtualCubeCrossJoinCalculatedMember1() { // calculated member appears in query checkNative( 18, 3, "WITH MEMBER [Measures].[Total Cost] as " + "'[Measures].[Store Cost] + [Measures].[Warehouse Cost]' " + "select " + "{[Measures].[Total Cost]} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testVirtualCubeCrossJoinCalculatedMember2() { // calculated member defined in schema checkNative( 18, 3, "select " + "{[Measures].[Profit Per Unit Shipped]} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testNotNativeVirtualCubeCrossJoinCalculatedMember() { // native cross join cannot be used due to CurrentMember in the // calculated member checkNotNative( 3, "WITH MEMBER [Measures].[CurrMember] as " + "'[Measures].CurrentMember' " + "select " + "{[Measures].[CurrMember]} on columns, " + "non empty crossjoin([Product].[All Products].children, " + "[Store].[All Stores].children) on rows " + "from [Warehouse and Sales]"); } public void testCjEnumCalcMembers() { // 3 cross joins -- 2 of the 4 arguments to the cross joins are // enumerated sets with calculated members // should be non-native due to the fix to testCjEnumCalcMembersBug() checkNotNative( 30, "with " + "member [Product].[All Products].[Drink].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Product].[All Products].[Drink]})' " + "member [Product].[All Products].[Non-Consumable].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Product].[All Products].[Non-Consumable]})' " + "member [Customers].[All Customers].[USA].[CA].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[USA].[CA]})' " + "member [Customers].[All Customers].[USA].[OR].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[USA].[OR]})' " + "member [Customers].[All Customers].[USA].[WA].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[USA].[WA]})' " + "select " + "{[Measures].[Unit Sales]} on columns, " + "non empty " + " crossjoin(" + " crossjoin(" + " crossjoin(" + " {[Product].[All Products].[Drink].[*SUBTOTAL_MEMBER_SEL~SUM], " + " [Product].[All Products].[Non-Consumable].[*SUBTOTAL_MEMBER_SEL~SUM]}, " + " " + EDUCATION_LEVEL_LEVEL + ".Members), " + " {[Customers].[All Customers].[USA].[CA].[*SUBTOTAL_MEMBER_SEL~SUM], " + " [Customers].[All Customers].[USA].[OR].[*SUBTOTAL_MEMBER_SEL~SUM], " + " [Customers].[All Customers].[USA].[WA].[*SUBTOTAL_MEMBER_SEL~SUM]}), " + " [Time].[Year].members)" + " on rows " + "from [Sales]"); } public void testCjEnumCalcMembersBug() { // make sure NECJ is forced to be non-native // before the fix, the query is natively evaluated and result // has empty rows for [Store Type].[All Store Types].[HeadQuarters] propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); propSaver.set(MondrianProperties.instance().ExpandNonNative, true); checkNotNative( 9, "with " + "member [Store Type].[All Store Types].[S] as sum({[Store Type].[All Store Types]}) " + "set [Enum Store Types] as {" + " [Store Type].[All Store Types].[HeadQuarters], " + " [Store Type].[All Store Types].[Small Grocery], " + " [Store Type].[All Store Types].[Supermarket], " + " [Store Type].[All Store Types].[S]}" + "select [Measures] on columns,\n" + " NonEmptyCrossJoin([Product].[All Products].Children, [Enum Store Types]) on rows\n" + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Drink], [Store Type].[Small Grocery]}\n" + "{[Product].[Drink], [Store Type].[Supermarket]}\n" + "{[Product].[Drink], [Store Type].[All Store Types].[S]}\n" + "{[Product].[Food], [Store Type].[Small Grocery]}\n" + "{[Product].[Food], [Store Type].[Supermarket]}\n" + "{[Product].[Food], [Store Type].[All Store Types].[S]}\n" + "{[Product].[Non-Consumable], [Store Type].[Small Grocery]}\n" + "{[Product].[Non-Consumable], [Store Type].[Supermarket]}\n" + "{[Product].[Non-Consumable], [Store Type].[All Store Types].[S]}\n" + "Row #0: 574\n" + "Row #1: 14,092\n" + "Row #2: 24,597\n" + "Row #3: 4,764\n" + "Row #4: 108,188\n" + "Row #5: 191,940\n" + "Row #6: 1,219\n" + "Row #7: 28,275\n" + "Row #8: 50,236\n"); } public void testCjEnumEmptyCalcMembers() { // Make sure maxConstraint settting is high enough int minConstraints = 3; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } // enumerated list of calculated members results in some empty cells checkNotNative( 5, "with " + "member [Customers].[All Customers].[USA].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[USA]})' " + "member [Customers].[All Customers].[Mexico].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[Mexico]})' " + "member [Customers].[All Customers].[Canada].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Customers].[All Customers].[Canada]})' " + "select " + "{[Measures].[Unit Sales]} on columns, " + "non empty " + " crossjoin(" + " {[Customers].[All Customers].[Mexico].[*SUBTOTAL_MEMBER_SEL~SUM], " + " [Customers].[All Customers].[Canada].[*SUBTOTAL_MEMBER_SEL~SUM], " + " [Customers].[All Customers].[USA].[*SUBTOTAL_MEMBER_SEL~SUM]}, " + " " + EDUCATION_LEVEL_LEVEL + ".Members) " + " on rows " + "from [Sales]"); } public void testCjUnionEnumCalcMembers() { // non-native due to the fix to testCjEnumCalcMembersBug() checkNotNative( 46, "with " + "member [Education Level].[*SUBTOTAL_MEMBER_SEL~SUM] as " + " 'sum({[Education Level].[All Education Levels]})' " + "member [Education Level].[*SUBTOTAL_MEMBER_SEL~AVG] as " + " 'avg([Education Level].[Education Level].Members)' select " + "{[Measures].[Unit Sales]} on columns, " + "non empty union (Crossjoin(" + " [Product].[Product Department].Members, " + " {[Education Level].[*SUBTOTAL_MEMBER_SEL~AVG]}), " + "crossjoin(" + " [Product].[Product Department].Members, " + " {[Education Level].[*SUBTOTAL_MEMBER_SEL~SUM]})) on rows " + "from [Sales]"); } /** * Tests the behavior if you have NON EMPTY on both axes, and the default * member of a hierarchy is not 'all' or the first child. */ public void testNonEmptyWithWeirdDefaultMember() { if (!Bug.BugMondrian229Fixed) { return; } TestContext testContext = TestContext.instance().createSubstitutingCube( "Sales", " <Dimension name=\"Time\" type=\"TimeDimension\" foreignKey=\"time_id\">\n" + " <Hierarchy hasAll=\"false\" primaryKey=\"time_id\" defaultMember=\"[Time].[1997].[Q1].[1]\" >\n" + " <Table name=\"time_by_day\"/>\n" + " <Level name=\"Year\" column=\"the_year\" type=\"Numeric\" uniqueMembers=\"true\"\n" + " levelType=\"TimeYears\"/>\n" + " <Level name=\"Quarter\" column=\"quarter\" uniqueMembers=\"false\"\n" + " levelType=\"TimeQuarters\"/>\n" + " <Level name=\"Month\" column=\"month_of_year\" uniqueMembers=\"false\" type=\"Numeric\"\n" + " levelType=\"TimeMonths\"/>\n" + " </Hierarchy>\n" + " </Dimension>"); // Check that the grand total is different than when [Time].[1997] is // the default member. testContext.assertQueryReturns( "select from [Sales]", "Axis + "{}\n" + "21,628"); // Results of this query agree with MSAS 2000 SP1. // The query gives the same results if the default member of [Time] // is [Time].[1997] or [Time].[1997].[Q1].[1]. testContext.assertQueryReturns( "select\n" + "NON EMPTY Crossjoin({[Time].[1997].[Q2].[4]}, [Customers].[Country].members) on columns,\n" + "NON EMPTY [Product].[All Products].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].children on rows\n" + "from sales", "Axis + "{}\n" + "Axis + "{[Time].[1997].[Q2].[4], [Customers].[USA]}\n" + "Axis + "{[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].[Portsmouth Imported Beer]}\n" + "{[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth].[Portsmouth Light Beer]}\n" + "Row #0: 3\n" + "Row #1: 21\n"); } public void testCrossJoinNamedSets1() { checkNative( 3, 3, "with " + "SET [ProductChildren] as '[Product].[All Products].children' " + "SET [StoreMembers] as '[Store].[Store Country].members' " + "select {[Measures].[Store Sales]} on columns, " + "non empty crossjoin([ProductChildren], [StoreMembers]) " + "on rows from [Sales]"); } public void testCrossJoinNamedSets2() { // Make sure maxConstraint settting is high enough int minConstraints = 3; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } checkNative( 3, 3, "with " + "SET [ProductChildren] as '{[Product].[All Products].[Drink], " + "[Product].[All Products].[Food], " + "[Product].[All Products].[Non-Consumable]}' " + "SET [StoreChildren] as '[Store].[All Stores].children' " + "select {[Measures].[Store Sales]} on columns, " + "non empty crossjoin([ProductChildren], [StoreChildren]) on rows from " + "[Sales]"); } public void testCrossJoinSetWithDifferentParents() { // Verify that only the members explicitly referenced in the set // are returned. Note that different members are referenced in // each level in the time dimension. checkNative( 5, 5, "select " + "{[Measures].[Unit Sales]} on columns, " + "NonEmptyCrossJoin(" + EDUCATION_LEVEL_LEVEL + ".Members, " + "{[Time].[1997].[Q1], [Time].[1998].[Q2]}) on rows from Sales"); } public void testCrossJoinSetWithCrossProdMembers() { // Make sure maxConstraint settting is high enough int minConstraints = 6; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } // members in set are a cross product of (1997, 1998) and (Q1, Q2, Q3) checkNative( 50, 15, "select " + "{[Measures].[Unit Sales]} on columns, " + "NonEmptyCrossJoin(" + EDUCATION_LEVEL_LEVEL + ".Members, " + "{[Time].[1997].[Q1], [Time].[1997].[Q2], [Time].[1997].[Q3], " + "[Time].[1998].[Q1], [Time].[1998].[Q2], [Time].[1998].[Q3]})" + "on rows from Sales"); } public void testCrossJoinSetWithSameParent() { // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } // members in set have the same parent checkNative( 10, 10, "select " + "{[Measures].[Unit Sales]} on columns, " + "NonEmptyCrossJoin(" + EDUCATION_LEVEL_LEVEL + ".Members, " + "{[Store].[All Stores].[USA].[CA].[Beverly Hills], " + "[Store].[All Stores].[USA].[CA].[San Francisco]}) " + "on rows from Sales"); } public void testCrossJoinSetWithUniqueLevel() { // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } // members in set have different parents but there is a unique level checkNative( 10, 10, "select " + "{[Measures].[Unit Sales]} on columns, " + "NonEmptyCrossJoin(" + EDUCATION_LEVEL_LEVEL + ".Members, " + "{[Store].[All Stores].[USA].[CA].[Beverly Hills].[Store 6], " + "[Store].[All Stores].[USA].[WA].[Bellingham].[Store 2]}) " + "on rows from Sales"); } public void testCrossJoinMultiInExprAllMember() { checkNative( 10, 10, "select " + "{[Measures].[Unit Sales]} on columns, " + "NonEmptyCrossJoin(" + EDUCATION_LEVEL_LEVEL + ".Members, " + "{[Product].[All Products].[Drink].[Alcoholic Beverages], " + "[Product].[All Products].[Food].[Breakfast Foods]}) " + "on rows from Sales"); } public void testCrossJoinEvaluatorContext1() { // This test ensures that the proper measure members context is // set when evaluating a non-empty cross join. The context should // not include the calculated measure [*TOP_BOTTOM_SET]. If it // does, the query will result in an infinite loop because the cross // join will try evaluating the calculated member (when it shouldn't) // and the calculated member references the cross join, resulting // in the loop assertQueryReturns( "With " + "Set [*NATIVE_CJ_SET] as " + "'NonEmptyCrossJoin([*BASE_MEMBERS_Store], [*BASE_MEMBERS_Products])' " + "Set [*TOP_BOTTOM_SET] as " + "'Order([*GENERATED_MEMBERS_Store], ([Measures].[Unit Sales], " + "[Product].[All Products].[*TOP_BOTTOM_MEMBER]), BDESC)' " + "Set [*BASE_MEMBERS_Store] as '[Store].members' " + "Set [*GENERATED_MEMBERS_Store] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' " + "Set [*BASE_MEMBERS_Products] as " + "'{[Product].[All Products].[Food], [Product].[All Products].[Drink], " + "[Product].[All Products].[Non-Consumable]}' " + "Set [*GENERATED_MEMBERS_Products] as " + "'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' " + "Member [Product].[All Products].[*TOP_BOTTOM_MEMBER] as " + "'Aggregate([*GENERATED_MEMBERS_Products])'" + "Member [Measures].[*TOP_BOTTOM_MEMBER] as 'Rank([Store].CurrentMember,[*TOP_BOTTOM_SET])' " + "Member [Store].[All Stores].[*SUBTOTAL_MEMBER_SEL~SUM] as " + "'sum(Filter([*GENERATED_MEMBERS_Store], [Measures].[*TOP_BOTTOM_MEMBER] <= 10))'" + "Select {[Measures].[Store Cost]} on columns, " + "Non Empty Filter(Generate([*NATIVE_CJ_SET], {([Store].CurrentMember)}), " + "[Measures].[*TOP_BOTTOM_MEMBER] <= 10) on rows From [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Store Cost]}\n" + "Axis + "{[Store].[All Stores]}\n" + "{[Store].[USA]}\n" + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[OR]}\n" + "{[Store].[USA].[OR].[Portland]}\n" + "{[Store].[USA].[OR].[Salem]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[USA].[WA]}\n" + "{[Store].[USA].[WA].[Tacoma]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17]}\n" + "Row #0: 225,627.23\n" + "Row #1: 225,627.23\n" + "Row #2: 63,530.43\n" + "Row #3: 56,772.50\n" + "Row #4: 21,948.94\n" + "Row #5: 34,823.56\n" + "Row #6: 34,823.56\n" + "Row #7: 105,324.31\n" + "Row #8: 29,959.28\n" + "Row #9: 29,959.28\n"); } public void testCrossJoinEvaluatorContext2() { // Make sure maxConstraint settting is high enough int minConstraints = 2; if (MondrianProperties.instance().MaxConstraints.get() < minConstraints) { propSaver.set( MondrianProperties.instance().MaxConstraints, minConstraints); } // calculated measure contains a calculated member assertQueryReturns( "With Set [*NATIVE_CJ_SET] as " + "'NonEmptyCrossJoin([*BASE_MEMBERS_Dates], [*BASE_MEMBERS_Stores])' " + "Set [*BASE_MEMBERS_Dates] as '{[Time].[1997].[Q1], [Time].[1997].[Q2]}' " + "Set [*GENERATED_MEMBERS_Dates] as " + "'Generate([*NATIVE_CJ_SET], {[Time].[Time].CurrentMember})' " + "Set [*GENERATED_MEMBERS_Measures] as '{[Measures].[*SUMMARY_METRIC_0]}' " + "Set [*BASE_MEMBERS_Stores] as '{[Store].[USA].[CA], [Store].[USA].[WA]}' " + "Set [*GENERATED_MEMBERS_Stores] as " + "'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' " + "Member [Time].[Time].[*SM_CTX_SEL] as 'Aggregate([*GENERATED_MEMBERS_Dates])' " + "Member [Measures].[*SUMMARY_METRIC_0] as " + "'[Measures].[Unit Sales]/([Measures].[Unit Sales],[Time].[*SM_CTX_SEL])', " + "FORMAT_STRING = '0.00%' " + "Member [Time].[Time].[*SUBTOTAL_MEMBER_SEL~SUM] as 'sum([*GENERATED_MEMBERS_Dates])' " + "Member [Store].[*SUBTOTAL_MEMBER_SEL~SUM] as " + "'sum(Filter([*GENERATED_MEMBERS_Stores], " + "([Measures].[Unit Sales], [Time].[*SUBTOTAL_MEMBER_SEL~SUM]) > 0.0))' " + "Select Union " + "(CrossJoin " + "(Filter " + "(Generate([*NATIVE_CJ_SET], {([Time].[Time].CurrentMember)}), " + "Not IsEmpty ([Measures].[Unit Sales])), " + "[*GENERATED_MEMBERS_Measures]), " + "CrossJoin " + "(Filter " + "({[Time].[*SUBTOTAL_MEMBER_SEL~SUM]}, " + "Not IsEmpty ([Measures].[Unit Sales])), " + "[*GENERATED_MEMBERS_Measures])) on columns, " + "Non Empty Union " + "(Filter " + "(Filter " + "(Generate([*NATIVE_CJ_SET], " + "{([Store].CurrentMember)}), " + "([Measures].[Unit Sales], " + "[Time].[*SUBTOTAL_MEMBER_SEL~SUM]) > 0.0), " + "Not IsEmpty ([Measures].[Unit Sales])), " + "Filter(" + "{[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}, " + "Not IsEmpty ([Measures].[Unit Sales]))) on rows " + "From [Sales]", "Axis + "{}\n" + "Axis + "{[Time].[1997].[Q1], [Measures].[*SUMMARY_METRIC_0]}\n" + "{[Time].[1997].[Q2], [Measures].[*SUMMARY_METRIC_0]}\n" + "{[Time].[*SUBTOTAL_MEMBER_SEL~SUM], [Measures].[*SUMMARY_METRIC_0]}\n" + "Axis + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[WA]}\n" + "{[Store].[*SUBTOTAL_MEMBER_SEL~SUM]}\n" + "Row #0: 48.34%\n" + "Row #0: 51.66%\n" + "Row #0: 100.00%\n" + "Row #1: 50.53%\n" + "Row #1: 49.47%\n" + "Row #1: 100.00%\n" + "Row #2: 49.72%\n" + "Row #2: 50.28%\n" + "Row #2: 100.00%\n"); } public void testVCNativeCJWithIsEmptyOnMeasure() { // Don't use checkNative method here because in the case where // native cross join isn't used, the query causes a stack overflow. // A measures member is referenced in the IsEmpty() function. This // shouldn't prevent native cross join from being used. assertQueryReturns( "with " + "set BM_PRODUCT as {[Product].[All Products].[Drink]} " + "set BM_EDU as [Education Level].[Education Level].Members " + "set BM_GENDER as {[Gender].[Gender].[M]} " + "set CJ as NonEmptyCrossJoin(BM_GENDER,NonEmptyCrossJoin(BM_EDU,BM_PRODUCT)) " + "set GM_PRODUCT as Generate(CJ, {[Product].CurrentMember}) " + "set GM_EDU as Generate(CJ, {[Education Level].CurrentMember}) " + "set GM_GENDER as Generate(CJ, {[Gender].CurrentMember}) " + "set GM_MEASURE as {[Measures].[Unit Sales]} " + "member [Education Level].FILTER1 as Aggregate(GM_EDU) " + "member [Gender].FILTER2 as Aggregate(GM_GENDER) " + "select " + "Filter(GM_PRODUCT, Not IsEmpty([Measures].[Unit Sales])) on rows, " + "GM_MEASURE on columns " + "from [Warehouse and Sales] " + "where ([Education Level].FILTER1, [Gender].FILTER2)", "Axis + "{[Education Level].[FILTER1], [Gender].[FILTER2]}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Drink]}\n" + "Row #0: 12,395\n"); } public void testVCNativeCJWithTopPercent() { // The reference to [Store Sales] inside the topPercent function // should not prevent native cross joins from being used checkNative( 92, 1, "select {topPercent(nonemptycrossjoin([Product].[Product Department].members, " + "[Time].[1997].children),10,[Measures].[Store Sales])} on columns, " + "{[Measures].[Store Sales]} on rows from " + "[Warehouse and Sales]"); } public void testVCOrdinalExpression() { // [Customers].[Name] is an ordinal expression. Make sure ordering // is done on the column corresponding to that expression. checkNative( 67, 67, "select {[Measures].[Store Sales]} on columns," + " NON EMPTY Crossjoin([Customers].[Name].Members," + " [Product].[Product Name].Members) ON rows " + " from [Warehouse and Sales] where (" + " [Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]," + " [Time].[1997].[Q1].[1])"); } /** * Test for bug #1696772 * Modified which calculations are tested for non native, non empty joins */ public void testNonEmptyWithCalcMeasure() { checkNative( 15, 6, "With " + "Set [*NATIVE_CJ_SET] as 'NonEmptyCrossJoin([*BASE_MEMBERS_Store],NonEmptyCrossJoin([*BASE_MEMBERS_Education Level],[*BASE_MEMBERS_Product]))' " + "Set [*METRIC_CJ_SET] as 'Filter([*NATIVE_CJ_SET],[Measures].[*Store Sales_SEL~SUM] > 50000.0 And [Measures].[*Unit Sales_SEL~MAX] > 50000.0)' " + "Set [*BASE_MEMBERS_Store] as '[Store].[Store Country].Members' " + "Set [*NATIVE_MEMBERS_Store] as 'Generate([*NATIVE_CJ_SET], {[Store].CurrentMember})' " + "Set [*METRIC_MEMBERS_Store] as 'Generate([*METRIC_CJ_SET], {[Store].CurrentMember})' " + "Set [*BASE_MEMBERS_Measures] as '{[Measures].[Store Sales],[Measures].[Unit Sales]}' " + "Set [*BASE_MEMBERS_Education Level] as '" + EDUCATION_LEVEL_LEVEL + ".Members' " + "Set [*NATIVE_MEMBERS_Education Level] as 'Generate([*NATIVE_CJ_SET], {[Education Level].CurrentMember})' " + "Set [*METRIC_MEMBERS_Education Level] as 'Generate([*METRIC_CJ_SET], {[Education Level].CurrentMember})' " + "Set [*BASE_MEMBERS_Product] as '[Product].[Product Family].Members' " + "Set [*NATIVE_MEMBERS_Product] as 'Generate([*NATIVE_CJ_SET], {[Product].CurrentMember})' " + "Set [*METRIC_MEMBERS_Product] as 'Generate([*METRIC_CJ_SET], {[Product].CurrentMember})' " + "Member [Product].[*CTX_METRIC_MEMBER_SEL~SUM] as 'Sum({[Product].[All Products]})' " + "Member [Store].[*CTX_METRIC_MEMBER_SEL~SUM] as 'Sum({[Store].[All Stores]})' " + "Member [Measures].[*Store Sales_SEL~SUM] as '([Measures].[Store Sales],[Education Level].CurrentMember,[Product].[*CTX_METRIC_MEMBER_SEL~SUM],[Store].[*CTX_METRIC_MEMBER_SEL~SUM])' " + "Member [Product].[*CTX_METRIC_MEMBER_SEL~MAX] as 'Max([*NATIVE_MEMBERS_Product])' " + "Member [Store].[*CTX_METRIC_MEMBER_SEL~MAX] as 'Max([*NATIVE_MEMBERS_Store])' " + "Member [Measures].[*Unit Sales_SEL~MAX] as '([Measures].[Unit Sales],[Education Level].CurrentMember,[Product].[*CTX_METRIC_MEMBER_SEL~MAX],[Store].[*CTX_METRIC_MEMBER_SEL~MAX])' " + "Select " + "CrossJoin(Generate([*METRIC_CJ_SET], {([Store].CurrentMember)}),[*BASE_MEMBERS_Measures]) on columns, " + "Non Empty Generate([*METRIC_CJ_SET], {([Education Level].CurrentMember,[Product].CurrentMember)}) on rows " + "From [Sales]"); } public void testCalculatedSlicerMember() { // This test verifies that members(the FILTER members in the query // below) on the slicer are ignored in CrossJoin emptiness check. // Otherwise, if they are not ignored, stack over flow will occur // because emptiness check depends on a calculated slicer member // which references the non-empty set being computed. // Bcause native evaluation already ignores calculated members on // the slicer, both native and non-native evaluation should return // the same result. checkNative( 20, 1, "With " + "Set BM_PRODUCT as '{[Product].[All Products].[Drink]}' " + "Set BM_EDU as '" + EDUCATION_LEVEL_LEVEL + ".Members' " + "Set BM_GENDER as '{[Gender].[Gender].[M]}' " + "Set NECJ_SET as 'NonEmptyCrossJoin(BM_GENDER, NonEmptyCrossJoin(BM_EDU,BM_PRODUCT))' " + "Set GM_PRODUCT as 'Generate(NECJ_SET, {[Product].CurrentMember})' " + "Set GM_EDU as 'Generate(NECJ_SET, {[Education Level].CurrentMember})' " + "Set GM_GENDER as 'Generate(NECJ_SET, {[Gender].CurrentMember})' " + "Set GM_MEASURE as '{[Measures].[Unit Sales]}' " + "Member [Education Level].FILTER1 as 'Aggregate(GM_EDU)' " + "Member [Gender].FILTER2 as 'Aggregate(GM_GENDER)' " + "Select " + "GM_PRODUCT on rows, GM_MEASURE on columns " + "From [Sales] Where ([Education Level].FILTER1, [Gender].FILTER2)"); } // next two verify that when NECJ references dimension from slicer, // slicer is correctly ignored for purposes of evaluating NECJ emptiness, // regardless of whether evaluation is native or non-native public void testIndependentSlicerMemberNonNative() { checkIndependentSlicerMemberNative(false); } public void testIndependentSlicerMemberNative() { checkIndependentSlicerMemberNative(true); } private void checkIndependentSlicerMemberNative(boolean useNative) { propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, useNative); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. final TestContext context = getTestContext().withFreshConnection(); try { context.assertQueryReturns( "with set [p] as '[Product].[Product Family].members' " + "set [s] as '[Store].[Store Country].members' " + "set [ne] as 'nonemptycrossjoin([p],[s])' " + "set [nep] as 'Generate([ne],{[Product].CurrentMember})' " + "select [nep] on columns from sales " + "where ([Store].[Store Country].[Mexico])", "Axis + "{[Store].[Mexico]}\n" + "Axis + "{[Product].[Drink]}\n" + "{[Product].[Food]}\n" + "{[Product].[Non-Consumable]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: \n"); } finally { context.close(); } } public void testDependentSlicerMemberNonNative() { propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, false); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. final TestContext context = getTestContext().withFreshConnection(); try { context.assertQueryReturns( "with set [p] as '[Product].[Product Family].members' " + "set [s] as '[Store].[Store Country].members' " + "set [ne] as 'nonemptycrossjoin([p],[s])' " + "set [nep] as 'Generate([ne],{[Product].CurrentMember})' " + "select [nep] on columns from sales " + "where ([Time].[1998])", "Axis + "{[Time].[1998]}\n" + "Axis } finally { context.close(); } } public void testDependentSlicerMemberNative() { propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. final TestContext context = getTestContext().withFreshConnection(); try { context.assertQueryReturns( "with set [p] as '[Product].[Product Family].members' " + "set [s] as '[Store].[Store Country].members' " + "set [ne] as 'nonemptycrossjoin([p],[s])' " + "set [nep] as 'Generate([ne],{[Product].CurrentMember})' " + "select [nep] on columns from sales " + "where ([Time].[1998])", "Axis + "{[Time].[1998]}\n" + "Axis } finally { context.close(); } } /** * Tests bug 1791609, "CrossJoin non empty optimizer eliminates calculated * member". */ public void testBug1791609NonEmptyCrossJoinEliminatesCalcMember() { if (!Bug.BugMondrian328Fixed) { return; } // From the bug: // With NON EMPTY (mondrian.rolap.nonempty) behavior set to true // the following mdx return no result. The same mdx returns valid // result when NON EMPTY is turned off. assertQueryReturns( "WITH \n" + "MEMBER Measures.Calc AS '[Measures].[Profit] * 2', SOLVE_ORDER=1000\n" + "MEMBER Product.Conditional as 'Iif (Measures.CurrentMember IS Measures.[Calc], " + "Measures.CurrentMember, null)', SOLVE_ORDER=2000\n" + "SET [S2] AS '{[Store].MEMBERS}' \n" + "SET [S1] AS 'CROSSJOIN({[Customers].[All Customers]},{Product.Conditional})' \n" + "SELECT \n" + "NON EMPTY GENERATE({Measures.[Calc]}, \n" + " CROSSJOIN(HEAD( {([Measures].CURRENTMEMBER)}, \n" + " 1\n" + " ), \n" + " {[S1]}\n" + " ), \n" + " ALL\n" + " ) \n" + " ON AXIS(0), \n" + "NON EMPTY [S2] ON AXIS(1) \n" + "FROM [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Calc], [Customers].[All Customers], [Product].[Conditional]}\n" + "Axis + "{[Store].[All Stores]}\n" + "{[Store].[USA]}\n" + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[USA].[CA].[Los Angeles]}\n" + "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[USA].[CA].[San Diego]}\n" + "{[Store].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[USA].[CA].[San Francisco]}\n" + "{[Store].[USA].[CA].[San Francisco].[Store 14]}\n" + "{[Store].[USA].[OR]}\n" + "{[Store].[USA].[OR].[Portland]}\n" + "{[Store].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[USA].[OR].[Salem]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[USA].[WA]}\n" + "{[Store].[USA].[WA].[Bellingham]}\n" + "{[Store].[USA].[WA].[Bellingham].[Store 2]}\n" + "{[Store].[USA].[WA].[Bremerton]}\n" + "{[Store].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[USA].[WA].[Seattle]}\n" + "{[Store].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[USA].[WA].[Spokane]}\n" + "{[Store].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[USA].[WA].[Tacoma]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17]}\n" + "{[Store].[USA].[WA].[Walla Walla]}\n" + "{[Store].[USA].[WA].[Walla Walla].[Store 22]}\n" + "{[Store].[USA].[WA].[Yakima]}\n" + "{[Store].[USA].[WA].[Yakima].[Store 23]}\n" + "Row #0: $679,221.79\n" + "Row #1: $679,221.79\n" + "Row #2: $191,274.83\n" + "Row #3: $54,967.60\n" + "Row #4: $54,967.60\n" + "Row #5: $65,547.49\n" + "Row #6: $65,547.49\n" + "Row #7: $65,435.21\n" + "Row #8: $65,435.21\n" + "Row #9: $5,324.53\n" + "Row #10: $5,324.53\n" + "Row #11: $171,009.14\n" + "Row #12: $66,219.69\n" + "Row #13: $66,219.69\n" + "Row #14: $104,789.45\n" + "Row #15: $104,789.45\n" + "Row #16: $316,937.82\n" + "Row #17: $5,685.23\n" + "Row #18: $5,685.23\n" + "Row #19: $63,548.67\n" + "Row #20: $63,548.67\n" + "Row #21: $63,374.53\n" + "Row #22: $63,374.53\n" + "Row #23: $59,677.94\n" + "Row #24: $59,677.94\n" + "Row #25: $89,769.36\n" + "Row #26: $89,769.36\n" + "Row #27: $5,651.26\n" + "Row #28: $5,651.26\n" + "Row #29: $29,230.83\n" + "Row #30: $29,230.83\n"); } /** * Test that executes &lt;Level&gt;.Members and applies a non-empty * constraint. Must work regardless of whether * {@link MondrianProperties#EnableNativeNonEmpty native} is enabled. * Testcase for bug * 1722959, "NON EMPTY Level.MEMBERS fails if nonempty.enable=false" */ public void testNonEmptyLevelMembers() { boolean currentNativeNonEmpty = MondrianProperties.instance().EnableNativeNonEmpty.get(); boolean currentNonEmptyOnAllAxis = MondrianProperties.instance().EnableNonEmptyOnAllAxis.get(); try { MondrianProperties.instance().EnableNativeNonEmpty.set(false); MondrianProperties.instance().EnableNonEmptyOnAllAxis.set(true); assertQueryReturns( "WITH MEMBER [Measures].[One] AS '1' " + "SELECT " + "NON EMPTY {[Measures].[One], [Measures].[Store Sales]} ON rows, " + "NON EMPTY [Store].[Store State].MEMBERS on columns " + "FROM sales", "Axis + "{}\n" + "Axis + "{[Store].[Canada].[BC]}\n" + "{[Store].[Mexico].[DF]}\n" + "{[Store].[Mexico].[Guerrero]}\n" + "{[Store].[Mexico].[Jalisco]}\n" + "{[Store].[Mexico].[Veracruz]}\n" + "{[Store].[Mexico].[Yucatan]}\n" + "{[Store].[Mexico].[Zacatecas]}\n" + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[OR]}\n" + "{[Store].[USA].[WA]}\n" + "Axis + "{[Measures].[One]}\n" + "{[Measures].[Store Sales]}\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 159,167.84\n" + "Row #1: 142,277.07\n" + "Row #1: 263,793.22\n"); if (Bug.BugMondrian446Fixed) { MondrianProperties.instance().EnableNativeNonEmpty.set(true); assertQueryReturns( "WITH MEMBER [Measures].[One] AS '1' " + "SELECT " + "NON EMPTY {[Measures].[One], [Measures].[Store Sales]} ON rows, " + "NON EMPTY [Store].[Store State].MEMBERS on columns " + "FROM sales", "Axis + "{}\n" + "Axis + "{[Store].[Canada].[BC]}\n" + "{[Store].[Mexico].[DF]}\n" + "{[Store].[Mexico].[Guerrero]}\n" + "{[Store].[Mexico].[Jalisco]}\n" + "{[Store].[Mexico].[Veracruz]}\n" + "{[Store].[Mexico].[Yucatan]}\n" + "{[Store].[Mexico].[Zacatecas]}\n" + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[OR]}\n" + "{[Store].[USA].[WA]}\n" + "Axis + "{[Measures].[One]}\n" + "{[Measures].[Store Sales]}\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #0: 1\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 159,167.84\n" + "Row #1: 142,277.07\n" + "Row #1: 263,793.22\n"); } } finally { MondrianProperties.instance().EnableNativeNonEmpty.set( currentNativeNonEmpty); MondrianProperties.instance().EnableNonEmptyOnAllAxis.set( currentNonEmptyOnAllAxis); } } public void testNonEmptyResults() { // This unit test was failing with a NullPointerException in JPivot // after the highcardinality feature was added, I've included it // here to make sure it continues to work. assertQueryReturns( "select NON EMPTY {[Measures].[Unit Sales], [Measures].[Store Cost]} ON columns, " + "NON EMPTY Filter([Product].[Brand Name].Members, ([Measures].[Unit Sales] > 100000.0)) ON rows " + "from [Sales] where [Time].[1997]", "Axis + "{[Time].[1997]}\n" + "Axis + "Axis } public void testBugMondrian412() { TestContext ctx = getTestContext(); ctx.assertQueryReturns( "with member [Measures].[AvgRevenue] as 'Avg([Store].[Store Name].Members, [Measures].[Store Sales])' " + "select NON EMPTY {[Measures].[Store Sales], [Measures].[AvgRevenue]} ON COLUMNS, " + "NON EMPTY Filter([Store].[Store Name].Members, ([Measures].[AvgRevenue] < [Measures].[Store Sales])) ON ROWS " + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "{[Measures].[AvgRevenue]}\n" + "Axis + "{[Store].[USA].[CA].[Beverly Hills].[Store 6]}\n" + "{[Store].[USA].[CA].[Los Angeles].[Store 7]}\n" + "{[Store].[USA].[CA].[San Diego].[Store 24]}\n" + "{[Store].[USA].[OR].[Portland].[Store 11]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13]}\n" + "{[Store].[USA].[WA].[Bremerton].[Store 3]}\n" + "{[Store].[USA].[WA].[Seattle].[Store 15]}\n" + "{[Store].[USA].[WA].[Spokane].[Store 16]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17]}\n" + "Row #0: 45,750.24\n" + "Row #0: 43,479.86\n" + "Row #1: 54,545.28\n" + "Row #1: 43,479.86\n" + "Row #2: 54,431.14\n" + "Row #2: 43,479.86\n" + "Row #3: 55,058.79\n" + "Row #3: 43,479.86\n" + "Row #4: 87,218.28\n" + "Row #4: 43,479.86\n" + "Row #5: 52,896.30\n" + "Row #5: 43,479.86\n" + "Row #6: 52,644.07\n" + "Row #6: 43,479.86\n" + "Row #7: 49,634.46\n" + "Row #7: 43,479.86\n" + "Row #8: 74,843.96\n" + "Row #8: 43,479.86\n"); } public void testNonEmpyOnVirtualCubeWithNonJoiningDimension() { assertQueryReturns( "select non empty {[Warehouse].[Warehouse name].members} on 0," + "{[Measures].[Units Shipped],[Measures].[Unit Sales]} on 1" + " from [Warehouse and Sales]", "Axis + "{}\n" + "Axis + "{[Warehouse].[USA].[CA].[Beverly Hills].[Big Quality Warehouse]}\n" + "{[Warehouse].[USA].[CA].[Los Angeles].[Artesia Warehousing, Inc.]}\n" + "{[Warehouse].[USA].[CA].[San Diego].[Jorgensen Service Storage]}\n" + "{[Warehouse].[USA].[CA].[San Francisco].[Food Service Storage, Inc.]}\n" + "{[Warehouse].[USA].[OR].[Portland].[Quality Distribution, Inc.]}\n" + "{[Warehouse].[USA].[OR].[Salem].[Treehouse Distribution]}\n" + "{[Warehouse].[USA].[WA].[Bellingham].[Foster Products]}\n" + "{[Warehouse].[USA].[WA].[Bremerton].[Destination, Inc.]}\n" + "{[Warehouse].[USA].[WA].[Seattle].[Quality Warehousing and Trucking]}\n" + "{[Warehouse].[USA].[WA].[Spokane].[Jones International]}\n" + "{[Warehouse].[USA].[WA].[Tacoma].[Jorge Garcia, Inc.]}\n" + "{[Warehouse].[USA].[WA].[Walla Walla].[Valdez Warehousing]}\n" + "{[Warehouse].[USA].[WA].[Yakima].[Maddock Stored Foods]}\n" + "Axis + "{[Measures].[Units Shipped]}\n" + "{[Measures].[Unit Sales]}\n" + "Row #0: 10759.0\n" + "Row #0: 24587.0\n" + "Row #0: 23835.0\n" + "Row #0: 1696.0\n" + "Row #0: 8515.0\n" + "Row #0: 32393.0\n" + "Row #0: 2348.0\n" + "Row #0: 22734.0\n" + "Row #0: 24110.0\n" + "Row #0: 11889.0\n" + "Row #0: 32411.0\n" + "Row #0: 1860.0\n" + "Row #0: 10589.0\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n" + "Row #1: \n"); } public void testNonEmptyOnNonJoiningValidMeasure() { assertQueryReturns( "with member [Measures].[vm] as 'ValidMeasure([Measures].[Unit Sales])'" + "select non empty {[Warehouse].[Warehouse name].members} on 0," + "{[Measures].[Units Shipped],[Measures].[vm]} on 1" + " from [Warehouse and Sales]", "Axis + "{}\n" + "Axis + "{[Warehouse].[USA].[CA].[Beverly Hills].[Big Quality Warehouse]}\n" + "{[Warehouse].[USA].[CA].[Los Angeles].[Artesia Warehousing, Inc.]}\n" + "{[Warehouse].[USA].[CA].[San Diego].[Jorgensen Service Storage]}\n" + "{[Warehouse].[USA].[CA].[San Francisco].[Food Service Storage, Inc.]}\n" + "{[Warehouse].[USA].[OR].[Portland].[Quality Distribution, Inc.]}\n" + "{[Warehouse].[USA].[OR].[Salem].[Treehouse Distribution]}\n" + "{[Warehouse].[USA].[WA].[Bellingham].[Foster Products]}\n" + "{[Warehouse].[USA].[WA].[Bremerton].[Destination, Inc.]}\n" + "{[Warehouse].[USA].[WA].[Seattle].[Quality Warehousing and Trucking]}\n" + "{[Warehouse].[USA].[WA].[Spokane].[Jones International]}\n" + "{[Warehouse].[USA].[WA].[Tacoma].[Jorge Garcia, Inc.]}\n" + "{[Warehouse].[USA].[WA].[Walla Walla].[Valdez Warehousing]}\n" + "{[Warehouse].[USA].[WA].[Yakima].[Maddock Stored Foods]}\n" + "Axis + "{[Measures].[Units Shipped]}\n" + "{[Measures].[vm]}\n" + "Row #0: 10759.0\n" + "Row #0: 24587.0\n" + "Row #0: 23835.0\n" + "Row #0: 1696.0\n" + "Row #0: 8515.0\n" + "Row #0: 32393.0\n" + "Row #0: 2348.0\n" + "Row #0: 22734.0\n" + "Row #0: 24110.0\n" + "Row #0: 11889.0\n" + "Row #0: 32411.0\n" + "Row #0: 1860.0\n" + "Row #0: 10589.0\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n" + "Row #1: 266,773\n"); } public void testCrossjoinWithTwoDimensionsJoiningToOppositeBaseCubes() { assertQueryReturns( "with member [Measures].[vm] as 'ValidMeasure([Measures].[Unit Sales])'\n" + "select non empty Crossjoin([Warehouse].[Warehouse Name].members, [Gender].[Gender].members) on 0,\n" + "{[Measures].[Units Shipped],[Measures].[vm]} on 1\n" + "from [Warehouse and Sales]", "Axis + "{}\n" + "Axis + "Axis + "{[Measures].[Units Shipped]}\n" + "{[Measures].[vm]}\n"); } public void testCrossjoinWithOneDimensionThatDoesNotJoinToBothBaseCubes() { assertQueryReturns( "with member [Measures].[vm] as 'ValidMeasure([Measures].[Units Shipped])'" + "select non empty Crossjoin([Store].[Store Name].members, [Gender].[Gender].members) on 0," + "{[Measures].[Unit Sales],[Measures].[vm]} on 1" + " from [Warehouse and Sales]", "Axis + "{}\n" + "Axis + "{[Store].[USA].[CA].[Beverly Hills].[Store 6], [Gender].[F]}\n" + "{[Store].[USA].[CA].[Beverly Hills].[Store 6], [Gender].[M]}\n" + "{[Store].[USA].[CA].[Los Angeles].[Store 7], [Gender].[F]}\n" + "{[Store].[USA].[CA].[Los Angeles].[Store 7], [Gender].[M]}\n" + "{[Store].[USA].[CA].[San Diego].[Store 24], [Gender].[F]}\n" + "{[Store].[USA].[CA].[San Diego].[Store 24], [Gender].[M]}\n" + "{[Store].[USA].[CA].[San Francisco].[Store 14], [Gender].[F]}\n" + "{[Store].[USA].[CA].[San Francisco].[Store 14], [Gender].[M]}\n" + "{[Store].[USA].[OR].[Portland].[Store 11], [Gender].[F]}\n" + "{[Store].[USA].[OR].[Portland].[Store 11], [Gender].[M]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13], [Gender].[F]}\n" + "{[Store].[USA].[OR].[Salem].[Store 13], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Bellingham].[Store 2], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Bellingham].[Store 2], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Bremerton].[Store 3], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Bremerton].[Store 3], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Seattle].[Store 15], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Seattle].[Store 15], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Spokane].[Store 16], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Spokane].[Store 16], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Tacoma].[Store 17], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Walla Walla].[Store 22], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Walla Walla].[Store 22], [Gender].[M]}\n" + "{[Store].[USA].[WA].[Yakima].[Store 23], [Gender].[F]}\n" + "{[Store].[USA].[WA].[Yakima].[Store 23], [Gender].[M]}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "{[Measures].[vm]}\n" + "Row #0: 10,771\n" + "Row #0: 10,562\n" + "Row #0: 12,089\n" + "Row #0: 13,574\n" + "Row #0: 12,835\n" + "Row #0: 12,800\n" + "Row #0: 1,064\n" + "Row #0: 1,053\n" + "Row #0: 12,488\n" + "Row #0: 13,591\n" + "Row #0: 20,548\n" + "Row #0: 21,032\n" + "Row #0: 1,096\n" + "Row #0: 1,141\n" + "Row #0: 11,640\n" + "Row #0: 12,936\n" + "Row #0: 13,513\n" + "Row #0: 11,498\n" + "Row #0: 12,068\n" + "Row #0: 11,523\n" + "Row #0: 17,420\n" + "Row #0: 17,837\n" + "Row #0: 1,019\n" + "Row #0: 1,184\n" + "Row #0: 5,007\n" + "Row #0: 6,484\n" + "Row #1: 10759.0\n" + "Row #1: 10759.0\n" + "Row #1: 24587.0\n" + "Row #1: 24587.0\n" + "Row #1: 23835.0\n" + "Row #1: 23835.0\n" + "Row #1: 1696.0\n" + "Row #1: 1696.0\n" + "Row #1: 8515.0\n" + "Row #1: 8515.0\n" + "Row #1: 32393.0\n" + "Row #1: 32393.0\n" + "Row #1: 2348.0\n" + "Row #1: 2348.0\n" + "Row #1: 22734.0\n" + "Row #1: 22734.0\n" + "Row #1: 24110.0\n" + "Row #1: 24110.0\n" + "Row #1: 11889.0\n" + "Row #1: 11889.0\n" + "Row #1: 32411.0\n" + "Row #1: 32411.0\n" + "Row #1: 1860.0\n" + "Row #1: 1860.0\n" + "Row #1: 10589.0\n" + "Row #1: 10589.0\n"); } public void testLeafMembersOfParentChildDimensionAreNativelyEvaluated() { final String query = "SELECT" + " NON EMPTY " + "Crossjoin(" + "{" + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Gabriel Walton]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Bishop Meastas]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Paula Duran]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Margaret Earley]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Elizabeth Horne]" + "}," + "[Store].[Store Name].members" + ") on 0 from hr"; checkNative(50, 5, query); } public void testNonLeafMembersOfPCDimensionAreNotNativelyEvaluated() { final String query = "SELECT" + " NON EMPTY " + "Crossjoin(" + "{" + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Beverly Baker]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Gabriel Walton]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley]," + "[Employees].[Sheri Nowmer].[Derrick Whelply].[Pedro Castillo].[Lin Conley].[Paul Tays].[Pat Chin].[Elizabeth Horne]" + "}," + "[Store].[Store Name].members" + ") on 0 from hr"; checkNotNative(9, query); } public void testNativeWithOverriddenNullMemberRepAndNullConstraint() { String preMdx = "SELECT FROM [Sales]"; String mdx = "SELECT \n" + " [Gender].[Gender].MEMBERS ON ROWS\n" + " ,{[Measures].[Unit Sales]} ON COLUMNS\n" + "FROM [Sales]\n" + "WHERE \n" + " [Store Size in SQFT].[All Store Size in SQFTs].[~Missing ]"; // run an mdx query with the default NullMemberRepresentation executeQuery(preMdx); propSaver.set( MondrianProperties.instance().NullMemberRepresentation, "~Missing "); propSaver.set( MondrianProperties.instance().EnableNonEmptyOnAllAxis, true); RolapUtil.reloadNullLiteral(); executeQuery(mdx); } public void testBugMondrian321() { assertQueryReturns( "WITH SET [#DataSet#] AS 'Crossjoin({Descendants([Customers].[All Customers], 2)}, {[Product].[All Products]})' \n" + "SELECT {[Measures].[Unit Sales], [Measures].[Store Sales]} on columns, \n" + "Hierarchize({[#DataSet#]}) on rows FROM [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Sales]}\n" + "Axis + "{[Customers].[USA].[CA], [Product].[All Products]}\n" + "{[Customers].[USA].[OR], [Product].[All Products]}\n" + "{[Customers].[USA].[WA], [Product].[All Products]}\n" + "Row #0: 74,748\n" + "Row #0: 159,167.84\n" + "Row #1: 67,659\n" + "Row #1: 142,277.07\n" + "Row #2: 124,366\n" + "Row #2: 263,793.22\n"); } public void testNativeCrossjoinWillConstrainUsingArgsFromAllAxes() { propSaver.set(propSaver.properties.GenerateFormattedSql, true); String mdx = "select " + "non empty Crossjoin({[Gender].[Gender].[F]},{[Measures].[Unit Sales]}) on 0," + "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1" + " from [Warehouse and Sales]"; SqlPattern oraclePattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, propSaver.properties.UseAggregates.get() ? "select\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"agg_c_14_sales_fact_1997\" \"agg_c_14_sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"agg_c_14_sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"agg_c_14_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" = 'F')\n" + "and\n" + " (\"agg_c_14_sales_fact_1997\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST" : "select\n" + " \"time_by_day\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"time_by_day\" \"time_by_day\",\n" + " \"sales_fact_1997\" \"sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\"\n" + "and\n" + " \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" = 'F')\n" + "and\n" + " (\"time_by_day\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"time_by_day\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"time_by_day\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST", 611); assertQuerySql(mdx, new SqlPattern[]{oraclePattern}); } public void testLevelMembersWillConstrainUsingArgsFromAllAxes() { propSaver.set(propSaver.properties.GenerateFormattedSql, true); String mdx = "select " + "non empty Crossjoin({[Gender].[Gender].[F]},{[Measures].[Unit Sales]}) on 0," + "non empty [Promotions].[Promotions].members on 1" + " from [Warehouse and Sales]"; SqlPattern oraclePattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, propSaver.properties.UseAggregates.get() ? "select\n" + " \"promotion\".\"promotion_name\" as \"c0\"\n" + "from\n" + " \"promotion\" \"promotion\",\n" + " \"agg_c_14_sales_fact_1997\" \"agg_c_14_sales_fact_1997\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"agg_c_14_sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"agg_c_14_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" = 'F')\n" + "group by\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST" : "select\n" + " \"promotion\".\"promotion_name\" as \"c0\"\n" + "from\n" + " \"promotion\" \"promotion\",\n" + " \"sales_fact_1997\" \"sales_fact_1997\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" = 'F')\n" + "group by\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST", 347); assertQuerySql(mdx, new SqlPattern[]{oraclePattern}); } public void testNativeCrossjoinWillExpandFirstLastChild() { propSaver.set(propSaver.properties.GenerateFormattedSql, true); String mdx = "select " + "non empty Crossjoin({[Gender].firstChild,[Gender].lastChild},{[Measures].[Unit Sales]}) on 0," + "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1" + " from [Warehouse and Sales]"; final SqlPattern pattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, propSaver.properties.UseAggregates.get() ? "select\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"agg_c_14_sales_fact_1997\" \"agg_c_14_sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"agg_c_14_sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"agg_c_14_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" in ('F', 'M'))\n" + "and\n" + " (\"agg_c_14_sales_fact_1997\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST" : "select\n" + " \"time_by_day\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"time_by_day\" \"time_by_day\",\n" + " \"sales_fact_1997\" \"sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\"\n" + "and\n" + " \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" in ('F', 'M'))\n" + "and\n" + " (\"time_by_day\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"time_by_day\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"time_by_day\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST", 611); assertQuerySql(mdx, new SqlPattern[]{pattern}); } public void testNativeCrossjoinWillExpandLagInNamedSet() { propSaver.set(propSaver.properties.GenerateFormattedSql, true); String mdx = "with set [blah] as '{[Gender].lastChild.lag(1),[Gender].[M]}' " + "select " + "non empty Crossjoin([blah],{[Measures].[Unit Sales]}) on 0," + "non empty Crossjoin({[Time].[1997]},{[Promotions].[All Promotions].[Bag Stuffers],[Promotions].[All Promotions].[Best Savings]}) on 1" + " from [Warehouse and Sales]"; final SqlPattern pattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, propSaver.properties.UseAggregates.get() ? "select\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"agg_c_14_sales_fact_1997\" \"agg_c_14_sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"agg_c_14_sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"agg_c_14_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" in ('F', 'M'))\n" + "and\n" + " (\"agg_c_14_sales_fact_1997\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST" : "select\n" + " \"time_by_day\".\"the_year\" as \"c0\",\n" + " \"promotion\".\"promotion_name\" as \"c1\"\n" + "from\n" + " \"time_by_day\" \"time_by_day\",\n" + " \"sales_fact_1997\" \"sales_fact_1997\",\n" + " \"promotion\" \"promotion\",\n" + " \"customer\" \"customer\"\n" + "where\n" + " \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\"\n" + "and\n" + " \"sales_fact_1997\".\"promotion_id\" = \"promotion\".\"promotion_id\"\n" + "and\n" + " \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\"\n" + "and\n" + " (\"customer\".\"gender\" in ('F', 'M'))\n" + "and\n" + " (\"time_by_day\".\"the_year\" = 1997)\n" + "and\n" + " (\"promotion\".\"promotion_name\" in ('Bag Stuffers', 'Best Savings'))\n" + "group by\n" + " \"time_by_day\".\"the_year\",\n" + " \"promotion\".\"promotion_name\"\n" + "order by\n" + " \"time_by_day\".\"the_year\" ASC NULLS LAST,\n" + " \"promotion\".\"promotion_name\" ASC NULLS LAST", 611); assertQuerySql(mdx, new SqlPattern[]{pattern}); } public void testConstrainedMeasureGetsOptimized() { String mdx = "with member [Measures].[unit sales Male] as '([Measures].[Unit Sales],[Gender].[Gender].[M])' " + "member [Measures].[unit sales Female] as '([Measures].[Unit Sales],[Gender].[Gender].[F])' " + "member [Measures].[store sales Female] as '([Measures].[Store Sales],[Gender].[Gender].[F])' " + "member [Measures].[literal one] as '1' " + "select " + "non empty {{[Measures].[unit sales Male]}, {([Measures].[literal one])}, " + "[Measures].[unit sales Female], [Measures].[store sales Female]} on 0, " + "non empty [Customers].[name].members on 1 " + "from Sales"; final String sqlOracle = MondrianProperties.instance().UseAggregates.get() ? "select \"customer\".\"country\" as \"c0\"," + " \"customer\".\"state_province\" as \"c1\", \"customer\".\"city\" as \"c2\", \"customer\".\"customer_id\" as \"c3\", \"fname\" || ' ' || \"lname\" as \"c4\", \"fname\" || ' ' || \"lname\" as \"c5\", \"customer\".\"gender\" as \"c6\", \"customer\".\"marital_status\" as \"c7\", \"customer\".\"education\" as \"c8\", \"customer\".\"yearly_income\" as \"c9\" from \"customer\" \"customer\", \"agg_l_03_sales_fact_1997\" \"agg_l_03_sales_fact_1997\" where \"agg_l_03_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" and (\"customer\".\"gender\" in ('M', 'F')) group by \"customer\".\"country\", \"customer\".\"state_province\", \"customer\".\"city\", \"customer\".\"customer_id\", \"fname\" || ' ' || \"lname\", \"customer\".\"gender\", \"customer\".\"marital_status\", \"customer\".\"education\", \"customer\".\"yearly_income\" order by \"customer\".\"country\" ASC NULLS LAST, \"customer\".\"state_province\" ASC NULLS LAST, \"customer\".\"city\" ASC NULLS LAST, \"fname\" || ' ' || \"lname\" ASC NULLS LAST" : "select \"customer\".\"country\" as \"c0\"," + " \"customer\".\"state_province\" as \"c1\", \"customer\".\"city\" as \"c2\", \"customer\".\"customer_id\" as \"c3\", \"fname\" || ' ' || \"lname\" as \"c4\", \"fname\" || ' ' || \"lname\" as \"c5\", \"customer\".\"gender\" as \"c6\", \"customer\".\"marital_status\" as \"c7\", \"customer\".\"education\" as \"c8\", \"customer\".\"yearly_income\" as \"c9\" from \"customer\" \"customer\", \"sales_fact_1997\" \"sales_fact_1997\" where \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" and (\"customer\".\"gender\" in ('M', 'F')) group by \"customer\".\"country\", \"customer\".\"state_province\", \"customer\".\"city\", \"customer\".\"customer_id\", \"fname\" || ' ' || \"lname\", \"customer\".\"gender\", \"customer\".\"marital_status\", \"customer\".\"education\", \"customer\".\"yearly_income\" order by \"customer\".\"country\" ASC NULLS LAST, \"customer\".\"state_province\" ASC NULLS LAST, \"customer\".\"city\" ASC NULLS LAST, \"fname\" || ' ' || \"lname\" ASC NULLS LAST"; assertQuerySql( mdx, new SqlPattern[]{ new SqlPattern( Dialect.DatabaseProduct.ORACLE, sqlOracle, sqlOracle.length())}); } public void testNestedMeasureConstraintsGetOptimized() { String mdx = "with member [Measures].[unit sales Male] as '([Measures].[Unit Sales],[Gender].[Gender].[M])' " + "member [Measures].[unit sales Male Married] as '([Measures].[unit sales Male],[Marital Status].[Marital Status].[M])' " + "select " + "non empty {[Measures].[unit sales Male Married]} on 0, " + "non empty [Customers].[name].members on 1 " + "from Sales"; final String sqlOracle = MondrianProperties.instance().UseAggregates.get() ? "select \"customer\".\"country\" as \"c0\"," + " \"customer\".\"state_province\" as \"c1\", \"customer\".\"city\" as \"c2\", \"customer\".\"customer_id\" as \"c3\", \"fname\" || ' ' || \"lname\" as \"c4\", \"fname\" || ' ' || \"lname\" as \"c5\", \"customer\".\"gender\" as \"c6\", \"customer\".\"marital_status\" as \"c7\", \"customer\".\"education\" as \"c8\", \"customer\".\"yearly_income\" as \"c9\" from \"customer\" \"customer\", \"agg_l_03_sales_fact_1997\" \"agg_l_03_sales_fact_1997\" where \"agg_l_03_sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" and (\"customer\".\"gender\" = 'M') and (\"customer\".\"marital_status\" = 'M') group by \"customer\".\"country\", \"customer\".\"state_province\", \"customer\".\"city\", \"customer\".\"customer_id\", \"fname\" || ' ' || \"lname\", \"customer\".\"gender\", \"customer\".\"marital_status\", \"customer\".\"education\", \"customer\".\"yearly_income\" order by \"customer\".\"country\" ASC NULLS LAST, \"customer\".\"state_province\" ASC NULLS LAST, \"customer\".\"city\" ASC NULLS LAST, \"fname\" || ' ' || \"lname\" ASC NULLS LAST" : "select \"customer\".\"country\" as \"c0\", " + "\"customer\".\"state_province\" as \"c1\", " + "\"customer\".\"city\" as \"c2\", " + "\"customer\".\"customer_id\" as \"c3\", " + "\"fname\" || \" \" || \"lname\" as \"c4\", " + "\"fname\" || \" \" || \"lname\" as \"c5\", " + "\"customer\".\"gender\" as \"c6\", " + "\"customer\".\"marital_status\" as \"c7\", " + "\"customer\".\"education\" as \"c8\", " + "\"customer\".\"yearly_income\" as \"c9\" " + "from \"customer\" \"customer\", " + "\"sales_fact_1997\" \"sales_fact_1997\" " + "where \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" " + "and (\"customer\".\"gender\" = \"M\") " + "and (\"customer\".\"marital_status\" = \"M\") " + "group by \"customer\".\"country\", " + "\"customer\".\"state_province\", " + "\"customer\".\"city\", " + "\"customer\".\"customer_id\", " + "\"fname\" || \" \" || \"lname\", " + "\"customer\".\"gender\", " + "\"customer\".\"marital_status\", " + "\"customer\".\"education\", " + "\"customer\".\"yearly_income\" " + "order by \"customer\".\"country\" ASC NULLS LAST, " + "\"customer\".\"state_province\" ASC NULLS LAST, " + "\"customer\".\"city\" ASC NULLS LAST, " + "\"fname\" || \" \" || \"lname\" ASC NULLS LAST"; SqlPattern pattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, sqlOracle, sqlOracle.length()); assertQuerySql(mdx, new SqlPattern[]{pattern}); } public void testNonUniformNestedMeasureConstraintsGetOptimized() { if (MondrianProperties.instance().UseAggregates.get()) { // This test can't work with aggregates becaused // the aggregate table doesn't include member properties. return; } String mdx = "with member [Measures].[unit sales Male] as '([Measures].[Unit Sales],[Gender].[Gender].[M])' " + "member [Measures].[unit sales Female] as '([Measures].[Unit Sales],[Gender].[Gender].[F])' " + "member [Measures].[unit sales Male Married] as '([Measures].[unit sales Male],[Marital Status].[Marital Status].[M])' " + "select " + "non empty {[Measures].[unit sales Male Married],[Measures].[unit sales Female]} on 0, " + "non empty [Customers].[name].members on 1 " + "from Sales"; final SqlPattern pattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, "select \"customer\".\"country\" as \"c0\", " + "\"customer\".\"state_province\" as \"c1\", " + "\"customer\".\"city\" as \"c2\", " + "\"customer\".\"customer_id\" as \"c3\", " + "\"fname\" || ' ' || \"lname\" as \"c4\", " + "\"fname\" || ' ' || \"lname\" as \"c5\", " + "\"customer\".\"gender\" as \"c6\", " + "\"customer\".\"marital_status\" as \"c7\", " + "\"customer\".\"education\" as \"c8\", " + "\"customer\".\"yearly_income\" as \"c9\" " + "from \"customer\" \"customer\", \"sales_fact_1997\" \"sales_fact_1997\" " + "where \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" " + "and (\"customer\".\"gender\" in ('M', 'F')) " + "group by \"customer\".\"country\", " + "\"customer\".\"state_province\", " + "\"customer\".\"city\", " + "\"customer\".\"customer_id\", " + "\"fname\" || ' ' || \"lname\", " + "\"customer\".\"gender\", " + "\"customer\".\"marital_status\", " + "\"customer\".\"education\", " + "\"customer\".\"yearly_income\" " + "order by \"customer\".\"country\" ASC NULLS LAST," + " \"customer\".\"state_province\" ASC NULLS LAST," + " \"customer\".\"city\" ASC NULLS LAST, " + "\"fname\" || ' ' || \"lname\" ASC NULLS LAST", 852); assertQuerySql(mdx, new SqlPattern[]{pattern}); } public void testNonUniformConstraintsAreNotUsedForOptimization() { String mdx = "with member [Measures].[unit sales Male] as '([Measures].[Unit Sales],[Gender].[Gender].[M])' " + "member [Measures].[unit sales Married] as '([Measures].[Unit Sales],[Marital Status].[Marital Status].[M])' " + "select " + "non empty {[Measures].[unit sales Male], [Measures].[unit sales Married]} on 0, " + "non empty [Customers].[name].members on 1 " + "from Sales"; final String sqlOracle = "select \"customer\".\"country\" as \"c0\", \"customer\".\"state_province\" as \"c1\", \"customer\".\"city\" as \"c2\", \"customer\".\"customer_id\" as \"c3\", \"fname\" || ' ' || \"lname\" as \"c4\", \"fname\" || ' ' || \"lname\" as \"c5\", \"customer\".\"gender\" as \"c6\", \"customer\".\"marital_status\" as \"c7\", \"customer\".\"education\" as \"c8\", \"customer\".\"yearly_income\" as \"c9\" from \"customer\" \"customer\", \"sales_fact_1997\" \"sales_fact_1997\" where \"sales_fact_1997\".\"customer_id\" = \"customer\".\"customer_id\" and (\"customer\".\"gender\" in ('M', 'F')) group by \"customer\".\"country\", \"customer\".\"state_province\", \"customer\".\"city\", \"customer\".\"customer_id\", \"fname\" || ' ' || \"lname\", \"customer\".\"gender\", \"customer\".\"marital_status\", \"customer\".\"education\", \"customer\".\"yearly_income\" order by \"customer\".\"country\" ASC NULLS LAST, \"customer\".\"state_province\" ASC NULLS LAST, \"customer\".\"city\" ASC NULLS LAST, \"fname\" || ' ' || \"lname\" ASC NULLS LAST"; final SqlPattern pattern = new SqlPattern( Dialect.DatabaseProduct.ORACLE, sqlOracle, sqlOracle.length()); assertQuerySqlOrNot( getTestContext(), mdx, new SqlPattern[]{pattern},true, false, true); } public void testMeasureConstraintsInACrossjoinHaveCorrectResults() { propSaver.set(MondrianProperties.instance().EnableNativeNonEmpty, true); String mdx = "with " + " member [Measures].[aa] as '([Measures].[Store Cost],[Gender].[M])'" + " member [Measures].[bb] as '([Measures].[Store Cost],[Gender].[F])'" + " select" + " non empty " + " crossjoin({[Store].[All Stores].[USA].[CA]}," + " {[Measures].[aa], [Measures].[bb]}) on columns," + " non empty " + " [Marital Status].[Marital Status].members on rows" + " from sales"; assertQueryReturns( mdx, "Axis + "{}\n" + "Axis + "{[Store].[USA].[CA], [Measures].[aa]}\n" + "{[Store].[USA].[CA], [Measures].[bb]}\n" + "Axis + "{[Marital Status].[M]}\n" + "{[Marital Status].[S]}\n" + "Row #0: 15,339.94\n" + "Row #0: 15,941.98\n" + "Row #1: 16,598.87\n" + "Row #1: 15,649.64\n"); } public void testContextAtAllWorksWithConstraint() { TestContext ctx = TestContext.instance().create( null, "<Cube name=\"onlyGender\"> \n" + " <Table name=\"sales_fact_1997\"/> \n" + "<Dimension name=\"Gender\" foreignKey=\"customer_id\">\n" + " <Hierarchy hasAll=\"true\" allMemberName=\"All Gender\" primaryKey=\"customer_id\">\n" + " <Table name=\"customer\"/>\n" + " <Level name=\"Gender\" column=\"gender\" uniqueMembers=\"true\"/>\n" + " </Hierarchy>\n" + " </Dimension>" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"/> \n" + "</Cube> \n", null, null, null, null); String mdx = " select " + " NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS, " + " NON EMPTY {[Gender].[Gender].Members} ON ROWS " + " from [onlyGender] "; ctx.assertQueryReturns( mdx, "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Gender].[F]}\n" + "{[Gender].[M]}\n" + "Row #0: 131,558\n" + "Row #1: 135,215\n"); } /*** * Before the fix this test would throw an IndexOutOfBounds exception * in SqlConstraintUtils.removeDefaultMembers. The method assumed that the * first member in the list would exist and be a measure. But, when the * default measure is calculated, it would have already been removed from * the list by removeCalculatedMembers, and thus the assumption was wrong. */ public void testCalculatedDefaultMeasureOnVirtualCubeNoThrowException() { propSaver.set(MondrianProperties.instance().EnableNativeNonEmpty, true); final TestContext context = TestContext.instance().withSchema( "<Schema name=\"FoodMart\">" + " <Dimension name=\"Store\">" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">" + " <Table name=\"store\" />" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\" />" + " <Level name=\"Store State\" column=\"store_state\" uniqueMembers=\"true\" />" + " <Level name=\"Store City\" column=\"store_city\" uniqueMembers=\"false\" />" + " <Level name=\"Store Name\" column=\"store_name\" uniqueMembers=\"true\">" + " <Property name=\"Store Type\" column=\"store_type\" />" + " <Property name=\"Store Manager\" column=\"store_manager\" />" + " <Property name=\"Store Sqft\" column=\"store_sqft\" type=\"Numeric\" />" + " <Property name=\"Grocery Sqft\" column=\"grocery_sqft\" type=\"Numeric\" />" + " <Property name=\"Frozen Sqft\" column=\"frozen_sqft\" type=\"Numeric\" />" + " <Property name=\"Meat Sqft\" column=\"meat_sqft\" type=\"Numeric\" />" + " <Property name=\"Has coffee bar\" column=\"coffee_bar\" type=\"Boolean\" />" + " <Property name=\"Street address\" column=\"store_street_address\" type=\"String\" />" + " </Level>" + " </Hierarchy>" + " </Dimension>" + " <Cube name=\"Sales\" defaultMeasure=\"Unit Sales\">" + " <Table name=\"sales_fact_1997\" />" + " <DimensionUsage name=\"Store\" source=\"Store\" foreignKey=\"store_id\" />" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\" formatString=\"Standard\" />" + " <CalculatedMember name=\"dummyMeasure\" dimension=\"Measures\">" + " <Formula>1</Formula>" + " </CalculatedMember>" + " </Cube>" + " <VirtualCube defaultMeasure=\"dummyMeasure\" name=\"virtual\">" + " <VirtualCubeDimension name=\"Store\" />" + " <VirtualCubeMeasure cubeName=\"Sales\" name=\"[Measures].[Unit Sales]\" />" + " <VirtualCubeMeasure name=\"[Measures].[dummyMeasure]\" cubeName=\"Sales\" />" + " </VirtualCube>" + "</Schema>"); context.assertQueryReturns( "select " + " [Measures].[Unit Sales] on COLUMNS, " + " NON EMPTY {[Store].[Store State].Members} ON ROWS " + " from [virtual] ", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Store].[USA].[CA]}\n" + "{[Store].[USA].[OR]}\n" + "{[Store].[USA].[WA]}\n" + "Row #0: 74,748\n" + "Row #1: 67,659\n" + "Row #2: 124,366\n"); } public void testExpandNonNativeWithEnableNativeCrossJoin() { final MondrianProperties mondrianProperties = MondrianProperties.instance(); propSaver.set(mondrianProperties.EnableNativeCrossJoin, true); propSaver.set(mondrianProperties.ExpandNonNative, true); String mdx = "select NON EMPTY {[Measures].[Unit Sales]} ON COLUMNS," + " NON EMPTY Crossjoin(Hierarchize(Crossjoin({[Store].[All Stores]}, Crossjoin({[Store Size in SQFT].[All Store Size in SQFTs]}, Crossjoin({[Store Type].[All Store Types]}, Union(Crossjoin({[Time].[1997]}, {[Product].[All Products]}), Crossjoin({[Time].[1997]}, [Product].[All Products].Children)))))), {([Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes])}) ON ROWS" + " from [Sales]"; assertQueryReturns( mdx, "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997], [Product].[All Products], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997], [Product].[Drink], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997], [Product].[Food], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "{[Store].[All Stores], [Store Size in SQFT].[All Store Size in SQFTs], [Store Type].[All Store Types], [Time].[1997], [Product].[Non-Consumable], [Promotion Media].[All Media], [Promotions].[All Promotions], [Customers].[All Customers], [Education Level].[All Education Levels], [Gender].[All Gender], [Marital Status].[All Marital Status], [Yearly Income].[All Yearly Incomes]}\n" + "Row #0: 266,773\n" + "Row #1: 24,597\n" + "Row #2: 191,940\n" + "Row #3: 50,236\n"); } public void testNonEmptyCJWithMultiPositionSlicer() { final String mdx = "select NON EMPTY NonEmptyCrossJoin([Measures].[Sales Count], [Store].[USA].Children) ON COLUMNS, " + " NON EMPTY CrossJoin({[Customers].[All Customers]}, {([Promotions].[Bag Stuffers] : [Promotions].[Bye Bye Baby])}) ON ROWS " + "from [Sales Ragged] " + "where ({[Product].[Drink]} * {[Time].[1997].[Q1], [Time].[1997].[Q2]})"; final String expected = "Axis + "{[Product].[Drink], [Time].[1997].[Q1]}\n" + "{[Product].[Drink], [Time].[1997].[Q2]}\n" + "Axis + "{[Measures].[Sales Count], [Store].[USA].[CA]}\n" + "{[Measures].[Sales Count], [Store].[USA].[USA].[Washington]}\n" + "{[Measures].[Sales Count], [Store].[USA].[WA]}\n" + "Axis + "{[Customers].[All Customers], [Promotions].[Bag Stuffers]}\n" + "{[Customers].[All Customers], [Promotions].[Best Savings]}\n" + "{[Customers].[All Customers], [Promotions].[Big Promo]}\n" + "{[Customers].[All Customers], [Promotions].[Big Time Savings]}\n" + "{[Customers].[All Customers], [Promotions].[Bye Bye Baby]}\n" + "Row #0: \n" + "Row #0: \n" + "Row #0: 2\n" + "Row #1: \n" + "Row #1: \n" + "Row #1: 13\n" + "Row #2: \n" + "Row #2: \n" + "Row #2: 9\n" + "Row #3: \n" + "Row #3: 12\n" + "Row #3: \n" + "Row #4: 1\n" + "Row #4: 21\n" + "Row #4: \n"; propSaver.set( MondrianProperties.instance().EnableNativeCrossJoin, true); propSaver.set( MondrianProperties.instance().ExpandNonNative, true); // Get a fresh connection; Otherwise the mondrian property setting // is not refreshed for this parameter. checkNative( 0, 5, mdx, expected, true); } void clearAndHardenCache(MemberCacheHelper helper) { helper.mapLevelToMembers.setCache( new HardSmartCache<Pair<RolapLevel, Object>, List<RolapMember>>()); helper.mapMemberToChildren.setCache( new HardSmartCache<Pair<RolapMember, Object>, List<RolapMember>>()); helper.mapKeyToMember.clear(); } SmartMemberReader getSmartMemberReader(String hierName) { Connection con = getTestContext().getConnection(); return getSmartMemberReader(con, hierName); } SmartMemberReader getSmartMemberReader(Connection con, String hierName) { RolapCube cube = (RolapCube) con.getSchema().lookupCube("Sales", true); RolapSchemaReader schemaReader = (RolapSchemaReader) cube.getSchemaReader(); RolapHierarchy hierarchy = (RolapHierarchy) cube.lookupHierarchy( new Id.NameSegment(hierName, Id.Quoting.UNQUOTED), false); assertNotNull(hierarchy); return (SmartMemberReader) hierarchy.createMemberReader(schemaReader.getRole()); } SmartMemberReader getSharedSmartMemberReader(String hierName) { Connection con = getTestContext().getConnection(); return getSharedSmartMemberReader(con, hierName); } SmartMemberReader getSharedSmartMemberReader( Connection con, String hierName) { RolapCube cube = (RolapCube) con.getSchema().lookupCube("Sales", true); RolapSchemaReader schemaReader = (RolapSchemaReader) cube.getSchemaReader(); RolapCubeHierarchy hierarchy = (RolapCubeHierarchy) cube.lookupHierarchy( new Id.NameSegment(hierName, Id.Quoting.UNQUOTED), false); assertNotNull(hierarchy); return (SmartMemberReader) hierarchy.getRolapHierarchy() .createMemberReader(schemaReader.getRole()); } RolapEvaluator getEvaluator(Result res, int[] pos) { while (res instanceof NonEmptyResult) { res = ((NonEmptyResult) res).underlying; } return (RolapEvaluator) ((RolapResult) res).getEvaluator(pos); } public void testFilterChildlessSnowflakeMembers2() { if (MondrianProperties.instance().FilterChildlessSnowflakeMembers.get()) { // If FilterChildlessSnowflakeMembers is true, then // [Product].[Drink].[Baking Goods].[Coffee] does not even exist! return; } // children across a snowflake boundary assertQueryReturns( "select [Product].[Drink].[Baking Goods].[Dry Goods].[Coffee].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis } public void testFilterChildlessSnowflakeMembers() { propSaver.set( MondrianProperties.instance().FilterChildlessSnowflakeMembers, false); SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.MYSQL, "select `product_class`.`product_family` as `c0` " + "from `product_class` as `product_class` " + "group by `product_class`.`product_family` " + "order by ISNULL(`product_class`.`product_family`) ASC," + " `product_class`.`product_family` ASC", null) }; final TestContext context = getTestContext().withFreshConnection(); try { assertQuerySql( context, "select [Product].[Product Family].Members on 0\n" + "from [Sales]", patterns); // note that returns an extra member, // [Product].[Drink].[Baking Goods] context.assertQueryReturns( "select [Product].[Drink].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Product].[Drink].[Alcoholic Beverages]}\n" + "{[Product].[Drink].[Baking Goods]}\n" + "{[Product].[Drink].[Beverages]}\n" + "{[Product].[Drink].[Dairy]}\n" + "Row #0: 6,838\n" + "Row #0: \n" + "Row #0: 13,573\n" + "Row #0: 4,186\n"); // [Product].[Drink].[Baking Goods] has one child, but no fact data context.assertQueryReturns( "select [Product].[Drink].[Baking Goods].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Product].[Drink].[Baking Goods].[Dry Goods]}\n" + "Row #0: \n"); // NON EMPTY filters out that child context.assertQueryReturns( "select non empty [Product].[Drink].[Baking Goods].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis // [Product].[Drink].[Baking Goods].[Dry Goods] has one child, but // no fact data context.assertQueryReturns( "select [Product].[Drink].[Baking Goods].[Dry Goods].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Product].[Drink].[Baking Goods].[Dry Goods].[Coffee]}\n" + "Row #0: \n"); // NON EMPTY filters out that child context.assertQueryReturns( "select non empty [Product].[Drink].[Baking Goods].[Dry Goods].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis // [Coffee] has no children context.assertQueryReturns( "select [Product].[Drink].[Baking Goods].[Dry Goods].[Coffee].Children on 0\n" + "from [Sales]", "Axis + "{}\n" + "Axis context.assertQueryReturns( "select [Measures].[Unit Sales] on 0,\n" + " [Product].[Product Family].Members on 1\n" + "from [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Unit Sales]}\n" + "Axis + "{[Product].[Drink]}\n" + "{[Product].[Food]}\n" + "{[Product].[Non-Consumable]}\n" + "Row #0: 24,597\n" + "Row #1: 191,940\n" + "Row #2: 50,236\n"); } finally { context.close(); } } public void testBugMondrian897DoubleNamedSetDefinitions() { TestContext ctx = getTestContext(); ctx.assertQueryReturns( "WITH SET [CustomerSet] as {[Customers].[Canada].[BC].[Burnaby].[Alexandra Wellington], [Customers].[USA].[WA].[Tacoma].[Eric Coleman]} " + "SET [InterestingCustomers] as [CustomerSet] " + "SET [TimeRange] as {[Time].[1998].[Q1], [Time].[1998].[Q2]} " + "SELECT {[Measures].[Store Sales]} ON COLUMNS, " + "CrossJoin([InterestingCustomers], [TimeRange]) ON ROWS " + "FROM [Sales]", "Axis + "{}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Customers].[Canada].[BC].[Burnaby].[Alexandra Wellington], [Time].[1998].[Q1]}\n" + "{[Customers].[Canada].[BC].[Burnaby].[Alexandra Wellington], [Time].[1998].[Q2]}\n" + "{[Customers].[USA].[WA].[Tacoma].[Eric Coleman], [Time].[1998].[Q1]}\n" + "{[Customers].[USA].[WA].[Tacoma].[Eric Coleman], [Time].[1998].[Q2]}\n" + "Row #0: \n" + "Row #1: \n" + "Row #2: \n" + "Row #3: \n"); } public void testMondrian1133() { propSaver.set( propSaver.properties.UseAggregates, false); propSaver.set( propSaver.properties.ReadAggregates, false); propSaver.set( propSaver.properties.GenerateFormattedSql, true); final String schema = "<?xml version=\"1.0\"?>\n" + "<Schema name=\"custom\">\n" + " <Dimension name=\"Store\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store State\" column=\"store_state\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store City\" column=\"store_city\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Store Name\" column=\"store_name\" uniqueMembers=\"true\">\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Time\" type=\"TimeDimension\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"time_id\">\n" + " <Table name=\"time_by_day\"/>\n" + " <Level name=\"Year\" column=\"the_year\" type=\"Numeric\" uniqueMembers=\"true\"\n" + " levelType=\"TimeYears\"/>\n" + " <Level name=\"Quarter\" column=\"quarter\" uniqueMembers=\"false\"\n" + " levelType=\"TimeQuarters\"/>\n" + " <Level name=\"Month\" column=\"month_of_year\" uniqueMembers=\"false\" type=\"Numeric\"\n" + " levelType=\"TimeMonths\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Cube name=\"Sales1\" defaultMeasure=\"Unit Sales\">\n" + " <Table name=\"sales_fact_1997\">\n" + " <AggExclude name=\"agg_c_special_sales_fact_1997\" />" + " </Table>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\" + " </Cube>\n" + "<Role name=\"Role1\">\n" + " <SchemaGrant access=\"none\">\n" + " <CubeGrant cube=\"Sales1\" access=\"all\">\n" + " <HierarchyGrant hierarchy=\"[Time]\" access=\"custom\" rollupPolicy=\"partial\">\n" + " <MemberGrant member=\"[Time].[Year].[1997]\" access=\"all\"/>\n" + " </HierarchyGrant>\n" + " </CubeGrant>\n" + " </SchemaGrant>\n" + "</Role> \n" + "</Schema>\n"; final String query = "With\n" + "Set [*BASE_MEMBERS_Product] as 'Filter([Store].[Store State].Members,[Store].CurrentMember.Caption Matches (\"(?i).*CA.*\"))'\n" + "Select\n" + "[*BASE_MEMBERS_Product] on columns\n" + "From [Sales1] \n"; final String mysql = "select\n" + " `store`.`store_country` as `c0`,\n" + " `store`.`store_state` as `c1`\n" + "from\n" + " `store` as `store`\n" + "group by\n" + " `store`.`store_country`,\n" + " `store`.`store_state`\n" + "having\n" + " UPPER(c1) REGEXP '.*CA.*'\n" + "order by\n" + " ISNULL(`store`.`store_country`) ASC, `store`.`store_country` ASC,\n" + " ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC"; final String mysqlWithRoles = "select\n" + " `store`.`store_country` as `c0`,\n" + " `store`.`store_state` as `c1`\n" + "from\n" + " `store` as `store`,\n" + " `sales_fact_1997` as `sales_fact_1997`,\n" + " `time_by_day` as `time_by_day`\n" + "where\n" + " `sales_fact_1997`.`store_id` = `store`.`store_id`\n" + "and\n" + " `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`\n" + "and\n" + " `time_by_day`.`the_year` = 1997\n" + "group by\n" + " `store`.`store_country`,\n" + " `store`.`store_state`\n" + "having\n" + " UPPER(c1) REGEXP '.*CA.*'\n" + "order by\n" + " ISNULL(`store`.`store_country`) ASC, `store`.`store_country` ASC,\n" + " ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC"; final String oracle = "select\n" + " \"store\".\"store_country\" as \"c0\",\n" + " \"store\".\"store_state\" as \"c1\"\n" + "from\n" + " \"store\" \"store\"\n" + "group by\n" + " \"store\".\"store_country\",\n" + " \"store\".\"store_state\"\n" + "having\n" + " REGEXP_LIKE(\"store\".\"store_state\", '.*CA.*', 'i')\n" + "order by\n" + " \"store\".\"store_country\" ASC NULLS LAST,\n" + " \"store\".\"store_state\" ASC NULLS LAST"; final String oracleWithRoles = "select\n" + " \"store\".\"store_country\" as \"c0\",\n" + " \"store\".\"store_state\" as \"c1\"\n" + "from\n" + " \"store\" \"store\",\n" + " \"sales_fact_1997\" \"sales_fact_1997\",\n" + " \"time_by_day\" \"time_by_day\"\n" + "where\n" + " \"sales_fact_1997\".\"store_id\" = \"store\".\"store_id\"\n" + "and\n" + " \"sales_fact_1997\".\"time_id\" = \"time_by_day\".\"time_id\"\n" + "and\n" + " \"time_by_day\".\"the_year\" = 1997\n" + "group by\n" + " \"store\".\"store_country\",\n" + " \"store\".\"store_state\"\n" + "having\n" + " REGEXP_LIKE(\"store\".\"store_state\", '.*CA.*', 'i')\n" + "order by\n" + " \"store\".\"store_country\" ASC NULLS LAST,\n" + " \"store\".\"store_state\" ASC NULLS LAST"; final SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.MYSQL, mysql, mysql), new SqlPattern( Dialect.DatabaseProduct.ORACLE, oracle, oracle) }; final SqlPattern[] patternsWithRoles = { new SqlPattern( Dialect.DatabaseProduct.MYSQL, mysqlWithRoles, mysqlWithRoles), new SqlPattern( Dialect.DatabaseProduct.ORACLE, oracleWithRoles, oracleWithRoles) }; final TestContext context = TestContext.instance().withSchema(schema); // Actual tests. assertQuerySql(context, query, patterns); // Roles must join to the fact table or it will create // a cross join. assertQuerySql(context.withRole("Role1"), query, patternsWithRoles); } public void testMondrian1133WithAggs() { propSaver.set( propSaver.properties.UseAggregates, true); propSaver.set( propSaver.properties.ReadAggregates, true); propSaver.set( propSaver.properties.GenerateFormattedSql, true); final String schema = "<?xml version=\"1.0\"?>\n" + "<Schema name=\"custom\">\n" + " <Dimension name=\"Store\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"store_id\">\n" + " <Table name=\"store\"/>\n" + " <Level name=\"Store Country\" column=\"store_country\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store State\" column=\"store_state\" uniqueMembers=\"true\"/>\n" + " <Level name=\"Store City\" column=\"store_city\" uniqueMembers=\"false\"/>\n" + " <Level name=\"Store Name\" column=\"store_name\" uniqueMembers=\"true\">\n" + " </Level>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Dimension name=\"Time\" type=\"TimeDimension\">\n" + " <Hierarchy hasAll=\"true\" primaryKey=\"time_id\">\n" + " <Table name=\"time_by_day\"/>\n" + " <Level name=\"Year\" column=\"the_year\" type=\"Numeric\" uniqueMembers=\"true\"\n" + " levelType=\"TimeYears\"/>\n" + " <Level name=\"Quarter\" column=\"quarter\" uniqueMembers=\"false\"\n" + " levelType=\"TimeQuarters\"/>\n" + " <Level name=\"Month\" column=\"month_of_year\" uniqueMembers=\"false\" type=\"Numeric\"\n" + " levelType=\"TimeMonths\"/>\n" + " </Hierarchy>\n" + " </Dimension>\n" + " <Cube name=\"Sales1\" defaultMeasure=\"Unit Sales\">\n" + " <Table name=\"sales_fact_1997\">\n" + " <AggExclude name=\"agg_c_special_sales_fact_1997\" />" + " </Table>\n" + " <DimensionUsage name=\"Store\" source=\"Store\" foreignKey=\"store_id\"/>\n" + " <DimensionUsage name=\"Time\" source=\"Time\" foreignKey=\"time_id\"/>\n" + " <Measure name=\"Unit Sales\" column=\"unit_sales\" aggregator=\"sum\"\n" + " formatString=\"Standard\"/>\n" + " <Measure name=\"Store Cost\" column=\"store_cost\" aggregator=\"sum\"\n" + " formatString=\" + " <Measure name=\"Store Sales\" column=\"store_sales\" aggregator=\"sum\"\n" + " formatString=\" + " </Cube>\n" + "<Role name=\"Role1\">\n" + " <SchemaGrant access=\"none\">\n" + " <CubeGrant cube=\"Sales1\" access=\"all\">\n" + " <HierarchyGrant hierarchy=\"[Time]\" access=\"custom\" rollupPolicy=\"partial\">\n" + " <MemberGrant member=\"[Time].[Year].[1997]\" access=\"all\"/>\n" + " </HierarchyGrant>\n" + " </CubeGrant>\n" + " </SchemaGrant>\n" + "</Role> \n" + "</Schema>\n"; final String query = "With\n" + "Set [*BASE_MEMBERS_Product] as 'Filter([Store].[Store State].Members,[Store].CurrentMember.Caption Matches (\"(?i).*CA.*\"))'\n" + "Select\n" + "[*BASE_MEMBERS_Product] on columns\n" + "From [Sales1] \n"; final String mysql = "select\n" + " `store`.`store_country` as `c0`,\n" + " `store`.`store_state` as `c1`\n" + "from\n" + " `store` as `store`\n" + "group by\n" + " `store`.`store_country`,\n" + " `store`.`store_state`\n" + "having\n" + " UPPER(c1) REGEXP '.*CA.*'\n" + "order by\n" + " ISNULL(`store`.`store_country`) ASC, `store`.`store_country` ASC,\n" + " ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC"; final String mysqlWithRoles = "select\n" + " `store`.`store_country` as `c0`,\n" + " `store`.`store_state` as `c1`\n" + "from\n" + " `store` as `store`,\n" + " `agg_c_14_sales_fact_1997` as `agg_c_14_sales_fact_1997`\n" + "where\n" + " `agg_c_14_sales_fact_1997`.`store_id` = `store`.`store_id`\n" + "and\n" + " `agg_c_14_sales_fact_1997`.`the_year` = 1997\n" + "group by\n" + " `store`.`store_country`,\n" + " `store`.`store_state`\n" + "having\n" + " UPPER(c1) REGEXP '.*CA.*'\n" + "order by\n" + " ISNULL(`store`.`store_country`) ASC, `store`.`store_country` ASC,\n" + " ISNULL(`store`.`store_state`) ASC, `store`.`store_state` ASC"; final String oracle = "select\n" + " \"store\".\"store_country\" as \"c0\",\n" + " \"store\".\"store_state\" as \"c1\"\n" + "from\n" + " \"store\" \"store\"\n" + "group by\n" + " \"store\".\"store_country\",\n" + " \"store\".\"store_state\"\n" + "having\n" + " REGEXP_LIKE(\"store\".\"store_state\", '.*CA.*', 'i')\n" + "order by\n" + " \"store\".\"store_country\" ASC NULLS LAST,\n" + " \"store\".\"store_state\" ASC NULLS LAST"; final String oracleWithRoles = "select\n" + " \"store\".\"store_country\" as \"c0\",\n" + " \"store\".\"store_state\" as \"c1\"\n" + "from\n" + " \"store\" \"store\",\n" + " \"agg_c_14_sales_fact_1997\" \"agg_c_14_sales_fact_1997\"\n" + "where\n" + " \"agg_c_14_sales_fact_1997\".\"store_id\" = \"store\".\"store_id\"\n" + "and\n" + " \"agg_c_14_sales_fact_1997\".\"the_year\" = 1997\n" + "group by\n" + " \"store\".\"store_country\",\n" + " \"store\".\"store_state\"\n" + "having\n" + " REGEXP_LIKE(\"store\".\"store_state\", '.*CA.*', 'i')\n" + "order by\n" + " \"store\".\"store_country\" ASC NULLS LAST,\n" + " \"store\".\"store_state\" ASC NULLS LAST"; final SqlPattern[] patterns = { new SqlPattern( Dialect.DatabaseProduct.MYSQL, mysql, mysql), new SqlPattern( Dialect.DatabaseProduct.ORACLE, oracle, oracle) }; final SqlPattern[] patternsWithRoles = { new SqlPattern( Dialect.DatabaseProduct.MYSQL, mysqlWithRoles, mysqlWithRoles), new SqlPattern( Dialect.DatabaseProduct.ORACLE, oracleWithRoles, oracleWithRoles) }; final TestContext context = TestContext.instance().withSchema(schema); // Actual tests. assertQuerySql(context, query, patterns); // Roles must join to the fact table or it will create // a cross join. assertQuerySql(context.withRole("Role1"), query, patternsWithRoles); } /** * Native CrossJoin with a ranged slicer. */ public void testNonEmptyAggregateSlicerIsNative() { final String mdx = "select NON EMPTY\n" + " Crossjoin([Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth]\n" + " , [Customers].[USA].[WA].[Puyallup].Children) ON COLUMNS\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q2].[5])"; propSaver.set(propSaver.properties.GenerateFormattedSql, true); String mysqlNativeCrossJoinQuery = "select\n" + " `time_by_day`.`the_year` as `c0`,\n" + " `time_by_day`.`quarter` as `c1`,\n" + " `time_by_day`.`month_of_year` as `c2`,\n" + " `product_class`.`product_family` as `c3`,\n" + " `product_class`.`product_department` as `c4`,\n" + " `product_class`.`product_category` as `c5`,\n" + " `product_class`.`product_subcategory` as `c6`,\n" + " `product`.`brand_name` as `c7`,\n" + " `customer`.`customer_id` as `c8`,\n" + " sum(`sales_fact_1997`.`unit_sales`) as `m0`\n" + "from\n" + " `time_by_day` as `time_by_day`,\n" + " `sales_fact_1997` as `sales_fact_1997`,\n" + " `product_class` as `product_class`,\n" + " `product` as `product`,\n" + " `customer` as `customer`\n" + "where\n" + " `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`\n" + "and\n" + " `time_by_day`.`the_year` = 1997\n" + "and\n" + " `time_by_day`.`quarter` in ('Q1', 'Q2')\n" + "and\n" + " `time_by_day`.`month_of_year` in (2, 3, 4, 5)\n" + "and\n" + " `sales_fact_1997`.`product_id` = `product`.`product_id`\n" + "and\n" + " `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "and\n" + " `product_class`.`product_family` = 'Drink'\n" + "and\n" + " `product_class`.`product_department` = 'Alcoholic Beverages'\n" + "and\n" + " `product_class`.`product_category` = 'Beer and Wine'\n" + "and\n" + " `product_class`.`product_subcategory` = 'Beer'\n" + "and\n" + " `product`.`brand_name` = 'Portsmouth'\n" + "and\n" + " `sales_fact_1997`.`customer_id` = `customer`.`customer_id`\n" + "and\n" + " `customer`.`customer_id` = 5219\n" + "group by\n" + " `time_by_day`.`the_year`,\n" + " `time_by_day`.`quarter`,\n" + " `time_by_day`.`month_of_year`,\n" + " `product_class`.`product_family`,\n" + " `product_class`.`product_department`,\n" + " `product_class`.`product_category`,\n" + " `product_class`.`product_subcategory`,\n" + " `product`.`brand_name`,\n" + " `customer`.`customer_id`"; String triggerSql = "select\n" + " `time_by_day`.`the_year` as `c0`,\n" + " `time_by_day`.`quarter` as `c1`,\n" + " `time_by_day`.`month_of_year` as `c2`,\n" + " `product_class`.`product_family` as `c3`,\n"; if (MondrianProperties.instance().UseAggregates.get() && MondrianProperties.instance().ReadAggregates.get()) { mysqlNativeCrossJoinQuery = "select\n" + " `agg_c_14_sales_fact_1997`.`the_year` as `c0`,\n" + " `agg_c_14_sales_fact_1997`.`quarter` as `c1`,\n" + " `agg_c_14_sales_fact_1997`.`month_of_year` as `c2`,\n" + " `product_class`.`product_family` as `c3`,\n" + " `product_class`.`product_department` as `c4`,\n" + " `product_class`.`product_category` as `c5`,\n" + " `product_class`.`product_subcategory` as `c6`,\n" + " `product`.`brand_name` as `c7`,\n" + " `customer`.`customer_id` as `c8`,\n" + " sum(`agg_c_14_sales_fact_1997`.`unit_sales`) as `m0`\n" + "from\n" + " `agg_c_14_sales_fact_1997` as `agg_c_14_sales_fact_1997`,\n" + " `product_class` as `product_class`,\n" + " `product` as `product`,\n" + " `customer` as `customer`\n" + "where\n" + " `agg_c_14_sales_fact_1997`.`the_year` = 1997\n" + "and\n" + " `agg_c_14_sales_fact_1997`.`quarter` in ('Q1', 'Q2')\n" + "and\n" + " `agg_c_14_sales_fact_1997`.`month_of_year` in (2, 3, 4, 5)\n" + "and\n" + " `agg_c_14_sales_fact_1997`.`product_id` = `product`.`product_id`\n" + "and\n" + " `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "and\n" + " `product_class`.`product_family` = 'Drink'\n" + "and\n" + " `product_class`.`product_department` = 'Alcoholic Beverages'\n" + "and\n" + " `product_class`.`product_category` = 'Beer and Wine'\n" + "and\n" + " `product_class`.`product_subcategory` = 'Beer'\n" + "and\n" + " `product`.`brand_name` = 'Portsmouth'\n" + "and\n" + " `agg_c_14_sales_fact_1997`.`customer_id` = `customer`.`customer_id`\n" + "and\n" + " `customer`.`customer_id` = 5219\n" + "group by\n" + " `agg_c_14_sales_fact_1997`.`the_year`,\n" + " `agg_c_14_sales_fact_1997`.`quarter`,\n" + " `agg_c_14_sales_fact_1997`.`month_of_year`,\n" + " `product_class`.`product_family`,\n" + " `product_class`.`product_department`,\n" + " `product_class`.`product_category`,\n" + " `product_class`.`product_subcategory`,\n" + " `product`.`brand_name`,\n" + " `customer`.`customer_id`"; triggerSql = "select\n" + " `agg_c_14_sales_fact_1997`.`the_year` as `c0`,\n" + " `agg_c_14_sales_fact_1997`.`quarter` as `c1`,\n" + " `agg_c_14_sales_fact_1997`.`month_of_year` as `c2`,\n" + " `product_class`.`product_family` as `c3`,\n"; } SqlPattern mysqlPattern = new SqlPattern( DatabaseProduct.MYSQL, mysqlNativeCrossJoinQuery, triggerSql); assertQuerySql(mdx, new SqlPattern[]{mysqlPattern}); checkNative( 20, 1, "select NON EMPTY\n" + " Crossjoin([Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth]\n" + " , [Customers].[USA].[WA].[Puyallup].Children) ON COLUMNS\n" + "from [Sales]\n" + "where ([Time].[1997].[Q1].[2] : [Time].[1997].[Q2].[5])", "Axis + "{[Time].[1997].[Q1].[2]}\n" + "{[Time].[1997].[Q1].[3]}\n" + "{[Time].[1997].[Q2].[4]}\n" + "{[Time].[1997].[Q2].[5]}\n" + "Axis + "{[Product].[Drink].[Alcoholic Beverages].[Beer and Wine].[Beer].[Portsmouth], [Customers].[USA].[WA].[Puyallup].[Diane Biondo]}\n" + "Row #0: 2\n", true); } } // End NonEmptyTest.java
package org.mockito.internal.invocation; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; import org.mockitoutil.TestBase; public class SerializableMockitoMethodTest extends TestBase { private SerializableMockitoMethod mockMethod; private Method toStringMethod; private Class<?>[] args; @Before public void createMethodToTestWith() throws SecurityException, NoSuchMethodException { args = new Class<?>[0]; toStringMethod = this.getClass().getMethod("toString", args); mockMethod = new SerializableMockitoMethod(toStringMethod); } @Test public void shouldBeSerializable() throws Exception { ByteArrayOutputStream serialized = new ByteArrayOutputStream(); new ObjectOutputStream(serialized).writeObject(mockMethod); } @Test public void shouldBeAbleToRetrieveMethodExceptionTypes() throws Exception { assertArrayEquals(toStringMethod.getExceptionTypes(), mockMethod.getExceptionTypes()); } @Test public void shouldBeAbleToRetrieveMethodName() throws Exception { assertEquals(toStringMethod.getName(), mockMethod.getName()); } @Test public void shouldBeAbleToCheckIsArgVargs() throws Exception { assertEquals(toStringMethod.isVarArgs(), mockMethod.isVarArgs()); } @Test public void shouldBeAbleToGetParameterTypes() throws Exception { assertArrayEquals(toStringMethod.getParameterTypes(), mockMethod.getParameterTypes()); } @Test public void shouldBeAbleToGetReturnType() throws Exception { assertEquals(toStringMethod.getReturnType(), mockMethod.getReturnType()); } @Test public void shouldBeEqualForTwoInstances() throws Exception { assertTrue(new SerializableMockitoMethod(toStringMethod).equals(mockMethod)); } @Test public void shouldNotBeEqualForSameMethodFromTwoDifferentClasses() throws Exception { Method testBaseToStringMethod = String.class.getMethod("toString", args); assertFalse(new SerializableMockitoMethod(testBaseToStringMethod).equals(mockMethod)); } //TODO: add tests for generated equals() method }
package net.jforum.api.integration.mail.pop; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Date; import java.util.List; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import junit.framework.TestCase; import net.jforum.ConfigLoader; import net.jforum.ForumStartup; import net.jforum.JForumExecutionContext; import net.jforum.TestCaseUtils; import net.jforum.dao.DataAccessDriver; import net.jforum.dao.PostDAO; import net.jforum.dao.TopicDAO; import net.jforum.entities.Post; import net.jforum.entities.Topic; import net.jforum.entities.User; import net.jforum.repository.RankingRepository; import net.jforum.repository.SmiliesRepository; import net.jforum.util.DbUtils; import net.jforum.util.preferences.ConfigKeys; import net.jforum.util.preferences.SystemGlobals; /** * @author Rafael Steil * @version $Id: POPListenerTestCase.java,v 1.11 2006/09/26 03:23:35 rafaelsteil Exp $ */ public class POPListenerTestCase extends TestCase { private static boolean started; /** * A single and simple message */ public void testSimple() throws Exception { int beforeTopicId = this.maxTopicId(); String sender = "ze@zinho.com"; String subject = "Mail Message " + new Date(); String forumAddress = "forum_test@jforum.testcase"; String contents = "Mail message contents " + new Date(); this.sendMessage(sender, subject, forumAddress, contents, null); int afterTopicId = this.maxTopicId(); assertTrue("The message was not inserted", afterTopicId > beforeTopicId); try { this.assertPost(afterTopicId, sender, subject, contents); } finally { this.deleteTopic(afterTopicId); } } /** * Sends an invalid In-Reply-To header, which should cause the system * to create a new topic, instead of adding the message as a reply * to something else. */ public void testInReplyToIncorrectShouldCreateNewTopic() throws Exception { int beforeTopicId = this.maxTopicId(); String sender = "ze@zinho.com"; String subject = "Mail Message " + new Date(); String forumAddress = "forum_test@jforum.testcase"; String contents = "Mail message contents " + new Date(); this.sendMessage(sender, subject, forumAddress, contents, InReplyTo.build(999999, 888888)); int afterTopicId = this.maxTopicId(); assertTrue("The message was not inserted", afterTopicId > beforeTopicId); try { this.assertPost(afterTopicId, sender, subject, contents); } finally { this.deleteTopic(afterTopicId); } } /** * Create a new topic, then send a message with the In-Reply-To header, * which should create an answer to the previously created topic * @throws Exception */ public void testInReplyToCreateNewTopicThenReply() throws Exception { int beforeTopicId = this.maxTopicId(); String sender = "ze@zinho.com"; String subject = "Mail Message " + new Date(); String forumAddress = "forum_test@jforum.testcase"; String contents = "Mail message contents " + new Date(); this.sendMessage(sender, subject, forumAddress, contents, null); int afterTopicId = this.maxTopicId(); assertTrue("The message was not inserted", afterTopicId > beforeTopicId); try { this.assertPost(afterTopicId, sender, subject, contents); // Ok, now send a new message, replying to the previously topic subject = "Reply subject for topic " + afterTopicId; contents = "Changed contents, replying tpoic " + afterTopicId; this.sendMessage(sender, subject, forumAddress, contents, InReplyTo.build(afterTopicId, 999999)); assertTrue("A new message was created, instead of a reply", afterTopicId == maxTopicId()); PostDAO postDAO = DataAccessDriver.getInstance().newPostDAO(); List posts = postDAO.selectAllByTopic(afterTopicId); assertTrue("There should be two posts", posts.size() == 2); // The first message was already validated Post p = (Post)posts.get(1); User user = DataAccessDriver.getInstance().newUserDAO().selectById(p.getUserId()); assertNotNull("User should not be null", user); assertEquals("sender", sender, user.getEmail()); assertEquals("subject", subject, p.getSubject()); assertEquals("text", contents, p.getText()); } finally { this.deleteTopic(afterTopicId); } } private void sendMessage(String sender, String subject, String forumAddress, String contents, String inReplyTo) throws Exception { POPListener listener = new POPListenerMock(); MimeMessageMock message = this.newMessageMock(sender, subject, forumAddress, contents); if (inReplyTo != null) { message.addHeader("In-Reply-To", inReplyTo); } ((POPConnectorMock)listener.getConnector()).setMessages(new Message[] { message }); listener.execute(null); } /** * Asserts the post instance, after execution some part of the testcase * @param topicId the topic's id of the new message * @param sender the matching sender email * @param subject the matching subject * @param contents the matching message contents */ private void assertPost(int topicId, String sender, String subject, String contents) { PostDAO postDAO = DataAccessDriver.getInstance().newPostDAO(); List posts = postDAO.selectAllByTopic(topicId); assertTrue("There should be exactly one post", posts.size() == 1); Post p = (Post)posts.get(0); User user = DataAccessDriver.getInstance().newUserDAO().selectById(p.getUserId()); assertNotNull("User should not be null", user); assertEquals("sender", sender, user.getEmail()); assertEquals("subject", subject, p.getSubject()); assertEquals("text", contents, p.getText()); } /** * Gets the latest topic id existent * @return the topic id, or -1 if something went wrong * @throws Exception */ private int maxTopicId() throws Exception { int topicId = -1; PreparedStatement p = null; ResultSet rs = null; try { p = JForumExecutionContext.getConnection().prepareStatement("select max(topic_id) from jforum_topics"); rs = p.executeQuery(); if (rs.next()) { topicId = rs.getInt(1); } } finally { DbUtils.close(rs, p); } return topicId; } /** * Deletes a topic * @param topicId the topic's id to delete */ private void deleteTopic(int topicId) { try { TopicDAO dao = DataAccessDriver.getInstance().newTopicDAO(); Topic t = new Topic(topicId); t.setForumId(2); dao.delete(t); JForumExecutionContext.finish(); } catch (Exception e) { e.printStackTrace(); } } private MimeMessageMock newMessageMock(String sender, String subject, String listEmail, String text) throws Exception { MimeMessageMock m = new MimeMessageMock(null, new ByteArrayInputStream(text.getBytes())); m.setFrom(new InternetAddress(sender)); m.setRecipient(RecipientType.TO, new InternetAddress(listEmail)); m.setSubject(subject); return m; } /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { if (!started) { TestCaseUtils.loadEnvironment(); TestCaseUtils.initDatabaseImplementation(); ConfigLoader.startCacheEngine(); ForumStartup.startForumRepository(); RankingRepository.loadRanks(); SmiliesRepository.loadSmilies(); SystemGlobals.setValue(ConfigKeys.SEARCH_INDEXING_ENABLED, "false"); started = true; } } private static class MimeMessageMock extends MimeMessage { private InputStream is; private String messageId; public MimeMessageMock(Session session, InputStream is) throws MessagingException { super(session, is); this.is = is; } public InputStream getInputStream() throws IOException, MessagingException { return this.is; } protected void updateMessageID() throws MessagingException { if (this.messageId != null) { this.setMessageId(this.messageId); } else { super.updateMessageID(); } } public void setMessageId(String messageId) throws MessagingException { this.addHeader("Message-ID", messageId); this.messageId = messageId; } public String getContentType() throws MessagingException { return "text/plain"; } } }
package org.jgroups.protocols; import org.jgroups.*; import org.jgroups.util.Util; import org.jgroups.protocols.ENCRYPT.EncryptHeader; import org.jgroups.stack.Protocol; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import javax.crypto.Cipher; import java.io.*; import java.security.MessageDigest; import java.security.Security; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Vector; /** * @author xenephon */ @Test(groups=Global.FUNCTIONAL, sequential=false) public class ENCRYPTAsymmetricTest { @BeforeClass public static void initProvider() { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } public static void testInitNoProperties() throws Exception { ENCRYPT encrypt=new ENCRYPT(); encrypt.init(); // test the default asymetric key assert "RSA".equals(encrypt.getAsymAlgorithm()); assert encrypt.getAsymInit() == 512; assert "RSA".equals(encrypt.getKpair().getPublic().getAlgorithm()); assert "X.509".equals(encrypt.getKpair().getPublic().getFormat()); assert encrypt.getKpair().getPublic().getEncoded() != null; // test the default symetric key assert "Blowfish".equals(encrypt.getSymAlgorithm()); assert encrypt.getSymInit() == 56; assert "Blowfish".equals(encrypt.getDesKey().getAlgorithm()); assert "RAW".equals(encrypt.getDesKey().getFormat()); assert encrypt.getDesKey().getEncoded() != null; //test the resulting ciphers System.out.println("Provider:" + encrypt.getAsymCipher().getProvider()); assert encrypt.getAsymCipher() != null; assert encrypt.getSymDecodingCipher() != null; assert encrypt.getSymEncodingCipher() != null; } public static void testInitBCAsymProperties() throws Exception { Properties props=new Properties(); props.put("asym_provider", "BC"); props.put("asym_algorithm", "RSA"); //javax. ENCRYPT encrypt=new ENCRYPT(); encrypt.setProperties(props); encrypt.init(); // test the default asymetric key assert "RSA".equals(encrypt.getAsymAlgorithm()); assert encrypt.getAsymInit() == 512; assert "RSA".equals(encrypt.getKpair().getPublic().getAlgorithm()); //Strangely this returns differently from the default provider for RSA which is also BC! assert "X.509".equals(encrypt.getKpair().getPublic().getFormat()); assert encrypt.getKpair().getPublic().getEncoded() != null; //test the resulting ciphers assert encrypt.getAsymCipher() != null; } /* public static void XtestInitRSABlockAsymProperties() throws Exception { Properties props=new Properties(); props.put("asym_algorithm", "RSA/ECB/OAEPPadding"); ENCRYPT encrypt=new ENCRYPT(); encrypt.setProperties(props); encrypt.init(); // test the default asymetric key Util.assertEquals("RSA/ECB/OAEPPadding", encrypt.getAsymAlgorithm()); Util.assertEquals(512, encrypt.getAsymInit()); Util.assertEquals("RSA", encrypt.getKpair().getPublic().getAlgorithm()); //Strangely this returns differently from the default provider for RSA which is also BC! Util.assertEquals("X509", encrypt.getKpair().getPublic().getFormat()); Util.assertNotNull(encrypt.getKpair().getPublic().getEncoded()); //test the resulting ciphers Util.assertNotNull(encrypt.getAsymCipher()); }*/ public static void testInitIDEAProperties() throws Exception { Properties props=new Properties(); props.put("sym_algorithm", "IDEA"); props.put("sym_init", "128"); ENCRYPT encrypt=new ENCRYPT(); encrypt.setProperties(props); encrypt.init(); // test the default symetric key assert "IDEA".equals(encrypt.getSymAlgorithm()) : "expected IDEA but was " + encrypt.getSymAlgorithm(); Util.assertEquals(128, encrypt.getSymInit()); Util.assertEquals("IDEA", encrypt.getDesKey().getAlgorithm()); Util.assertEquals("RAW", encrypt.getDesKey().getFormat()); Util.assertNotNull(encrypt.getDesKey().getEncoded()); //test the resulting ciphers Util.assertNotNull(encrypt.getSymDecodingCipher()); Util.assertNotNull(encrypt.getSymEncodingCipher()); } public static void testInitAESProperties() throws Exception { Properties props=new Properties(); props.put("sym_algorithm", "AES"); props.put("sym_init", "128"); ENCRYPT encrypt=new ENCRYPT(); encrypt.setProperties(props); encrypt.init(); // test the default symetric key assert "AES".equals(encrypt.getSymAlgorithm()) : "expected AES but was " + encrypt.getSymAlgorithm(); Util.assertEquals(128, encrypt.getSymInit()); Util.assertEquals("AES", encrypt.getDesKey().getAlgorithm()); Util.assertEquals("RAW", encrypt.getDesKey().getFormat()); Util.assertNotNull(encrypt.getDesKey().getEncoded()); //test the resulting ciphers Util.assertNotNull(encrypt.getSymDecodingCipher()); Util.assertNotNull(encrypt.getSymEncodingCipher()); } public static void testViewChangeBecomeKeyserver() throws Exception { // set up the peer ENCRYPT encrypt=new ENCRYPT(); encrypt.init(); // set in the observer MockAddress tempAddress=new MockAddress("encrypt"); encrypt.setLocal_addr(tempAddress); MockObserver observer=new MockObserver(); encrypt.setObserver(observer); // produce encrypted message Cipher cipher=encrypt.getSymEncodingCipher(); MessageDigest digest=MessageDigest.getInstance("MD5"); digest.reset(); digest.update(encrypt.getDesKey().getEncoded()); String symVersion=new String(digest.digest(), "UTF-8"); encrypt.keyServer=false; Message msg=new Message(); msg.setBuffer(cipher.doFinal("hello".getBytes())); msg.putHeader(EncryptHeader.KEY, new EncryptHeader( EncryptHeader.ENCRYPT, symVersion)); Event evt=new Event(Event.MSG, msg); //pass in event to encrypt layer encrypt.up(evt); // assert that message is queued as we have no key Util.assertTrue(observer.getUpMessages().isEmpty()); // send a view change to trigger the become key server // we use the fact that our address is now the controller one Vector tempVector=new Vector(); tempVector.add(tempAddress); View tempView=new View(new ViewId(tempAddress, 1), tempVector); Event event=new Event(Event.VIEW_CHANGE, tempView); // this should have changed us to the key server encrypt.up(event); // send another encrypted message Message msg2=new Message(); msg2.setBuffer(cipher.doFinal("hello2".getBytes())); msg2.putHeader(EncryptHeader.KEY, new EncryptHeader( EncryptHeader.ENCRYPT, symVersion)); // we should have three messages now in our observer // that are decrypted Event evt2=new Event(Event.MSG, msg2); encrypt.up(evt2); Util.assertEquals(3, observer.getUpMessages().size()); Event sent=(Event)observer.getUpMessages().get("message1"); Util.assertEquals("hello", new String(((Message)sent.getArg()).getBuffer())); sent=(Event)observer.getUpMessages().get("message2"); Util.assertEquals("hello2", new String(((Message)sent.getArg()).getBuffer())); } public static void testViewChangeNewKeyServer() throws Exception { // create peer and server ENCRYPT peer=new ENCRYPT(); peer.init(); ENCRYPT server=new ENCRYPT(); server.init(); // set up server server.keyServer=true; MockObserver serverObserver=new MockObserver(); server.setObserver(serverObserver); Address serverAddress=new MockAddress("server"); server.setLocal_addr(serverAddress); //set the server up as keyserver Vector serverVector=new Vector(); serverVector.add(serverAddress); View tempView=new View(new ViewId(serverAddress, 1), serverVector); Event serverEvent=new Event(Event.VIEW_CHANGE, tempView); server.up(serverEvent); // set up peer Address peerAddress=new MockAddress("peer"); peer.setLocal_addr(peerAddress); MockObserver peerObserver=new MockObserver(); peer.setObserver(peerObserver); peer.keyServer=false; MessageDigest digest=MessageDigest.getInstance("MD5"); digest.reset(); digest.update(server.getDesKey().getEncoded()); String symVersion=new String(digest.digest(), "UTF-8"); // encrypt and send an initial message to peer Cipher cipher=server.getSymEncodingCipher(); Message msg=new Message(); msg.setBuffer(cipher.doFinal("hello".getBytes())); msg.putHeader(EncryptHeader.KEY, new EncryptHeader( EncryptHeader.ENCRYPT, symVersion)); Event evt=new Event(Event.MSG, msg); peer.up(evt); //assert that message is queued as we have no key from server Util.assertTrue(peerObserver.getUpMessages().isEmpty()); // send a view change where we are not the controller // send to peer - which should have peer2 as its key server peer.up(serverEvent); // assert that peer\ keyserver address is now set Util.assertEquals(serverAddress, peer.getKeyServerAddr()); // get the resulting message from the peer - should be a key request Event sent=(Event)peerObserver.getDownMessages().get("message0"); Util.assertEquals(((EncryptHeader)((Message)sent.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.KEY_REQUEST); Util.assertEquals(new String(((Message)sent.getArg()).getBuffer()), new String(peer.getKpair().getPublic().getEncoded())); // send this event to server server.up(sent); Event reply=(Event)serverObserver.getDownMessages().get("message1"); //assert that reply is the session key encrypted with peer's public key Util.assertEquals(((EncryptHeader)((Message)reply.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.SECRETKEY); assert !peer.getDesKey().equals(server.getDesKey()); // now send back to peer peer.up(reply); // assert that both now have same key Util.assertEquals(peer.getDesKey(), server.getDesKey()); // send another encrypted message to peer to test queue Message msg2=new Message(); msg2.setBuffer(cipher.doFinal("hello2".getBytes())); msg2.putHeader(EncryptHeader.KEY, new EncryptHeader( EncryptHeader.ENCRYPT, symVersion)); Event evt2=new Event(Event.MSG, msg2); peer.up(evt2); // make sure we have the events now in the up layers Util.assertEquals(3, peerObserver.getUpMessages().size()); Event tempEvt=(Event)peerObserver.getUpMessages().get("message2"); Util.assertEquals("hello", new String(((Message)tempEvt.getArg()).getBuffer())); tempEvt=(Event)peerObserver.getUpMessages().get("message3"); Util.assertEquals("hello2", new String(((Message)tempEvt.getArg()).getBuffer())); } public static void testViewChangeNewKeyServerNewKey() throws Exception { // create peer and server ENCRYPT peer=new ENCRYPT(); peer.init(); ENCRYPT server=new ENCRYPT(); server.init(); ENCRYPT peer2=new ENCRYPT(); peer2.init(); // set up server server.keyServer=true; MockObserver serverObserver=new MockObserver(); server.setObserver(serverObserver); //set the local address and view change to simulate a started instance Address serverAddress=new MockAddress("server"); server.setLocal_addr(serverAddress); // set the server up as keyserver Vector serverVector=new Vector(); serverVector.add(serverAddress); View tempView=new View(new ViewId(serverAddress, 1), serverVector); Event serverEvent=new Event(Event.VIEW_CHANGE, tempView); server.up(serverEvent); // set up peer as if it has started but not recieved view change Address peerAddress=new MockAddress("peer"); peer.setLocal_addr(peerAddress); MockObserver peerObserver=new MockObserver(); peer.setObserver(peerObserver); peer.keyServer=false; // set up peer2 with server as key server Address peer2Address=new MockAddress("peer2"); peer2.setLocal_addr(peer2Address); MockObserver peer2Observer=new MockObserver(); peer2.setObserver(peer2Observer); peer2.keyServer=false; peer2.setKeyServerAddr(serverAddress); // send an encrypted message from the server Message msg=new Message(); msg.setBuffer("hello".getBytes()); Event evt=new Event(Event.MSG, msg); server.down(evt); // message0 is in response to view change Event encEvt=(Event)serverObserver.getDownMessages().get("message1"); // sent to peer encrypted - should be queued in encyption layer as we do not have a keyserver set peer.up(encEvt); //assert that message is queued as we have no key from server Util.assertTrue(peerObserver.getUpMessages().isEmpty()); // send a view change to peer where peer2 is controller Vector peerVector=new Vector(); peerVector.add(peer2Address); View tempPeerView=new View(new ViewId(peer2Address, 1), peerVector); Event event=new Event(Event.VIEW_CHANGE, tempPeerView); // send to peer - should set peer2 as keyserver peer.up(event); // assert that peer\ keyserver address is now set Util.assertEquals(peer2Address, peer.getKeyServerAddr()); // get the resulting message from the peer - should be a key request to peer2 Event sent=(Event)peerObserver.getDownMessages().get("message0"); // ensure type and that request contains peers pub key Util.assertEquals(((EncryptHeader)((Message)sent.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.KEY_REQUEST); Util.assertEquals(new String(((Message)sent.getArg()).getBuffer()), new String(peer.getKpair().getPublic().getEncoded())); //assume that server is no longer available and peer2 is new server // but did not get the key from server before assuming role // send this event to peer2 // send a view change to trigger the become key server // we use the fact that our address is now the controller one // send a view change where we are not the controller Vector peer2Vector=new Vector(); peer2Vector.add(peer2Address); View tempPeer2View=new View(new ViewId(peer2Address, 1), peer2Vector); Event event2=new Event(Event.VIEW_CHANGE, tempPeer2View); // this should have changed us to the key server peer2.up(event2); peer2.up(sent); Event reply=(Event)peer2Observer.getDownMessages().get("message1"); //assert that reply is the session key encrypted with peer's public key Util.assertEquals(((EncryptHeader)((Message)reply.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.SECRETKEY); assert !peer.getDesKey().equals(peer2.getDesKey()); assert !server.getDesKey().equals(peer2.getDesKey()); // now send back to peer peer.up(reply); // assert that both now have same key Util.assertEquals(peer.getDesKey(), peer2.getDesKey()); assert !server.getDesKey().equals(peer.getDesKey()); // send another encrypted message to peer to test queue Message msg2=new Message(); msg2.setBuffer("hello2".getBytes()); Event evt2=new Event(Event.MSG, msg2); peer2.down(evt2); Event Evt2=(Event)peer2Observer.getDownMessages().get("message2"); peer.up(Evt2); // make sure we have the events now in the up layers Util.assertEquals(2, peerObserver.getUpMessages().size()); Event tempEvt=(Event)peerObserver.getUpMessages().get("message2"); Util.assertEquals("hello2", new String(((Message)tempEvt.getArg()).getBuffer())); } static class MockObserver implements ENCRYPT.Observer { private Map upMessages=new HashMap(); private Map downMessages=new HashMap(); private int counter=0; /* (non-Javadoc) * @see org.jgroups.UpHandler#up(org.jgroups.Event) */ private void storeUp(Event evt) { upMessages.put("message" + counter++, evt); } private void storeDown(Event evt) { downMessages.put("message" + counter++, evt); } public void up(Event evt) { storeUp(evt); } public void setProtocol(Protocol prot) { } public void passUp(Event evt) { storeUp(evt); } public void down(Event evt) { } public void passDown(Event evt) { storeDown(evt); } protected Map getUpMessages() { return upMessages; } protected void setUpMessages(Map upMessages) { this.upMessages=upMessages; } protected Map getDownMessages() { return downMessages; } protected void setDownMessages(Map downMessages) { this.downMessages=downMessages; } } static class MockAddress implements Address { private static final long serialVersionUID=-479331506050129599L; String name; public MockAddress(String name) { this.name=name; } public MockAddress() { } public boolean isMulticastAddress() { return false; } public int size() { return 0; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } public void writeExternal(ObjectOutput out) throws IOException { } public int compareTo(Address o) { return -1; } public boolean equals(Object obj) { MockAddress address=(MockAddress)obj; return address.name.equals(this.name); } public void writeTo(DataOutputStream out) throws IOException { } public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { } } }
package network.thunder.core.communication; import io.netty.channel.ChannelHandlerContext; import network.thunder.core.communication.objects.subobjects.AuthenticationObject; import network.thunder.core.etc.crypto.CryptoTools; import org.bitcoinj.core.ECKey; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.sql.ResultSet; import java.sql.SQLException; public class Node { private String host; private int port; private boolean connected = false; private ChannelHandlerContext nettyContext; private byte[] pubkey; private boolean isAuth; private boolean sentAuth; private boolean authFinished; private boolean isReady; private boolean hasOpenChannel; public Node (String host, int port) { this.host = host; this.port = port; } public Node(ResultSet set) throws SQLException { this.host = set.getString("host"); this.port = set.getInt("port"); } public Node () { } public boolean processAuthentication (AuthenticationObject authentication, ECKey pubkeyClient, ECKey pubkeyServerTemp) throws NoSuchProviderException, NoSuchAlgorithmException { byte[] data = new byte[pubkeyClient.getPubKey().length+pubkeyServerTemp.getPubKey().length]; System.arraycopy(pubkeyClient.getPubKey(), 0, data, 0, pubkeyClient.getPubKey().length); System.arraycopy(pubkeyServerTemp.getPubKey(), 0, data, pubkeyClient.getPubKey().length, pubkeyServerTemp.getPubKey().length); CryptoTools.verifySignature(pubkeyClient, data, authentication.signature); isAuth = true; if (sentAuth) { authFinished = true; } return true; } public AuthenticationObject getAuthenticationObject (ECKey keyServer, ECKey keyClientTemp) throws NoSuchProviderException, NoSuchAlgorithmException { byte[] data = new byte[keyServer.getPubKey().length+keyClientTemp.getPubKey().length]; System.arraycopy(keyServer.getPubKey(), 0, data, 0, keyServer.getPubKey().length); System.arraycopy(keyClientTemp.getPubKey(), 0, data, keyServer.getPubKey().length, keyClientTemp.getPubKey().length); AuthenticationObject obj = new AuthenticationObject(); obj.pubkeyServer = keyServer.getPubKey(); obj.signature = CryptoTools.createSignature(keyServer, data); sentAuth = true; return obj; } public ChannelHandlerContext getNettyContext () { return nettyContext; } public void setNettyContext (ChannelHandlerContext nettyContext) { this.nettyContext = nettyContext; } public int getPort () { return port; } public void setPort (int port) { this.port = port; } public String getHost () { return host; } public void setHost (String host) { this.host = host; } public boolean isConnected () { return connected; } public void setConnected (boolean connected) { this.connected = connected; } public boolean hasSentAuth () { return sentAuth; } public boolean isAuth () { return isAuth; } public boolean allowsAuth () { return !isAuth; } public void finishAuth () { authFinished = true; } public boolean isAuthFinished () { return authFinished; } }
package org.apache.james.transport.mailets; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.StringTokenizer; import java.util.ArrayList; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.mailet.RFC2822Headers; import org.apache.mailet.dates.RFC822DateFormat; import org.apache.james.core.MailImpl; import org.apache.mailet.GenericMailet; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; /** * <P>Abstract mailet providing configurable redirection services.<BR> * This mailet can be subclassed to make authoring redirection mailets simple.<BR> * By extending it and overriding one or more of these methods new behaviour can * be quickly created without the author having to address any other issue than * the relevant one:</P> * <UL> * <LI>attachError() , should error messages be appended to the message</LI> * <LI>getAttachmentType(), what should be attached to the message</LI> * <LI>getInLineType(), what should be included in the message</LI> * <LI>getMessage(), The text of the message itself</LI> * <LI>getRecipients(), the recipients the mail is sent to</LI> * <LI>getReplyTo(), where replies to this message will be sent</LI> * <LI>getReturnPath(), what to set the Return-Path to</LI> * <LI>getSender(), who the mail is from</LI> * <LI>getSubjectPrefix(), a prefix to be added to the message subject</LI> * <LI>getTo(), a list of people to whom the mail is *apparently* sent</LI> * <LI>isReply(), should this mailet set the IN_REPLY_TO header to the id of the current message</LI> * <LI>getPassThrough(), should this mailet allow the original message to continue processing or GHOST it.</LI> * <LI>isStatic(), should this mailet run the get methods for every mail, or just once.</LI> * </UL> * <P>For each of the methods above (generically called "getX()" methods in this class * and its subclasses), there is an associated "getX(Mail)" method and most times * a "setX(Mail, Tx, Mail)" method.<BR> * The roles are the following:</P> * <UL> * <LI>a "setX()" method returns the correspondent "X" value that can be evaluated "statically" * once at init time and then stored in a variable and made available for later use by a * "getX(Mail)" method;</LI> * <LI>a "getX(Mail)" method is the one called to return the correspondent "X" value * that can be evaluated "dynamically", tipically based on the currently serviced mail; * the default behaviour is to return the value of getX().</LI> * <LI>a "setX(Mail, Tx, Mail)" method is called to change the correspondent "X" value * of the redirected Mail object, using the value returned by "gexX(Mail)".</LI> * </UL> * <P>Here follows the typical pattern of those methods:</P> * <PRE><CODE> * ... * Tx x; * ... * protected boolean getX(Mail originalMail) throws MessagingException { * boolean x = (isStatic()) ? this.x : getX(); * ... * return x; * } * ... * public void init() throws MessagingException { * ... * isStatic = (getInitParameter("static") == null) ? false : new Boolean(getInitParameter("static")).booleanValue(); * if(isStatic()) { * ... * X = getX(); * ... * } * ... * public void service(Mail originalMail) throws MessagingException { * ... * setX(newMail, getX(originalMail), originalMail); * ... * } * ... * </CODE></PRE> * <P>The <I>isStatic</I> variable and method is used to allow for the situations * (deprecated since version 2.2, but possibly used by previoulsy written extensions * to {@link Redirect}) in which the getX() methods are non static: in this case * {@link #isStatic()} must return false.<BR> * Finally, a "getX()" method may return a "special address" (see {@link SpecialAddress}), * that later will be resolved ("late bound") by a "getX(Mail)" or "setX(Mail, Tx, Mail)": * it is a dynamic value that does not require <CODE>isStatic</CODE> to be false.</P> * * <P>Supports by default the <CODE>passThrough</CODE> init parameter (false if missing). * Subclasses can override this behaviour overriding {@link #getPassThrough()}.</P> * */ public abstract class AbstractRedirect extends GenericMailet { /** * Controls certain log messages. */ protected boolean isDebug = false; /** * Holds the value of the <CODE>static</CODE> init parameter. */ protected boolean isStatic = false; private static class AddressMarker { public static MailAddress SENDER; public static MailAddress RETURN_PATH; public static MailAddress TO; public static MailAddress RECIPIENTS; public static MailAddress DELETE; public static MailAddress UNALTERED; public static MailAddress NULL; static { try { SENDER = new MailAddress("sender","address.marker"); RETURN_PATH = new MailAddress("return.path","address.marker"); TO = new MailAddress("to","address.marker"); RECIPIENTS = new MailAddress("recipients","address.marker"); DELETE = new MailAddress("delete","address.marker"); UNALTERED = new MailAddress("unaltered","address.marker"); NULL = new MailAddress("null","address.marker"); } catch (Exception _) {} } } /** * Class containing "special addresses" constants. * Such addresses mean dynamic values that later will be resolved ("late bound") * by a "getX(Mail)" or "setX(Mail, Tx, Mail)". */ protected static class SpecialAddress { public static final MailAddress SENDER = AddressMarker.SENDER; public static final MailAddress RETURN_PATH = AddressMarker.RETURN_PATH; public static final MailAddress TO = AddressMarker.TO; public static final MailAddress RECIPIENTS = AddressMarker.RECIPIENTS; public static final MailAddress DELETE = AddressMarker.DELETE; public static final MailAddress UNALTERED = AddressMarker.UNALTERED; public static final MailAddress NULL = AddressMarker.NULL; } // The values that indicate how to attach the original mail // to the new mail. protected static final int UNALTERED = 0; protected static final int HEADS = 1; protected static final int BODY = 2; protected static final int ALL = 3; protected static final int NONE = 4; protected static final int MESSAGE = 5; private boolean passThrough = false; private int attachmentType = NONE; private int inLineType = BODY; private String messageText; private Collection recipients; private MailAddress replyTo; private MailAddress returnPath; private MailAddress sender; private String subjectPrefix; private InternetAddress[] apparentlyTo; private boolean attachError = false; private boolean isReply = false; private RFC822DateFormat rfc822DateFormat = new RFC822DateFormat(); /** * <P>Gets the <CODE>static</CODE> property.</P> * <P>Return true to reduce calls to getTo, getSender, getRecipients, getReplyTo, getReturnPath amd getMessage * where these values don't change (eg hard coded, or got at startup from the mailet config); * return false where any of these methods generate their results dynamically eg in response to the message being processed, * or by reference to a repository of users.</P> * <P>It is now (from version 2.2) somehow obsolete, as should be always true because the "good practice" * is to use "getX()" methods statically, and use instead "getX(Mail)" methods for dynamic situations. * A false value is now meaningful only for subclasses of {@link Redirect} older than version 2.2 * that were relying on this.</P> * * <P>Is a "getX()" method.</P> * * @return true, as normally "getX()" methods shouls be static */ protected boolean isStatic() { return true; } /** * Gets the <CODE>passThrough</CODE> property. * Return true to allow the original message to continue through the processor, false to GHOST it. * Is a "getX()" method. * * @return the <CODE>passThrough</CODE> init parameter, or false if missing */ protected boolean getPassThrough() throws MessagingException { if(getInitParameter("passThrough") == null) { return false; } else { return new Boolean(getInitParameter("passThrough")).booleanValue(); } } /** * Gets the <CODE>passThrough</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getPassThrough()} */ protected boolean getPassThrough(Mail originalMail) throws MessagingException { boolean passThrough = (isStatic()) ? this.passThrough : getPassThrough(); return passThrough; } /** * Gets the <CODE>inline</CODE> property. * May return one of the following values to indicate how to append the original message * to build the new message: * <ul> * <li><CODE>UNALTERED</CODE> : original message is the new message body</li> * <li><CODE>BODY</CODE> : original message body is appended to the new message</li> * <li><CODE>HEADS</CODE> : original message headers are appended to the new message</li> * <li><CODE>ALL</CODE> : original is appended with all headers</li> * <li><CODE>NONE</CODE> : original is not appended</li> * </ul> * Is a "getX()" method. * * @return UNALTERED */ protected int getInLineType() throws MessagingException { return UNALTERED; } /** * Gets the <CODE>inline</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getInLineType()} */ protected int getInLineType(Mail originalMail) throws MessagingException { int inLineType = (isStatic()) ? this.inLineType : getInLineType(); return inLineType; } /** Gets the <CODE>attachment</CODE> property. * May return one of the following values to indicate how to attach the original message * to the new message: * <ul> * <li><CODE>BODY</CODE> : original message body is attached as plain text to the new message</li> * <li><CODE>HEADS</CODE> : original message headers are attached as plain text to the new message</li> * <li><CODE>ALL</CODE> : original is attached as plain text with all headers</li> * <li><CODE>MESSAGE</CODE> : original message is attached as type message/rfc822, a complete mail message.</li> * <li><CODE>NONE</CODE> : original is not attached</li> * </ul> * Is a "getX()" method. * * @return NONE */ protected int getAttachmentType() throws MessagingException { return NONE; } /** * Gets the <CODE>attachment</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getAttachmentType()} */ protected int getAttachmentType(Mail originalMail) throws MessagingException { int attachmentType = (isStatic()) ? this.attachmentType : getAttachmentType(); return attachmentType; } /** * Gets the <CODE>message</CODE> property. * Returns a message to which the original message can be attached/appended * to build the new message. * Is a "getX()" method. * * @return "" */ protected String getMessage() throws MessagingException { return ""; } /** * Gets the <CODE>message</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getMessage()} */ protected String getMessage(Mail originalMail) throws MessagingException { String messageText = (isStatic()) ? this.messageText : getMessage(); return messageText; } /** * Gets the <CODE>recipients</CODE> property. * Returns the collection of recipients of the new message, * or null if no change is requested. * Is a "getX()" method. * * @return null */ protected Collection getRecipients() throws MessagingException { return null; } /** * Gets the <CODE>recipients</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getRecipients()}, replacing <CODE>SpecialAddress.SENDER</CODE> if applicable */ protected Collection getRecipients(Mail originalMail) throws MessagingException { Collection recipients = (isStatic()) ? this.recipients : getRecipients(); if (recipients != null && recipients.size() == 1) { if (recipients.contains(SpecialAddress.SENDER)) { recipients = new ArrayList(); recipients.add(originalMail.getSender()); } else if (recipients.contains(SpecialAddress.RETURN_PATH)) { recipients = new ArrayList(); MailAddress mailAddress = getExistingReturnPath(originalMail); if (mailAddress == SpecialAddress.NULL) { // should never get here throw new MessagingException("NULL return path found getting recipients"); } if (mailAddress == null) { recipients.add(originalMail.getSender()); } else { recipients.add(mailAddress); } } } return recipients; } /** * Sets the recipients of <I>newMail</I> to <I>recipients</I>. */ protected void setRecipients(Mail newMail, Collection recipients, Mail originalMail) throws MessagingException { if (recipients != null) { ((MailImpl) newMail).setRecipients(recipients); if (isDebug) { log("recipients set to: " + arrayToString(recipients.toArray())); } } } /** * Gets the <CODE>to</CODE> property. * Returns the "To:" recipients of the new message. * or null if no change is requested. * Is a "getX()" method. * * @return null */ protected InternetAddress[] getTo() throws MessagingException { return null; } /** * Gets the <CODE>to</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getTo()}, replacing <CODE>SpecialAddress.SENDER</CODE> and <CODE>SpecialAddress.UNALTERED</CODE> if applicable */ protected InternetAddress[] getTo(Mail originalMail) throws MessagingException { InternetAddress[] apparentlyTo = (isStatic()) ? this.apparentlyTo : getTo(); if (apparentlyTo != null && apparentlyTo.length == 1) { if (apparentlyTo[0].equals(SpecialAddress.SENDER.toInternetAddress())) { apparentlyTo = new InternetAddress[1]; apparentlyTo[0] = originalMail.getSender().toInternetAddress(); } else if (apparentlyTo[0].equals(SpecialAddress.UNALTERED.toInternetAddress())) { apparentlyTo = (InternetAddress[]) originalMail.getMessage().getRecipients(Message.RecipientType.TO); } else if (apparentlyTo[0].equals(SpecialAddress.RETURN_PATH.toInternetAddress())) { MailAddress mailAddress = getExistingReturnPath(originalMail); if (mailAddress == SpecialAddress.NULL) { // should never get here throw new MessagingException("NULL return path found getting recipients"); } if (mailAddress == null) { apparentlyTo[0] = originalMail.getSender().toInternetAddress(); } else { apparentlyTo[0] = mailAddress.toInternetAddress(); } } } return apparentlyTo; } /** * Sets the "To:" header of <I>newMail</I> to <I>to</I>. */ protected void setTo(Mail newMail, InternetAddress[] to, Mail originalMail) throws MessagingException { if (to != null) { newMail.getMessage().setRecipients(Message.RecipientType.TO, to); if (isDebug) { log("apparentlyTo set to: " + arrayToString(to)); } } } /** * Gets the <CODE>replyto</CODE> property. * Returns the Reply-To address of the new message, * or null if no change is requested. * Is a "getX()" method. * * @return null */ protected MailAddress getReplyTo() throws MessagingException { return null; } /** * Gets the <CODE>replyTo</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getReplyTo()} */ protected MailAddress getReplyTo(Mail originalMail) throws MessagingException { MailAddress replyTo = (isStatic()) ? this.replyTo : getReplyTo(); return replyTo; } /** * Sets the "Reply-To:" header of <I>newMail</I> to <I>replyTo</I>. */ protected void setReplyTo(Mail newMail, MailAddress replyTo, Mail originalMail) throws MessagingException { if(replyTo != null) { InternetAddress[] iart = new InternetAddress[1]; iart[0] = replyTo.toInternetAddress(); newMail.getMessage().setReplyTo(iart); if (isDebug) { log("replyTo set to: " + replyTo); } } } /** * Gets the <CODE>returnPath</CODE> property. * Returns the Return-Path of the new message, * or null if no change is requested. * Is a "getX()" method. * * @return null */ protected MailAddress getReturnPath() throws MessagingException { return null; } /** * Gets the <CODE>returnPath</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getReturnPath()}, replacing <CODE>SpecialAddress.SENDER</CODE> if applicable, but not replacing <CODE>SpecialAddress.NULL</CODE> */ protected MailAddress getReturnPath(Mail originalMail) throws MessagingException { MailAddress returnPath = (isStatic()) ? this.returnPath : getReturnPath(); if (returnPath != null) { if (returnPath == SpecialAddress.SENDER) { returnPath = originalMail.getSender(); } } return returnPath; } /** * Sets the "Return-Path:" header of <I>newMail</I> to <I>returnPath</I>. */ protected void setReturnPath(Mail newMail, MailAddress returnPath, Mail originalMail) throws MessagingException { if(returnPath != null) { String returnPathString; if (returnPath == SpecialAddress.NULL) { returnPathString = ""; } else { returnPathString = returnPath.toString(); } newMail.getMessage().setHeader(RFC2822Headers.RETURN_PATH, "<" + returnPathString + ">"); if (isDebug) { log("returnPath set to: " + returnPath); } } } /** * Gets the <CODE>sender</CODE> property. * Returns the new sender as a MailAddress, * or null if no change is requested. * Is a "getX()" method. * * @return null */ protected MailAddress getSender() throws MessagingException { return null; } /** * Gets the <CODE>sender</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getSender()} */ protected MailAddress getSender(Mail originalMail) throws MessagingException { MailAddress sender = (isStatic()) ? this.sender : getSender(); return sender; } /** * Sets the sender and the "From:" header of <I>newMail</I> to <I>sender</I>. * If sender is null will set such values to the ones in <I>originalMail</I>. */ protected void setSender(Mail newMail, MailAddress sender, Mail originalMail) throws MessagingException { if (sender == null) { MailAddress originalSender = new MailAddress(((InternetAddress) originalMail.getMessage().getFrom()[0]).getAddress()); newMail.getMessage().setHeader(RFC2822Headers.FROM, originalMail.getMessage().getHeader(RFC2822Headers.FROM, ",")); ((MailImpl) newMail).setSender(originalSender); } else { newMail.getMessage().setFrom(sender.toInternetAddress()); ((MailImpl) newMail).setSender(sender); if (isDebug) { log("sender set to: " + sender); } } } /** * Gets the <CODE>prefix</CODE> property. * Returns a prefix for the new message subject. * Is a "getX()" method. * * @return "" */ protected String getSubjectPrefix() throws MessagingException { return ""; } /** * Gets the <CODE>subjectPrefix</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #getSubjectPrefix()} */ protected String getSubjectPrefix(Mail originalMail) throws MessagingException { String subjectPrefix = (isStatic()) ? this.subjectPrefix : getSubjectPrefix(); return subjectPrefix; } /** * Builds the subject of <I>newMail</I> appending the subject * of <I>originalMail</I> to <I>subjectPrefix</I>. */ protected void setSubjectPrefix(Mail newMail, String subjectPrefix, Mail originalMail) throws MessagingException { String subject = originalMail.getMessage().getSubject(); if (subject == null) { subject = ""; } newMail.getMessage().setSubject(subjectPrefix + subject); if (isDebug) { log("subjectPrefix set to: " + subjectPrefix); } } /** * Gets the <CODE>attachError</CODE> property. * Returns a boolean indicating whether to append a description of any error to the main body part * of the new message, if getInlineType does not return "UNALTERED". * Is a "getX()" method. * * @return false */ protected boolean attachError() throws MessagingException { return false; } /** * Gets the <CODE>attachError</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #attachError()} */ protected boolean attachError(Mail originalMail) throws MessagingException { boolean attachError = (isStatic()) ? this.attachError : attachError(); return attachError; } /** * Gets the <CODE>isReply</CODE> property. * Returns a boolean indicating whether the new message must be considered * a reply to the original message, setting the IN_REPLY_TO header of the new * message to the id of the original message. * Is a "getX()" method. * * @return false */ protected boolean isReply() throws MessagingException { return false; } /** * Gets the <CODE>isReply</CODE> property, * built dynamically using the original Mail object. * Is a "getX(Mail)" method. * * @return {@link #isReply()} */ protected boolean isReply(Mail originalMail) throws MessagingException { boolean isReply = (isStatic()) ? this.isReply : isReply(); return isReply; } /** * Sets the "In-Reply-To:" header of <I>newMail</I> to the "Message-Id:" of * <I>originalMail</I>, if <I>isReply</I> is true. */ protected void setIsReply(Mail newMail, boolean isReply, Mail originalMail) throws MessagingException { if (isReply) { String messageId = originalMail.getMessage().getMessageID(); if (messageId != null) { newMail.getMessage().setHeader(RFC2822Headers.IN_REPLY_TO, messageId); if (isDebug) { log("IN_REPLY_TO set to: " + messageId); } } } } /** * Mailet initialization routine. * Will setup static values for each "x" initialization parameter in config.xml, * using getX(), if {@link #isStatic()} returns true. */ public void init() throws MessagingException { if (isDebug) { log("Redirect init"); } isDebug = (getInitParameter("debug") == null) ? false : new Boolean(getInitParameter("debug")).booleanValue(); isStatic = (getInitParameter("static") == null) ? false : new Boolean(getInitParameter("static")).booleanValue(); if(isStatic()) { passThrough = getPassThrough(); attachmentType = getAttachmentType(); inLineType = getInLineType(); messageText = getMessage(); recipients = getRecipients(); replyTo = getReplyTo(); returnPath = getReturnPath(); sender = getSender(); subjectPrefix = getSubjectPrefix(); apparentlyTo = getTo(); attachError = attachError(); isReply = isReply(); if (isDebug) { StringBuffer logBuffer = new StringBuffer(1024) .append("static") .append(", passThrough=").append(passThrough) .append(", sender=").append(sender) .append(", replyTo=").append(replyTo) .append(", returnPath=").append(returnPath) .append(", message=").append(messageText) .append(", recipients=").append(arrayToString(recipients.toArray())) .append(", subjectPrefix=").append(subjectPrefix) .append(", apparentlyTo=").append(arrayToString(apparentlyTo)) .append(", attachError=").append(attachError) .append(", isReply=").append(isReply) .append(", attachmentType=").append(attachmentType) .append(", inLineType=").append(inLineType) .append(" "); log(logBuffer.toString()); } } } /** * Service does the hard work,and redirects the originalMail in the form specified. * * @param originalMail the mail to process and redirect * @throws MessagingException if a problem arises formulating the redirected mail */ public void service(Mail originalMail) throws MessagingException { boolean keepMessageId = false; // duplicates the Mail object, to be able to modify the new mail keeping the original untouched Mail newMail = ((MailImpl) originalMail).duplicate(newName((MailImpl) originalMail)); // We don't need to use the original Remote Address and Host, // and doing so would likely cause a loop with spam detecting // matchers. try { ((MailImpl) newMail).setRemoteAddr(java.net.InetAddress.getLocalHost().getHostAddress()); ((MailImpl) newMail).setRemoteHost(java.net.InetAddress.getLocalHost().getHostName()); } catch (java.net.UnknownHostException _) { ((MailImpl) newMail).setRemoteAddr("127.0.0.1"); ((MailImpl) newMail).setRemoteHost("localhost"); } if (isDebug) { MailImpl newMailImpl = (MailImpl) newMail; log("New mail - sender: " + newMailImpl.getSender() + ", recipients: " + arrayToString(newMailImpl.getRecipients().toArray()) + ", name: " + newMailImpl.getName() + ", remoteHost: " + newMailImpl.getRemoteHost() + ", remoteAddr: " + newMailImpl.getRemoteAddr() + ", state: " + newMailImpl.getState() + ", lastUpdated: " + newMailImpl.getLastUpdated() + ", errorMessage: " + newMailImpl.getErrorMessage()); } //Create the message if(getInLineType(originalMail) != UNALTERED) { if (isDebug) { log("Alter message inline=:" + getInLineType(originalMail)); } newMail.setMessage(new MimeMessage(Session.getDefaultInstance(System.getProperties(), null))); // handle the new message if altered buildAlteredMessage(newMail, originalMail); setTo(newMail, getTo(originalMail), originalMail); } else { // if we need the original, create a copy of this message to redirect if (getPassThrough(originalMail)) { newMail.setMessage(new MimeMessage(originalMail.getMessage()) { protected void updateHeaders() throws MessagingException { if (getMessageID() == null) super.updateHeaders(); else { modified = false; } } }); } if (isDebug) { log("Message resent unaltered."); } keepMessageId = true; } //Set additional headers setRecipients(newMail, getRecipients(originalMail), originalMail); setSubjectPrefix(newMail, getSubjectPrefix(originalMail), originalMail); if(newMail.getMessage().getHeader(RFC2822Headers.DATE) == null) { newMail.getMessage().setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date())); } setReplyTo(newMail, getReplyTo(originalMail), originalMail); setReturnPath(newMail, getReturnPath(originalMail), originalMail); setSender(newMail, getSender(originalMail), originalMail); setIsReply(newMail, isReply(originalMail), originalMail); newMail.getMessage().saveChanges(); if (keepMessageId) { setMessageId(newMail, originalMail); } if (senderDomainIsValid(newMail)) { //Send it off... getMailetContext().sendMail(newMail); } else { StringBuffer logBuffer = new StringBuffer(256) .append(getMailetName()) .append(" mailet cannot forward ") .append(((MailImpl) originalMail).getName()) .append(". Invalid sender domain for ") .append(newMail.getSender()) .append(". Consider using the Redirect mailet ") .append("using a different sender."); log(logBuffer.toString()); } if(!getPassThrough(originalMail)) { originalMail.setState(Mail.GHOST); } } private static final java.util.Random random = new java.util.Random(); // Used to generate new mail names /** * Create a unique new primary key name. * * @param mail the mail to use as the basis for the new mail name * @return a new name */ private String newName(MailImpl mail) { StringBuffer nameBuffer = new StringBuffer(64) .append(mail.getName()) .append("-!") .append(random.nextInt(1048576)); return nameBuffer.toString(); } /** * A private method to convert types from string to int. * * @param param the string type * @return the corresponding int enumeration */ protected int getTypeCode(String param) { param = param.toLowerCase(Locale.US); if(param.compareTo("unaltered") == 0) { return UNALTERED; } if(param.compareTo("heads") == 0) { return HEADS; } if(param.compareTo("body") == 0) { return BODY; } if(param.compareTo("all") == 0) { return ALL; } if(param.compareTo("none") == 0) { return NONE; } if(param.compareTo("message") == 0) { return MESSAGE; } return NONE; } /** * Gets the MailAddress corresponding to the existing "Return-Path" header of * <I>mail</I>. * If empty returns <CODE>SpecialAddress.NULL</CODE>, * if missing return <CODE>SpecialAddress.SENDER</CODE>. */ protected MailAddress getExistingReturnPath(Mail mail) throws MessagingException { MailAddress mailAddress = null; String[] returnPathHeaders = mail.getMessage().getHeader(RFC2822Headers.RETURN_PATH); String returnPathHeader = null; if (returnPathHeaders != null) { returnPathHeader = returnPathHeaders[0]; if (returnPathHeader != null) { returnPathHeader = returnPathHeader.trim(); if (returnPathHeader.equals("<>")) { mailAddress = SpecialAddress.NULL; } else { mailAddress = new MailAddress(new InternetAddress(returnPathHeader)); } } } return mailAddress; } /** * Utility method for obtaining a string representation of an array of Objects. */ private String arrayToString(Object[] array) { StringBuffer sb = new StringBuffer(1024); sb.append("["); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(","); } sb.append(array[i]); } sb.append("]"); return sb.toString(); } /** * Utility method for obtaining a string representation of a * Message's headers */ private String getMessageHeaders(MimeMessage message) throws MessagingException { Enumeration heads = message.getAllHeaderLines(); StringBuffer headBuffer = new StringBuffer(1024); while(heads.hasMoreElements()) { headBuffer.append(heads.nextElement().toString()).append("\r\n"); } return headBuffer.toString(); } /** * Utility method for obtaining a string representation of a * Message's body */ private String getMessageBody(MimeMessage message) throws Exception { java.io.InputStream bis = null; java.io.OutputStream bos = null; java.io.ByteArrayOutputStream bodyOs = new java.io.ByteArrayOutputStream(); try { // Get the message as a stream. This will encode // objects as necessary, and we have some overhead from // decoding and re-encoding the stream. I'd prefer the // raw stream, but see the WARNING below. bos = javax.mail.internet.MimeUtility.encode(bodyOs, message.getEncoding()); bis = message.getInputStream(); } catch(javax.activation.UnsupportedDataTypeException udte) { /* If we get an UnsupportedDataTypeException try using * the raw input stream as a "best attempt" at rendering * a message. * * WARNING: JavaMail v1.3 getRawInputStream() returns * INVALID (unchanged) content for a changed message. * getInputStream() works properly, but in this case * has failed due to a missing DataHandler. * * MimeMessage.getRawInputStream() may throw a "no * content" MessagingException. In JavaMail v1.3, when * you initially create a message using MimeMessage * APIs, there is no raw content available. * getInputStream() works, but getRawInputStream() * throws an exception. If we catch that exception, * throw the UDTE. It should mean that someone has * locally constructed a message part for which JavaMail * doesn't have a DataHandler. */ try { bis = message.getRawInputStream(); bos = bodyOs; } catch(javax.mail.MessagingException _) { throw udte; } } catch(javax.mail.MessagingException me) { /* This could be another kind of MessagingException * thrown by MimeMessage.getInputStream(), such as a * javax.mail.internet.ParseException. * * The ParseException is precisely one of the reasons * why the getRawInputStream() method exists, so that we * can continue to stream the content, even if we cannot * handle it. Again, if we get an exception, we throw * the one that caused us to call getRawInputStream(). */ try { bis = message.getRawInputStream(); bos = bodyOs; } catch(javax.mail.MessagingException _) { throw me; } } try { byte[] block = new byte[1024]; int read = 0; while ((read = bis.read(block)) > -1) { bos.write(block, 0, read); } bos.flush(); return bodyOs.toString(); } finally { bis.close(); } } /** * Builds the message of the newMail in case it has to be altered. * * @param originalMail the original Mail object * @param newMail the Mail object to build */ protected void buildAlteredMessage(Mail newMail, Mail originalMail) throws MessagingException { MimeMessage message = originalMail.getMessage(); StringWriter sout = new StringWriter(); PrintWriter out = new PrintWriter(sout, true); String head = getMessageHeaders(message); boolean all = false; String messageText = getMessage(originalMail); if(messageText != null) { out.println(messageText); } switch(getInLineType(originalMail)) { case ALL: //ALL: all = true; case HEADS: //HEADS: out.println("Message Headers:"); out.println(head); if(!all) { break; } case BODY: //BODY: out.println("Message:"); try { out.println(getMessageBody(message)); } catch(Exception e) { out.println("body unavailable"); } break; default: case NONE: //NONE: break; } try { //Create the message body MimeMultipart multipart = new MimeMultipart("mixed"); // Create the message MimeMultipart mpContent = new MimeMultipart("alternative"); MimeBodyPart contentPartRoot = new MimeBodyPart(); contentPartRoot.setContent(mpContent); multipart.addBodyPart(contentPartRoot); MimeBodyPart part = new MimeBodyPart(); part.setText(sout.toString()); part.setDisposition("inline"); mpContent.addBodyPart(part); if(getAttachmentType(originalMail) != NONE) { part = new MimeBodyPart(); switch(getAttachmentType(originalMail)) { case HEADS: //HEADS: part.setText(head); break; case BODY: //BODY: try { part.setText(getMessageBody(message)); } catch(Exception e) { part.setText("body unavailable"); } break; case ALL: //ALL: StringBuffer textBuffer = new StringBuffer(1024) .append(head) .append("\r\nMessage:\r\n") .append(getMessageBody(message)); part.setText(textBuffer.toString()); break; case MESSAGE: //MESSAGE: part.setContent(message, "message/rfc822"); break; } if ((message.getSubject() != null) && (message.getSubject().trim().length() > 0)) { part.setFileName(message.getSubject().trim()); } else { part.setFileName("No Subject"); } part.setDisposition("Attachment"); multipart.addBodyPart(part); } //if set, attach the original mail's error message if (attachError(originalMail) && originalMail.getErrorMessage() != null) { part = new MimeBodyPart(); part.setContent(originalMail.getErrorMessage(), "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); part.setFileName("Reasons"); part.setDisposition(javax.mail.Part.ATTACHMENT); multipart.addBodyPart(part); } newMail.getMessage().setContent(multipart); newMail.getMessage().setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); } catch (Exception ioe) { throw new MessagingException("Unable to create multipart body", ioe); } } /** * Sets the message id of originalMail into newMail. */ private void setMessageId(Mail newMail, Mail originalMail) throws MessagingException { String messageId = originalMail.getMessage().getMessageID(); if (messageId != null) { newMail.getMessage().setHeader(RFC2822Headers.MESSAGE_ID, messageId); if (isDebug) { log("MESSAGE_ID restored to: " + messageId); } } } /** * Returns the {@link SpecialAddress} that corresponds to an init parameter value. * The init parameter value is checked against a String[] of allowed values. * The checks are case insensitive. * * @param addressString the string to check if is a special address * @param allowedSpecials a String[] with the allowed special addresses * @return a SpecialAddress if found, null if not found or addressString is null * @throws MessagingException if is a special address not in the allowedSpecials array */ protected final MailAddress getSpecialAddress(String addressString, String[] allowedSpecials) throws MessagingException { if (addressString == null) { return null; } addressString = addressString.toLowerCase(Locale.US); addressString = addressString.trim(); MailAddress specialAddress = null; if(addressString.compareTo("postmaster") == 0) { specialAddress = getMailetContext().getPostmaster(); } if(addressString.compareTo("sender") == 0) { specialAddress = SpecialAddress.SENDER; } if(addressString.compareTo("returnpath") == 0) { specialAddress = SpecialAddress.RETURN_PATH; } if(addressString.compareTo("to") == 0) { specialAddress = SpecialAddress.TO; } if(addressString.compareTo("recipients") == 0) { specialAddress = SpecialAddress.RECIPIENTS; } if(addressString.compareTo("delete") == 0) { specialAddress = SpecialAddress.DELETE; } if(addressString.compareTo("unaltered") == 0) { specialAddress = SpecialAddress.UNALTERED; } if(addressString.compareTo("null") == 0) { specialAddress = SpecialAddress.NULL; } // if is a special address, must be in the allowedSpecials array if (specialAddress != null) { // check if is an allowed special boolean allowed = false; for (int i = 0; i < allowedSpecials.length; i++) { String allowedSpecial = allowedSpecials[i]; allowedSpecial = allowedSpecial.toLowerCase(Locale.US); allowedSpecial = allowedSpecial.trim(); if(addressString.compareTo(allowedSpecial) == 0) { allowed = true; break; } } if (!allowed) { throw new MessagingException("Special (\"magic\") address found not allowed: " + addressString + ", allowed values are \"" + arrayToString(allowedSpecials) + "\""); } } return specialAddress; } /** * <P>Checks if a sender domain of <I>mail</I> is valid. * It is valid if the sender is null or * {@link org.apache.mailet.MailetContext#getMailServers} returns true for * the sender host part.</P> * <P>If we do not do this check, and someone uses a redirection mailet in a * processor initiated by SenderInFakeDomain, then a fake * sender domain will cause an infinite loop (the forwarded * e-mail still appears to come from a fake domain).<BR> * Although this can be viewed as a configuration error, the * consequences of such a mis-configuration are severe enough * to warrant protecting against the infinite loop.</P> */ protected final boolean senderDomainIsValid(Mail mail) { return mail.getSender() == null || getMailetContext().getMailServers(mail.getSender().getHost()).size() != 0; } }
package com.continuuity.test.app; import com.continuuity.api.data.dataset.table.Get; import com.continuuity.api.data.dataset.table.Put; import com.continuuity.api.data.dataset.table.Table; import com.continuuity.data2.OperationException; import com.continuuity.test.ApplicationManager; import com.continuuity.test.DataSetManager; import com.continuuity.test.FlowManager; import com.continuuity.test.MapReduceManager; import com.continuuity.test.ProcedureClient; import com.continuuity.test.ProcedureManager; import com.continuuity.test.ReactorTestBase; import com.continuuity.test.RuntimeMetrics; import com.continuuity.test.RuntimeStats; import com.continuuity.test.StreamWriter; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.primitives.Longs; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class TestFrameworkTest extends ReactorTestBase { @Test public void testFlowRuntimeArguments() throws Exception { ApplicationManager applicationManager = deployApplication(FilterApp.class); Map<String, String> args = Maps.newHashMap(); args.put("threshold", "10"); applicationManager.startFlow("FilterFlow", args); StreamWriter input = applicationManager.getStreamWriter("input"); input.send("1"); input.send("11"); ProcedureManager queryManager = applicationManager.startProcedure("Count"); ProcedureClient client = queryManager.getClient(); Gson gson = new Gson(); Assert.assertEquals("1", gson.fromJson(client.query("result", ImmutableMap.of("type", "highpass")), String.class)); applicationManager.stopAll(); } @Test(timeout = 240000) public void testMultiInput() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(JoinMultiStreamApp.class); try { applicationManager.startFlow("JoinMultiFlow"); StreamWriter s1 = applicationManager.getStreamWriter("s1"); StreamWriter s2 = applicationManager.getStreamWriter("s2"); StreamWriter s3 = applicationManager.getStreamWriter("s3"); s1.send("testing 1"); s2.send("testing 2"); s3.send("testing 3"); RuntimeMetrics terminalMetrics = RuntimeStats.getFlowletMetrics("JoinMulti", "JoinMultiFlow", "Terminal"); terminalMetrics.waitForProcessed(3, 5, TimeUnit.SECONDS); TimeUnit.SECONDS.sleep(1); ProcedureManager queryManager = applicationManager.startProcedure("Query"); Gson gson = new Gson(); ProcedureClient client = queryManager.getClient(); Assert.assertEquals("testing 1", gson.fromJson(client.query("get", ImmutableMap.of("key", "input1")), String.class)); Assert.assertEquals("testing 2", gson.fromJson(client.query("get", ImmutableMap.of("key", "input2")), String.class)); Assert.assertEquals("testing 3", gson.fromJson(client.query("get", ImmutableMap.of("key", "input3")), String.class)); } finally { applicationManager.stopAll(); // Sleep a second before clear. There is a race between removal of RuntimeInfo // in the AbstractProgramRuntimeService class and the clear() method, which loops all RuntimeInfo. // The reason for the race is because removal is done through callback. TimeUnit.SECONDS.sleep(1); clear(); } } @Test(timeout = 360000) public void testApp() throws InterruptedException, IOException, TimeoutException, OperationException { ApplicationManager applicationManager = deployApplication(WordCountApp2.class); try { applicationManager.startFlow("WordCountFlow"); // Send some inputs to streams StreamWriter streamWriter = applicationManager.getStreamWriter("text"); for (int i = 0; i < 100; i++) { streamWriter.send(ImmutableMap.of("title", "title " + i), "testing message " + i); } // Check the flowlet metrics RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("WordCountApp", "WordCountFlow", "CountByField"); flowletMetrics.waitForProcessed(500, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, flowletMetrics.getException()); // Query the result ProcedureManager procedureManager = applicationManager.startProcedure("WordFrequency"); ProcedureClient procedureClient = procedureManager.getClient(); // Verify the query result Type resultType = new TypeToken<Map<String, Long>>() { }.getType(); Gson gson = new Gson(); Map<String, Long> result = gson.fromJson(procedureClient.query("wordfreq", ImmutableMap.of("word", "text:testing")), resultType); Assert.assertEquals(100L, result.get("text:testing").longValue()); // Verify by looking into dataset DataSetManager<MyKeyValueTable> mydatasetManager = applicationManager.getDataSet("mydataset"); Assert.assertEquals(100L, Longs.fromByteArray(mydatasetManager.get().read("title:title".getBytes(Charsets.UTF_8)))); // check the metrics RuntimeMetrics procedureMetrics = RuntimeStats.getProcedureMetrics("WordCountApp", "WordFrequency"); procedureMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, procedureMetrics.getException()); // Run mapreduce job MapReduceManager mrManager = applicationManager.startMapReduce("countTotal"); mrManager.waitForFinish(120L, TimeUnit.SECONDS); long totalCount = Long.valueOf(procedureClient.query("total", Collections.<String, String>emptyMap())); // every event has 5 tokens Assert.assertEquals(5 * 100L, totalCount); } finally { applicationManager.stopAll(); TimeUnit.SECONDS.sleep(1); clear(); } } @Test public void testGenerator() throws InterruptedException, IOException, TimeoutException { ApplicationManager applicationManager = deployApplication(GenSinkApp2.class); try { applicationManager.startFlow("GenSinkFlow"); // Check the flowlet metrics RuntimeMetrics genMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "GenFlowlet"); RuntimeMetrics sinkMetrics = RuntimeStats.getFlowletMetrics("GenSinkApp", "GenSinkFlow", "SinkFlowlet"); sinkMetrics.waitForProcessed(99, 5, TimeUnit.SECONDS); Assert.assertEquals(0L, sinkMetrics.getException()); Assert.assertEquals(1L, genMetrics.getException()); } finally { applicationManager.stopAll(); TimeUnit.SECONDS.sleep(1); clear(); } } @Test public void testAppRedeployKeepsData() { ApplicationManager appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager = appManager.getDataSet("my_table"); myTableManager.get().put(new Put("key1", "column1", "value1")); myTableManager.flush(); // Changes should be visible to other instances of datasets DataSetManager<Table> myTableManager2 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager2.get().get(new Get("key1", "column1")).getString("column1")); // Even after redeploy of an app: changes should be visible to other instances of datasets appManager = deployApplication(AppWithTable.class); DataSetManager<Table> myTableManager3 = appManager.getDataSet("my_table"); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); // Calling commit again (to test we can call it multiple times) myTableManager.get().put(new Put("key1", "column1", "value2")); myTableManager.flush(); Assert.assertEquals("value1", myTableManager3.get().get(new Get("key1", "column1")).getString("column1")); } @Test (timeout = 30000L) public void testInitDataSetAccess() throws TimeoutException, InterruptedException { ApplicationManager appManager = deployApplication(DataSetInitApp.class); FlowManager flowManager = appManager.startFlow("DataSetFlow"); RuntimeMetrics flowletMetrics = RuntimeStats.getFlowletMetrics("DataSetInitApp", "DataSetFlow", "Consumer"); flowletMetrics.waitForProcessed(1, 5, TimeUnit.SECONDS); flowManager.stop(); DataSetManager<Table> dataSetManager = appManager.getDataSet("conf"); Table confTable = dataSetManager.get(); Assert.assertEquals("generator", confTable.get(new Get("key", "column")).getString("column")); dataSetManager.flush(); } }
package com.messagebird; import com.messagebird.exceptions.GeneralException; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; /** * Builder for effortlessly constructing spy services of MessageBirdServiceImpl. * * The following example configures a mock to return an OK response with a * response of your choice whenever doRequest() is called: * * <pre> * MessageBirdService messageBirdService = SpyService * .expects("GET", "conversatons/convid") * .withConversationsAPIBaseURL() * .andReturns(new ApiResponse("YOUR_RESPONSE_BODY")); * </pre> * * @param <P> Type of the payload being (optionally) returned. */ class SpyService<P> { private String method; private String url; private P payload; private String baseURL; SpyService() { } /** * Gets the access key for the MessageBirdService. Can be overridden, but * if a use case requires this, the mock is likely not used properly. * * It is strongly advisable to NOT make this a valid access key for several * reasons, but also because Mockito uses loose mocks. This means that if a * mocked method is invoked without any matching expectations (for example, * with the wrong parameters), it does not throw exceptions. It instead * calls the real implementation. Leaving the access key blank ensures an * exception is thrown ("not authorized"), causing the test to fail. * * @return Access key for MessageBirdService. */ protected String getAccessKey() { return ""; } /** * Sets up a spy and configures its expectations for doRequest(). * * @param method Method that doRequest() expects. * @param url URL that doRequest() expects. * @param payload Payload that doRequest() expects. * @param <P> Type of the payload. * * @return Intermediate SpyService that can be finalized through * andReturns(). */ static <P> SpyService expects(final String method, final String url, final P payload) { SpyService service = new SpyService<P>(); service.method = method; service.url = url; service.payload = payload; return service; } /** * Sets up a spy and configures its expectations for doRequest(). This sets * the expected payload to null - useful for requests without bodies, like * GETs and DELETEs. To provide an expected payload, use the overload. * * @param method Method that doRequest() expects. * @param url URL that doRequest() expects. * * @return Intermediate SpyService that can be finalized through * andReturns(). */ static SpyService expects(final String method, final String url) { return SpyService.expects(method, url, null); } /** * Sets a base URL to prefix the URL provided to expects() with when * building the spy. * * @param baseURL String to prefix the URL with when building the spy. * * @return Intermediate SpyService that can be finalized through * andReturns(). */ SpyService withBaseURL(final String baseURL) { this.baseURL = baseURL; return this; } /** * Finalizes the SpyService by configuring its return value for * doRequest() and builds the spy. * * @param apiResponse APIResponse to return from the spy when doRequest() * is invoked with the configured expectation. * @return MessageBirdServiceImpl with a spy on doRequest(). * @throws GeneralException */ MessageBirdService andReturns(final APIResponse apiResponse) throws GeneralException { if (baseURL != null && !baseURL.isEmpty()) { url = String.format("%s/%s", baseURL, url); } System.out.printf("expecting doRequest(%s, %s, %s);\n\n", method, url, payload); MessageBirdServiceImpl messageBirdService = spy(new MessageBirdServiceImpl(getAccessKey())); doReturn(apiResponse).when(messageBirdService).doRequest(method, url, payload); return messageBirdService; } }
package view; import javafx.animation.AnimationTimer; import javafx.application.Platform; import javafx.scene.Group; import javafx.scene.canvas.Canvas; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.Stage; import lombok.val; import model.Game; import utils.Config; import utils.Utils; import java.util.Optional; import java.util.Timer; import java.util.TimerTask; public class View extends Group{ private Game game; private Canvas canvas; private Timer gameTimer = new Timer(); private AnimationTimer animationTimer; private Stage stage; public View(Game game, Stage stage) { this.game = game; this.stage = stage; initialize(); } private void initialize() { val map = game.getCurrentLevel().getMap(); canvas = new Canvas(map.getWidth() * Config.GAME_OBJECT_SIZE, map.getHeight() * Config.GAME_OBJECT_SIZE); this.getChildren().add( canvas ); animationTimer = new AnimationTimer(){ @Override public void handle(long now) { animationTimerTick(); } }; animationTimer.start(); gameTimer.schedule( new TimerTask() { @Override public void run() { Platform.runLater(() -> game.makeGameIteration()); } }, 0, 1000 / game.getDifficult()); game.addEndGameHandler(this::onEndGame); game.addChangeLevelHandler(this::onLevelChanged); } private void onLevelChanged(int level) { resizeField(); } private void onEndGame(int levelNumber, int snakeLength, boolean snakeIsDead) { animationTimer.stop(); gameTimer.cancel(); stage.hide(); val alert = new Alert(Alert.AlertType.CONFIRMATION); val message = String.format(snakeIsDead ? "Game over!\n Level: %d Apples: %d\n" : "Success! Game finished!\n Level: %d Apples: %d\n" , levelNumber, snakeLength - 2); alert.setHeaderText(message); alert.setContentText("Do you want try again?\n"); val yesButton = new ButtonType("Yes"); val noButton = new ButtonType("No"); alert.getButtonTypes().setAll(yesButton, noButton); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == yesButton){ refreshGame(!snakeIsDead); stage.show(); } else if (result.get() == noButton) { Platform.exit(); } } private void refreshGame(boolean startOver) { game.refreshGame(startOver); resizeField(); gameTimer = new Timer(); gameTimer.schedule( new TimerTask() { @Override public void run() { Platform.runLater(() -> game.makeGameIteration()); } }, 0, 1000 / game.getDifficult()); animationTimer.start(); } private void resizeField() { val map = game.getCurrentLevel().getMap(); canvas.setWidth(map.getWidth() * Config.GAME_OBJECT_SIZE); canvas.setHeight(map.getHeight() * Config.GAME_OBJECT_SIZE); stage.sizeToScene(); } private void animationTimerTick() { val map = game.getCurrentLevel().getMap(); val size = Config.GAME_OBJECT_SIZE; val graphicsContext = canvas.getGraphicsContext2D(); for (int x = 0; x < map.getWidth(); x++) for (int y = 0; y < map.getHeight(); y++) { val gameObject = map.get(x, y); graphicsContext.setFill(Utils.getUnitsImages().get(gameObject.getClass())); graphicsContext.fillRect(x * size, y * size, size, size); } } public void closeTimer() { gameTimer.cancel(); } }
package org.webrtc.videoengineapp; import android.app.AlertDialog; import android.app.TabActivity; 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.Canvas; import android.graphics.Paint; import android.graphics.PixelFormat; import android.hardware.SensorManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.OrientationEventListener; import android.view.Surface; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TabHost.TabSpec; import android.widget.TextView; import org.webrtc.videoengine.ViERenderer; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class WebRTCDemo extends TabActivity implements IViEAndroidCallback, View.OnClickListener, OnItemSelectedListener { private ViEAndroidJavaAPI vieAndroidAPI = null; // remote renderer private SurfaceView remoteSurfaceView = null; // local renderer and camera private SurfaceView svLocal = null; // channel number private int channel; private int cameraId; private int voiceChannel = -1; // flags private boolean viERunning = false; private boolean voERunning = false; // debug private boolean enableTrace = false; // Constant private static final String TAG = "WEBRTC"; private static final int RECEIVE_CODEC_FRAMERATE = 15; private static final int SEND_CODEC_FRAMERATE = 15; private static final int INIT_BITRATE = 500; private static final String LOOPBACK_IP = "127.0.0.1"; private static final String RINGTONE_URL = "content://settings/system/ringtone"; private int volumeLevel = 204; private TabHost mTabHost = null; private TabSpec mTabSpecConfig; private TabSpec mTabSpecVideo; private LinearLayout mLlRemoteSurface = null; private LinearLayout mLlLocalSurface = null; private Button btStartStopCall; private Button btSwitchCamera; // Global Settings private CheckBox cbVideoSend; private boolean enableVideoSend = true; private CheckBox cbVideoReceive; private boolean enableVideoReceive = true; private boolean enableVideo = true; private CheckBox cbVoice; private boolean enableVoice = true; private EditText etRemoteIp; private String remoteIp = ""; private CheckBox cbLoopback; private boolean loopbackMode = true; private CheckBox cbStats; private boolean isStatsOn = true; private CheckBox cbCPULoad; private boolean isCPULoadOn = true; private boolean useOpenGLRender = true; // Video settings private Spinner spCodecType; private int codecType = 0; private Spinner spCodecSize; private int codecSizeWidth = 0; private int codecSizeHeight = 0; private TextView etVRxPort; private int receivePortVideo = 11111; private TextView etVTxPort; private int destinationPortVideo = 11111; private CheckBox cbEnableNack; private boolean enableNack = true; private CheckBox cbEnableVideoRTPDump; // Audio settings private Spinner spVoiceCodecType; private int voiceCodecType = 0; private TextView etARxPort; private int receivePortVoice = 11113; private TextView etATxPort; private int destinationPortVoice = 11113; private CheckBox cbEnableSpeaker; private boolean enableSpeaker = false; private CheckBox cbEnableAGC; private boolean enableAGC = false; private CheckBox cbEnableAECM; private boolean enableAECM = false; private CheckBox cbEnableNS; private boolean enableNS = false; private CheckBox cbEnableDebugAPM; private CheckBox cbEnableVoiceRTPDump; // Stats variables private int frameRateI; private int bitRateI; private int packetLoss; private int frameRateO; private int bitRateO; // Variable for storing variables private String webrtcName = "/webrtc"; private String webrtcDebugDir = null; private WakeLock wakeLock; private boolean usingFrontCamera = true; private String[] mVideoCodecsStrings = null; private String[] mVideoCodecsSizeStrings = { "176x144", "320x240", "352x288", "640x480" }; private String[] mVoiceCodecsStrings = null; private Thread mBackgroundLoad = null; private boolean mIsBackgroudLoadRunning = false; private OrientationEventListener orientationListener; int currentOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; int currentCameraOrientation = 0; private StatsView statsView = null; private BroadcastReceiver receiver; public int getCameraOrientation(int cameraOrientation) { Display display = this.getWindowManager().getDefaultDisplay(); int displatyRotation = display.getRotation(); int degrees = 0; switch (displatyRotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result = 0; if (cameraOrientation > 180) { result = (cameraOrientation + degrees) % 360; } else { result = (cameraOrientation - degrees + 360) % 360; } return result; } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); int newRotation = getCameraOrientation(currentCameraOrientation); if (viERunning) { vieAndroidAPI.SetRotation(cameraId, newRotation); } } // Called when the activity is first created. @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Set screen orientation setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); PowerManager pm = (PowerManager) this.getSystemService( Context.POWER_SERVICE); wakeLock = pm.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); setContentView(R.layout.tabhost); IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().compareTo(Intent.ACTION_HEADSET_PLUG) == 0) { int state = intent.getIntExtra("state", 0); Log.v(TAG, "Intent.ACTION_HEADSET_PLUG state: " + state + " microphone: " + intent.getIntExtra("microphone", 0)); if (voERunning) { if (state == 1) { enableSpeaker = true; } else { enableSpeaker = false; } routeAudio(enableSpeaker); } } } }; registerReceiver(receiver, receiverFilter); mTabHost = getTabHost(); // Main tab mTabSpecVideo = mTabHost.newTabSpec("tab_video"); mTabSpecVideo.setIndicator("Main"); mTabSpecVideo.setContent(R.id.tab_video); mTabHost.addTab(mTabSpecVideo); // Shared config tab mTabHost = getTabHost(); mTabSpecConfig = mTabHost.newTabSpec("tab_config"); mTabSpecConfig.setIndicator("Settings"); mTabSpecConfig.setContent(R.id.tab_config); mTabHost.addTab(mTabSpecConfig); TabSpec mTabv; mTabv = mTabHost.newTabSpec("tab_vconfig"); mTabv.setIndicator("Video"); mTabv.setContent(R.id.tab_vconfig); mTabHost.addTab(mTabv); TabSpec mTaba; mTaba = mTabHost.newTabSpec("tab_aconfig"); mTaba.setIndicator("Audio"); mTaba.setContent(R.id.tab_aconfig); mTabHost.addTab(mTaba); int childCount = mTabHost.getTabWidget().getChildCount(); for (int i = 0; i < childCount; i++) { mTabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 50; } orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) { public void onOrientationChanged (int orientation) { if (orientation != ORIENTATION_UNKNOWN) { currentOrientation = orientation; } } }; orientationListener.enable (); // Create a folder named webrtc in /scard for debugging webrtcDebugDir = Environment.getExternalStorageDirectory().toString() + webrtcName; File webrtcDir = new File(webrtcDebugDir); if (!webrtcDir.exists() && webrtcDir.mkdir() == false) { Log.v(TAG, "Failed to create " + webrtcDebugDir); } else if (!webrtcDir.isDirectory()) { Log.v(TAG, webrtcDebugDir + " exists but not a folder"); webrtcDebugDir = null; } startMain(); return; } // Called before the activity is destroyed. @Override public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); unregisterReceiver(receiver); } private class StatsView extends View{ public StatsView(Context context){ super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint mLoadPaint = new Paint(); mLoadPaint.setAntiAlias(true); mLoadPaint.setTextSize(16); mLoadPaint.setARGB(255, 255, 255, 255); String mLoadText; mLoadText = "> " + frameRateI + " fps/" + bitRateI + "k bps/ " + packetLoss; canvas.drawText(mLoadText, 4, 172, mLoadPaint); mLoadText = "< " + frameRateO + " fps/ " + bitRateO + "k bps"; canvas.drawText(mLoadText, 4, 192, mLoadPaint); updateDisplay(); } void updateDisplay() { invalidate(); } } private String getLocalIpAddress() { String localIPs = ""; try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { localIPs += inetAddress.getHostAddress().toString() + " "; // Set the remote ip address the same as // the local ip address of the last netif remoteIp = inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(TAG, ex.toString()); } return localIPs; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (viERunning) { stopAll(); startMain(); } finish(); return true; } return super.onKeyDown(keyCode, event); } private void stopAll() { Log.d(TAG, "stopAll"); if (vieAndroidAPI != null) { stopCPULoad(); if (voERunning) { voERunning = false; stopVoiceEngine(); } if (viERunning) { viERunning = false; vieAndroidAPI.StopRender(channel); vieAndroidAPI.StopReceive(channel); vieAndroidAPI.StopSend(channel); vieAndroidAPI.RemoveRemoteRenderer(channel); vieAndroidAPI.StopCamera(cameraId); vieAndroidAPI.Terminate(); mLlRemoteSurface.removeView(remoteSurfaceView); mLlLocalSurface.removeView(svLocal); remoteSurfaceView = null; svLocal = null; } } } /** {@ArrayAdapter} */ public class SpinnerAdapter extends ArrayAdapter<String> { private String[] mCodecString = null; public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) { super(context, textViewResourceId, objects); mCodecString = objects; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } public View getCustomView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.row, parent, false); TextView label = (TextView) row.findViewById(R.id.spinner_row); label.setText(mCodecString[position]); return row; } } private void startMain() { mTabHost.setCurrentTab(0); mLlRemoteSurface = (LinearLayout) findViewById(R.id.llRemoteView); mLlLocalSurface = (LinearLayout) findViewById(R.id.llLocalView); if (null == vieAndroidAPI) { vieAndroidAPI = new ViEAndroidJavaAPI(this); } if (0 > setupVoE() || 0 > vieAndroidAPI.GetVideoEngine() || 0 > vieAndroidAPI.Init(enableTrace)) { // Show dialog AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("WebRTC Error"); alertDialog.setMessage("Can not init video engine."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); alertDialog.show(); } btSwitchCamera = (Button) findViewById(R.id.btSwitchCamera); btSwitchCamera.setOnClickListener(this); btStartStopCall = (Button) findViewById(R.id.btStartStopCall); btStartStopCall.setOnClickListener(this); findViewById(R.id.btExit).setOnClickListener(this); // cleaning remoteSurfaceView = null; svLocal = null; // Video codec mVideoCodecsStrings = vieAndroidAPI.GetCodecs(); spCodecType = (Spinner) findViewById(R.id.spCodecType); spCodecType.setOnItemSelectedListener(this); spCodecType.setAdapter(new SpinnerAdapter(this, R.layout.row, mVideoCodecsStrings)); spCodecType.setSelection(0); // Video Codec size spCodecSize = (Spinner) findViewById(R.id.spCodecSize); spCodecSize.setOnItemSelectedListener(this); spCodecSize.setAdapter(new SpinnerAdapter(this, R.layout.row, mVideoCodecsSizeStrings)); spCodecSize.setSelection(0); // Voice codec mVoiceCodecsStrings = vieAndroidAPI.VoE_GetCodecs(); spVoiceCodecType = (Spinner) findViewById(R.id.spVoiceCodecType); spVoiceCodecType.setOnItemSelectedListener(this); spVoiceCodecType.setAdapter(new SpinnerAdapter(this, R.layout.row, mVoiceCodecsStrings)); spVoiceCodecType.setSelection(0); // Find ISAC and use it for (int i = 0; i < mVoiceCodecsStrings.length; ++i) { if (mVoiceCodecsStrings[i].contains("ISAC")) { spVoiceCodecType.setSelection(i); break; } } RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group1); radioGroup.clearCheck(); if (useOpenGLRender == true) { radioGroup.check(R.id.radio_opengl); } else { radioGroup.check(R.id.radio_surface); } etRemoteIp = (EditText) findViewById(R.id.etRemoteIp); etRemoteIp.setText(remoteIp); cbLoopback = (CheckBox) findViewById(R.id.cbLoopback); cbLoopback.setChecked(loopbackMode); cbStats = (CheckBox) findViewById(R.id.cbStats); cbStats.setChecked(isStatsOn); cbCPULoad = (CheckBox) findViewById(R.id.cbCPULoad); cbCPULoad.setChecked(isCPULoadOn); cbVoice = (CheckBox) findViewById(R.id.cbVoice); cbVoice.setChecked(enableVoice); cbVideoSend = (CheckBox) findViewById(R.id.cbVideoSend); cbVideoSend.setChecked(enableVideoSend); cbVideoReceive = (CheckBox) findViewById(R.id.cbVideoReceive); cbVideoReceive.setChecked(enableVideoReceive); etVTxPort = (EditText) findViewById(R.id.etVTxPort); etVTxPort.setText(Integer.toString(destinationPortVideo)); etVRxPort = (EditText) findViewById(R.id.etVRxPort); etVRxPort.setText(Integer.toString(receivePortVideo)); etATxPort = (EditText) findViewById(R.id.etATxPort); etATxPort.setText(Integer.toString(destinationPortVoice)); etARxPort = (EditText) findViewById(R.id.etARxPort); etARxPort.setText(Integer.toString(receivePortVoice)); cbEnableNack = (CheckBox) findViewById(R.id.cbNack); cbEnableNack.setChecked(enableNack); cbEnableSpeaker = (CheckBox) findViewById(R.id.cbSpeaker); cbEnableSpeaker.setChecked(enableSpeaker); cbEnableAGC = (CheckBox) findViewById(R.id.cbAutoGainControl); cbEnableAGC.setChecked(enableAGC); cbEnableAECM = (CheckBox) findViewById(R.id.cbAECM); cbEnableAECM.setChecked(enableAECM); cbEnableNS = (CheckBox) findViewById(R.id.cbNoiseSuppression); cbEnableNS.setChecked(enableNS); cbEnableDebugAPM = (CheckBox) findViewById(R.id.cbDebugRecording); cbEnableDebugAPM.setChecked(false); // Disable APM debugging by default cbEnableVideoRTPDump = (CheckBox) findViewById(R.id.cbVideoRTPDump); cbEnableVideoRTPDump.setChecked(false); // Disable Video RTP Dump cbEnableVoiceRTPDump = (CheckBox) findViewById(R.id.cbVoiceRTPDump); cbEnableVoiceRTPDump.setChecked(false); // Disable Voice RTP Dump etRemoteIp.setOnClickListener(this); cbLoopback.setOnClickListener(this); cbStats.setOnClickListener(this); cbCPULoad.setOnClickListener(this); cbEnableNack.setOnClickListener(this); cbEnableSpeaker.setOnClickListener(this); cbEnableAECM.setOnClickListener(this); cbEnableAGC.setOnClickListener(this); cbEnableNS.setOnClickListener(this); cbEnableDebugAPM.setOnClickListener(this); cbEnableVideoRTPDump.setOnClickListener(this); cbEnableVoiceRTPDump.setOnClickListener(this); if (loopbackMode) { remoteIp = LOOPBACK_IP; etRemoteIp.setText(remoteIp); } else { getLocalIpAddress(); etRemoteIp.setText(remoteIp); } // Read settings to refresh each configuration readSettings(); } private String getRemoteIPString() { return etRemoteIp.getText().toString(); } private void startPlayingRingtone() { MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, Uri.parse(RINGTONE_URL)); mMediaPlayer.prepare(); mMediaPlayer.seekTo(0); mMediaPlayer.start(); } catch (IOException e) { Log.v(TAG, "MediaPlayer Failed: " + e); } } private void startCall() { int ret = 0; startPlayingRingtone(); if (enableVoice) { startVoiceEngine(); } if (enableVideo) { if (enableVideoSend) { // camera and preview surface svLocal = ViERenderer.CreateLocalRenderer(this); } channel = vieAndroidAPI.CreateChannel(voiceChannel); ret = vieAndroidAPI.SetLocalReceiver(channel, receivePortVideo); ret = vieAndroidAPI.SetSendDestination(channel, destinationPortVideo, getRemoteIPString()); if (enableVideoReceive) { if (useOpenGLRender) { Log.v(TAG, "Create OpenGL Render"); remoteSurfaceView = ViERenderer.CreateRenderer(this, true); ret = vieAndroidAPI.AddRemoteRenderer(channel, remoteSurfaceView); } else { Log.v(TAG, "Create SurfaceView Render"); remoteSurfaceView = ViERenderer.CreateRenderer(this, false); ret = vieAndroidAPI.AddRemoteRenderer(channel, remoteSurfaceView); } ret = vieAndroidAPI.SetReceiveCodec(channel, codecType, INIT_BITRATE, codecSizeWidth, codecSizeHeight, RECEIVE_CODEC_FRAMERATE); ret = vieAndroidAPI.StartRender(channel); ret = vieAndroidAPI.StartReceive(channel); } if (enableVideoSend) { currentCameraOrientation = vieAndroidAPI.GetCameraOrientation(usingFrontCamera ? 1 : 0); ret = vieAndroidAPI.SetSendCodec(channel, codecType, INIT_BITRATE, codecSizeWidth, codecSizeHeight, SEND_CODEC_FRAMERATE); int camId = vieAndroidAPI.StartCamera(channel, usingFrontCamera ? 1 : 0); if (camId > 0) { cameraId = camId; int neededRotation = getCameraOrientation(currentCameraOrientation); vieAndroidAPI.SetRotation(cameraId, neededRotation); } else { ret = camId; } ret = vieAndroidAPI.StartSend(channel); } // TODO(leozwang): Add more options besides PLI, currently use pli // as the default. Also check return value. ret = vieAndroidAPI.EnablePLI(channel, true); ret = vieAndroidAPI.EnableNACK(channel, enableNack); ret = vieAndroidAPI.SetCallback(channel, this); if (enableVideoSend) { if (mLlLocalSurface != null) { mLlLocalSurface.addView(svLocal); } } if (enableVideoReceive) { if (mLlRemoteSurface != null) { mLlRemoteSurface.addView(remoteSurfaceView); } } isStatsOn = cbStats.isChecked(); if (isStatsOn) { addStatusView(); } else { removeStatusView(); } isCPULoadOn = cbCPULoad.isChecked(); if (isCPULoadOn) { startCPULoad(); } else { stopCPULoad(); } viERunning = true; } } private void stopVoiceEngine() { // Stop send if (0 != vieAndroidAPI.VoE_StopSend(voiceChannel)) { Log.d(TAG, "VoE stop send failed"); } // Stop listen if (0 != vieAndroidAPI.VoE_StopListen(voiceChannel)) { Log.d(TAG, "VoE stop listen failed"); } // Stop playout if (0 != vieAndroidAPI.VoE_StopPlayout(voiceChannel)) { Log.d(TAG, "VoE stop playout failed"); } if (0 != vieAndroidAPI.VoE_DeleteChannel(voiceChannel)) { Log.d(TAG, "VoE delete channel failed"); } voiceChannel = -1; // Terminate if (0 != vieAndroidAPI.VoE_Terminate()) { Log.d(TAG, "VoE terminate failed"); } } private int setupVoE() { // Create VoiceEngine // Error logging is done in native API wrapper vieAndroidAPI.VoE_Create(getApplicationContext()); // Initialize if (0 != vieAndroidAPI.VoE_Init(enableTrace)) { Log.d(TAG, "VoE init failed"); return -1; } // Create channel voiceChannel = vieAndroidAPI.VoE_CreateChannel(); if (0 != voiceChannel) { Log.d(TAG, "VoE create channel failed"); return -1; } // Suggest to use the voice call audio stream for hardware volume controls setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); return 0; } private int startVoiceEngine() { // Set local receiver if (0 != vieAndroidAPI.VoE_SetLocalReceiver(voiceChannel, receivePortVoice)) { Log.d(TAG, "VoE set local receiver failed"); } if (0 != vieAndroidAPI.VoE_StartListen(voiceChannel)) { Log.d(TAG, "VoE start listen failed"); } // Route audio routeAudio(enableSpeaker); // set volume to default value if (0 != vieAndroidAPI.VoE_SetSpeakerVolume(volumeLevel)) { Log.d(TAG, "VoE set speaker volume failed"); } // Start playout if (0 != vieAndroidAPI.VoE_StartPlayout(voiceChannel)) { Log.d(TAG, "VoE start playout failed"); } if (0 != vieAndroidAPI.VoE_SetSendDestination(voiceChannel, destinationPortVoice, getRemoteIPString())) { Log.d(TAG, "VoE set send destination failed"); } if (0 != vieAndroidAPI.VoE_SetSendCodec(voiceChannel, voiceCodecType)) { Log.d(TAG, "VoE set send codec failed"); } if (0 != vieAndroidAPI.VoE_SetECStatus(enableAECM)) { Log.d(TAG, "VoE set EC Status failed"); } if (0 != vieAndroidAPI.VoE_SetAGCStatus(enableAGC)) { Log.d(TAG, "VoE set AGC Status failed"); } if (0 != vieAndroidAPI.VoE_SetNSStatus(enableNS)) { Log.d(TAG, "VoE set NS Status failed"); } if (0 != vieAndroidAPI.VoE_StartSend(voiceChannel)) { Log.d(TAG, "VoE start send failed"); } voERunning = true; return 0; } private void routeAudio(boolean enableSpeaker) { if (0 != vieAndroidAPI.VoE_SetLoudspeakerStatus(enableSpeaker)) { Log.d(TAG, "VoE set louspeaker status failed"); } } public void onClick(View arg0) { switch (arg0.getId()) { case R.id.btSwitchCamera: if (usingFrontCamera) { btSwitchCamera.setText(R.string.frontCamera); } else { btSwitchCamera.setText(R.string.backCamera); } usingFrontCamera = !usingFrontCamera; if (viERunning) { currentCameraOrientation = vieAndroidAPI.GetCameraOrientation(usingFrontCamera ? 1 : 0); vieAndroidAPI.StopCamera(cameraId); mLlLocalSurface.removeView(svLocal); vieAndroidAPI.StartCamera(channel, usingFrontCamera ? 1 : 0); mLlLocalSurface.addView(svLocal); int neededRotation = getCameraOrientation(currentCameraOrientation); vieAndroidAPI.SetRotation(cameraId, neededRotation); } break; case R.id.btStartStopCall: readSettings(); if (viERunning || voERunning) { stopAll(); startMain(); wakeLock.release(); // release the wake lock btStartStopCall.setText(R.string.startCall); } else if (enableVoice || enableVideo){ startCall(); wakeLock.acquire(); // screen stay on during the call btStartStopCall.setText(R.string.stopCall); } break; case R.id.btExit: stopAll(); finish(); break; case R.id.cbLoopback: loopbackMode = cbLoopback.isChecked(); if (loopbackMode) { remoteIp = LOOPBACK_IP; etRemoteIp.setText(LOOPBACK_IP); } else { getLocalIpAddress(); etRemoteIp.setText(remoteIp); } break; case R.id.etRemoteIp: remoteIp = etRemoteIp.getText().toString(); break; case R.id.cbStats: isStatsOn = cbStats.isChecked(); if (isStatsOn) { addStatusView(); } else { removeStatusView(); } break; case R.id.cbCPULoad: isCPULoadOn = cbCPULoad.isChecked(); if (isCPULoadOn) { startCPULoad(); } else { stopCPULoad(); } break; case R.id.radio_surface: useOpenGLRender = false; break; case R.id.radio_opengl: useOpenGLRender = true; break; case R.id.cbNack: enableNack = cbEnableNack.isChecked(); if (viERunning) { vieAndroidAPI.EnableNACK(channel, enableNack); } break; case R.id.cbSpeaker: enableSpeaker = cbEnableSpeaker.isChecked(); if (voERunning) { routeAudio(enableSpeaker); } break; case R.id.cbDebugRecording: if (voERunning && webrtcDebugDir != null) { if (cbEnableDebugAPM.isChecked()) { vieAndroidAPI.VoE_StartDebugRecording( webrtcDebugDir + String.format("/apm_%d.dat", System.currentTimeMillis())); } else { vieAndroidAPI.VoE_StopDebugRecording(); } } break; case R.id.cbVoiceRTPDump: if (voERunning && webrtcDebugDir != null) { if (cbEnableVoiceRTPDump.isChecked()) { vieAndroidAPI.VoE_StartIncomingRTPDump(channel, webrtcDebugDir + String.format("/voe_%d.rtp", System.currentTimeMillis())); } else { vieAndroidAPI.VoE_StopIncomingRTPDump(channel); } } break; case R.id.cbVideoRTPDump: if (viERunning && webrtcDebugDir != null) { if (cbEnableVideoRTPDump.isChecked()) { vieAndroidAPI.StartIncomingRTPDump(channel, webrtcDebugDir + String.format("/vie_%d.rtp", System.currentTimeMillis())); } else { vieAndroidAPI.StopIncomingRTPDump(channel); } } break; case R.id.cbAutoGainControl: enableAGC = cbEnableAGC.isChecked(); if (voERunning) { vieAndroidAPI.VoE_SetAGCStatus(enableAGC); } break; case R.id.cbNoiseSuppression: enableNS = cbEnableNS.isChecked(); if (voERunning) { vieAndroidAPI.VoE_SetNSStatus(enableNS); } break; case R.id.cbAECM: enableAECM = cbEnableAECM.isChecked(); if (voERunning) { vieAndroidAPI.VoE_SetECStatus(enableAECM); } break; } } private void readSettings() { codecType = spCodecType.getSelectedItemPosition(); voiceCodecType = spVoiceCodecType.getSelectedItemPosition(); String sCodecSize = spCodecSize.getSelectedItem().toString(); String[] aCodecSize = sCodecSize.split("x"); codecSizeWidth = Integer.parseInt(aCodecSize[0]); codecSizeHeight = Integer.parseInt(aCodecSize[1]); loopbackMode = cbLoopback.isChecked(); enableVoice = cbVoice.isChecked(); enableVideoSend = cbVideoSend.isChecked(); enableVideoReceive = cbVideoReceive.isChecked(); enableVideo = enableVideoSend || enableVideoReceive; destinationPortVideo = Integer.parseInt(etVTxPort.getText().toString()); receivePortVideo = Integer.parseInt(etVRxPort.getText().toString()); destinationPortVoice = Integer.parseInt(etATxPort.getText().toString()); receivePortVoice = Integer.parseInt(etARxPort.getText().toString()); enableNack = cbEnableNack.isChecked(); enableSpeaker = cbEnableSpeaker.isChecked(); enableAGC = cbEnableAGC.isChecked(); enableAECM = cbEnableAECM.isChecked(); enableNS = cbEnableNS.isChecked(); } public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { if ((adapterView == spCodecType || adapterView == spCodecSize) && viERunning) { readSettings(); // change the codectype if (enableVideoReceive) { if (0 != vieAndroidAPI.SetReceiveCodec(channel, codecType, INIT_BITRATE, codecSizeWidth, codecSizeHeight, RECEIVE_CODEC_FRAMERATE)) { Log.d(TAG, "ViE set receive codec failed"); } } if (enableVideoSend) { if (0 != vieAndroidAPI.SetSendCodec(channel, codecType, INIT_BITRATE, codecSizeWidth, codecSizeHeight, SEND_CODEC_FRAMERATE)) { Log.d(TAG, "ViE set send codec failed"); } } } else if ((adapterView == spVoiceCodecType) && voERunning) { // change voice engine codec readSettings(); if (0 != vieAndroidAPI.VoE_SetSendCodec(voiceChannel, voiceCodecType)) { Log.d(TAG, "VoE set send codec failed"); } } } public void onNothingSelected(AdapterView<?> arg0) { Log.d(TAG, "No setting selected"); } public int updateStats(int inFrameRateI, int inBitRateI, int inPacketLoss, int inFrameRateO, int inBitRateO) { frameRateI = inFrameRateI; bitRateI = inBitRateI; packetLoss = inPacketLoss; frameRateO = inFrameRateO; bitRateO = inBitRateO; return 0; } private void addStatusView() { if (statsView != null) { return; } statsView = new StatsView(this); WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.RIGHT | Gravity.TOP; params.setTitle("Load Average"); mTabHost.addView(statsView, params); statsView.setBackgroundColor(0); } private void removeStatusView() { mTabHost.removeView(statsView); statsView = null; } private void startCPULoad() { if (null == mBackgroundLoad) { mBackgroundLoad = new Thread(new Runnable() { public void run() { Log.v(TAG, "Background load started"); mIsBackgroudLoadRunning = true; try { while (mIsBackgroudLoadRunning) { // This while loop simulates cpu load. // Log.v(TAG, "Runnable!!!"); } } catch (Throwable t) { Log.v(TAG, "startCPULoad failed"); } } }); mBackgroundLoad.start(); } else { if (mBackgroundLoad.getState() == Thread.State.TERMINATED) { mBackgroundLoad.start(); } } } private void stopCPULoad() { if (null != mBackgroundLoad) { mIsBackgroudLoadRunning = false; try { mBackgroundLoad.join(); mBackgroundLoad = null; } catch (Throwable t) { Log.v(TAG, "stopCPULoad failed"); } } } }
package org.xcolab.view.config.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter; import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter.XFrameOptionsMode; import org.springframework.security.web.util.matcher.NegatedRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RegexRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.xcolab.view.auth.AuthenticationContext; import org.xcolab.view.auth.handlers.AuthenticationFailureHandler; import org.xcolab.view.auth.handlers.AuthenticationSuccessHandler; import org.xcolab.view.auth.handlers.LogoutSuccessHandler; import org.xcolab.view.auth.login.spring.MemberDetailsService; import org.xcolab.view.auth.login.spring.MemberPasswordEncoder; import java.util.ArrayList; import java.util.List; @Configuration @EnableWebSecurity @SuppressWarnings("ProhibitedExceptionDeclared") public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private final RememberMeServices rememberMeServices; private final MemberDetailsService memberDetailsService; private final WebProperties webProperties; @Autowired public WebSecurityConfig(RememberMeServices rememberMeServices, MemberDetailsService memberDetailsService, WebProperties webProperties) { this.rememberMeServices = rememberMeServices; this.memberDetailsService = memberDetailsService; this.webProperties = webProperties; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests()
package org.archive.wayback.core; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.apache.commons.httpclient.URIException; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.archive.wayback.WaybackConstants; import org.archive.wayback.requestparser.OpenSearchRequestParser; import org.archive.wayback.util.ObjectFilter; import org.archive.wayback.util.StringFormatter; import org.archive.wayback.webapp.AccessPoint; /** * Abstraction of all the data associated with a users request to the Wayback * Machine. * * @author Brad Tofel * @version $Date$, $Revision$ */ public class WaybackRequest { public final static String REQUEST_ANCHOR_DATE = "request.anchordate"; public final static String REQUEST_ANCHOR_WINDOW = "request.anchorwindow"; private int resultsPerPage = 10; private int pageNum = 1; private String contextPrefix = null; private String serverPrefix = null; private AccessPoint context = null; private ObjectFilter<CaptureSearchResult> exclusionFilter = null; private HashMap<String,String> filters = new HashMap<String,String>(); private StringFormatter formatter = null; private static String UI_RESOURCE_BUNDLE_NAME = "WaybackUI"; private final static String standardHeaders[] = { WaybackConstants.REQUEST_REFERER_URL, WaybackConstants.REQUEST_REMOTE_ADDRESS, WaybackConstants.REQUEST_WAYBACK_HOSTNAME, WaybackConstants.REQUEST_WAYBACK_PORT, WaybackConstants.REQUEST_WAYBACK_CONTEXT, WaybackConstants.REQUEST_AUTH_TYPE, WaybackConstants.REQUEST_REMOTE_USER, WaybackConstants.REQUEST_LOCALE_LANG }; /** * Constructor, possibly/probably this should BE a Properties, instead of * HAVEing a Properties... */ public WaybackRequest() { super(); } /** * @return true if REQUEST_TYPE is set, and is set to REQUEST_REPLAY_QUERY */ public boolean isReplayRequest() { String type = get(WaybackConstants.REQUEST_TYPE); if(type != null && type.equals(WaybackConstants.REQUEST_REPLAY_QUERY)) { return true; } return false; } /** * @return true if true if REQUEST_TYPE is not set, or is set to a value * other than REQUEST_REPLAY_QUERY */ public boolean isQueryRequest() { return !isReplayRequest(); } /** * @return Returns the pageNum. */ public int getPageNum() { return pageNum; } /** * @param pageNum * The pageNum to set. */ public void setPageNum(int pageNum) { this.pageNum = pageNum; } /** * @return Returns the resultsPerPage. */ public int getResultsPerPage() { return resultsPerPage; } /** * @param resultsPerPage * The resultsPerPage to set. */ public void setResultsPerPage(int resultsPerPage) { this.resultsPerPage = resultsPerPage; } /** * @param key * @return boolean, true if the request contains key 'key' */ public boolean containsKey(String key) { return filters.containsKey(key); } /** * @param key * @return String value for key 'key', or null if no value exists */ public String get(String key) { return (String) filters.get(key); } /** * @param key * @param value */ public void put(String key, String value) { filters.put(key, value); } private String emptyIfNull(String arg) { if (arg == null) { return ""; } return arg; } /** * Set the Locale for the request, which impacts UI Strings * @param l */ public void setLocale(Locale l) { ResourceBundle b = ResourceBundle.getBundle(UI_RESOURCE_BUNDLE_NAME,l); formatter = new StringFormatter(b,l); } private String getUserLocale(HttpServletRequest httpRequest) { Locale l = httpRequest.getLocale(); ResourceBundle b = ResourceBundle.getBundle(UI_RESOURCE_BUNDLE_NAME, httpRequest.getLocale()); formatter = new StringFormatter(b,l); return emptyIfNull(httpRequest.getLocale().getDisplayLanguage()); } /** * extract REFERER, remote IP and authorization information from the * HttpServletRequest * * @param httpRequest */ private void extractHttpRequestInfo(HttpServletRequest httpRequest) { // attempt to get the HTTP referer if present.. put(WaybackConstants.REQUEST_REFERER_URL, emptyIfNull(httpRequest .getHeader("REFERER"))); put(WaybackConstants.REQUEST_REMOTE_ADDRESS, emptyIfNull(httpRequest .getRemoteAddr())); put(WaybackConstants.REQUEST_WAYBACK_HOSTNAME, emptyIfNull(httpRequest .getLocalName())); put(WaybackConstants.REQUEST_WAYBACK_PORT, String.valueOf(httpRequest .getLocalPort())); put(WaybackConstants.REQUEST_WAYBACK_CONTEXT, emptyIfNull(httpRequest .getContextPath())); put(WaybackConstants.REQUEST_AUTH_TYPE, emptyIfNull(httpRequest .getAuthType())); put(WaybackConstants.REQUEST_REMOTE_USER, emptyIfNull(httpRequest .getRemoteUser())); put(WaybackConstants.REQUEST_LOCALE_LANG,getUserLocale(httpRequest)); Cookie[] cookies = httpRequest.getCookies(); if(cookies != null) { for(Cookie cookie : cookies) { put(cookie.getName(),cookie.getValue()); } } } /** * @param prefix */ public void setServerPrefix(String prefix) { serverPrefix = prefix; } /** * @param prefix * @return an absolute String URL that will point to the root of the * server that is handling the request. */ public String getServerPrefix() { if(serverPrefix == null) { return ""; } return serverPrefix; } /** * @param prefix */ public void setContextPrefix(String prefix) { contextPrefix = prefix; } /** * Construct an absolute URL that points to the root of the context that * recieved the request, including a trailing "/". * * @return String absolute URL pointing to the Context root where the * request was revieved. */ public String getContextPrefix() { if(contextPrefix == null) { return ""; } return contextPrefix; } /** * attempt to fixup this WaybackRequest, mostly with respect to dates: if * only "date" was specified, infer start and end dates from it. Also grab * useful info from the HttpServletRequest, cookies, remote address, etc. * * @param httpRequest */ public void fixup(HttpServletRequest httpRequest) { extractHttpRequestInfo(httpRequest); String startDate = get(WaybackConstants.REQUEST_START_DATE); String endDate = get(WaybackConstants.REQUEST_END_DATE); String exactDate = get(WaybackConstants.REQUEST_EXACT_DATE); String partialDate = get(WaybackConstants.REQUEST_DATE); if (partialDate == null) { partialDate = ""; } if (startDate == null || startDate.length() == 0) { put(WaybackConstants.REQUEST_START_DATE, Timestamp .padStartDateStr(partialDate)); } else if (startDate.length() < 14) { put(WaybackConstants.REQUEST_START_DATE, Timestamp .padStartDateStr(startDate)); } if (endDate == null || endDate.length() == 0) { put(WaybackConstants.REQUEST_END_DATE, Timestamp .padEndDateStr(partialDate)); } else if (endDate.length() < 14) { put(WaybackConstants.REQUEST_END_DATE, Timestamp .padEndDateStr(endDate)); } if (exactDate == null || exactDate.length() == 0) { put(WaybackConstants.REQUEST_EXACT_DATE, Timestamp .padEndDateStr(partialDate)); } else if (exactDate.length() < 14) { put(WaybackConstants.REQUEST_EXACT_DATE, Timestamp .padEndDateStr(exactDate)); } } /** * @return String hex-encoded GET CGI arguments which will duplicate this * wayback request */ public String getQueryArguments() { return getQueryArguments(pageNum); } /** * @param pageNum * @return String hex-encoded GET CGI arguments which will duplicate the * same request, but for page 'pageNum' of the results */ public String getQueryArguments(int pageNum) { int numPerPage = resultsPerPage; StringBuffer queryString = new StringBuffer(""); Iterator<String> itr = filters.keySet().iterator(); while(itr.hasNext()) { String key = itr.next(); boolean isStandard = false; for(int i=0; i<standardHeaders.length; i++) { if(standardHeaders[i].equals(key)) { isStandard = true; break; } } if(isStandard) continue; String val = filters.get(key); if (queryString.length() > 0) { queryString.append(" "); } queryString.append(key + ":" + val); } String escapedQuery = queryString.toString(); try { escapedQuery = URLEncoder.encode(escapedQuery, "UTF-8"); } catch (UnsupportedEncodingException e) { // oops.. what to do? e.printStackTrace(); } return OpenSearchRequestParser.SEARCH_QUERY + "=" + escapedQuery + "&" + OpenSearchRequestParser.SEARCH_RESULTS + "=" + numPerPage + "&" + OpenSearchRequestParser.START_PAGE + "=" + pageNum; } /** * Set the request URL. * Also populates request url cleaned. * @param urlStr Request URL. * @throws URIException */ public void setRequestUrl(String urlStr) throws URIException { if (!urlStr.startsWith("http: if(urlStr.startsWith("http:/")) { urlStr = "http://" + urlStr.substring(6); } else { urlStr = "http://" + urlStr; } } // If its not http, next line throws exception. TODO: Fix. UURI requestURI = UURIFactory.getInstance(urlStr); put(WaybackConstants.REQUEST_URL_CLEANED, requestURI.toString()); put(WaybackConstants.REQUEST_URL, urlStr); } /** * @return StringFormatter based on user request info */ public StringFormatter getFormatter() { if(formatter == null) { setLocale(Locale.getAvailableLocales()[0]); } return formatter; } public WaybackRequest clone() { WaybackRequest wbRequest = new WaybackRequest(); wbRequest.resultsPerPage = resultsPerPage; wbRequest.pageNum = pageNum; wbRequest.contextPrefix = contextPrefix; wbRequest.serverPrefix = serverPrefix; wbRequest.formatter = formatter; wbRequest.filters = new HashMap<String,String>(); Iterator<String> itr = filters.keySet().iterator(); while(itr.hasNext()) { String key = itr.next(); String val = filters.get(key); wbRequest.filters.put(key, val); } return wbRequest; } /** * @return the context */ public AccessPoint getContext() { return context; } /** * @param context the context to set */ public void setContext(AccessPoint context) { this.context = context; } public ObjectFilter<CaptureSearchResult> getExclusionFilter() { return exclusionFilter; } public void setExclusionFilter(ObjectFilter<CaptureSearchResult> exclusionFilter) { this.exclusionFilter = exclusionFilter; } public Set<String> keySet() { return filters.keySet(); } }
package se.sics.cooja; import java.util.Collection; import javax.swing.JInternalFrame; import javax.swing.event.InternalFrameEvent; import javax.swing.event.InternalFrameListener; import org.jdom.Element; /** * Abstract class VisPlugin should be implemented by all plugins with * visualizers. By extending JInternalFrame, the visual apperence is decided by * the plugin itself. * * To add a new plugin to the simulator environment either add it via a project * directory or by altering the standard configuration files. * * For example how to implement a plugin see plugins SimControl or Visualizer2D. * * @author Fredrik Osterlind */ public abstract class VisPlugin extends JInternalFrame implements Plugin { private Object tag = null; /** * Sets frame title * @param title Frame title */ public VisPlugin(String title, final GUI gui) { super(title, true, true, true, true); // Close via gui setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // Detect frame events addInternalFrameListener(new InternalFrameListener() { public void internalFrameClosing(InternalFrameEvent e) { gui.removePlugin(VisPlugin.this, true); } public void internalFrameClosed(InternalFrameEvent e) { // NOP } public void internalFrameOpened(InternalFrameEvent e) { // NOP } public void internalFrameIconified(InternalFrameEvent e) { // NOP } public void internalFrameDeiconified(InternalFrameEvent e) { // NOP } public void internalFrameActivated(InternalFrameEvent e) { // Signal mote highlight if (VisPlugin.this.tag != null && tag instanceof Mote) { gui.signalMoteHighlight((Mote) tag); } } public void internalFrameDeactivated(InternalFrameEvent e) { // NOP } } ); } public JInternalFrame getGUI() { return this; } public Collection<Element> getConfigXML() { return null; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { return false; } public void tagWithObject(Object tag) { this.tag = tag; } public Object getTag() { return tag; } }
package com.netcracker.controllers; import com.netcracker.entities.FullLabelInfo; import com.netcracker.services.impl.LabelService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @Controller public class GettingJsonController { @Autowired LabelService labelService; @RequestMapping(value = "/json1", method = RequestMethod.GET) @ResponseBody public FullLabelInfo printJson() { return labelService.getFullLabelInfo(1); } @RequestMapping(value = "/json2", method = RequestMethod.GET) public String insertJsonIntoJsp(ModelMap model) { model.addAttribute("json_text", labelService.getFullLabelInfoJson(1)); return "json"; } @RequestMapping(value = "/json3", method = RequestMethod.GET) public String showJsonInputForm() { return "json_input_form"; } @RequestMapping(value = "/json4", method = RequestMethod.POST) public String handleRetrievedJsonText(HttpServletRequest request, ModelMap model) { String retrievedJson = request.getParameter("json_text"); FullLabelInfo fullLabelInfo = labelService.getFullLabelInfoFromJson(retrievedJson); if (fullLabelInfo != null) { model.addAttribute("json_text", labelService.getFullLabelInfoJson(fullLabelInfo.getId())); } return "result"; } }
package com.hextilla.cardbook.auth; import java.util.Calendar; import java.util.Properties; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.samskivert.depot.PersistenceContext; import com.samskivert.io.PersistenceException; import com.samskivert.jdbc.ConnectionProvider; import com.samskivert.servlet.RedirectException; import com.samskivert.servlet.user.AuthenticationFailedException; import com.samskivert.servlet.user.Authenticator; import com.samskivert.servlet.user.InvalidPasswordException; import com.samskivert.servlet.user.NoSuchUserException; import com.samskivert.servlet.util.CookieUtil; import com.samskivert.servlet.util.RequestUtils; import com.samskivert.util.Interval; import com.samskivert.util.RunQueue; import com.samskivert.util.StringUtil; import com.samskivert.util.Tuple; import com.hextilla.cardbox.server.persist.FBUserRecord; import com.hextilla.cardbox.server.persist.FBUserRepository; import com.hextilla.cardbox.facebook.CardBoxFacebookConfig; import static com.hextilla.cardbook.Log.log; /** * The user manager provides easy access to user objects for servlets. It takes care of cookie * management involved in login, logout and loading a user record during an authenticated session. */ public class FBUserManager { /** * Prepares this user manager for operation. See {@link #init(Properties,ConnectionProvider)}. * * @param pruneQueue an optional run queue on which to run our periodic session pruning task. */ public FBUserManager (PersistenceContext pctx) throws PersistenceException { // create the user repository _repository = createRepository(pctx); if (USERMGR_DEBUG) { log.info("FBUserManager initialized", "acook", _userAuthCookie, "login", _loginURL); } } public void shutdown () { } /** * Returns a reference to the repository in use by this user manager. */ public FBUserRepository getRepository () { return _repository; } /** * Fetches the necessary authentication information from the http request and loads the user * identified by that information. * * @return the user associated with the request or null if no user was associated with the * request or if the authentication information is bogus. */ public FBUserRecord loadUser (HttpServletRequest req) throws PersistenceException { String authcook = CookieUtil.getCookieValue(req, _userAuthCookie); if (USERMGR_DEBUG) { log.info("Loading user by cookie", _userAuthCookie, authcook); } return loadUser(authcook); } /** * Loads up a user based on the supplied session hash. */ public FBUserRecord loadUser (String sessionId) throws PersistenceException { FBUserRecord user = (sessionId == null) ? null : _repository.loadUser(sessionId); if (USERMGR_DEBUG) { log.info("Loaded user by authcode", "code", sessionId, "user", user); } return user; } /** * Loads up a user based on the supplied user ID. */ public FBUserRecord loadUser (int userId) throws PersistenceException { FBUserRecord user = (userId < 0) ? null : _repository.loadUser(userId); if (USERMGR_DEBUG) { log.info("Loaded user by userId", "userId", userId, "user", user); } return user; } /** * Fetches the necessary authentication information from the http request and loads the user * identified by that information. If no user could be loaded (because the requester is not * authenticated), a redirect exception will be thrown to redirect the user to the login page * specified in the user manager configuration. * * @return the user associated with the request. */ public FBUserRecord requireUser (HttpServletRequest req) throws PersistenceException, RedirectException { FBUserRecord user = loadUser(req); // if no user was loaded, we need to redirect these fine people to the login page if (user == null) { // first construct the redirect URL String target = CardBoxFacebookConfig.getLoginRedirectURL(); if (USERMGR_DEBUG) { log.info("No user found in require, redirecting", "to", target); } throw new RedirectException(target); } return user; } public String getSession (HttpServletRequest req) { return CookieUtil.getCookieValue(req, _userAuthCookie); } /** * Attempts to authenticate the requester and initiate an authenticated session for them. An * authenticated session involves their receiving a cookie that proves them to be authenticated * and an entry in the session database being created that maps their information to their * userid. If this call completes, the session was established and the proper cookies were set * in the supplied response object. If invalid authentication information is provided or some * other error occurs, an exception will be thrown. * * @param fbId The user's unique Facebook ID. * @param token The OAuth token returned from Facebook API. * @param expires Number of seconds until the access token expires. * @param req The request via which the login page was loaded. * @param rsp The response in which the cookie is to be set. * @param auth The authenticator used to check whether the user should be authenticated. * * @return the user object of the authenticated user. */ public FBUserRecord login (String fbId, String token, int expires, HttpServletRequest req, HttpServletResponse rsp) throws PersistenceException, AuthenticationFailedException { // load up the requested user FBUserRecord user = _repository.loadUser(Long.valueOf(fbId)); if (user == null) { log.warning("Couldn't load user by facebook ID", "fbId", fbId); throw new NoSuchUserException("error.no_such_user"); } // give them the necessary cookies and business effectLogin(user, token, expires, req, rsp); return user; } /** * If a user is already known to be authenticated for one reason or other, this method can be * used to give them the appropriate authentication cookies to effect their login. * * @param expires Date in milliseconds when the access token expires. */ public void effectLogin ( FBUserRecord user, String token, int expires, HttpServletRequest req, HttpServletResponse rsp) throws PersistenceException { Calendar now = Calendar.getInstance(); now.add(Calendar.SECOND, expires); long expiration = now.getTimeInMillis(); String sessionId = _repository.registerSession(user, token, expiration); Cookie acookie = new Cookie(_userAuthCookie, sessionId); acookie.setPath("/"); acookie.setMaxAge((expires > 0) ? expires : 60*60); if (USERMGR_DEBUG) { log.info("Setting cookie " + acookie + "."); } rsp.addCookie(acookie); } /** * Logs the user out. */ public void logout (HttpServletRequest req, HttpServletResponse rsp) { // nothing to do if they don't already have an auth cookie String authcode = CookieUtil.getCookieValue(req, _userAuthCookie); if (authcode == null) { return; } // set them up the bomb Cookie c = new Cookie(_userAuthCookie, "x"); c.setPath("/"); c.setMaxAge(0); CookieUtil.widenDomain(req, c); if (USERMGR_DEBUG) { log.info("Clearing cookie " + c + "."); } rsp.addCookie(c); // we need an unwidened one to ensure that old-style cookies are wiped as well c = new Cookie(_userAuthCookie, "x"); c.setPath("/"); c.setMaxAge(0); rsp.addCookie(c); } /** * Called by the user manager to create the user repository. Derived classes can override this * and create a specialized repository if they so desire. */ protected FBUserRepository createRepository (PersistenceContext pctx) throws PersistenceException { return new FBUserRepository(pctx); } /** The user repository. */ protected FBUserRepository _repository; /** The URL for the user login page. */ protected static String _loginURL; /** The name of our user authentication cookie. */ protected String _userAuthCookie = USERAUTH_COOKIE; /** The user authentication cookie name. */ protected static final String USERAUTH_COOKIE = "id_"; /** Prune the session table every hour. */ protected static final long SESSION_PRUNE_INTERVAL = 60L * 60L * 1000L; /** Indicates how long (in days) that a "persisting" session token should last. */ protected static final int PERSIST_EXPIRE_DAYS = 30; /** Indicates how long (in days) that a "non-persisting" session token should last. */ protected static final int NON_PERSIST_EXPIRE_DAYS = 1; /** Change this to true and recompile to debug cookie handling. */ protected static final boolean USERMGR_DEBUG = false; }
package providers; import com.feth.play.module.mail.Mailer.Mail.Body; import com.feth.play.module.pa.PlayAuthenticate; import com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider; import com.feth.play.module.pa.providers.password.UsernamePasswordAuthUser; import controllers.routes; import models.LinkedAccount; import models.TokenAction; import models.TokenAction.Type; import models.User; import play.Application; import play.Logger; import play.data.Form; import play.data.validation.Constraints.Email; import play.data.validation.Constraints.MinLength; import play.data.validation.Constraints.Required; import play.i18n.Lang; import play.i18n.Messages; import play.mvc.Call; import play.mvc.Http.Context; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static play.data.Form.form; public class MyUsernamePasswordAuthProvider extends UsernamePasswordAuthProvider<String, MyLoginUsernamePasswordAuthUser, MyUsernamePasswordAuthUser, MyUsernamePasswordAuthProvider.MyLogin, MyUsernamePasswordAuthProvider.MySignup> { private static final String SETTING_KEY_VERIFICATION_LINK_SECURE = SETTING_KEY_MAIL + "." + "verificationLink.secure"; private static final String SETTING_KEY_LINK_LOGIN_AFTER_PASSWORD_RESET = "loginAfterPasswordReset"; private static final String EMAIL_TEMPLATE_FALLBACK_LANGUAGE = "en"; @Override protected List<String> neededSettingKeys() { final List<String> needed = new ArrayList<String>( super.neededSettingKeys()); needed.add(SETTING_KEY_VERIFICATION_LINK_SECURE); needed.add(SETTING_KEY_LINK_LOGIN_AFTER_PASSWORD_RESET); return needed; } public static MyUsernamePasswordAuthProvider getProvider() { return (MyUsernamePasswordAuthProvider) PlayAuthenticate .getProvider(UsernamePasswordAuthProvider.PROVIDER_KEY); } public static class MyIdentity { public MyIdentity() { } public MyIdentity(final String email) { this.email = email; } @Required @Email public String email; } public static class MyLogin extends MyIdentity implements com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider.UsernamePassword { @Required @MinLength(5) public String password; @Override public String getEmail() { return email; } @Override public String getPassword() { return password; } } public static class MySignup extends MyLogin { @Required @MinLength(5) public String repeatPassword; @Required public String name; public String validate() { if (password == null || !password.equals(repeatPassword)) { return Messages .get("playauthenticate.password.signup.error.passwords_not_same"); } return null; } } public static final Form<MySignup> SIGNUP_FORM = form(MySignup.class); public static final Form<MyLogin> LOGIN_FORM = form(MyLogin.class); public MyUsernamePasswordAuthProvider(Application app) { super(app); } protected Form<MySignup> getSignupForm() { return SIGNUP_FORM; } protected Form<MyLogin> getLoginForm() { return LOGIN_FORM; } @Override protected com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider.SignupResult signupUser(final MyUsernamePasswordAuthUser user) { final User u = User.findByUsernamePasswordIdentity(user); if (u != null) { if (u.emailValidated()) { // This user exists, has its email validated and is active return SignupResult.USER_EXISTS; } else { // this user exists, is active but has not yet validated its // email return SignupResult.USER_EXISTS_UNVERIFIED; } } // The user either does not exist or is inactive - create a new one @SuppressWarnings("unused") final User newUser = User.create(user); // Usually the email should be verified before allowing login, however // if you return // return SignupResult.USER_CREATED; // then the user gets logged in directly return SignupResult.USER_CREATED_UNVERIFIED; } @Override protected com.feth.play.module.pa.providers.password.UsernamePasswordAuthProvider.LoginResult loginUser( final MyLoginUsernamePasswordAuthUser authUser) { final User u = User.findByUsernamePasswordIdentity(authUser); if (u == null) { return LoginResult.NOT_FOUND; } else { if (!u.emailValidated()) { return LoginResult.USER_UNVERIFIED; } else { for (final LinkedAccount acc : u.linkedAccounts()) { if (getKey().equals(acc.providerKey)) { if (authUser.checkPassword(acc.providerUserId, authUser.getPassword())) { // Password was correct return LoginResult.USER_LOGGED_IN; } else { // if you don't return here, // you would allow the user to have // multiple passwords defined // usually we don't want this return LoginResult.WRONG_PASSWORD; } } } return LoginResult.WRONG_PASSWORD; } } } @Override protected Call userExists(final UsernamePasswordAuthUser authUser) { return routes.Signup.exists(); } @Override protected Call userUnverified(final UsernamePasswordAuthUser authUser) { return routes.Application.index(); } @Override protected MyUsernamePasswordAuthUser buildSignupAuthUser( final MySignup signup, final Context ctx) { return new MyUsernamePasswordAuthUser(signup); } @Override protected MyLoginUsernamePasswordAuthUser buildLoginAuthUser( final MyLogin login, final Context ctx) { return new MyLoginUsernamePasswordAuthUser(login.getPassword(), login.getEmail()); } @Override protected MyLoginUsernamePasswordAuthUser transformAuthUser(final MyUsernamePasswordAuthUser authUser, final Context context) { return new MyLoginUsernamePasswordAuthUser(authUser.getEmail()); } @Override protected String getVerifyEmailMailingSubject( final MyUsernamePasswordAuthUser user, final Context ctx) { return Messages.get("playauthenticate.password.verify_signup.subject"); } @Override protected String onLoginUserNotFound(final Context context) { context.flash() .put(controllers.ApplicationConstants.FLASH_ERROR_KEY(), Messages.get("playauthenticate.password.login.unknown_user_or_pw")); return super.onLoginUserNotFound(context); } @Override protected Body getVerifyEmailMailingBody(final String token, final MyUsernamePasswordAuthUser user, final Context ctx) { throw new UnsupportedOperationException(); } private static String generateToken() { return UUID.randomUUID().toString(); } @Override protected String generateVerificationRecord( final MyUsernamePasswordAuthUser user) { return generateVerificationRecord(User.findByAuthUserIdentity(user)); } protected String generateVerificationRecord(final User user) { final String token = generateToken(); // Do database actions, etc. TokenAction.create(Type.EMAIL_VERIFICATION, token, user); return token; } protected String getEmailTemplate(final String template, final String langCode, final String url, final String token, final String name, final String email) { Class<?> cls = null; String ret = null; try { cls = Class.forName(template + "_" + langCode); } catch (ClassNotFoundException e) { Logger.warn("Template: '" + template + "_" + langCode + "' was not found! Trying to use English fallback template instead."); } if (cls == null) { try { cls = Class.forName(template + "_" + EMAIL_TEMPLATE_FALLBACK_LANGUAGE); } catch (ClassNotFoundException e) { Logger.error("Fallback template: '" + template + "_" + EMAIL_TEMPLATE_FALLBACK_LANGUAGE + "' was not found either!"); } } if (cls != null) { Method htmlRender = null; try { htmlRender = cls.getMethod("render", String.class, String.class, String.class, String.class); ret = htmlRender.invoke(null, url, token, name, email) .toString(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return ret; } private String getEmailName(final User user) { return getEmailName(user.email(), user.name()); } }
package com.turlir.abakcalc; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import com.turlir.converter.Printer; import com.turlir.converter.Visual; import java.util.Collections; import java.util.List; public class Editor extends android.support.v7.widget.AppCompatEditText { private List<Visual> mViews; private final Printer mPrinter = new DirectPrinter(); private final StringBuilder mCopy = new StringBuilder(); public Editor(Context context) { this(context, null); } public Editor(Context context, AttributeSet attrs) { super(context, attrs); setShowSoftInputOnFocus(false); mViews = Collections.emptyList(); } @Override public void setText(CharSequence text, BufferType type) { super.setText(text, type); if (mCopy != null) { mCopy.replace(0, mCopy.length(), text.toString()); } } @Override protected void onSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); Log.d("Editor", "onSelectionChanged " + selStart + " " + selEnd); if (mViews != null /*selStart != 0 || selStart != selEnd*/) { int l = getText().length(); for (Visual item : mViews) { if (item.selectionConstraint(selEnd, l)) { item.interceptSelection(this); return; } } } } public void setRepresentation(List<Visual> views) { for (Visual view : views) { view.print(mPrinter); } String s = mPrinter.toString(); mPrinter.reset(); mViews = views; int ss = getSelectionStart(); int oldLength = getText().length(); setText(s); setSelection(ss + (s.length() - oldLength)); //return s; } public String removeSymbol(int index) { int length = getText().length(); if (length > 0 && index > 0) { for (Visual item : mViews) { if (item.selectionConstraint(index, length)) { int s = item.constraintStart(); int e = item.constraintEnd(); return getText().replace(s, e, "").toString(); } } return getText().replace(index - 1, index, "").toString(); } return ""; } public String insertSymbol(int index, String s) { mCopy.insert(index, s); return mCopy.toString(); } }
package in.tosc.ghumo; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.util.Log; public class MeterService extends Service { public LocationManager locationManager; public Location lastLocation = null; public Float distance = (float) 0.0, finalKilometers = (float) 0, finalFare = (float) 0; public Criteria criteria; LocationListener locLis; public MeterService() { } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locLis = new LocationListener() { @Override public void onLocationChanged(Location location) { Log.d("Location", location.getLatitude() + " " + location.getLongitude()); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // int[] grantResults) // for Activity return; } } locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, false), 600, 50, this); } @Override public void onProviderDisabled(String provider) { } }; try { locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, false), 600, 50, locLis); } catch (SecurityException e) { e.printStackTrace(); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); try { locationManager.removeUpdates(locLis); } catch (Exception e ) { //Nothing to do here } } }
package com.thoughtworks.xstream.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to define an XStream class or field alias. * * @author Emil Kirschner * @author Chung-Onn Cheong * @see com.thoughtworks.xstream.XStream#alias(String, Class) * @see com.thoughtworks.xstream.XStream#alias(String, Class, Class) * @see com.thoughtworks.xstream.XStream#addDefaultImplementation(Class, Class) */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.FIELD}) public @interface XStreamAlias { /** * The name of the class or field alias. */ public String value(); /** * A possible default implementation if the annotated type is an interface. */ public Class<?> impl() default Void.class; //Use Void to denote as Null }
package org.yamcs.web.rest.mdb; import java.nio.ByteOrder; import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.bind.DatatypeConverter; import org.yamcs.parameter.ParameterValue; import org.yamcs.protobuf.Mdb; import org.yamcs.protobuf.Mdb.AlarmInfo; import org.yamcs.protobuf.Mdb.AlarmLevelType; import org.yamcs.protobuf.Mdb.AlarmRange; import org.yamcs.protobuf.Mdb.AlgorithmInfo; import org.yamcs.protobuf.Mdb.AlgorithmInfo.Scope; import org.yamcs.protobuf.Mdb.ArgumentAssignmentInfo; import org.yamcs.protobuf.Mdb.ArgumentInfo; import org.yamcs.protobuf.Mdb.ArgumentTypeInfo; import org.yamcs.protobuf.Mdb.CommandInfo; import org.yamcs.protobuf.Mdb.ComparisonInfo; import org.yamcs.protobuf.Mdb.ContainerInfo; import org.yamcs.protobuf.Mdb.DataEncodingInfo; import org.yamcs.protobuf.Mdb.DataEncodingInfo.Type; import org.yamcs.protobuf.Mdb.DataSourceType; import org.yamcs.protobuf.Mdb.InputParameterInfo; import org.yamcs.protobuf.Mdb.OutputParameterInfo; import org.yamcs.protobuf.Mdb.ParameterInfo; import org.yamcs.protobuf.Mdb.ParameterTypeInfo; import org.yamcs.protobuf.Mdb.RepeatInfo; import org.yamcs.protobuf.Mdb.SequenceEntryInfo; import org.yamcs.protobuf.Mdb.SignificanceInfo; import org.yamcs.protobuf.Mdb.SignificanceInfo.SignificanceLevelType; import org.yamcs.protobuf.Mdb.TransmissionConstraintInfo; import org.yamcs.protobuf.Mdb.UnitInfo; import org.yamcs.protobuf.Yamcs.NamedObjectId; import org.yamcs.protobuf.YamcsManagement.HistoryInfo; import org.yamcs.protobuf.YamcsManagement.SpaceSystemInfo; import org.yamcs.web.rest.RestRequest; import org.yamcs.web.rest.RestRequest.Option; import org.yamcs.xtce.AlarmRanges; import org.yamcs.xtce.Algorithm; import org.yamcs.xtce.Argument; import org.yamcs.xtce.ArgumentAssignment; import org.yamcs.xtce.ArgumentType; import org.yamcs.xtce.BaseDataType; import org.yamcs.xtce.BinaryArgumentType; import org.yamcs.xtce.BinaryDataEncoding; import org.yamcs.xtce.BooleanArgumentType; import org.yamcs.xtce.BooleanDataEncoding; import org.yamcs.xtce.Calibrator; import org.yamcs.xtce.Comparison; import org.yamcs.xtce.ComparisonList; import org.yamcs.xtce.ContainerEntry; import org.yamcs.xtce.CustomAlgorithm; import org.yamcs.xtce.DataEncoding; import org.yamcs.xtce.DataSource; import org.yamcs.xtce.DynamicIntegerValue; import org.yamcs.xtce.EnumeratedArgumentType; import org.yamcs.xtce.EnumeratedParameterType; import org.yamcs.xtce.EnumerationAlarm; import org.yamcs.xtce.EnumerationAlarm.EnumerationAlarmItem; import org.yamcs.xtce.FixedIntegerValue; import org.yamcs.xtce.FloatArgumentType; import org.yamcs.xtce.FloatDataEncoding; import org.yamcs.xtce.FloatParameterType; import org.yamcs.xtce.Header; import org.yamcs.xtce.History; import org.yamcs.xtce.InputParameter; import org.yamcs.xtce.IntegerArgumentType; import org.yamcs.xtce.IntegerDataEncoding; import org.yamcs.xtce.IntegerParameterType; import org.yamcs.xtce.MetaCommand; import org.yamcs.xtce.NumericAlarm; import org.yamcs.xtce.OnParameterUpdateTrigger; import org.yamcs.xtce.OnPeriodicRateTrigger; import org.yamcs.xtce.OperatorType; import org.yamcs.xtce.OutputParameter; import org.yamcs.xtce.Parameter; import org.yamcs.xtce.ParameterEntry; import org.yamcs.xtce.ParameterType; import org.yamcs.xtce.Repeat; import org.yamcs.xtce.SequenceContainer; import org.yamcs.xtce.SequenceEntry; import org.yamcs.xtce.Significance; import org.yamcs.xtce.SpaceSystem; import org.yamcs.xtce.StringArgumentType; import org.yamcs.xtce.StringDataEncoding; import org.yamcs.xtce.TransmissionConstraint; import org.yamcs.xtce.TriggerSetType; import org.yamcs.xtce.UnitType; import org.yamcs.xtce.ValueEnumeration; public class XtceToGpbAssembler { public enum DetailLevel { LINK, SUMMARY, FULL } public static ContainerInfo toContainerInfo(SequenceContainer c, String instanceURL, DetailLevel detail, Set<Option> options) { ContainerInfo.Builder cb = ContainerInfo.newBuilder(); cb.setName(c.getName()); cb.setQualifiedName(c.getQualifiedName()); if (!options.contains(Option.NO_LINK)) { cb.setUrl(instanceURL + "/containers" + c.getQualifiedName()); } if (detail == DetailLevel.SUMMARY || detail == DetailLevel.FULL) { if (c.getShortDescription() != null) { cb.setShortDescription(c.getShortDescription()); } if (c.getLongDescription() != null) { cb.setLongDescription(c.getLongDescription()); } if (c.getAliasSet() != null) { Map<String, String> aliases = c.getAliasSet().getAliases(); for (Entry<String, String> me : aliases.entrySet()) { cb.addAlias(NamedObjectId.newBuilder().setName(me.getValue()).setNamespace(me.getKey())); } } if (c.getRateInStream() != null) { cb.setMaxInterval(c.getRateInStream().getMaxInterval()); } if (c.getSizeInBits() != -1) { cb.setSizeInBits(c.getSizeInBits()); } if (c.getBaseContainer() != null) { if (detail == DetailLevel.SUMMARY) { cb.setBaseContainer(toContainerInfo(c.getBaseContainer(), instanceURL, DetailLevel.LINK, options)); } else if (detail == DetailLevel.FULL) { cb.setBaseContainer(toContainerInfo(c.getBaseContainer(), instanceURL, DetailLevel.FULL, options)); } } if (c.getRestrictionCriteria() != null) { if (c.getRestrictionCriteria() instanceof ComparisonList) { ComparisonList xtceList = (ComparisonList) c.getRestrictionCriteria(); for (Comparison comparison : xtceList.getComparisonList()) { cb.addRestrictionCriteria(toComparisonInfo(comparison, instanceURL, options)); } } else if (c.getRestrictionCriteria() instanceof Comparison) { cb.addRestrictionCriteria( toComparisonInfo((Comparison) c.getRestrictionCriteria(), instanceURL, options)); } } for (SequenceEntry entry : c.getEntryList()) { if (detail == DetailLevel.SUMMARY) { cb.addEntry(toSequenceEntryInfo(entry, instanceURL, DetailLevel.LINK, options)); } else if (detail == DetailLevel.FULL) { cb.addEntry(toSequenceEntryInfo(entry, instanceURL, DetailLevel.FULL, options)); } } } return cb.build(); } public static SequenceEntryInfo toSequenceEntryInfo(SequenceEntry e, String instanceURL, DetailLevel detail, Set<Option> options) { SequenceEntryInfo.Builder b = SequenceEntryInfo.newBuilder(); b.setLocationInBits(e.getLocationInContainerInBits()); switch (e.getReferenceLocation()) { case containerStart: b.setReferenceLocation(SequenceEntryInfo.ReferenceLocationType.CONTAINER_START); break; case previousEntry: b.setReferenceLocation(SequenceEntryInfo.ReferenceLocationType.PREVIOUS_ENTRY); break; default: throw new IllegalStateException("Unexpected reference location " + e); } if (e instanceof ContainerEntry) { ContainerEntry ce = (ContainerEntry) e; if (detail == DetailLevel.LINK || detail == DetailLevel.SUMMARY) { b.setContainer(toContainerInfo(ce.getRefContainer(), instanceURL, DetailLevel.LINK, options)); } else if (detail == DetailLevel.FULL) { b.setContainer(toContainerInfo(ce.getRefContainer(), instanceURL, DetailLevel.FULL, options)); } } else if (e instanceof ParameterEntry) { ParameterEntry pe = (ParameterEntry) e; if (detail == DetailLevel.LINK || detail == DetailLevel.SUMMARY) { b.setParameter(toParameterInfo(pe.getParameter(), instanceURL, DetailLevel.LINK, options)); } else if (detail == DetailLevel.FULL) { b.setParameter(toParameterInfo(pe.getParameter(), instanceURL, DetailLevel.FULL, options)); } } else { throw new IllegalStateException("Unexpected entry " + e); } return b.build(); } public static RepeatInfo toRepeatInfo(Repeat xtceRepeat, String instanceURL, DetailLevel detail, Set<Option> options) { RepeatInfo.Builder b = RepeatInfo.newBuilder(); b.setBitsBetween(xtceRepeat.getOffsetSizeInBits()); if (xtceRepeat.getCount() instanceof FixedIntegerValue) { FixedIntegerValue val = (FixedIntegerValue) xtceRepeat.getCount(); b.setFixedCount(val.getValue()); } else if (xtceRepeat.getCount() instanceof DynamicIntegerValue) { DynamicIntegerValue val = (DynamicIntegerValue) xtceRepeat.getCount(); if (detail == DetailLevel.SUMMARY) { b.setDynamicCount(toParameterInfo(val.getParameterInstnaceRef().getParameter(), instanceURL, DetailLevel.LINK, options)); } else if (detail == DetailLevel.FULL) { b.setDynamicCount(toParameterInfo(val.getParameterInstnaceRef().getParameter(), instanceURL, DetailLevel.FULL, options)); } } else { throw new IllegalStateException("Unexpected repeat count " + xtceRepeat.getCount()); } return b.build(); } /** * @param detail * whether base commands should be expanded */ public static CommandInfo toCommandInfo(MetaCommand cmd, String instanceURL, DetailLevel detail, Set<Option> options) { CommandInfo.Builder cb = CommandInfo.newBuilder(); cb.setName(cmd.getName()); cb.setQualifiedName(cmd.getQualifiedName()); if (!options.contains(Option.NO_LINK)) { cb.setUrl(instanceURL + "/commands" + cmd.getQualifiedName()); } if (detail == DetailLevel.SUMMARY || detail == DetailLevel.FULL) { if (cmd.getShortDescription() != null) { cb.setShortDescription(cmd.getShortDescription()); } if (cmd.getLongDescription() != null) { cb.setLongDescription(cmd.getLongDescription()); } if (cmd.getAliasSet() != null) { Map<String, String> aliases = cmd.getAliasSet().getAliases(); for (Entry<String, String> me : aliases.entrySet()) { cb.addAlias(NamedObjectId.newBuilder().setName(me.getValue()).setNamespace(me.getKey())); } } if (cmd.getDefaultSignificance() != null) { cb.setSignificance(toSignificanceInfo(cmd.getDefaultSignificance())); } if (cmd.getArgumentList() != null) { for (Argument xtceArgument : cmd.getArgumentList()) { cb.addArgument(toArgumentInfo(xtceArgument)); } } if (cmd.getArgumentAssignmentList() != null) { for (ArgumentAssignment xtceAssignment : cmd.getArgumentAssignmentList()) { cb.addArgumentAssignment(toArgumentAssignmentInfo(xtceAssignment)); } } cb.setAbstract(cmd.isAbstract()); if (cmd.getTransmissionConstraintList() != null) { for (TransmissionConstraint xtceConstraint : cmd.getTransmissionConstraintList()) { cb.addConstraint(toTransmissionConstraintInfo(xtceConstraint, instanceURL, options)); } } if (detail == DetailLevel.SUMMARY) { if (cmd.getBaseMetaCommand() != null) { cb.setBaseCommand(toCommandInfo(cmd.getBaseMetaCommand(), instanceURL, DetailLevel.LINK, options)); } } else if (detail == DetailLevel.FULL) { if (cmd.getBaseMetaCommand() != null) { cb.setBaseCommand(toCommandInfo(cmd.getBaseMetaCommand(), instanceURL, DetailLevel.FULL, options)); } } } return cb.build(); } public static ArgumentInfo toArgumentInfo(Argument xtceArgument) { ArgumentInfo.Builder b = ArgumentInfo.newBuilder(); b.setName(xtceArgument.getName()); if (xtceArgument.getShortDescription() != null) { b.setDescription(xtceArgument.getShortDescription()); } if (xtceArgument.getInitialValue() != null) { b.setInitialValue(xtceArgument.getInitialValue()); } if (xtceArgument.getArgumentType() != null) { ArgumentType xtceType = xtceArgument.getArgumentType(); b.setType(toArgumentTypeInfo(xtceType)); if (!b.hasInitialValue()) { String initialValue = null; initialValue = getArgumentTypeInitialValue(xtceArgument.getArgumentType()); if (initialValue != null) { b.setInitialValue(initialValue); } } } return b.build(); } public static ArgumentAssignmentInfo toArgumentAssignmentInfo(ArgumentAssignment xtceArgument) { ArgumentAssignmentInfo.Builder b = ArgumentAssignmentInfo.newBuilder(); b.setName(xtceArgument.getArgumentName()); b.setValue(xtceArgument.getArgumentValue()); return b.build(); } public static TransmissionConstraintInfo toTransmissionConstraintInfo(TransmissionConstraint xtceConstraint, String instanceURL, Set<Option> options) { TransmissionConstraintInfo.Builder b = TransmissionConstraintInfo.newBuilder(); if (xtceConstraint.getMatchCriteria() instanceof Comparison) { b.addComparison(toComparisonInfo((Comparison) xtceConstraint.getMatchCriteria(), instanceURL, options)); } else if (xtceConstraint.getMatchCriteria() instanceof ComparisonList) { ComparisonList xtceList = (ComparisonList) xtceConstraint.getMatchCriteria(); for (Comparison xtceComparison : xtceList.getComparisonList()) { b.addComparison(toComparisonInfo(xtceComparison, instanceURL, options)); } } else { throw new IllegalStateException("Unexpected match criteria " + xtceConstraint.getMatchCriteria()); } b.setTimeout(xtceConstraint.getTimeout()); return b.build(); } public static ComparisonInfo toComparisonInfo(Comparison xtceComparison, String instanceURL, Set<Option> options) { ComparisonInfo.Builder b = ComparisonInfo.newBuilder(); b.setParameter(toParameterInfo(xtceComparison.getParameter(), instanceURL, DetailLevel.LINK, options)); b.setOperator(toOperatorType(xtceComparison.getComparisonOperator())); b.setValue(xtceComparison.getStringValue()); return b.build(); } public static ComparisonInfo.OperatorType toOperatorType(OperatorType xtceOperator) { switch (xtceOperator) { case EQUALITY: return ComparisonInfo.OperatorType.EQUAL_TO; case INEQUALITY: return ComparisonInfo.OperatorType.NOT_EQUAL_TO; case LARGEROREQUALTHAN: return ComparisonInfo.OperatorType.GREATER_THAN_OR_EQUAL_TO; case LARGERTHAN: return ComparisonInfo.OperatorType.GREATER_THAN; case SMALLEROREQUALTHAN: return ComparisonInfo.OperatorType.SMALLER_THAN_OR_EQUAL_TO; case SMALLERTHAN: return ComparisonInfo.OperatorType.SMALLER_THAN; default: throw new IllegalStateException("Unexpected operator " + xtceOperator); } } public static SignificanceInfo toSignificanceInfo(Significance xtceSignificance) { SignificanceInfo.Builder b = SignificanceInfo.newBuilder(); switch (xtceSignificance.getConsequenceLevel()) { case none: b.setConsequenceLevel(SignificanceLevelType.NONE); break; case watch: b.setConsequenceLevel(SignificanceLevelType.WATCH); break; case warning: b.setConsequenceLevel(SignificanceLevelType.WARNING); break; case distress: b.setConsequenceLevel(SignificanceLevelType.DISTRESS); break; case critical: b.setConsequenceLevel(SignificanceLevelType.CRITICAL); break; case severe: b.setConsequenceLevel(SignificanceLevelType.SEVERE); break; default: throw new IllegalStateException("Unexpected level " + xtceSignificance.getConsequenceLevel()); } if (xtceSignificance.getReasonForWarning() != null) { b.setReasonForWarning(xtceSignificance.getReasonForWarning()); } return b.build(); } public static ParameterInfo toParameterInfo(Parameter p, String mdbURL, DetailLevel detail, Set<Option> options) { ParameterInfo.Builder b = ParameterInfo.newBuilder(); b.setName(p.getName()); b.setQualifiedName(p.getQualifiedName()); if (!options.contains(Option.NO_LINK)) { b.setUrl(mdbURL + "/parameters" + p.getQualifiedName()); } if (detail == DetailLevel.SUMMARY || detail == DetailLevel.FULL) { if (p.getShortDescription() != null) { b.setShortDescription(p.getShortDescription()); } DataSource xtceDs = p.getDataSource(); if (xtceDs != null) { switch (xtceDs) { case TELEMETERED: b.setDataSource(DataSourceType.TELEMETERED); break; case LOCAL: b.setDataSource(DataSourceType.LOCAL); break; case COMMAND: b.setDataSource(DataSourceType.COMMAND); break; case COMMAND_HISTORY: b.setDataSource(DataSourceType.COMMAND_HISTORY); break; case CONSTANT: b.setDataSource(DataSourceType.CONSTANT); break; case DERIVED: b.setDataSource(DataSourceType.DERIVED); break; case SYSTEM: b.setDataSource(DataSourceType.SYSTEM); break; default: throw new IllegalStateException("Unexpected data source " + xtceDs); } } if (p.getParameterType() != null) b.setType(toParameterTypeInfo(p.getParameterType(), detail)); } if (detail == DetailLevel.FULL) { if (p.getLongDescription() != null) { b.setLongDescription(p.getLongDescription()); } if (p.getAliasSet() != null) { Map<String, String> aliases = p.getAliasSet().getAliases(); for (Entry<String, String> me : aliases.entrySet()) { b.addAlias(NamedObjectId.newBuilder().setName(me.getValue()).setNamespace(me.getKey())); } } } return b.build(); } public static ParameterTypeInfo toParameterTypeInfo(ParameterType parameterType, DetailLevel detail) { ParameterTypeInfo.Builder infob = ParameterTypeInfo.newBuilder(); infob.setEngType(parameterType.getTypeAsString()); for (UnitType ut : parameterType.getUnitSet()) { infob.addUnitSet(toUnitInfo(ut)); } if (detail == DetailLevel.FULL) { if (parameterType.getEncoding() != null) { infob.setDataEncoding(toDataEncodingInfo(parameterType.getEncoding())); } if (parameterType instanceof IntegerParameterType) { IntegerParameterType ipt = (IntegerParameterType) parameterType; if (ipt.getDefaultAlarm() != null) { infob.setDefaultAlarm(toAlarmInfo(ipt.getDefaultAlarm())); } } else if (parameterType instanceof FloatParameterType) { FloatParameterType fpt = (FloatParameterType) parameterType; if (fpt.getDefaultAlarm() != null) { infob.setDefaultAlarm(toAlarmInfo(fpt.getDefaultAlarm())); } } else if (parameterType instanceof EnumeratedParameterType) { EnumeratedParameterType ept = (EnumeratedParameterType) parameterType; if (ept.getDefaultAlarm() != null) { infob.setDefaultAlarm(toAlarmInfo(ept.getDefaultAlarm())); } for (ValueEnumeration xtceValue : ept.getValueEnumerationList()) { infob.addEnumValue(toEnumValue(xtceValue)); } } } return infob.build(); } private static String getArgumentTypeInitialValue(ArgumentType argumentType) { if (argumentType == null) return null; if (argumentType instanceof IntegerArgumentType) { return ((IntegerArgumentType) argumentType).getInitialValue(); } else if (argumentType instanceof FloatArgumentType) { return ((FloatArgumentType) argumentType).getInitialValue() != null ? ((FloatArgumentType) argumentType).getInitialValue() + "" : null; } else if (argumentType instanceof EnumeratedArgumentType) { return ((EnumeratedArgumentType) argumentType).getInitialValue(); } else if (argumentType instanceof StringArgumentType) { return ((StringArgumentType) argumentType).getInitialValue(); } else if (argumentType instanceof BinaryArgumentType) { byte[] initialValue = ((BinaryArgumentType) argumentType).getInitialValue(); return initialValue != null ? DatatypeConverter.printHexBinary(initialValue) : null; } else if (argumentType instanceof BooleanArgumentType) { return ((BooleanArgumentType) argumentType).getInitialValue() != null ? ((BooleanArgumentType) argumentType).getInitialValue().toString() : null; } return null; } public static ArgumentTypeInfo toArgumentTypeInfo(ArgumentType argumentType) { ArgumentTypeInfo.Builder infob = ArgumentTypeInfo.newBuilder(); if (((BaseDataType) argumentType).getEncoding() != null) { infob.setDataEncoding(toDataEncodingInfo(((BaseDataType) argumentType).getEncoding())); } infob.setEngType(argumentType.getTypeAsString()); for (UnitType ut : argumentType.getUnitSet()) { infob.addUnitSet(toUnitInfo(ut)); } if (argumentType instanceof IntegerArgumentType) { IntegerArgumentType iat = (IntegerArgumentType) argumentType; if (iat.getValidRange() != null) { infob.setRangeMin(iat.getValidRange().getMinInclusive()); infob.setRangeMax(iat.getValidRange().getMaxInclusive()); } } else if (argumentType instanceof FloatArgumentType) { FloatArgumentType fat = (FloatArgumentType) argumentType; if (fat.getValidRange() != null) { infob.setRangeMin(fat.getValidRange().getMin()); infob.setRangeMax(fat.getValidRange().getMax()); } } else if (argumentType instanceof EnumeratedArgumentType) { EnumeratedArgumentType eat = (EnumeratedArgumentType) argumentType; for (ValueEnumeration xtceValue : eat.getValueEnumerationList()) { infob.addEnumValue(toEnumValue(xtceValue)); } } return infob.build(); } // Simplifies the XTCE structure a bit for outside use. // String-encoded numeric types see some sort of two-step conversion from raw to eng // with the first to interpret the string (stored in a nested StringDataEncoding) // and the second to apply any regular integer calibrations (stored in the actual DataEncoding) // Below code will represent all of those things as type 'STRING' as the user should expect it. public static DataEncodingInfo toDataEncodingInfo(DataEncoding xtceDataEncoding) { DataEncodingInfo.Builder infob = DataEncodingInfo.newBuilder(); infob.setLittleEndian(xtceDataEncoding.getByteOrder() == ByteOrder.LITTLE_ENDIAN); if (xtceDataEncoding.getSizeInBits() >= 0) { infob.setSizeInBits(xtceDataEncoding.getSizeInBits()); } if (xtceDataEncoding instanceof BinaryDataEncoding) { infob.setType(Type.BINARY); } else if (xtceDataEncoding instanceof BooleanDataEncoding) { infob.setType(Type.BOOLEAN); } else if (xtceDataEncoding instanceof FloatDataEncoding) { FloatDataEncoding fde = (FloatDataEncoding) xtceDataEncoding; if (fde.getEncoding() == FloatDataEncoding.Encoding.STRING) { infob.setType(Type.STRING); infob.setEncoding(toTextualEncoding(fde.getStringDataEncoding())); } else { infob.setType(Type.FLOAT); infob.setEncoding(fde.getEncoding().toString()); } if (fde.getDefaultCalibrator() != null) { Calibrator calibrator = fde.getDefaultCalibrator(); infob.setDefaultCalibrator(calibrator.toString()); } } else if (xtceDataEncoding instanceof IntegerDataEncoding) { IntegerDataEncoding ide = (IntegerDataEncoding) xtceDataEncoding; if (ide.getEncoding() == IntegerDataEncoding.Encoding.STRING) { infob.setType(Type.STRING); infob.setEncoding(toTextualEncoding(ide.getStringEncoding())); } else { infob.setType(Type.INTEGER); infob.setEncoding(ide.getEncoding().toString()); } if (ide.getDefaultCalibrator() != null) { Calibrator calibrator = ide.getDefaultCalibrator(); infob.setDefaultCalibrator(calibrator.toString()); } } else if (xtceDataEncoding instanceof StringDataEncoding) { infob.setType(Type.STRING); StringDataEncoding sde = (StringDataEncoding) xtceDataEncoding; infob.setEncoding(toTextualEncoding(sde)); } return infob.build(); } public static String toTextualEncoding(StringDataEncoding sde) { String result = sde.getSizeType() + "("; switch (sde.getSizeType()) { case FIXED: result += sde.getSizeInBits(); break; case LEADING_SIZE: result += sde.getSizeInBitsOfSizeTag(); break; case TERMINATION_CHAR: String hexChar = Integer.toHexString(sde.getTerminationChar()).toUpperCase(); if (hexChar.length() == 1) hexChar = "0" + hexChar; result += "0x" + hexChar; break; default: throw new IllegalStateException("Unexpected size type " + sde.getSizeType()); } return result + ")"; } public static Mdb.EnumValue toEnumValue(ValueEnumeration xtceValue) { Mdb.EnumValue.Builder b = Mdb.EnumValue.newBuilder(); b.setValue(xtceValue.getValue()); b.setLabel(xtceValue.getLabel()); return b.build(); } public static UnitInfo toUnitInfo(UnitType ut) { return UnitInfo.newBuilder().setUnit(ut.getUnit()).build(); } public static AlarmInfo toAlarmInfo(NumericAlarm numericAlarm) { AlarmInfo.Builder alarmInfob = AlarmInfo.newBuilder(); alarmInfob.setMinViolations(numericAlarm.getMinViolations()); AlarmRanges staticRanges = numericAlarm.getStaticAlarmRanges(); if (staticRanges.getWatchRange() != null) { AlarmRange watchRange = ParameterValue.toGpbAlarmRange(AlarmLevelType.WATCH, staticRanges.getWatchRange()); alarmInfob.addStaticAlarmRange(watchRange); } if (staticRanges.getWarningRange() != null) { AlarmRange warningRange = ParameterValue.toGpbAlarmRange(AlarmLevelType.WARNING, staticRanges.getWarningRange()); alarmInfob.addStaticAlarmRange(warningRange); } if (staticRanges.getDistressRange() != null) { AlarmRange distressRange = ParameterValue.toGpbAlarmRange(AlarmLevelType.DISTRESS, staticRanges.getDistressRange()); alarmInfob.addStaticAlarmRange(distressRange); } if (staticRanges.getCriticalRange() != null) { AlarmRange criticalRange = ParameterValue.toGpbAlarmRange(AlarmLevelType.CRITICAL, staticRanges.getCriticalRange()); alarmInfob.addStaticAlarmRange(criticalRange); } if (staticRanges.getSevereRange() != null) { AlarmRange severeRange = ParameterValue.toGpbAlarmRange(AlarmLevelType.SEVERE, staticRanges.getSevereRange()); alarmInfob.addStaticAlarmRange(severeRange); } return alarmInfob.build(); } public static AlarmInfo toAlarmInfo(EnumerationAlarm enumerationAlarm) { AlarmInfo.Builder alarmInfob = AlarmInfo.newBuilder(); alarmInfob.setMinViolations(enumerationAlarm.getMinViolations()); for (EnumerationAlarmItem item : enumerationAlarm.getAlarmList()) { alarmInfob.addEnumerationAlarm(toEnumerationAlarm(item)); } return alarmInfob.build(); } public static Mdb.EnumerationAlarm toEnumerationAlarm(EnumerationAlarmItem xtceAlarmItem) { Mdb.EnumerationAlarm.Builder resultb = Mdb.EnumerationAlarm.newBuilder(); resultb.setLabel(xtceAlarmItem.getEnumerationLabel()); switch (xtceAlarmItem.getAlarmLevel()) { case normal: resultb.setLevel(AlarmLevelType.NORMAL); break; case watch: resultb.setLevel(AlarmLevelType.WATCH); break; case warning: resultb.setLevel(AlarmLevelType.WARNING); break; case distress: resultb.setLevel(AlarmLevelType.DISTRESS); break; case critical: resultb.setLevel(AlarmLevelType.CRITICAL); break; case severe: resultb.setLevel(AlarmLevelType.SEVERE); break; default: throw new IllegalStateException("Unexpected alarm level " + xtceAlarmItem.getAlarmLevel()); } return resultb.build(); } public static AlgorithmInfo toAlgorithmInfo(Algorithm a, String mdbURL, DetailLevel detail, Set<Option> options) { AlgorithmInfo.Builder b = AlgorithmInfo.newBuilder(); b.setName(a.getName()); b.setQualifiedName(a.getQualifiedName()); if (!options.contains(Option.NO_LINK)) { b.setUrl(mdbURL + "/algorithms" + a.getQualifiedName()); } if (detail == DetailLevel.SUMMARY || detail == DetailLevel.FULL) { if (a.getShortDescription() != null) { b.setShortDescription(a.getShortDescription()); } if (a.getLongDescription() != null) { b.setLongDescription(a.getLongDescription()); } if (a.getAliasSet() != null) { Map<String, String> aliases = a.getAliasSet().getAliases(); for (Entry<String, String> me : aliases.entrySet()) { b.addAlias(NamedObjectId.newBuilder().setName(me.getValue()).setNamespace(me.getKey())); } } switch (a.getScope()) { case GLOBAL: b.setScope(Scope.GLOBAL); break; case COMMAND_VERIFICATION: b.setScope(Scope.COMMAND_VERIFICATION); break; default: throw new IllegalStateException("Unexpected scope " + a.getScope()); } if (a instanceof CustomAlgorithm) { CustomAlgorithm ca = (CustomAlgorithm) a; if (ca.getLanguage() != null) { b.setLanguage(ca.getLanguage()); } if (ca.getAlgorithmText() != null) { b.setText(ca.getAlgorithmText()); } } } if (detail == DetailLevel.FULL) { for (InputParameter p : a.getInputSet()) { b.addInputParameter(toInputParameterInfo(p, mdbURL, options)); } for (OutputParameter p : a.getOutputSet()) { b.addOutputParameter(toOutputParameterInfo(p, mdbURL, options)); } TriggerSetType triggerSet = a.getTriggerSet(); if (triggerSet != null) { for (OnParameterUpdateTrigger trig : triggerSet.getOnParameterUpdateTriggers()) { b.addOnParameterUpdate(toParameterInfo(trig.getParameter(), mdbURL, DetailLevel.SUMMARY, options)); } for (OnPeriodicRateTrigger trig : triggerSet.getOnPeriodicRateTriggers()) { b.addOnPeriodicRate(trig.getFireRate()); } } } return b.build(); } public static InputParameterInfo toInputParameterInfo(InputParameter xtceInput, String mdbURL, Set<Option> options) { InputParameterInfo.Builder resultb = InputParameterInfo.newBuilder(); resultb.setParameter( toParameterInfo(xtceInput.getParameterInstance().getParameter(), mdbURL, DetailLevel.SUMMARY, options)); if (xtceInput.getInputName() != null) { resultb.setInputName(xtceInput.getInputName()); } resultb.setParameterInstance(xtceInput.getParameterInstance().getInstance()); resultb.setMandatory(xtceInput.isMandatory()); return resultb.build(); } public static OutputParameterInfo toOutputParameterInfo(OutputParameter xtceOutput, String mdbUrl, Set<Option> options) { OutputParameterInfo.Builder resultb = OutputParameterInfo.newBuilder(); resultb.setParameter(toParameterInfo(xtceOutput.getParameter(), mdbUrl, DetailLevel.SUMMARY, options)); if (xtceOutput.getOutputName() != null) { resultb.setOutputName(xtceOutput.getOutputName()); } return resultb.build(); } public static SpaceSystemInfo toSpaceSystemInfo(RestRequest req, String instance, SpaceSystem ss) { SpaceSystemInfo.Builder b = SpaceSystemInfo.newBuilder(); b.setName(ss.getName()); b.setQualifiedName(ss.getQualifiedName()); if (ss.getShortDescription() != null) { b.setShortDescription(ss.getShortDescription()); } if (ss.getLongDescription() != null) { b.setLongDescription(ss.getLongDescription()); } Header h = ss.getHeader(); if (h != null) { if (h.getVersion() != null) { b.setVersion(h.getVersion()); } History[] sortedHistory = h.getHistoryList().toArray(new History[] {}); Arrays.sort(sortedHistory); for (History history : sortedHistory) { HistoryInfo.Builder historyb = HistoryInfo.newBuilder(); if (history.getVersion() != null) historyb.setVersion(history.getVersion()); if (history.getDate() != null) historyb.setDate(history.getDate()); if (history.getMessage() != null) historyb.setMessage(history.getMessage()); if (history.getAuthor() != null) historyb.setAuthor(history.getAuthor()); b.addHistory(historyb); } } boolean aggregate = req.getQueryParameterAsBoolean("aggregate", false); b.setParameterCount(ss.getParameterCount(aggregate)); b.setContainerCount(ss.getSequenceContainerCount(aggregate)); b.setCommandCount(ss.getMetaCommandCount(aggregate)); b.setAlgorithmCount(ss.getAlgorithmCount(aggregate)); for (SpaceSystem sub : ss.getSubSystems()) { b.addSub(toSpaceSystemInfo(req, instance, sub)); } if (!req.getOptions().contains(Option.NO_LINK)) { String url = req.getApiURL() + "/mdb/" + instance; b.setParametersUrl(url + "/parameters" + ss.getQualifiedName()); b.setContainersUrl(url + "/containers" + ss.getQualifiedName()); b.setCommandsUrl(url + "/commands" + ss.getQualifiedName()); b.setAlgorithmsUrl(url + "/algorithms" + ss.getQualifiedName()); } return b.build(); } }
package org.a11y.brltty.android; import java.lang.reflect.*; import java.util.Set; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.UUID; import android.os.Build; import android.util.Log; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; public class BluetoothConnection { private static final String LOG_TAG = BluetoothConnection.class.getName(); protected static final UUID SERIAL_PROFILE_UUID = UUID.fromString( "00001101-0000-1000-8000-00805F9B34FB" ); protected static final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); protected final BluetoothDevice bluetoothDevice; protected final String bluetoothAddress; protected BluetoothSocket bluetoothSocket = null; protected InputStream inputStream = null; protected OutputStream outputStream = null; protected OutputStream pipeStream = null; protected InputThread inputThread = null; private class InputThread extends Thread { volatile boolean stop = false; InputThread () { super("bluetooth-input-" + bluetoothAddress); } @Override public void run () { try { byte[] buffer = new byte[0X80]; while (!stop) { int byteCount; try { byteCount = inputStream.read(buffer); } catch (IOException exception) { Log.d(LOG_TAG, "Bluetooth input exception: " + bluetoothAddress + ": " + exception.getMessage()); break; } if (byteCount > 0) { pipeStream.write(buffer, 0, byteCount); pipeStream.flush(); } else if (byteCount < 0) { Log.d(LOG_TAG, "Bluetooth input end: " + bluetoothAddress); break; } } } catch (Throwable cause) { Log.e(LOG_TAG, "Bluetooth input failed: " + bluetoothAddress, cause); } closePipeStream(); } } public static BluetoothDevice getDevice (long deviceAddress) { byte[] hardwareAddress = new byte[6]; { int i = hardwareAddress.length; while (i > 0) { hardwareAddress[--i] = (byte)(deviceAddress & 0XFF); deviceAddress >>= 8; } } if (!ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { StringBuilder sb = new StringBuilder(); for (byte octet : hardwareAddress) { if (sb.length() > 0) sb.append(':'); sb.append(String.format("%02X", octet)); } return bluetoothAdapter.getRemoteDevice(sb.toString()); } return bluetoothAdapter.getRemoteDevice(hardwareAddress); } public static String getName (long deviceAddress) { return getDevice(deviceAddress).getName(); } public BluetoothConnection (long deviceAddress) { bluetoothDevice = getDevice(deviceAddress); bluetoothAddress = bluetoothDevice.getAddress(); } private void closeBluetoothSocket () { if (bluetoothSocket != null) { try { bluetoothSocket.close(); } catch (IOException exception) { Log.w(LOG_TAG, "Bluetooth socket close failure: " + bluetoothAddress, exception); } bluetoothSocket = null; } } private void closeInputStream () { if (inputStream != null) { try { inputStream.close(); } catch (IOException exception) { Log.w(LOG_TAG, "Bluetooth input stream close failure: " + bluetoothAddress, exception); } inputStream = null; } } private void closeOutputStream () { if (outputStream != null) { try { outputStream.close(); } catch (IOException exception) { Log.w(LOG_TAG, "Bluetooth output stream close failure: " + bluetoothAddress, exception); } outputStream = null; } } private void closePipeStream () { if (pipeStream != null) { try { pipeStream.close(); } catch (IOException exception) { Log.w(LOG_TAG, "Bluetooth pipe stream close failure: " + bluetoothAddress, exception); } pipeStream = null; } } private void stopInputThread () { if (inputThread != null) { inputThread.stop = true; inputThread = null; } } public void close () { stopInputThread(); closePipeStream(); closeInputStream(); closeOutputStream(); closeBluetoothSocket(); } public static BluetoothSocket createRfcommSocket (BluetoothDevice device, int channel) { String className = device.getClass().getName(); String methodName = "createRfcommSocket"; String reference = className + "." + methodName; try { Class[] arguments = new Class[] {int.class}; Method method = device.getClass().getMethod(methodName, arguments); return (BluetoothSocket)method.invoke(device, channel); } catch (NoSuchMethodException exception) { Log.w(LOG_TAG, "cannot find method: " + reference); } catch (IllegalAccessException exception) { Log.w(LOG_TAG, "cannot access method: " + reference); } catch (InvocationTargetException exception) { Log.w(LOG_TAG, reference + " failed", exception.getCause()); } return null; } public boolean open (int inputPipe, int channel, boolean secure) { if (channel == 0) { try { bluetoothSocket = secure? bluetoothDevice.createRfcommSocketToServiceRecord(SERIAL_PROFILE_UUID): bluetoothDevice.createInsecureRfcommSocketToServiceRecord(SERIAL_PROFILE_UUID); } catch (IOException exception) { Log.e(LOG_TAG, "Bluetooth UUID resolution failed: " + bluetoothAddress + ": " + exception.getMessage()); bluetoothSocket = null; } } else { bluetoothSocket = createRfcommSocket(bluetoothDevice, channel); } if (bluetoothSocket != null) { try { bluetoothSocket.connect(); inputStream = bluetoothSocket.getInputStream(); outputStream = bluetoothSocket.getOutputStream(); { File pipeFile = new File("/proc/self/fd/" + inputPipe); pipeStream = new FileOutputStream(pipeFile); } inputThread = new InputThread(); inputThread.start(); return true; } catch (IOException openException) { Log.d(LOG_TAG, "Bluetooth connect failed: " + bluetoothAddress + ": " + openException.getMessage()); } } close(); return false; } public boolean write (byte[] bytes) { try { outputStream.write(bytes); outputStream.flush(); return true; } catch (IOException exception) { Log.e(LOG_TAG, "Bluetooth write failed: " + bluetoothAddress, exception); } return false; } private static BluetoothDevice[] pairedDevices = null; public static int getPairedDeviceCount () { if (bluetoothAdapter != null) { Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); if (devices != null) { pairedDevices = devices.toArray(new BluetoothDevice[devices.size()]); return pairedDevices.length; } } pairedDevices = null; return 0; } private static BluetoothDevice getPairedDevice (int index) { if (index >= 0) { if (pairedDevices != null) { if (index < pairedDevices.length) { return pairedDevices[index]; } } } return null; } public static String getPairedDeviceAddress (int index) { BluetoothDevice device = getPairedDevice(index); if (device == null) return null; return device.getAddress(); } public static String getPairedDeviceName (int index) { BluetoothDevice device = getPairedDevice(index); if (device == null) return null; return device.getName(); } }
package networking; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.security.MessageDigest; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import am_utils.ArticleInfo; public class Connection extends Thread { private int port; // Port to listen for clients on. private Socket clientSocket; // Client socket object. private int failTolerance; // Number of consecutive communication failures to tolerate before the connection is considered terminated. private boolean waiting; // indicates whether thread is waiting on a client or not. If false, connection manager will place in connection list and spin up a new listener thread. private int consecFail; private int permissionLevel; private Object waitingLock = new Object(); Connection(int serverPort, int failTolerance) { port = serverPort; this.failTolerance = failTolerance; waiting = true; consecFail = 0; permissionLevel = -1; } public boolean isWaiting() { synchronized(waitingLock) { return waiting; } } private void sendString(String outString) { try { PrintWriter netOut = new PrintWriter(clientSocket.getOutputStream(), true); netOut.println(outString); } catch (IOException e) { System.err.println("Failed to send string to client."); e.printStackTrace(); } } private String receiveString() { String messageString; while(consecFail <= failTolerance) try { BufferedReader inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); messageString = inReader.readLine(); consecFail = 0; return messageString; } catch (IOException e) { consecFail++; } return null; } private void sendObject(Object outObj) { while(consecFail <= failTolerance) { try { ObjectOutputStream sendStream = new ObjectOutputStream(clientSocket.getOutputStream()); sendStream.writeObject(outObj); } catch (IOException e) { consecFail++; } } } private Object receiveObject() { Object receiveObject; try { ObjectInputStream receiveStream = new ObjectInputStream(clientSocket.getInputStream()); try { receiveObject = receiveStream.readObject(); } catch (ClassNotFoundException e) { System.err.println("Error reconstituting serialized object from stream."); e.printStackTrace(); return null; } return receiveObject; } catch (IOException e) { consecFail++; } return null; } private void sendFile(File fp) { byte[] fileBytes = new byte[(int)fp.length()]; OutputStream byteOutput; BufferedInputStream inputStream; try { inputStream = new BufferedInputStream(new FileInputStream(fp)); } catch(FileNotFoundException e) { e.printStackTrace(); return; } while(consecFail <= failTolerance) { try { inputStream.read(fileBytes, 0, fileBytes.length); byteOutput = clientSocket.getOutputStream(); byteOutput.write(fileBytes, 0, fileBytes.length); byteOutput.flush(); byteOutput.close(); return; } catch (IOException e) { consecFail++; } } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); return; } } private File receiveFile() // writes file to disk and returns file location as File object. { String byteString = receiveString(); int byteCount = Integer.parseInt(byteString); byte[] receivedBytes = new byte[byteCount]; File newFile = new File(new SimpleDateFormat("files/yyyyMMddHHmm.pdf").format(new Date())); while(consecFail <= failTolerance) { try { FileOutputStream fos = new FileOutputStream(newFile); BufferedOutputStream bos = new BufferedOutputStream(fos); int bytesRead = clientSocket.getInputStream().read(receivedBytes, 0, receivedBytes.length); bos.write(receivedBytes,0 , bytesRead); bos.close(); return newFile; } catch (IOException e) { consecFail++; } } return null; } private void parse(String input) { String[] substrings = input.split(" "); String opString; String arg1 = ""; String arg2 = ""; int opcode; opString = substrings[0]; opcode = Integer.parseInt(opString); ArrayList<ArticleInfo> returnedArticles; ArticleInfo tempArticleInfo; File tempFile; if(substrings.length > 1) { arg1 = substrings[1]; } if(substrings.length > 2) { arg2 = substrings[2]; } //Try to keep networking sends here and remember to update consecFail as necessary. switch(opcode) { //TODO: Add functionality for opcodes here, sending execution off to proper subsystems/modules if necessary. case 0: consecFail = 0; break; case 1: permissionLevel = users.Public.login(arg1, arg2); if(permissionLevel == -1) { sendString("-1"); } break; case 2: permissionLevel = -1; sendString("0"); //Confirm that logout was successful to client. break; case 3: if(users.Public.register(arg1, arg2)) { sendString("0"); } else { sendString("-1"); } break; case 4: returnedArticles = database.Public.getArticlesFromCategory(Integer.valueOf(arg1), Integer.valueOf(arg2)); sendObject(returnedArticles); break; case 5: tempFile = receiveFile(); tempArticleInfo = (ArticleInfo)receiveObject(); database.Public.insertArticle(tempFile, tempArticleInfo, permissionLevel); break; case 6: tempArticleInfo = database.Public.getArticleInfo(Integer.valueOf(arg1)); sendObject(tempArticleInfo); break; case 7: tempFile = database.Public.downloadArticle(Integer.valueOf(arg1)); sendFile(tempFile); break; case 8: sendString(Integer.toString(permissionLevel)); break; } } public void run() { BufferedReader clientStream; String clientMessage; try { ServerSocket listener = new ServerSocket(port); clientSocket = listener.accept(); clientSocket.setSoTimeout(2000); listener.close(); synchronized(waitingLock) { this.waiting = false; } } catch (IOException e) { System.err.println("Error listening for clients."); e.printStackTrace(); return; } try { clientStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); } catch (IOException e) { e.printStackTrace(); System.err.println("Failed to create buffered reader for client input stream."); return; } while(!clientSocket.isClosed() && consecFail <= failTolerance) { try { clientMessage = clientStream.readLine(); parse(clientMessage); consecFail = 0; } catch (IOException e) { System.out.println("Listen timeout, consecutive timeouts: " + (consecFail+1)); consecFail++; } } try { clientSocket.close(); } catch (IOException e) { System.err.println("Error closing client socket."); e.printStackTrace(); } } }
package org.kohsuke.args4j.apt; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * Entry point that invokes APT. * @author Kohsuke Kawaguchi */ public class Main { @Option(name="-o",usage="output directory to place generated HTML/XML") private File outDir = new File("."); @Option(name="-mode",usage="output format. 'XML' or 'HTML'") private Mode mode = Mode.HTML; @Option(name="-res",usage="resource file name to obtain usage strings from.\n"+ "Using this option will cause Option.usage() to be used as a key to this resource") private String resourceName = null; @Option(name="-r") private boolean hidden = false; // for testing @Argument private List<String> aptArgs = new ArrayList<String>(); public static void main(String[] args) throws Exception { System.exit(new Main().run(args)); } public int run(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); printUsage(parser); return -1; } if(aptArgs.isEmpty()) { printUsage(parser); return 0; } // we'll use a separate class loader to reload our classes, // so parameters need to be set as system properties. Ouch! System.setProperty("args4j.outdir",outDir.getPath()); System.setProperty("args4j.format",mode.name()); System.setProperty("args4j.resource",resourceName); // can be null aptArgs.add(0,"-nocompile"); // locate tools.jar ClassLoader cl = loadToolsJar(); Class<?> apt = cl.loadClass("com.sun.tools.apt.Main"); Method main = getProcessMethod(apt); return (Integer)main.invoke(null,new Object[]{ cl.loadClass("org.kohsuke.args4j.apt.AnnotationProcessorFactoryImpl").newInstance(), aptArgs.toArray(new String[0])}); } private void printUsage(CmdLineParser parser) { System.err.println("argsj-tools [options...] sourcefiles..."); System.err.println(" Generates the list of options in XML/HTML"); parser.printUsage(System.err); } private Method getProcessMethod(Class<?> apt) { for(Method m : apt.getDeclaredMethods()) { if(!m.getName().equals("process")) continue; Class<?>[] p = m.getParameterTypes(); if(p.length!=2) continue; if(p[1]!=String[].class) continue; if(!p[0].getName().endsWith("AnnotationProcessorFactory")) continue; return m; } throw new Error("Unable to find the entry point to APT. Please use the latest version of JDK 5.0"); } public ClassLoader loadToolsJar() { File jreHome = new File(System.getProperty("java.home")); File toolsJar = new File(jreHome.getParent(), "lib/tools.jar" ); try { return new ReloadingClassLoader(new URLClassLoader( new URL[]{ toolsJar.toURL() }, new IsolatingClassLoader(Main.class.getClassLoader())) ); } catch (MalformedURLException e) { throw new Error(e); } } }
package ae3.dao; import java.util.List; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrDocumentList; import org.junit.Test; import ae3.AtlasAbstractTest; import ae3.dao.AtlasDao; import ae3.dao.AtlasObjectNotFoundException; import ae3.model.AtlasExperiment; import ae3.model.AtlasGene; public class AtlasDaoTest extends AtlasAbstractTest { @Test public void test_getExperimentByIdAER() throws AtlasObjectNotFoundException { AtlasExperiment exp=AtlasDao.getExperimentByIdAER("1324144279"); assertNotNull(exp); assertNotNull(exp.getAerExpAccession()); assertNotNull(exp.getAerExpId()); assertNotNull(exp.getAerExpName()); assertNotNull(exp.getDwExpId()); if (exp.getDwExpId() != null) { AtlasExperiment exp1=AtlasDao.getExperimentByIdDw(exp.getDwExpId().toString()); assertNotNull(exp1); assertNotNull(exp1.getDwExpAccession()); assertNotNull(exp1.getDwExpId()); assertNotNull(exp1.getDwExpDescription()); } log.info(" log.info(" log.info(" } @Test public void test_getExperimentByIdDw() throws AtlasObjectNotFoundException { AtlasExperiment exp=AtlasDao.getExperimentByIdDw("334420710"); assertNotNull(exp); assertNotNull(exp.getDwExpAccession()); assertNotNull(exp.getAerExpId()); assertNotNull(exp.getDwExpType()); log.info(" log.info(" log.info(" } @Test public void test_getExperimentByAccession() throws AtlasObjectNotFoundException { AtlasExperiment exp=AtlasDao.getExperimentByAccession("E-MEXP-980"); } @Test public void test_getGeneByIdentifier(){ boolean notFound_thrown = false; boolean multi_thrown = false; //Test normal gene query try{ AtlasGene gene = AtlasDao.getGeneByIdentifier("ENSG00000066279"); assertNotNull(gene); }catch (AtlasObjectNotFoundException ex){ notFound_thrown = true; }catch (MultipleGeneException ex){ multi_thrown = true; } assertFalse(notFound_thrown); assertFalse(multi_thrown); //Test multiple gene hit exception multi_thrown = false; notFound_thrown = false; try{ AtlasGene gene2 = AtlasDao.getGeneByIdentifier("P08898"); }catch (MultipleGeneException ex){ multi_thrown = true; }catch (AtlasObjectNotFoundException ex){ notFound_thrown = true; } assertTrue(multi_thrown); assertFalse(notFound_thrown); //Test gene not found exception notFound_thrown = false; multi_thrown = false; try{ AtlasGene gene2 = AtlasDao.getGeneByIdentifier("mysteriousGene"); }catch (AtlasObjectNotFoundException ex){ notFound_thrown = true; }catch (MultipleGeneException ex){ multi_thrown = true; } assertTrue(notFound_thrown); assertFalse(multi_thrown); } }
package pagerank; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class InitPRPreProcessor { public static double pr; public static void main(String[] args) throws Exception { pr = Double.parseDouble(args[0]); Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "InitialPageRank converter"); job.setJarByClass(InitPRPreProcessor.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(InitPRPreProcessor.Map.class); job.setReducerClass(InitPRPreProcessor.Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(args[1] + "/part-r-00000")); FileOutputFormat.setOutputPath(job, new Path(args[2])); job.waitForCompletion(true); } public static class Map extends Mapper<LongWritable, Text, Text, Text> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] token = line.split(" "); if (token[0].length() > 0 && !token[0].startsWith(" Text k = new Text(); if (token.length > 1) { String[] edges = token[1].split(" "); String s = ""; for (int i = 0; i < edges.length; i++) { if (s.equals("")) { s = edges[i]; } else { s = s + " " + edges[i]; } } k.set(token[0]); context.write(k, new Text(s)); } else { context.write(new Text(token[0]), new Text()); } } } } public static class Reduce extends Reducer<Text, Text, Text, Text> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String s = ""; for (Text val : values) { s = s + pr + " " + val; } context.write(key, new Text(s)); } } }
package test; import java.io.*; import java.util.*; import java.util.jar.*; import junit.framework.*; import aQute.bnd.header.*; import aQute.bnd.osgi.*; import aQute.lib.io.*; @SuppressWarnings("resource") public class VerifierTest extends TestCase { /** * Verify that the Meta-Persistence header is correctly verified * @throws Exception */ public void verifyMetaPersistence() throws Exception { Builder b = new Builder(); b.setIncludeResource("foo.xml;literal='I exist'"); Jar inner = b.build(); assertTrue( b.check()); Jar outer = new Jar("x"); outer.putResource("foo.jar", new JarResource(inner)); Manifest m = new Manifest(); m.getMainAttributes().putValue(Constants.META_PERSISTENCE, "foo.jar, foo.jar!/foo.xml, absent.xml"); outer.setManifest(m); Verifier v = new Verifier(outer); v.verifyMetaPersistence(); assertTrue(v.check("Meta-Persistence refers to resources not in the bundle: \\[absent.xml\\]")); } /** * Check for reserved file names (INVALIDFILENAMES) * * @throws Exception */ public void testInvalidFileNames() throws Exception { testFileName("0ABC", null, true); testFileName("0ABC", "[0-9].*|${@}", false); testFileName("com1", null, false); testFileName("COM1", null, false); testFileName("cOm1", null, false); testFileName("aux", null, false); testFileName("AUX", null, false); testFileName("XYZ", null, true); testFileName("XYZ", "XYZ|${@}", false); testFileName("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", ".{33,}|${@}", false); testFileName("clock$", ".{1,32}|${@}", false); testFileName("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", null, true); } private void testFileName(String segment, String pattern, boolean answer) throws Exception { testFilePath(segment, pattern, answer); testFilePath("abc/" + segment, pattern, answer); testFilePath("abc/" + segment + "/def", pattern, answer); testFilePath(segment + "/def", pattern, answer); } private void testFilePath(String path, String pattern, boolean good) throws Exception { Builder b = new Builder(); try { b.setProperty("-includeresource", path + ";literal='x'"); if (pattern != null) b.setProperty(Constants.INVALIDFILENAMES, pattern); b.build(); if ( good ) assertTrue(b.check()); else assertTrue(b.check("Invalid file/directory")); } finally { b.close(); } } /** * Create a require capality filter verification test * * @throws Exception */ public void testInvalidFilterOnRequirement() throws Exception { Builder b = new Builder(); b.addClasspath(IO.getFile("jar/osgi.jar")); b.setExportPackage("org.osgi.framework"); b.setProperty( "Require-Capability", "test; filter:=\"(&(test=aName)(version>=1.1.0))\", " + " test; filter:=\"(&(version>=1.1)(string~=astring))\", " + " test; filter:=\"(&(version>=1.1)(long>=99))\", " + " test; filter:=\"(&(version>=1.1)(double>=1.0))\", " + " test; filter:=\"(&(version>=1.1)(version.list=1.0)(version.list=1.1)(version.list=1.2))\", " + " test; filter:=\"(&(version>=1.1)(long.list=1)(long.list=2)(long.list=3)(long.list=4))\", " + " test; filter:=\"(&(version>=1.1)(double.list=1.001)(double.list=1.002)(double.list=1.003)(double.list<=1.3))\", " + " test; filter:=\"(&(version>=1.1)(string.list~=astring)(string.list~=bstring)(string.list=cString))\", " + " test; filter:=\"(&(version>=1.1)(string.list2=a\\\"quote)(string.list2=a\\,comma)(string.list2= aSpace )(string.list2=\\\"start)(string.list2=\\,start)(string.list2=end\\\")(string.list2=end\\,))\", " + " test; filter:=\"(&(version>=1.1)(string.list3= aString )(string.list3= bString )(string.list3= cString ))\", " + " test.effective; effective:=\"active\"; filter:=\"(willResolve=false)\", test.no.attrs"); b.build(); assertTrue(b.check()); } /** * Create a require capality directive test * * @throws Exception */ public void testValidDirectivesOnRequirement() throws Exception { Builder b = new Builder(); b.addClasspath(IO.getFile("jar/osgi.jar")); b.setExportPackage("org.osgi.framework"); b.setProperty( "Require-Capability", "test; resolution:=mandatory, " + " test; resolution:=optional, " + " test; cardinality:=single, " + " test; cardinality:=multiple, " + " test; effective:=foo, " + " test; filter:=\"(&(version>=1.1)(long.list=1)(long.list=2))\", " + " test; x-custom:=bar, "); b.build(); assertTrue(b.check()); } /** * Test the strict flag */ public void testStrict() throws Exception { Builder bmaker = new Builder(); bmaker.addClasspath(IO.getFile("jar/osgi.jar")); bmaker.addClasspath(new File("bin")); bmaker.setProperty( "Export-Package", "org.osgi.service.eventadmin;version='[1,2)',org.osgi.framework;version=x13,test;-remove-attribute:=version,test.lib;specification-version=12,test.split"); bmaker.setProperty("Import-Package", "foo;version=1,bar;version='[1,x2)',baz;version='[2,1)',baz2;version='(1,1)',*"); bmaker.setProperty("-strict", "true"); Jar jar = bmaker.build(); assertTrue(bmaker .check("\\QExport-Package or -exportcontents refers to missing package 'org.osgi.service.eventadmin'\\E", "Import Package clauses without version range \\(excluding javax\\.\\*\\):", "Import Package bar has an invalid version range syntax \\[1,x2\\)", "Import Package baz2 has an empty version range syntax \\(1,1\\), likely want to use \\[1.0.0,1.0.0\\]", "Import Package baz has an invalid version range syntax \\[2,1\\):Low Range is higher than High Range: 2.0.0-1.0.0", "Import Package clauses which use a version instead of a version range. This imports EVERY later package and not as many expect until the next major number: \\[foo\\]", "Export Package org.osgi.framework version has invalid syntax: x13", "Export Package test.lib uses deprecated specification-version instead of version", "Export Package org.osgi.service.eventadmin version is a range: \\[1,2\\); Exports do not allow for ranges.")); } public static void testCapability() throws Exception { Parameters h = OSGiHeader .parseHeader("test; version.list:List < Version > = \"1.0, 1.1, 1.2\"; effective:=\"resolve\"; test =\"aName\";version : Version=\"1.0\"; long :Long=\"100\"; " + "double: Double=\"1.001\"; string:String =\"aString\"; " + "long.list : List <Long >=\"1, 2, 3, 4\";double.list: List< Double>= \"1.001, 1.002, 1.003\"; " + "string.list :List<String >= \"aString,bString,cString\""); assertEquals(Attrs.Type.VERSION, h.get("test").getType("version")); assertEquals(Attrs.Type.LONG, h.get("test").getType("long")); assertEquals(Attrs.Type.DOUBLE, h.get("test").getType("double")); assertEquals(Attrs.Type.STRING, h.get("test").getType("string")); assertEquals(Attrs.Type.STRING, h.get("test").getType("test")); assertEquals(Attrs.Type.LONGS, h.get("test").getType("long.list")); assertEquals(Attrs.Type.DOUBLES, h.get("test").getType("double.list")); assertEquals(Attrs.Type.STRINGS, h.get("test").getType("string.list")); assertEquals(Attrs.Type.VERSIONS, h.get("test").getType("version.list")); } public static void testFailedOSGiJar() throws Exception { Jar jar = new Jar("jar/osgi.residential-4.3.0.jar"); Verifier v = new Verifier(jar); assertTrue(v.check()); } public static void testnativeCode() throws Exception { Builder b = new Builder(); b.addClasspath(new File("bin")); b.setProperty("-resourceonly", "true"); b.setProperty("Include-Resource", "native/win32/NTEventLogAppender-1.2.dll;literal='abc'"); b.setProperty("Bundle-NativeCode", "native/win32/NTEventLogAppender-1.2.dll; osname=Win32; processor=x86"); b.build(); Verifier v = new Verifier(b); v.verifyNative(); System.err.println(v.getErrors()); assertEquals(0, v.getErrors().size()); v.close(); b.close(); } public static void testFilter() { testFilter("(&(a=b)(c=1))"); testFilter("(&(a=b)(!(c=1))(&(c=1))(c=1)(c=1)(c=1)(c=1)(c=1)(c=1)(c=1)(c=1))"); testFilter("(!(a=b))"); testInvalidFilter("(!(a=b)(c=2))"); testInvalidFilter("(axb)"); testInvalidFilter("(a=3 "); testFilter("(room=*)"); testFilter("(room=bedroom)"); testFilter("(room~= B E D R O O M )"); testFilter("(room=abc)"); testFilter(" ( room >=aaaa)"); testFilter("(room <=aaaa)"); testFilter(" ( room =b*) "); testFilter(" ( room =*m) "); testFilter("(room=bed*room)"); testFilter(" ( room =b*oo*m) "); testFilter(" ( room =*b*oo*m*) "); testFilter(" ( room =b*b* *m*) "); testFilter(" (& (room =bedroom) (channel ~=34))"); testFilter(" (& (room =b*) (room =*x) (channel=34))"); testFilter("(| (room =bed*)(channel=222)) "); testFilter("(| (room =boom*)(channel=101)) "); testFilter(" (! (room =ab*b*oo*m*) ) "); testFilter(" (status =\\(o*\\\\\\)\\*) "); testFilter(" (canRecord =true\\(x\\)) "); testFilter("(max Record Time <=140) "); testFilter("(shortValue >=100) "); testFilter("(intValue <=100001) "); testFilter("(longValue >=10000000000) "); testFilter(" ( & ( byteValue <=100) ( byteValue >=10) ) "); testFilter("(weirdValue =100) "); testFilter("(bigIntValue =4123456) "); testFilter("(bigDecValue =4.123456) "); testFilter("(floatValue >=1.0) "); testFilter("(doubleValue <=2.011) "); testFilter("(charValue ~=a) "); testFilter("(booleanValue =true) "); testFilter("(primIntArrayValue =1) "); testFilter("(primLongArrayValue =2) "); testFilter("(primByteArrayValue =3) "); testFilter("(primShortArrayValue =1) "); testFilter("(primFloatArrayValue =1.1) "); testFilter("(primDoubleArrayValue =2.2) "); testFilter("(primCharArrayValue ~=D) "); testFilter("(primBooleanArrayValue =false) "); testFilter("(& (| (room =d*m) (room =bed*) (room=abc)) (! (channel=999)))"); testFilter("(room=bedroom)"); testFilter("(*=foo)"); testInvalidFilter("(! ab=b)"); testInvalidFilter("(| ab=b)"); testInvalidFilter("(&=c)"); testInvalidFilter("(!=c)"); testInvalidFilter("(|=c)"); testInvalidFilter("(& ab=b)"); testInvalidFilter("(!ab=*)"); testInvalidFilter("(|ab=*)"); testInvalidFilter("(&ab=*)"); testFilter("(empty=)"); testFilter("(empty=*)"); testFilter("(space= )"); testFilter("(space=*)"); testFilter("(intvalue=*)"); testFilter("(intvalue=b)"); testFilter("(intvalue=)"); testFilter("(longvalue=*)"); testFilter("(longvalue=b)"); testFilter("(longvalue=)"); testFilter("(shortvalue=*)"); testFilter("(shortvalue=b)"); testFilter("(shortvalue=)"); testFilter("(bytevalue=*)"); testFilter("(bytevalue=b)"); testFilter("(bytevalue=)"); testFilter("(charvalue=*)"); testFilter("(charvalue=)"); testFilter("(floatvalue=*)"); testFilter("(floatvalue=b)"); testFilter("(floatvalue=)"); testFilter("(doublevalue=*)"); testFilter("(doublevalue=b)"); testFilter("(doublevalue=)"); testFilter("(booleanvalue=*)"); testFilter("(booleanvalue=b)"); testFilter("(booleanvalue=)"); testInvalidFilter(""); testInvalidFilter("()"); testInvalidFilter("(=foo)"); testInvalidFilter("("); testInvalidFilter("(abc = ))"); testInvalidFilter("(& (abc = xyz) (& (345))"); testInvalidFilter(" (room = b**oo!*m*) ) "); testInvalidFilter(" (room = b**oo)*m*) ) "); testInvalidFilter(" (room = *=b**oo*m*) ) "); testInvalidFilter(" (room = =b**oo*m*) ) "); testFilter("(shortValue =100*) "); testFilter("(intValue =100*) "); testFilter("(longValue =100*) "); testFilter("( byteValue =1*00 )"); testFilter("(bigIntValue =4*23456) "); testFilter("(bigDecValue =4*123456) "); testFilter("(floatValue =1*0) "); testFilter("(doubleValue =2*011) "); testFilter("(charValue =a*) "); testFilter("(booleanValue =t*ue) "); } private static void testFilter(String string) { int index = Verifier.verifyFilter(string, 0); while (index < string.length() && Character.isWhitespace(string.charAt(index))) index++; if (index != string.length()) throw new IllegalArgumentException("Characters after filter"); } private static void testInvalidFilter(String string) { try { testFilter(string); fail("Invalid filter"); } catch (Exception e) {} } public static void testBundleActivationPolicyNone() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "test.activator"); v.addClasspath(new File("bin")); v.build(); assertTrue(v.check()); } public static void testBundleActivationPolicyBad() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "test.activator"); v.addClasspath(new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "eager"); v.build(); assertTrue(v.check("Bundle-ActivationPolicy set but is not set to lazy: eager")); } public static void testBundleActivationPolicyGood() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "test.activator"); v.addClasspath(new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "lazy ; hello:=1"); v.build(); assertTrue(v.check()); } public static void testBundleActivationPolicyMultiple() throws Exception { Builder v = new Builder(); v.setProperty("Private-Package", "test.activator"); v.addClasspath(new File("bin")); v.setProperty(Constants.BUNDLE_ACTIVATIONPOLICY, "lazy;hello:=1,2"); v.build(); assertTrue(v.check("Bundle-ActivationPolicy has too many arguments lazy;hello:=1,2")); } public static void testInvalidCaseForHeader() throws Exception { Properties p = new Properties(); p.put("Export-package", "org.apache.mina.*"); p.put("Bundle-Classpath", "."); Analyzer analyzer = new Analyzer(); analyzer.setProperties(p); analyzer.getProperties(); System.err.println("Errors " + analyzer.getErrors()); System.err.println("Warnings " + analyzer.getWarnings()); assertEquals(0, analyzer.getErrors().size()); assertEquals(2, analyzer.getWarnings().size()); } public static void testSimple() throws Exception { Builder bmaker = new Builder(); bmaker.addClasspath(IO.getFile("jar/mina.jar")); bmaker.set("Export-Package", "org.apache.mina.*;version=1"); bmaker.set("DynamicImport-Package", "org.slf4j"); Jar jar = bmaker.build(); assertTrue(bmaker.check()); Manifest m = jar.getManifest(); m.write(System.err); assertTrue(m.getMainAttributes().getValue("Import-Package").indexOf("org.slf4j") >= 0); assertTrue(m.getMainAttributes().getValue("DynamicImport-Package").indexOf("org.slf4j") >= 0); } }
package time; import java.util.Calendar; public class StopWatch { final String format = "%1$02d:%2$02d:%3$02d.%4$03d"; boolean isRunning = false; long startTime, stopTime; final long CONST_H = 3600000; final long CONST_M = 60000; final long CONST_S = 1000; public boolean start(){ startTime = Calendar.getInstance().getTimeInMillis(); isRunning = true; return isRunning; } public boolean stop(){ stopTime = Calendar.getInstance().getTimeInMillis(); isRunning = false; return isRunning; } public String getTime(){ return convertTime(getTimeMilli()); } public long getTimeMilli(){ return stopTime-startTime; } public boolean isRunning(){ return isRunning; } public void reset(){ isRunning = false; startTime = 0; stopTime = 0; } protected String convertTime(long time){ if(time == 0){ return "00:00:00.000"; } if(time < 0){ return " } long remainder, hours, minutes, seconds, milliSec; hours = time / CONST_H; remainder = time - (hours*CONST_H); minutes = remainder / CONST_M; remainder = remainder - (minutes*CONST_M); seconds = remainder / CONST_S; remainder = remainder - (seconds*CONST_S); milliSec = remainder; return String.format(format, hours,minutes,seconds,milliSec); } }
package org.voltdb.benchmark; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map.Entry; import org.voltdb.benchmark.BenchmarkResults.Result; import org.voltdb.processtools.SSHTools; public class ResultsUploader implements BenchmarkController.BenchmarkInterest { Connection m_conn = null; Statement m_stmt = null; final BenchmarkConfig m_config; final String m_benchmarkName; String m_benchmarkOptions; final HashMap<String, String> m_hostIdCache = new HashMap<String, String>(); final HashMap<String, String[]> m_hostDistroCache = new HashMap<String, String[]>(); final HashMap<String, String> m_clientArgs = new HashMap<String, String>(); final HashMap<String, String> m_hostArgs = new HashMap<String, String>(); ResultsUploader(String benchmarkName, BenchmarkConfig config) { assert(config != null); m_config = config; m_benchmarkName = benchmarkName; m_benchmarkOptions = ""; for (Entry<String, String> param : config.parameters.entrySet()) m_benchmarkOptions += param.getKey() + "=" + param.getValue() + " "; m_benchmarkOptions = m_benchmarkOptions.trim(); } public void setCommandLineForClient(String clientAndIndex, String commandLine) { m_clientArgs.put(clientAndIndex, commandLine.trim()); } public void setCommandLineForHost(String host, String commandLine) { m_hostArgs.put(host, commandLine.trim()); } private void addToHostsTableIfMissing(String host) throws SQLException { assert m_stmt != null; String hostid = getHostIdForHostName(host); StringBuilder sql = new StringBuilder(); sql.append("SELECT hostid from hosts where hostid='").append(hostid).append("';"); java.sql.ResultSet rs = m_stmt.executeQuery(sql.toString()); // not present - insert entry if (!rs.first()) { sql = new StringBuilder(); sql.append("INSERT INTO `hosts` (`hostid`, `hostname`, `description`) values ("); sql.append("'").append(hostid).append("', "); sql.append("'").append(host).append("', "); sql.append("'").append(getDescriptionForHostName(host)).append("');"); m_stmt.executeUpdate(sql.toString()); } } @Override public void benchmarkHasUpdated(BenchmarkResults results) { int pollIndex = results.getCompletedIntervalCount(); long duration = results.getTotalDuration(); long interval = results.getIntervalDuration(); // don't do anything if not finished if ((pollIndex * interval) < duration) return; // connect to the server try { m_conn = DriverManager.getConnection(m_config.resultsDatabaseURL); m_stmt = m_conn.createStatement(); } catch (SQLException ex) { // handle any errors System.out.println("Unable to connect to MySQL results recording server."); System.out.println("SQLException: " + ex.getMessage()); return; } // upload try { StringBuilder sql = null; // safest thing possible m_conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); // commit everything or nothing m_conn.setAutoCommit(false); // insert the main data sql = new StringBuilder(); sql.append("INSERT INTO results (`userid`, `benchmarkname`, `benchmarkoptions`, " + "`duration`, `interval`, `sitesperhost`, `remotepath`, `hostcount`, `clientcount`, `totalhosts`, `totalclients`, `processesperclient`) values ("); sql.append("'").append(getCurrentUserId()).append("', "); sql.append("'").append(m_benchmarkName).append("', "); sql.append("'").append(m_benchmarkOptions).append("', "); sql.append(m_config.duration).append(", "); sql.append(m_config.interval).append(", "); sql.append(m_config.sitesPerHost).append(", "); sql.append("'").append(m_config.remotePath).append("', "); sql.append(m_config.hosts.length).append(", "); sql.append(m_config.clients.length).append(", "); sql.append(m_config.hosts.length * m_config.sitesPerHost).append(", "); sql.append(m_config.clients.length * m_config.processesPerClient).append(", "); sql.append(m_config.processesPerClient).append(");"); //System.out.println(sql.toString()); m_stmt.executeUpdate(sql.toString()); // get the result primary key int resultid = -1; java.sql.ResultSet rs = m_stmt.executeQuery("SELECT LAST_INSERT_ID()"); if (rs.next()) { resultid = rs.getInt(1); } else { throw new RuntimeException(); } // add all of the server participants in the benchmark for (String host : m_config.hosts) { String args = m_hostArgs.get(host); if (args == null) args = ""; addToHostsTableIfMissing(host); String distro[] = getHostDistroForHostName(host); sql = new StringBuilder(); sql.append("INSERT INTO participants (`resultid`, `hostid`, `distributor`, `release`, `role`, `commandline`) values ("); sql.append(String.valueOf(resultid)).append(", "); sql.append("'").append(getHostIdForHostName(host)).append("', "); sql.append("'").append(distro[0]).append("', "); sql.append("'").append(distro[1]).append("', "); sql.append("'SERVER', "); sql.append("'").append(args).append("');"); m_stmt.executeUpdate(sql.toString()); } // add of the actual benchmark data for (String clientName : results.getClientNames()) { // insert all the client participants String[] clientParts = clientName.split(":"); String clientHostId = getHostIdForHostName(clientParts[0].trim()); String processIndex = clientParts[1].trim(); String args = m_clientArgs.get(clientName); if (args == null) args = ""; addToHostsTableIfMissing(clientParts[0].trim()); sql = new StringBuilder(); sql.append("INSERT INTO participants (`resultid`, `hostid`, `processindex`, `role`, `commandline`) values ("); sql.append(String.valueOf(resultid)).append(", "); sql.append("'").append(clientHostId).append("', "); sql.append(processIndex).append(", "); sql.append("'CLIENT', "); sql.append("'").append(args).append("');"); m_stmt.executeUpdate(sql.toString()); for (String txnName : results.getTransactionNames()) { Result[] rset = results.getResultsForClientAndTransaction(clientName, txnName); for (int i = 0; i < rset.length; i++) { Result r = rset[i]; sql = new StringBuilder(); sql.append("INSERT INTO resultparts (`resultid`, `clienthost`, `processindex`, `transaction`, `interval`, `count`) values ("); sql.append(String.valueOf(resultid)).append(", "); sql.append("'").append(clientHostId).append("', "); sql.append(processIndex).append(", "); sql.append("'").append(txnName).append("', "); sql.append(i).append(", "); sql.append(r.transactionCount).append(");"); m_stmt.executeUpdate(sql.toString()); } } } // create rolled up information by interval sql = new StringBuilder(); sql.append("insert into resultintervals (`resultid`, `interval`, `seconds`, `intervaltxn`, `intervaltxnpersecond`) "); sql.append("select r.resultid, "); sql.append(" rp.interval, "); sql.append(" ((rp.interval + 1) * r.interval / 1000) seconds, "); sql.append(" sum(rp.count) intervaltxn, "); sql.append(" sum(rp.count) / (r.interval / 1000) intervaltxnpersecond "); sql.append("from results r, "); sql.append(" resultparts rp "); sql.append("where rp.resultid = r.resultid and "); sql.append(" r.resultid = ").append(String.valueOf(resultid)).append(" "); sql.append("group by rp.interval, r.interval;"); m_stmt.executeUpdate(sql.toString()); // Update main data (total transactions and transactions per second) sql = new StringBuilder(); sql.append("update results r "); sql.append("set r.totaltxn = (select sum(rp.count) from resultparts rp where rp.resultid = r.resultid), "); sql.append(" r.txnpersecond = (select sum(rp.count) from resultparts rp where rp.resultid = r.resultid) / r.duration * 1000 "); sql.append("where r.resultid = ").append(String.valueOf(resultid)).append(";"); m_stmt.executeUpdate(sql.toString()); m_conn.commit(); } catch (SQLException e) { System.err.println("Unable to save results to results server."); System.err.println(" Consider uncommenting debugging output in ResultsUploader.java."); System.err.flush(); // TODO Auto-generated catch block e.printStackTrace(); } } public String getDescriptionForHostName(String hostname) { /* * This is a total hack pending code to feed hostname * descriptions through benchmark controller main */ if (hostname.contains("amazonaws.com")) return "amazonws"; // really want m1.large or m1.xlarge if (hostname.contains("-bl")) return "desktop"; if (hostname.contains("-gr")) return "desktop"; if (hostname.contains("localhost")) return "desktop"; else return "unknown"; } public String getHostIdForHostName(String hostname) { String mac = m_hostIdCache.get(hostname); if (mac == null) { mac = SSHTools.cmd(m_config.remoteUser, hostname, m_config.remotePath, "./getmac.py"); mac = mac.trim(); m_hostIdCache.put(hostname, mac); } return mac; } public String[] getHostDistroForHostName(String hostname) { String[] retval = m_hostDistroCache.get(hostname); if (retval != null) return retval; retval = new String[2]; String distro = SSHTools.cmd(m_config.remoteUser, hostname, m_config.remotePath, "lsb_release -ir"); String[] lines = distro.trim().split("\n"); for (String l : lines) { String[] kv = l.split(":"); if (kv[0].startsWith("Distributor")) retval[0] = kv[1].trim(); else if (kv[0].startsWith("Release")) retval[1] = kv[1].trim(); } m_hostDistroCache.put(hostname, retval); return retval; } public String getCurrentUserId() { String username = System.getProperty("user.name"); java.sql.ResultSet rs; try { rs = m_stmt.executeQuery( "select count(*) from `users` where `username` = '" + username + "';"); if (rs.next()) { if (rs.getInt(1) != 1) { int rows = m_stmt.executeUpdate( "insert into `users` (`username`) values ('" + username + "')"); if (rows != 1) throw new RuntimeException(); } } else { throw new RuntimeException(); } } catch (SQLException e) { e.printStackTrace(); } return username; } }
/* Matthew Proetsch * Artificial Neural Network implementation - * COP3930h */ package com.proetsch.ann; import java.util.ArrayList; import java.util.Arrays; public class Network { ArrayList<Layer> layers; private double least_mean_squared_error; private double momentum; private double learning_rate; public Network(double lmse, double p, double lr) { least_mean_squared_error = lmse; momentum = p; learning_rate = lr; layers = new ArrayList<Layer>(); } public void initialize(int numInputs, int numHiddenNodes, int numHiddenLayers) throws Exception { Layer inputLayer = new Layer(); inputLayer.ID = 0; Layer[] hiddenLayers = new Layer[numHiddenLayers]; Layer outputLayer = new Layer(); outputLayer.ID = numHiddenLayers + 1; if (numHiddenLayers == 0) { throw new Exception("You must specify at least one hidden layer"); } // Initialize all layers, and set prev/next fields for (int i = 0; i < numHiddenLayers; ++i) { hiddenLayers[i] = new Layer(); hiddenLayers[i].ID = i + 1; if (i == 0) { hiddenLayers[0].setPrev(inputLayer); inputLayer.setNext(hiddenLayers[0]); } else if (i > 0) { hiddenLayers[i].setPrev(hiddenLayers[i-1]); hiddenLayers[i-1].setNext(hiddenLayers[i]); } if (i == numHiddenLayers - 1) { outputLayer.setPrev(hiddenLayers[i]); hiddenLayers[i].setNext(outputLayer); } } for (int i = 0; i < numInputs; ++i) { inputLayer.add(new InputLayerNeuron(inputLayer)); } for (int i = 0; i < numHiddenNodes; ++i) { for (int j = 0; j < numHiddenLayers; ++j) { hiddenLayers[j].add(new HiddenLayerNeuron(hiddenLayers[j])); } } // bias node inputLayer.add(new InputLayerNeuron(inputLayer)); for (int i = 0; i < numHiddenLayers; ++i) { hiddenLayers[i].assignRandomWeightsToHere(); } outputLayer.add(new OutputLayerNeuron(outputLayer)); outputLayer.assignRandomWeightsToHere(); layers.add(inputLayer); layers.addAll(Arrays.asList(hiddenLayers)); layers.add(outputLayer); } public void simulate(double[] inputs) throws Exception { if (inputs.length != layers.get(0).size() - 1) { throw new Exception(String.format("Input size: %1$s Expected: %2$s", inputs.length, layers.get(0).size())); } Layer inputLayer = layers.get(0); for (int i = 0; i < inputs.length; ++i) { InputLayerNeuron n = (InputLayerNeuron) inputLayer.get(i); n.setInput(inputs[i]); } InputLayerNeuron biasNode = (InputLayerNeuron) inputLayer.get(inputs.length); biasNode.setInput(1.0d); for (int i = 1; i < layers.size(); ++i) { layers.get(i).calculateOutput(); } System.out.println(layers.get(layers.size()-1).get(0).output_value); } // Train the network via backpropagation of error public void train(ArrayList<double[]> inputs, ArrayList<Double> expectedOutputs) throws Exception { if (inputs.size() != expectedOutputs.size()) { throw new Exception(String.format("Input ArrayList size: %1$s ExpectedOutput size: %2$s", inputs.size(), expectedOutputs.size())); } for (int i = 0; i < inputs.size(); ++i) { // 1. Simulate network on input simulate(inputs.get(i)); // 2. Calculate output layer delta Layer outputLayer = layers.get(layers.size() - 1); outputLayer.calculateDeltas(expectedOutputs.get(i)); // Calculate deltas for layers in reverse order (second-to-last, third-to-last, ..., the one before input) for (int j = layers.size() - 2; j > 0; --j) { // calculateDeltas's argument doesn't matter in the hidden layer layers.get(j).calculateDeltas(expectedOutputs.get(i)); } // 3. Finally, update weights of each link for (int j = 1; j < layers.size(); ++j) { layers.get(j).correctWeights(learning_rate, momentum); } } } public static void main(String[] args) throws Exception { Network ann = new Network(0.0d, 0.8d, 0.30d); ann.initialize(2, 3, 1); ArrayList<double[]> in = new ArrayList<double[]>(); in.add(new double[] { 0.0d, 0.0d, }); in.add(new double[] { 1.0d, 1.0d }); in.add(new double[] { 1.0d, 0.0d }); in.add(new double[] { 0.0d, 1.0d }); ArrayList<Double> expected = new ArrayList<Double>(); double[] answers = new double[] { 0.0d, 0.0d, 1.0d, 1.0d }; for (int i = 0; i < answers.length; ++i) { expected.add(answers[i]); } for (int i = 0; i < 40000; ++i) ann.train(in, expected); // System.out.println(); } }
package org.voltdb.compiler; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; import junit.framework.TestCase; import org.apache.commons.lang3.StringUtils; import org.voltdb.catalog.Column; import org.voltdb.catalog.Database; import org.voltdb.catalog.Table; import org.voltdb.utils.BuildDirectoryUtils; /** * @author scooper * */ public class TestPartitionDDL extends TestCase { String testout_jar; @Override public void setUp() { testout_jar = BuildDirectoryUtils.getBuildDirectoryPath() + File.pathSeparator + "testout.jar"; } @Override public void tearDown() { new File(testout_jar).delete(); } class Item { final String[] m_strings; Item(final String... strings) { m_strings = strings; } String toDDL() { return null; } String toXML() { return null; } } class DDL extends Item { DDL(final String... ddlStrings) { super(ddlStrings); } @Override String toDDL() { return StringUtils.join(m_strings, '\n'); } } class ReplicateDDL extends DDL { ReplicateDDL(final String tableName) { super(String.format("REPLICATE TABLE %s;", tableName)); } } class PartitionDDL extends DDL { PartitionDDL(final String tableName, final String columnName) { super(String.format("PARTITION TABLE %s ON COLUMN %s;", tableName, columnName)); } } class PartitionXML extends Item { PartitionXML(final String tableName, final String columnName) { super(tableName, columnName); } @Override String toXML() { return String.format("<partition table='%s' column='%s' />", m_strings[0], m_strings[1]); } } class Tester { final Item schemaItem; final static String partitionedProc = "org.voltdb.compiler.procedures.AddBook"; final static String replicatedProc = "org.voltdb.compiler.procedures.EmptyProcedure"; Tester() { schemaItem = new DDL( "create table books (", "cash integer default 0 NOT NULL,", "title varchar(10) default 'foo',", "PRIMARY KEY(cash)", ");"); } Tester(DDL schemaItemIn) { schemaItem = schemaItemIn; } String writeDDL(final Item... items) { StringBuilder sb = new StringBuilder(); sb.append(schemaItem.toDDL()); sb.append('\n'); for (Item item : items) { String line = item.toXML(); if (line == null) { sb.append(item.toDDL()); sb.append('\n'); } } final File ddlFile = VoltProjectBuilder.writeStringToTempFile(sb.toString()); return ddlFile.getPath(); } String writeXML(final boolean partitioned, final String ddlPath, final Item... items) { String xmlText = "<?xml version=\"1.0\"?>\n" + "<project>\n" + " <database>\n" + " <schemas>\n" + " <schema path='" + ddlPath + "' />\n" + " </schemas>\n"; int nxml = 0; for (Item item : items) { String line = item.toXML(); if (line != null) { nxml++; if (nxml == 1) { xmlText += " <partitions>\n"; } xmlText += String.format(" %s\n", line); } } if (nxml > 0) { xmlText += " </partitions>\n"; } xmlText += " <procedures>\n"; xmlText += String.format(" <procedure class='%s' />\n", partitioned ? partitionedProc : replicatedProc); xmlText += " </procedures>\n" + " </database>\n" + "</project>\n"; return VoltProjectBuilder.writeStringToTempFile(xmlText).getPath(); } String getMessages(final VoltCompiler compiler, final boolean success) { ByteArrayOutputStream ss = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(ss); if (success) { compiler.summarizeSuccess(null, ps); } else { compiler.summarizeErrors(null, ps); } // For some reason linefeeds break the regex pattern matching. return ss.toString().trim().replace('\n', ' '); } // Must provide a failRegex if failure is expected. void test(final boolean partitioned, final String failRegex, final int additionalTables, final Item... items) { // Generate DDL and XML files. String ddlPath = writeDDL(items); String xmlPath = writeXML(partitioned, ddlPath, items); // Compile the catalog. final VoltCompiler compiler = new VoltCompiler(); boolean success = compiler.compile(xmlPath, testout_jar); // Check for expected compilation success or failure. String s = getMessages(compiler, false); if (failRegex != null) { assertFalse("Expected compilation failure.", success); assertTrue(String.format("Expected error regex \"%s\" not matched.\n%s", failRegex, s), s.matches(failRegex)); } else { assertTrue(String.format("Unexpected compilation failure.\n%s", s), success); // Check that the catalog table is appropriately configured. Database db = compiler.m_catalog.getClusters().get("cluster").getDatabases().get("database"); assertNotNull(db); assertEquals(1 + additionalTables, db.getTables().size()); Table t = db.getTables().getIgnoreCase("books"); assertNotNull(t); Column c = t.getPartitioncolumn(); if (partitioned) { assertNotNull(c); } else { assertNull(c); } } } /** * Call when expected result is a partitioned table. * @param items */ void partitioned(final Item... items) { test(true, null, 0, items); } /** * Call when expected result is a replicated table. * @param items */ void replicated(final Item... items) { test(false, null, 0, items); } /** * Call when expected result is a failure. * Checks error message against failRegex. * @param failRegex * @param items */ void bad(final String failRegex, final Item... items) { test(false, failRegex, 0, items); } /** * Call when DDL has a view and it should pass. * @param items */ void view_good(final boolean partitioned, final Item... items) { test(partitioned, null, 1, items); } /** * Call when DDL has a view and it should fail. * @param items */ void view_bad(final String failRegex, final boolean partitioned, final Item... items) { test(partitioned, failRegex, 1, items); } } public void testGeneralDDLParsing() { Tester tester = new Tester(); // Just the CREATE TABLE statement. tester.replicated(); // Garbage statement added. tester.bad(".*unexpected token.*", new DDL("asldkf sadlfk;")); } public void testBadReplicate() { Tester tester = new Tester(); // REPLICATE statement with no semi-colon. tester.bad(".*no semicolon found.*", new DDL("REPLICATE TABLE books")); // REPLICATE statement with missing argument. tester.bad(".*Bad REPLICATE DDL statement.*", new DDL("REPLICATE TABLE;")); // REPLICATE statement with too many arguments. tester.bad(".*Bad REPLICATE DDL statement.*", new DDL("REPLICATE TABLE books NOW;")); // REPLICATE with bad table clause. tester.bad(".*Bad REPLICATE DDL statement.*", new DDL("REPLICATE TABLEX books;")); //REPLICATE with bad table identifier tester.bad(".*Bad indentifier in DDL.*", new DDL("REPLICATE TABLE 0books;")); } public void testGoodReplicate() { Tester tester = new Tester(); // REPLICATE with annoying whitespace. tester.replicated(new DDL("\t\t REPLICATE\r\nTABLE\nbooks\t\t\n ;")); // REPLICATE with clean statement. tester.replicated(new ReplicateDDL("books")); } public void testBadPartition() { Tester tester = new Tester(); // PARTITION statement with no semi-colon. tester.bad(".*no semicolon found.*", new DDL("PARTITION TABLE books ON COLUMN cash")); // PARTITION statement with missing arguments. tester.bad(".*Bad PARTITION DDL statement.*", new DDL("PARTITION TABLE;")); // PARTITION statement with too many arguments. tester.bad(".*Bad PARTITION DDL statement.*", new DDL("PARTITION TABLE books ON COLUMN cash COW;")); // PARTITION statement intermixed with procedure. tester.bad(".*Bad PARTITION DDL statement.*", new DDL("PARTITION TABLE books PROCEDURE bruha ON COLUMN cash;")); // PARTITION with bad table clause. tester.bad(".*Bad PARTITION DDL statement.*", new DDL("PARTITION TABLEX books ON COLUMN cash;")); } public void testGoodPartition() { Tester tester = new Tester(); // PARTITION with annoying whitespace. tester.partitioned(new DDL("\t\t PARTITION\r\nTABLE\nbooks\r\n\tON COLUMN cash\t\t\n ;")); // PARTITION from DDL. tester.partitioned(new PartitionDDL("books", "cash")); // PARTITION from XML. tester.partitioned(new PartitionXML("books", "cash")); } public void testRedundant() { Tester tester = new Tester(); // PARTITION from both XML and DDL. tester.bad(".*Partitioning already specified for table.*", new PartitionXML("books", "cash"), new PartitionDDL("books", "cash")); // PARTITION and REPLICATE from both XML and DDL. tester.bad(".*Partitioning already specified for table.*", new PartitionXML("books", "cash"), new ReplicateDDL("books")); // PARTITION and REPLICATE from DDL. tester.bad(".*Partitioning already specified for table.*", new PartitionDDL("books", "cash"), new ReplicateDDL("books")); // PARTITION twice from DDL. tester.bad(".*Partitioning already specified for table.*", new PartitionDDL("books", "cash"), new PartitionDDL("books", "cash")); } }
package org.jgroups.tests; import org.jgroups.*; import org.jgroups.protocols.FORWARD_TO_COORD; import org.jgroups.protocols.PING; import org.jgroups.protocols.SHARED_LOOPBACK; import org.jgroups.protocols.UNICAST3; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.protocols.pbcast.NAKACK2; import org.jgroups.protocols.relay.RELAY2; import org.jgroups.protocols.relay.Relayer; import org.jgroups.protocols.relay.SiteMaster; import org.jgroups.protocols.relay.config.RelayConfig; import org.jgroups.stack.Protocol; import org.jgroups.util.Util; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Various RELAY2-related tests * @author Bela Ban * @since 3.2 */ @Test(groups=Global.FUNCTIONAL,sequential=true) public class Relay2Test { protected JChannel a, b, c; // members in site "lon" protected JChannel x, y, z; // members in site "sfo protected static final String BRIDGE_CLUSTER = "global"; protected static final String LON_CLUSTER = "lon-cluster"; protected static final String SFO_CLUSTER = "sfo-cluster"; protected static final String SFO = "sfo", LON="lon"; @AfterMethod protected void destroy() {Util.close(z,y,x,c,b,a);} /** * Test that RELAY2 can be added to an already connected channel. */ public void testAddRelay2ToAnAlreadyConnectedChannel() throws Exception { // 1- Create and connect a channel. a = new JChannel(); a.connect(SFO_CLUSTER); System.out.println("Channel " + a.getName() + " is connected. View: " + a.getView()); // 3- Add RELAY2 protocol to the already connected channel. RELAY2 relayToInject = createRELAY2(SFO); // Util.setField(Util.getField(relayToInject.getClass(), "local_addr"), relayToInject, a.getAddress()); a.getProtocolStack().insertProtocolAtTop(relayToInject); relayToInject.down(new Event(Event.SET_LOCAL_ADDRESS, a.getAddress())); relayToInject.setProtocolStack(a.getProtocolStack()); relayToInject.configure(); relayToInject.handleView(a.getView()); // 4- Check RELAY2 presence. RELAY2 ar=(RELAY2)a.getProtocolStack().findProtocol(RELAY2.class); assert ar != null; waitUntilStatus(SFO, RELAY2.RouteStatus.UP, 2000, 500, a); assert !ar.printRoutes().equals("n/a (not site master)") : "This member should be site master"; Relayer.Route route=getRoute(a, SFO); System.out.println("Route at sfo to sfo: " + route); assert route != null; } public void testMissingRouteAfterMerge() throws Exception { a=createNode(LON, "A", LON_CLUSTER, null); b=createNode(LON, "B", LON_CLUSTER, null); Util.waitUntilAllChannelsHaveSameSize(30000, 500, a,b); x=createNode(SFO, "X", SFO_CLUSTER, null); assert x.getView().size() == 1; RELAY2 ar=(RELAY2)a.getProtocolStack().findProtocol(RELAY2.class), xr=(RELAY2)x.getProtocolStack().findProtocol(RELAY2.class); assert ar != null && xr != null; JChannel a_bridge=null, x_bridge=null; for(int i=0; i < 20; i++) { a_bridge=ar.getBridge(SFO); x_bridge=xr.getBridge(LON); if(a_bridge != null && x_bridge != null && a_bridge.getView().size() == 2 && x_bridge.getView().size() == 2) break; Util.sleep(500); } assert a_bridge != null && x_bridge != null; System.out.println("A's bridge channel: " + a_bridge.getView()); System.out.println("X's bridge channel: " + x_bridge.getView()); assert a_bridge.getView().size() == 2 : "bridge view is " + a_bridge.getView(); assert x_bridge.getView().size() == 2 : "bridge view is " + x_bridge.getView(); Relayer.Route route=getRoute(x, LON); System.out.println("Route at sfo to lon: " + route); assert route != null; // Now inject a partition into site LON System.out.println("Creating partition between A and B:"); createPartition(a, b); System.out.println("A's view: " + a.getView() + "\nB's view: " + b.getView()); assert a.getView().size() == 1 && b.getView().size() == 1; route=getRoute(x, LON); System.out.println("Route at sfo to lon: " + route); assert route != null; View bridge_view=xr.getBridgeView(BRIDGE_CLUSTER); System.out.println("bridge_view = " + bridge_view); // Now make A and B form a cluster again: View merge_view=new MergeView(a.getAddress(), 10, Arrays.asList(a.getAddress(), b.getAddress()), Arrays.asList(Util.createView(a.getAddress(), 5, a.getAddress()), Util.createView(b.getAddress(), 5, b.getAddress()))); GMS gms=(GMS)a.getProtocolStack().findProtocol(GMS.class); gms.installView(merge_view, null); gms=(GMS)b.getProtocolStack().findProtocol(GMS.class); gms.installView(merge_view, null); Util.waitUntilAllChannelsHaveSameSize(20000, 500, a, b); System.out.println("A's view: " + a.getView() + "\nB's view: " + b.getView()); for(int i=0; i < 20; i++) { bridge_view=xr.getBridgeView(BRIDGE_CLUSTER); if(bridge_view != null && bridge_view.size() == 2) break; Util.sleep(500); } route=getRoute(x, LON); System.out.println("Route at sfo to lon: " + route); assert route != null; } /** * Tests whether the bridge channel connects and disconnects ok. */ public void testConnectAndReconnectOfBridgeStack() throws Exception { a=new JChannel(createBridgeStack()); a.setName("A"); b=new JChannel(createBridgeStack()); b.setName("B"); a.connect(BRIDGE_CLUSTER); b.connect(BRIDGE_CLUSTER); Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b); b.disconnect(); Util.waitUntilAllChannelsHaveSameSize(10000, 500, a); b.connect(BRIDGE_CLUSTER); Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b); } /** * Tests sites LON and SFO, with SFO disconnecting (bridge view on LON should be 1) and reconnecting (bridge view on * LON and SFO should be 2) */ public void testDisconnectAndReconnect() throws Exception { a=createNode(LON, "A", LON_CLUSTER, null); x=createNode(SFO, "X", SFO_CLUSTER, null); System.out.println("Started A and X; waiting for bridge view of 2 on A and X"); waitForBridgeView(2, 20000, 500, a, x); System.out.println("Disconnecting X; waiting for a bridge view on 1 on A"); x.disconnect(); waitForBridgeView(1, 20000, 500, a); System.out.println("Reconnecting X again; waiting for a bridge view of 2 on A and X"); x.connect(SFO_CLUSTER); waitForBridgeView(2, 20000, 500, a, x); } public void testQueueingAndForwarding() throws Exception { MyReceiver rx=new MyReceiver(); a=createNode(LON, "A", LON_CLUSTER, null); x=createNode(SFO, "X", SFO_CLUSTER, rx); System.out.println("A: waiting for site SFO to be UP"); waitUntilStatus(SFO, RELAY2.RouteStatus.UP, 20000, 500, a); Address sm_sfo=new SiteMaster(SFO); System.out.println("A: sending message 0 to the site master of SFO"); a.send(sm_sfo, 0); List<Integer> list=rx.getList(); for(int i=0; i < 20; i++) { if(!list.isEmpty()) break; Util.sleep(500); } System.out.println("list = " + list); assert list.size() == 1 && list.get(0) == 0; rx.clear(); x.disconnect(); System.out.println("Waiting for site SFO to be UNKNOWN"); waitUntilStatus(SFO, RELAY2.RouteStatus.UNKNOWN, 20000, 500, a); System.out.println("A: sending 5 messages to site SFO - they should all get queued"); for(int i=1; i <= 5; i++) a.send(sm_sfo, i); System.out.println("Starting X again; the queued messages should now get re-sent from A to X"); x.connect(SFO_CLUSTER); for(int i=0; i < 20; i++) { if(list.size() == 5) break; Util.sleep(500); } System.out.println("list = " + list); assert list.size() == 5 : "list should be 5 but is: " + list; for(int i=1; i <= 5; i++) assert list.contains(i); } /** * Tests the following scenario: * <ul> * <li>Nodes A in LON and B in SFO, both are up</li> * <li>B goes down</li> * <li>The status of site SFO in LON is set to UNKNOWN and a task T is started which will set SFO's status * to DOWN in site_down_timeout ms</li> * <li>Before T kicks in, B in SFO is started again</li> * <li>The status of site SFO in LON is now UP</li> * <li>Make sure T is cancelled when transitioning from UNKNOWN to UP, or else it'll set the status * of SFO to DOWN when it triggers</li> * </ul> */ public void testUnknownAndUpStateTransitions() throws Exception { a=createNode(LON, "A", LON_CLUSTER, null); x=createNode(SFO, "X", SFO_CLUSTER, null); waitForBridgeView(2, 20000, 500, a, x); RELAY2 ra=(RELAY2)a.getProtocolStack().findProtocol(RELAY2.class); ra.siteDownTimeout(3000); System.out.println("Disconnecting X"); x.disconnect(); System.out.println("A: waiting for site SFO to be UNKNOWN"); waitUntilStatus(SFO, RELAY2.RouteStatus.UNKNOWN, 20000, 500, a); System.out.println("Reconnecting X, waiting for 5 seconds to see if the route is marked as DOWN"); x.connect(SFO_CLUSTER); Util.sleep(5000); Relayer.Route route=getRoute(a, SFO); assert route != null && route.status() == RELAY2.RouteStatus.UP : "route is " + route + " (expected to be UP)"; route=getRoute(x, LON); assert route != null && route.status() == RELAY2.RouteStatus.UP : "route is " + route + " (expected to be UP)"; } protected JChannel createNode(String site_name, String node_name, String cluster_name, Receiver receiver) throws Exception { JChannel ch=new JChannel(new SHARED_LOOPBACK(), new PING().setValue("timeout", 300).setValue("num_initial_members", 2), new NAKACK2(), new UNICAST3(), new GMS().setValue("print_local_addr", false), new FORWARD_TO_COORD(), createRELAY2(site_name)); ch.setName(node_name); if(receiver != null) ch.setReceiver(receiver); if(cluster_name != null) ch.connect(cluster_name); return ch; } protected RELAY2 createRELAY2(String site_name) { RELAY2 relay=new RELAY2().site(site_name).enableAddressTagging(false).asyncRelayCreation(true); RelayConfig.SiteConfig lon_cfg=new RelayConfig.SiteConfig(LON, (short)0), sfo_cfg=new RelayConfig.SiteConfig(SFO, (short)1); lon_cfg.addBridge(new RelayConfig.ProgrammaticBridgeConfig(BRIDGE_CLUSTER, createBridgeStack())); sfo_cfg.addBridge(new RelayConfig.ProgrammaticBridgeConfig(BRIDGE_CLUSTER, createBridgeStack())); relay.addSite(LON, lon_cfg).addSite(SFO, sfo_cfg); return relay; } protected static Protocol[] createBridgeStack() { return new Protocol[]{ new SHARED_LOOPBACK(), new PING().setValue("timeout", 500).setValue("num_initial_members", 2), new NAKACK2(), new UNICAST3(), new GMS().setValue("print_local_addr", false) }; } /** Creates a singleton view for each channel listed and injects it */ protected static void createPartition(JChannel ... channels) { for(JChannel ch: channels) { View view=Util.createView(ch.getAddress(), 5, ch.getAddress()); GMS gms=(GMS)ch.getProtocolStack().findProtocol(GMS.class); gms.installView(view); } } protected void waitForBridgeView(int expected_size, long timeout, long interval, JChannel ... channels) { long deadline=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < deadline) { boolean views_correct=true; for(JChannel ch: channels) { RELAY2 relay=(RELAY2)ch.getProtocolStack().findProtocol(RELAY2.class); View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER); if(bridge_view == null || bridge_view.size() != expected_size) { views_correct=false; break; } } if(views_correct) break; Util.sleep(interval); } System.out.println("Bridge views:\n"); for(JChannel ch: channels) { RELAY2 relay=(RELAY2)ch.getProtocolStack().findProtocol(RELAY2.class); View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER); System.out.println(ch.getAddress() + ": " + bridge_view); } for(JChannel ch: channels) { RELAY2 relay=(RELAY2)ch.getProtocolStack().findProtocol(RELAY2.class); View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER); assert bridge_view != null && bridge_view.size() == expected_size : ch.getAddress() + ": bridge view=" + bridge_view + ", expected=" + expected_size; } } protected void waitUntilStatus(String site_name, RELAY2.RouteStatus expected_status, long timeout, long interval, JChannel ch) throws Exception { RELAY2 relay=(RELAY2)ch.getProtocolStack().findProtocol(RELAY2.class); if(relay == null) throw new IllegalArgumentException("Protocol RELAY2 not found"); Relayer.Route route=null; long deadline=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < deadline) { route=relay.getRoute(site_name); if(route != null && route.status() == expected_status) break; Util.sleep(interval); } assert route.status() == expected_status : "status=" + (route != null? route.status() : "n/a") + ", expected status=" + expected_status; } protected Relayer.Route getRoute(JChannel ch, String site_name) { RELAY2 relay=(RELAY2)ch.getProtocolStack().findProtocol(RELAY2.class); return relay.getRoute(site_name); } protected static class MyReceiver extends ReceiverAdapter { protected final List<Integer> list=new ArrayList<Integer>(5); public List<Integer> getList() {return list;} public void clear() {list.clear();} public void receive(Message msg) { list.add((Integer)msg.getObject()); System.out.println("<-- " + msg.getObject()); } } }
package org.spine3.test; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Type; import java.security.acl.AclNotFoundException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EmptyStackException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @SuppressWarnings({"ClassWithTooManyMethods", "OverlyComplexClass"}) public class VerifyShould { private static final String emptyString = ""; private static final String notEmptyString = "Not empty string"; private static final String mapName = "map"; @Test public void extend_Assert_class() { final Type expectedSuperclass = Assert.class; final Type actualSuperclass = Verify.class.getGenericSuperclass(); assertEquals(expectedSuperclass, actualSuperclass); } @Test public void have_private_ctor() { assertTrue(Tests.hasPrivateUtilityConstructor(Verify.class)); } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; try { throw Verify.mangledException(sourceError); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - 1, framesAfter); } } @SuppressWarnings({"ThrowCaughtLocally", "ErrorNotRethrown"}) @Test public void mangle_assertion_error_for_specified_frame_count() { final AssertionError sourceError = new AssertionError(); final int framesBefore = sourceError.getStackTrace().length; final int framesToPop = 3; try { throw Verify.mangledException(sourceError, framesToPop); } catch (AssertionError e) { final int framesAfter = e.getStackTrace().length; assertEquals(framesBefore - framesToPop + 1, framesAfter); } } @SuppressWarnings("ErrorNotRethrown") @Test public void fail_with_specified_message_and_cause() { final String message = "Test failed"; final Throwable cause = new Error(); try { Verify.fail(message, cause); fail("Error was not thrown"); } catch (AssertionError e) { assertEquals(message, e.getMessage()); assertEquals(cause, e.getCause()); } } @Test(expected = AssertionError.class) public void fail_if_float_values_are_positive_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_negative_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_NaN() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.NaN, Float.NaN, anyDeltaAcceptable); } @Test(expected = AssertionError.class) public void fail_if_float_values_are_equal() { final float positiveValue = 5.0f; final float negativeValue = -positiveValue; final float equalToValuesDifference = positiveValue - negativeValue; Verify.assertNotEquals(positiveValue, negativeValue, equalToValuesDifference); } @Test public void pass_if_float_values_are_different_types_of_infinity() { final float anyDeltaAcceptable = 0.0f; Verify.assertNotEquals(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, anyDeltaAcceptable); Verify.assertNotEquals(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, anyDeltaAcceptable); } @Test public void pass_if_float_values_are_not_equal() { final float expected = 0.0f; final float actual = 1.0f; final float lessThanValuesDifference = Math.abs(expected - actual) - 0.1f; Verify.assertNotEquals(expected, actual, lessThanValuesDifference); } @Test(expected = AssertionError.class) public void fail_if_bool_values_are_equal() { Verify.assertNotEquals(true, true); } @Test public void pass_if_bool_values_are_not_equal() { Verify.assertNotEquals(true, false); } @Test(expected = AssertionError.class) public void fail_if_byte_values_are_equal() { Verify.assertNotEquals((byte) 0, (byte) 0); } @Test public void pass_if_byte_values_are_not_equal() { Verify.assertNotEquals((byte) 0, (byte) 1); } @Test(expected = AssertionError.class) public void fail_if_char_values_are_equal() { Verify.assertNotEquals('a', 'a'); } @Test public void pass_if_char_values_are_not_equal() { Verify.assertNotEquals('a', 'b'); } @Test(expected = AssertionError.class) public void fail_if_short_values_are_equal() { Verify.assertNotEquals((short) 0, (short) 0); } @Test public void pass_if_short_values_are_not_equal() { Verify.assertNotEquals((short) 0, (short) 1); } @Test(expected = AssertionError.class) public void fail_if_object_is_not_instance_of_specified_type() { Verify.assertInstanceOf(Integer.class, ""); } @Test public void pass_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertInstanceOf(instance.getClass(), instance); } @Test(expected = AssertionError.class) public void fail_if_object_is_instance_of_specified_type() { final String instance = ""; Verify.assertNotInstanceOf(instance.getClass(), instance); } @Test public void pass_if_object_is_not_instance_of_specified_type() { Verify.assertNotInstanceOf(Integer.class, ""); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_not_empty() { Verify.assertIterableEmpty(FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_empty() { Verify.assertIterableEmpty(null); } @Test public void pass_if_iterable_is_empty() { Verify.assertIterableEmpty(FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_is_not_empty() { Verify.assertEmpty(Collections.singletonMap(1, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_empty() { Verify.assertEmpty((Map) null); } @Test public void pass_if_map_is_empty() { Verify.assertEmpty(Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertEmpty(multimap); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_empty() { Verify.assertEmpty((Multimap) null); } @Test public void pass_if_multimap_is_empty() { Verify.assertEmpty(ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_iterable_is_empty() { Verify.assertNotEmpty(FluentIterable.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_iterable_not_empty() { Verify.assertIterableNotEmpty(null); } @Test public void pass_if_iterable_is_not_empty() { Verify.assertNotEmpty(FluentIterable.of(1)); } @Test(expected = AssertionError.class) public void fail_if_map_is_empty() { Verify.assertNotEmpty(Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_empty() { Verify.assertNotEmpty((Map) null); } @Test public void pass_if_map_is_not_empty() { Verify.assertNotEmpty(Collections.singletonMap(1, 1)); } @Test(expected = AssertionError.class) public void fail_if_multimap_is_empty() { Verify.assertNotEmpty(ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Multimap) null); } @Test public void pass_if_multimap_is_not_empty() { final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(1, 1); Verify.assertNotEmpty(multimap); } @SuppressWarnings("ZeroLengthArrayAllocation") @Test(expected = AssertionError.class) public void fail_if_array_is_empty() { Verify.assertNotEmpty(new Integer[0]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_not_empty() { Verify.assertNotEmpty((Integer[]) null); } @Test public void pass_if_array_is_not_empty() { final Integer[] array = {1, 2, 3}; Verify.assertNotEmpty(array); } @Test(expected = AssertionError.class) public void fail_if_object_array_size_is_not_equal() { Verify.assertSize(-1, new Object[1]); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_size() { Verify.assertSize(0, (Integer[]) null); } @Test public void pass_if_object_array_size_is_equal() { final int size = 0; Verify.assertSize(size, new Object[size]); } @Test(expected = AssertionError.class) public void fail_if_iterable_size_is_not_equal() { Verify.assertSize(-1, FluentIterable.of(1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_assert_size() { Verify.assertSize(0, (Iterable) null); } @Test public void pass_if_iterable_size_is_equal() { Verify.assertSize(0, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_assert_size() { Verify.assertSize(0, (Map) null); } @Test public void pass_if_map_size_is_equal() { Verify.assertSize(0, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_multimap_size_is_not_equal() { Verify.assertSize(-1, ArrayListMultimap.create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_assert_size() { Verify.assertSize(0, (Multimap) null); } @Test public void pass_if_multimap_size_is_equal() { Verify.assertSize(0, ArrayListMultimap.create()); } @Test(expected = AssertionError.class) public void fail_if_collection_size_is_not_equal() { Verify.assertSize(-1, Collections.emptyList()); } @Test public void pass_if_collection_size_is_equal() { Verify.assertSize(0, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_string_not_contains_char_sequence() { Verify.assertContains(notEmptyString, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_contains() { Verify.assertContains(null, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_contains() { Verify.assertContains(emptyString, (String) null); } @SuppressWarnings({"ConstantConditions", "ErrorNotRethrown"}) @Test(expected = AssertionError.class) public void fail_if_contains_char_sequence_or_string_is_null() { final String nullString = null; try { Verify.assertContains(null, emptyString); } catch (AssertionError e) { Verify.assertContains(emptyString, nullString); } } @Test public void pass_if_string_contains_char_sequence() { Verify.assertContains(emptyString, notEmptyString); } @Test(expected = AssertionError.class) public void fail_is_string_contains_char_sequence() { Verify.assertNotContains(emptyString, notEmptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_char_sequence_is_null_in_not_contains() { Verify.assertNotContains(null, emptyString); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_string_is_null_in_not_contains() { Verify.assertNotContains(emptyString, (String) null); } @Test public void pass_if_string_not_contains_char_sequence() { Verify.assertNotContains(notEmptyString, emptyString); } @Test(expected = AssertionError.class) public void fail_if_collection_not_contains_item() { Verify.assertContains(1, Collections.emptyList()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collections_is_null_in_contains() { Verify.assertContains(1, (Collection) null); } @Test public void pass_if_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, Collections.singletonList(item)); } @Test(expected = AssertionError.class) public void fail_if_immutable_collection_not_contains_item() { Verify.assertContains(1, ImmutableList.of()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_immutable_collections_is_null_in_contains() { Verify.assertContains(1, null); } @Test public void pass_if_immutable_collection_contains_item() { final Integer item = 1; Verify.assertContains(item, ImmutableList.of(item)); } @Test(expected = AssertionError.class) public void fail_if_iterable_not_contains_all() { Verify.assertContainsAll(Collections.emptyList(), 1); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_all() { Verify.assertContainsAll(null); } @Test public void pass_if_iterable_contains_all() { final Integer item = 1; Verify.assertContainsAll(Collections.singletonList(item), item); } @Test(expected = AssertionError.class) public void fail_if_map_are_not_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = Collections.singletonMap(1, Collections.singletonMap(1, 2)); Verify.assertMapsEqual(firstOne, secondOne, mapName); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_maps_are_null() { Verify.assertMapsEqual(null, null, mapName); } @Test public void pass_if_maps_are_equal() { final Map<Integer, Map<Integer, Integer>> firstOne = Collections.singletonMap(1, Collections.singletonMap(1, 1)); final Map<Integer, Map<Integer, Integer>> secondOne = new HashMap<>(firstOne); Verify.assertMapsEqual(firstOne, secondOne, mapName); } @Test(expected = AssertionError.class) public void fail_if_sets_are_not_equal() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3, 4); final Set<Integer> secondOne = Sets.newHashSet(1, 2, 4); Verify.assertSetsEqual(firstOne, secondOne); } @SuppressWarnings("ConstantConditions") @Test public void pass_if_sets_are_null() { Verify.assertSetsEqual(null, null); } @Test public void pass_if_sets_are_equal() { final Set<Integer> firstOne = Sets.newHashSet(1, 2, 3); final Set<Integer> secondOne = Sets.newHashSet(firstOne); Verify.assertSetsEqual(firstOne, secondOne); } @Test(expected = AssertionError.class) public void fail_if_multimap_not_contains_entry() { Verify.assertContainsEntry(1, 1, ArrayListMultimap.<Integer, Integer>create()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_multimap_is_null_in_contains_entry() { Verify.assertContainsEntry(1, 1, null); } @Test public void pass_if_multimap_contains_entry() { final Integer entryKey = 1; final Integer entryValue = 1; final Multimap<Integer, Integer> multimap = ArrayListMultimap.create(); multimap.put(entryKey, entryValue); Verify.assertContainsEntry(entryKey, entryValue, multimap); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_key() { Verify.assertContainsKey(1, Collections.emptyMap()); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key() { Verify.assertContainsKey(1, null); } @Test public void pass_if_map_contains_key() { final Integer key = 1; Verify.assertContainsKey(key, Collections.singletonMap(key, 1)); } @Test(expected = AssertionError.class) public void fail_if_map_contains_denied_key() { final Integer key = 1; Verify.denyContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_deny_contains_key() { Verify.denyContainsKey(1, null); } @Test public void pass_if_map_not_contains_denied_key() { Verify.denyContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_map_not_contains_entry() { final Integer key = 0; Verify.assertContainsKeyValue(key, 0, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_contains_key_value() { Verify.assertContainsKeyValue(1, 1, null); } @Test public void pass_if_map_contains_entry() { final Integer key = 1; final Integer value = 1; Verify.assertContainsKeyValue(key, value, Collections.singletonMap(key, value)); } @Test(expected = AssertionError.class) public void fail_if_collection_contains_item() { final Integer item = 1; Verify.assertNotContains(item, Collections.singletonList(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_collection_is_null_in_not_contains() { Verify.assertNotContains(1, null); } @Test public void pass_if_collection_not_contains_item() { Verify.assertNotContains(1, Collections.emptyList()); } @Test(expected = AssertionError.class) public void fail_if_iterable_contains_item() { final Integer item = 1; Verify.assertNotContains(item, FluentIterable.of(item)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_iterable_is_null_in_contains_item() { Verify.assertNotContains(1, (Iterable) null); } @Test public void pass_if_iterable_not_contains_item() { Verify.assertNotContains(1, FluentIterable.of()); } @Test(expected = AssertionError.class) public void fail_if_map_contains_key() { final Integer key = 1; Verify.assertNotContainsKey(key, Collections.singletonMap(key, 1)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_map_is_null_in_not_contains_key() { Verify.assertNotContainsKey(1, null); } @Test public void pass_if_map_not_contains_key() { Verify.assertNotContainsKey(1, Collections.emptyMap()); } @Test(expected = AssertionError.class) public void fail_if_former_later_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(secondItem, firstItem, list); } @Test(expected = AssertionError.class) public void fail_if_former_and_latter_are_equal() { final Integer sameItem = 1; Verify.assertBefore(sameItem, sameItem, Collections.singletonList(sameItem)); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_befor() { Verify.assertBefore(1, 2, null); } @Test public void pass_if_former_before_latter() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertBefore(firstItem, secondItem, list); } @Test(expected = AssertionError.class) public void fail_if_list_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final List<Integer> list = Arrays.asList(firstItem, secondItem); Verify.assertItemAtIndex(firstItem, list.indexOf(secondItem), list); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (List) null); } @Test public void pass_if_list_item_at_index() { final Integer value = 1; final List<Integer> list = Collections.singletonList(value); Verify.assertItemAtIndex(value, list.indexOf(value), list); } @Test(expected = AssertionError.class) public void fail_if_array_item_not_at_index() { final Integer firstItem = 1; final Integer secondItem = 2; final Object[] array = {firstItem, secondItem}; Verify.assertItemAtIndex(firstItem, 1, array); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_assert_item_at_index() { Verify.assertItemAtIndex(1, 1, (Object[]) null); } @Test public void pass_if_array_item_at_index() { final Integer value = 1; final Object[] array = {value}; Verify.assertItemAtIndex(value, 0, array); } @Test(expected = AssertionError.class) public void fail_if_array_not_starts_with_items() { final Integer[] array = {1, 2, 3}; final Integer notStartsWith = 777; Verify.assertStartsWith(array, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_starts_with() { Verify.assertStartsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_starts_with() { Verify.assertStartsWith(new Integer[1]); } @Test public void pass_if_array_starts_with_items() { final Integer[] array = {1, 2}; final Integer firstItem = array[0]; Verify.assertStartsWith(array, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notStartsWith = 777; Verify.assertStartsWith(list, notStartsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_starts_with() { Verify.assertStartsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_starts_with() { Verify.assertStartsWith(Collections.emptyList()); } @Test public void pass_if_list_starts_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer firstItem = list.get(0); Verify.assertStartsWith(list, firstItem); } @Test(expected = AssertionError.class) public void fail_if_list_not_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer notEndsWith = 777; Verify.assertEndsWith(list, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_list_is_null_in_ends_with() { Verify.assertEndsWith((List) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_list_ends_with() { Verify.assertEndsWith(Collections.emptyList()); } @Test public void pass_if_list_ends_with_items() { final List<Integer> list = Arrays.asList(1, 2, 3); final Integer lastItem = list.get(list.size() - 1); Verify.assertEndsWith(list, lastItem); } @Test(expected = AssertionError.class) public void fail_if_array_not_ends_with_items() { final Integer[] array = {1, 2, 3}; final Integer notEndsWith = 777; Verify.assertEndsWith(array, notEndsWith); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_array_is_null_in_ends_with() { Verify.assertEndsWith((Integer[]) null, 1, 2, 3); } @Test(expected = AssertionError.class) public void fail_if_items_is_empty_in_array_ends_with() { Verify.assertEndsWith(new Integer[1]); } @Test public void pass_if_array_ends_with() { final Integer[] array = {1, 2, 3}; final Integer lastItem = array[array.length - 1]; Verify.assertEndsWith(array, lastItem); } @Test(expected = AssertionError.class) public void fail_if_objects_are_not_equal() { Verify.assertEqualsAndHashCode(1, 2); } @Test(expected = AssertionError.class) public void fail_if_objects_are_equal_but_hash_codes_are_not_equal() { final ClassThatViolateHashCodeAndCloneableContract objectA = new ClassThatViolateHashCodeAndCloneableContract(1); final ClassThatViolateHashCodeAndCloneableContract objectB = new ClassThatViolateHashCodeAndCloneableContract(1); Verify.assertEqualsAndHashCode(objectA, objectB); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_objects_are_null() { Verify.assertEqualsAndHashCode(null, null); } @Test public void pass_if_objects_and_their_hash_codes_are_equal() { Verify.assertEqualsAndHashCode(1, 1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_negative() { Verify.assertNegative(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_negative() { Verify.assertNegative(0); } @Test public void pass_if_value_is_negative() { Verify.assertNegative(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_not_positive() { Verify.assertPositive(-1); } @Test(expected = AssertionError.class) public void fail_if_value_is_zero_in_assert_positive() { Verify.assertPositive(0); } @Test public void pass_if_value_is_positive() { Verify.assertPositive(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_positive() { Verify.assertZero(1); } @Test(expected = AssertionError.class) public void fail_if_value_is_negative() { Verify.assertZero(-1); } @Test public void pass_if_value_is_zero() { Verify.assertZero(0); } @Test(expected = AssertionError.class) public void fail_if_clone_returns_same_object() { Verify.assertShallowClone(new ClassThatViolateHashCodeAndCloneableContract(1)); } @Test(expected = AssertionError.class) public void fail_if_clone_does_not_work_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableIncorrectly(1)); } @Test public void pass_if_cloneable_equals_and_hash_code_overridden_correctly() { Verify.assertShallowClone(new ClassThatImplementCloneableCorrectly(1)); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable() { Verify.assertClassNonInstantiable(Object.class); } @Test(expected = AssertionError.class) public void fail_if_class_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassWithPrivateCtor.class); } @Test public void pass_if_new_instance_throw_instantiable_exception() { Verify.assertClassNonInstantiable(void.class); } @Test public void pass_if_class_non_instantiable_through_reflection() { Verify.assertClassNonInstantiable(ClassThatThrowExceptionInConstructor.class); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_error() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertError(AssertionError.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(Error.class, throwsAssertionError); } @Test public void pass_if_runnable_throws_specified_error() { final Runnable throwsAssertionError = new Runnable() { @Override public void run() { throw new AssertionError(); } }; Verify.assertError(AssertionError.class, throwsAssertionError); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_callable_throws_specified_exception() { final Callable throwsEmptyStackException = new Callable() { @Override public Object call() throws Exception { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrows(Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(Exception.class, throwsEmptyStackException); } @Test public void pass_if_runnable_throws_specified_exception() { final Runnable throwsEmptyStackException = new Runnable() { @Override public void run() { throw new EmptyStackException(); } }; Verify.assertThrows(EmptyStackException.class, throwsEmptyStackException); } @Test(expected = AssertionError.class) public void fail_if_callable_not_throws_exception_with_cause() { final Callable notThrowsException = new Callable() { @Override public Object call() throws Exception { return null; } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_callable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_callable_expected_cause_is_null() { final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_callable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @Test(expected = AssertionError.class) public void fail_if_runnable_not_throws_exception_with_cause() { final Runnable notThrowsException = new Runnable() { @Override public void run() { } }; Verify.assertThrowsWithCause(Exception.class, Exception.class, notThrowsException); } @Test(expected = AssertionError.class) public void fail_if_runnable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); } @SuppressWarnings("ConstantConditions") @Test(expected = AssertionError.class) public void fail_if_runnable_expected_cause_is_null() { final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw new RuntimeException(new EmptyStackException()); } }; Verify.assertThrowsWithCause(EmptyStackException.class, null, throwsRuntimeException); } @Test public void pass_if_runnable_throws_specified_exception_with_specified_cause() { final Throwable cause = new EmptyStackException(); final RuntimeException runtimeException = new RuntimeException(cause); final Runnable throwsRuntimeException = new Runnable() { @Override public void run() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), cause.getClass(), throwsRuntimeException); } @SuppressWarnings("EqualsAndHashcode") private static class ClassThatViolateHashCodeAndCloneableContract implements Cloneable { private final int value; private ClassThatViolateHashCodeAndCloneableContract(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatViolateHashCodeAndCloneableContract that = (ClassThatViolateHashCodeAndCloneableContract) o; return value == that.value; } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override protected Object clone() throws CloneNotSupportedException { return this; } } private static class ClassThatImplementCloneableCorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableCorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableCorrectly that = (ClassThatImplementCloneableCorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } } private static final class ClassThatImplementCloneableIncorrectly implements Cloneable { private final int value; private ClassThatImplementCloneableIncorrectly(int value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassThatImplementCloneableIncorrectly that = (ClassThatImplementCloneableIncorrectly) o; return value == that.value; } @Override public int hashCode() { return value; } @Override protected Object clone() throws CloneNotSupportedException { return new ClassThatImplementCloneableIncorrectly(value + 1); } } private static class ClassWithPrivateCtor { @SuppressWarnings("RedundantNoArgConstructor") private ClassWithPrivateCtor() { } } private static class ClassThatThrowExceptionInConstructor { private ClassThatThrowExceptionInConstructor() { throw new AssertionError("This is non-instantiable class"); } } }
package to.etc.domui.component.misc; import to.etc.domui.component.buttons.*; import to.etc.domui.component.layout.*; import to.etc.domui.component.meta.*; import to.etc.domui.dom.css.*; import to.etc.domui.dom.html.*; import to.etc.domui.trouble.*; import to.etc.domui.util.*; import to.etc.domui.util.bugs.*; public class MsgBox extends Window { public interface IAnswer { void onAnswer(MsgBoxButton result) throws Exception; } public static enum Type { INFO, WARNING, ERROR, DIALOG } private Img m_theImage = new Img(); private String m_theText; private Div m_theButtons = new Div(); private static final int WIDTH = 500; private static final int HEIGHT = 210; Object m_selectedChoice; IAnswer m_onAnswer; MsgBoxButton m_closeButtonObject; /** * Custom dialog message text renderer. */ private INodeContentRenderer<String> m_dataRenderer; protected MsgBox() { super(true, false, WIDTH, HEIGHT, ""); setErrorFence(null); // Do not accept handling errors!! m_theButtons.setCssClass("ui-mbx-bb"); setOnClose(new IWindowClosed() { @Override public void closed(String closeReason) throws Exception { if(null != m_onAnswer) { m_selectedChoice = m_closeButtonObject; try { m_onAnswer.onAnswer(m_closeButtonObject); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer. Other exceptions do not close. close(); throw ex; } } } }); } static public MsgBox create(NodeBase parent) { MsgBox w = new MsgBox(); // Create instance // //vmijic 20100326 - in case of cascading floating windows, z-index higher than one from parent floating window must be set. // FloatingWindow parentFloatingWindow = parent.getParent(FloatingWindow.class); // if(parentFloatingWindow != null) { // w.setZIndex(parentFloatingWindow.getZIndex() + 100); UrlPage body = parent.getPage().getBody(); body.add(w); return w; } protected void setType(Type type) { String ttl; String icon; switch(type){ default: throw new IllegalStateException(type + " ??"); case ERROR: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_ERROR); icon = "mbx-error.png"; break; case WARNING: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_WARNING); icon = "mbx-warning.png"; break; case INFO: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_INFO); icon = "mbx-info.png"; break; case DIALOG: ttl = Msgs.BUNDLE.getString(Msgs.UI_MBX_DIALOG); icon = "mbx-question.png"; break; } m_theImage.setSrc("THEME/" + icon); setWindowTitle(ttl); setTestID("msgBox"); } protected void setMessage(String txt) { m_theText = txt; } private void setCloseButton(MsgBoxButton val) { m_closeButtonObject = val; } MsgBoxButton getCloseObject() { return m_closeButtonObject; } public static void message(NodeBase dad, Type mt, String string) { if(mt == Type.DIALOG) { throw new IllegalArgumentException("Please use one of the predefined button calls for MsgType.DIALOG type MsgBox!"); } MsgBox box = create(dad); box.setType(mt); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.construct(); } public static void info(NodeBase dad, String string) { message(dad, Type.INFO, string); } public static void warning(NodeBase dad, String string) { message(dad, Type.WARNING, string); } public static void error(NodeBase dad, String string) { message(dad, Type.ERROR, string); } public static void message(NodeBase dad, Type mt, String string, IAnswer onAnswer) { if(mt == Type.DIALOG) { throw new IllegalArgumentException("Please use one of the predefined button calls for MsgType.DIALOG type MsgBox!"); } MsgBox box = create(dad); box.setType(mt); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.setCloseButton(MsgBoxButton.CONTINUE); box.setOnAnswer(onAnswer); box.construct(); } public static void dialog(NodeBase dad, String title, IAnswer onAnswer, INodeContentRenderer<String> contentRenderer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setWindowTitle(title); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.setDataRenderer(contentRenderer); box.construct(); } public static void yesNoCancel(NodeBase dad, String string, IAnswer onAnswer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a yes/no confirmation, and pass either YES or NO to the onAnswer delegate. Use this if you need the NO action too, else use the IClicked variant. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, String string, IAnswer onAnswer) { yesNo(dad, string, onAnswer, null); } /** * Ask a yes/no confirmation, and pass either YES or NO to the onAnswer delegate. Use this if you need the NO action too, else use the IClicked variant. * @param dad * @param string * @param onAnswer * @param msgRenderer Provides custom rendering of specified string message. */ public static void yesNo(NodeBase dad, String string, IAnswer onAnswer, INodeContentRenderer<String> msgRenderer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.setCloseButton(MsgBoxButton.NO); box.setOnAnswer(onAnswer); box.setDataRenderer(msgRenderer); box.construct(); } /** * Ask a yes/no confirmation; call the onAnswer handler if YES is selected and do nothing otherwise. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, String string, final IClicked<MsgBox> onAnswer) { yesNo(dad, MsgBox.Type.DIALOG, string, onAnswer); } /** * Ask a yes/no confirmation; call the onAnswer handler if YES is selected and do nothing otherwise. * @param dad * @param string * @param onAnswer */ public static void yesNo(NodeBase dad, Type msgtype, String string, final IClicked<MsgBox> onAnswer) { final MsgBox box = create(dad); box.setType(msgtype); box.setMessage(string); box.addButton(MsgBoxButton.YES); box.addButton(MsgBoxButton.NO); box.setCloseButton(MsgBoxButton.NO); box.setOnAnswer(new IAnswer() { @Override public void onAnswer(MsgBoxButton result) throws Exception { if(result == MsgBoxButton.YES) onAnswer.clicked(box); } }); box.construct(); } /** * Show message of specified type, and provide details (More...) button. Usually used to show some error details if user wants to see it. * @param dad * @param type * @param string * @param onAnswer */ public static void okMore(NodeBase dad, Type type, String string, IAnswer onAnswer) { final MsgBox box = create(dad); box.setType(type); box.setMessage(string); box.addButton(MsgBoxButton.OK); box.addButton(MsgBoxButton.MORE); box.setCloseButton(MsgBoxButton.OK); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a continue/cancel confirmation. This passes either choice to the handler. * @param dad * @param string * @param onAnswer */ public static void continueCancel(NodeBase dad, String string, IAnswer onAnswer) { MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(onAnswer); box.construct(); } /** * Ask a continue/cancel confirmation, and call the IClicked handler for CONTINUE only. * @param dad * @param string * @param onAnswer */ public static void continueCancel(NodeBase dad, String string, final IClicked<MsgBox> onAnswer) { final MsgBox box = create(dad); box.setType(Type.DIALOG); box.setMessage(string); box.addButton(MsgBoxButton.CONTINUE); box.addButton(MsgBoxButton.CANCEL); box.setCloseButton(MsgBoxButton.CANCEL); box.setOnAnswer(new IAnswer() { @Override public void onAnswer(MsgBoxButton result) throws Exception { if(result == MsgBoxButton.CONTINUE) onAnswer.clicked(box); } }); box.construct(); } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * @param icon * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static DefaultButton areYouSureButton(String text, String icon, final String message, final IClicked<DefaultButton> ch) { final DefaultButton btn = new DefaultButton(text, icon); IClicked<DefaultButton> bch = new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { yesNo(b, message, new IClicked<MsgBox>() { @Override public void clicked(MsgBox bx) throws Exception { ch.clicked(btn); } }); } }; btn.setClicked(bch); return btn; } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static DefaultButton areYouSureButton(String text, final String message, final IClicked<DefaultButton> ch) { return areYouSureButton(text, null, message, ch); } /** * Create a LinkButton which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * @param icon * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static LinkButton areYouSureLinkButton(String text, String icon, final String message, final IClicked<LinkButton> ch) { final LinkButton btn = new LinkButton(text, icon); IClicked<LinkButton> bch = new IClicked<LinkButton>() { @Override public void clicked(LinkButton b) throws Exception { yesNo(b, message, new IClicked<MsgBox>() { @Override public void clicked(MsgBox bx) throws Exception { ch.clicked(btn); } }); } }; btn.setClicked(bch); return btn; } /** * Create a button which will show an "are you sure" yes/no dialog with a specified text. Only if the user * presses the "yes" button will the clicked handler be executed. * * @param text The button's text. * @param message The message to show in the are you sure popup * @param ch The delegate to call when the user is sure. * @return */ public static LinkButton areYouSureLinkButton(String text, final String message, final IClicked<LinkButton> ch) { return areYouSureLinkButton(text, null, message, ch); } // /** // * Adjust dimensions in addition to inherited floater behavior. // * @see to.etc.domui.dom.html.NodeBase#createContent() // */ // @Override // public void createContent() throws Exception { // super.createContent(); // setDimensions(WIDTH, HEIGHT); private void construct() { Div a = new Div(); add(a); a.setCssClass("ui-mbx-top"); a.setStretchHeight(true); a.setOverflow(Overflow.AUTO); Table t = new Table(); a.add(t); TBody b = t.getBody(); TR row = b.addRow(); row.setVerticalAlign(VerticalAlignType.TOP); TD td = row.addCell(); td.add(m_theImage); m_theImage.setPosition(PositionType.ABSOLUTE); td.setNowrap(true); td.setWidth("50px"); td = row.addCell("ui-mbx-mc"); if(getDataRenderer() != null) { try { getDataRenderer().renderNodeContent(this, td, m_theText, null); } catch(Exception ex) { Bug.bug(ex); } } else { DomUtil.renderHtmlString(td, m_theText); // 20091206 Allow simple markup in message } add(m_theButtons); //FIXME: vmijic 20090911 Set initial focus to first button. However preventing of keyboard input focus on window in background has to be resolved properly. setFocusOnButton(); } private void setFocusOnButton() { if(m_theButtons.getChildCount() > 0 && m_theButtons.getChild(0) instanceof Button) { ((Button) m_theButtons.getChild(0)).setFocus(); } } @Override public void setDimensions(int width, int height) { super.setDimensions(width, height); setTop("50%"); // center floating window horizontally on screen setMarginLeft("-" + width / 2 + "px"); setMarginTop("-" + height / 2 + "px"); } void setSelectedChoice(Object selectedChoice) { m_selectedChoice = selectedChoice; } protected void answer(Object sel) throws Exception { m_selectedChoice = sel; if(m_onAnswer != null) { try { m_onAnswer.onAnswer((MsgBoxButton) m_selectedChoice); } catch(ValidationException ex) { //close message box in case of validation exception is thrown as result of answer close(); throw ex; } } close(); } /** * Add a default kind of button. * @param mbb */ protected void addButton(final MsgBoxButton mbb) { if(mbb == null) throw new NullPointerException("A message button cannot be null, dufus"); String lbl = MetaManager.findEnumLabel(mbb); if(lbl == null) lbl = mbb.name(); DefaultButton btn = new DefaultButton(lbl, new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { answer(mbb); } }); btn.setTestID(mbb.name()); m_theButtons.add(btn); } protected void addButton(final String lbl, final Object selval) { m_theButtons.add(new DefaultButton(lbl, new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton b) throws Exception { answer(selval); } })); } protected IAnswer getOnAnswer() { return m_onAnswer; } protected void setOnAnswer(IAnswer onAnswer) { m_onAnswer = onAnswer; } protected INodeContentRenderer<String> getDataRenderer() { return m_dataRenderer; } protected void setDataRenderer(INodeContentRenderer<String> dataRenderer) { m_dataRenderer = dataRenderer; } }
package to.etc.domui.themes; import java.io.*; import java.util.*; import javax.resource.spi.IllegalStateException; import javax.script.*; import to.etc.domui.util.resources.*; import to.etc.util.*; public class CssPropertySet { final private CssFragmentCollector m_collector; /** The root name of the map containing the styles. This must be a real slashed "directory" name that can be looked up in resources and WebContent files. */ final private String m_dirname; final private String m_name; final private String m_fragmentSuffix; /** When style a EXTENDS style B etc, this starts with the base class (b) and ends with the topmost one (A). */ private List<String> m_inheritanceStack = new ArrayList<String>(); private ResourceDependencyList m_rdl = new ResourceDependencyList(); private Map<String, Object> m_propertyMap; private ScriptEngine m_engine; private Bindings m_rootBindings; private Bindings m_bindings; CssPropertySet(CssFragmentCollector fc, String dirname, String name, String fragments) { m_collector = fc; m_dirname = dirname; m_name = name; m_fragmentSuffix = fragments; } private ScriptEngine getEngine() throws Exception { if(m_engine == null) { m_engine = m_collector.getEngineManager().getEngineByName("js"); m_rootBindings = m_engine.getBindings(ScriptContext.GLOBAL_SCOPE); m_rootBindings.put("collector", this); m_bindings = m_engine.createBindings(); m_engine.eval("function inherit(s) { collector.internalInherit(s); }", m_rootBindings); // m_bindings.put("browser", DomUITestUtil.getBrowserVersionIE8()); } return m_engine; } /** * Load a property set including it's base sets in proper inheritance order. * * Load the properties for the current style *and it's base styles*. After this, the style sheet * property files have executed in the proper order, and the context contains the proper properties. */ void loadStyleProperties(String dirname) throws Exception { if(m_propertyMap != null) throw new IllegalStateException("Already loaded!"); try { loadProperties(dirname, m_name); // Start loading all files-by-name if(m_fragmentSuffix != null) loadFragments(); //-- Ok: the binding now contains stuff to add/replace to the map m_propertyMap = new HashMap<String, Object>(); for(Map.Entry<String, Object> e : m_bindings.entrySet()) { String name = e.getKey(); if("context".equals(name)) continue; Object v = e.getValue(); if(v != null) { String cn = v.getClass().getName(); if(cn.startsWith("sun.")) continue; } // System.out.println("prop: " + name + " = " + v); m_propertyMap.put(name, v); } } finally { cleanup(); } } /** * Walks the inheritance stack, and loads all fragments present there as properties too. * @throws Exception */ private void loadFragments() throws Exception { long ts = System.nanoTime(); //-- Find all possible files/resources, then sort them by their name. List<String> reslist = m_collector.collectFragments(m_inheritanceStack, m_fragmentSuffix); //-- Load every one of them as a javascript file. int count = 0; for(String name : reslist) { String full = "$" + name; loadScript(full); count++; } ts = System.nanoTime() - ts; System.out.println("css: loading " + m_dirname + "+: loaded " + count + " fragments took " + StringTool.strNanoTime(ts)); } private void cleanup() { m_engine = null; m_bindings = null; m_rootBindings = null; } /** * Load a specific theme's style properties. Core part of inherit('') command. * @param dirname * @throws Exception */ private void loadProperties(String dirname, String filename) throws Exception { if(dirname.startsWith("/")) dirname = dirname.substring(1); if(dirname.endsWith("/")) dirname = dirname.substring(0, dirname.length() - 1); if(dirname.startsWith("$")) dirname = dirname.substring(1); //-- If already loaded- abort; if(m_inheritanceStack.contains(dirname)) throw new StyleException(m_name + ": inherited style '" + dirname + "' is used before (cyclic loop in styles, or double inheritance)"); m_inheritanceStack.add(0, dirname); // Insert BEFORE the others (this is a base class for 'm) //-- Load the .props.js file which must exist as either resource or webfile. String pname = "$" + dirname + "/" + filename; loadScript(pname); } /** * Load the specified resource as a Javascript thingy. * @param pname * @throws Exception */ private void loadScript(String pname) throws Exception { IResourceRef ires = m_collector.findRef(m_rdl, pname); if(null == ires) throw new StyleException("The " + pname + " file is not found."); InputStream is = ires.getInputStream(); if(null == is) throw new StyleException("The " + pname + " file is not found."); System.out.println("css: loading " + pname + " as " + ires); try { //-- Execute Javascript; Reader r = new InputStreamReader(is, "utf-8"); getEngine().getBindings(ScriptContext.ENGINE_SCOPE).put(ScriptEngine.FILENAME, pname); getEngine().getBindings(ScriptContext.GLOBAL_SCOPE).put(ScriptEngine.FILENAME, pname); m_bindings.put(ScriptEngine.FILENAME, pname); getEngine().eval(r, m_bindings); } finally { try { is.close(); } catch(Exception x) {} } } public Map<String, Object> getMap() { return m_propertyMap; } public List<String> getInheritanceStack() { return m_inheritanceStack; } public ResourceDependencyList getResourceDependencyList() { return m_rdl; } /* CODING: Javascript-callable global functions. */ /** * Implements the root-level "inherit" command. * @param scheme * @throws Exception */ public void internalInherit(String scheme) throws Exception { loadProperties(scheme, m_name); } }
package uk.ac.ox.oucs.vle; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.ext.ContextResolver; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.codehaus.jackson.map.annotate.JsonSerialize; import org.codehaus.jackson.map.type.TypeFactory; import org.sakaiproject.user.cover.UserDirectoryService; import com.sun.jersey.api.view.Viewable; import uk.ac.ox.oucs.vle.CourseSignupService.Status; @Path("/signup") public class SignupResource { private CourseSignupService courseService; private ObjectMapper objectMapper; public SignupResource(@Context ContextResolver<Object> resolver) { this.courseService = (CourseSignupService) resolver.getContext(CourseSignupService.class); objectMapper = new ObjectMapper(); objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); objectMapper.configure(SerializationConfig.Feature.USE_STATIC_TYPING, true); objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); } @Path("/my") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getMySignups() { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } final List<CourseSignup> signups = courseService.getMySignups(null); return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/my/course/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getMyCourseSignups(@PathParam("id") String courseId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } final List<CourseSignup> signups = courseService.getMySignups(null); final List<CourseSignup> courseSignups = new ArrayList<CourseSignup>(); for(CourseSignup signup: signups) { if (courseId.equals(signup.getGroup().getId())) { courseSignups.add(signup); } } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, courseSignups); } }; } @Path("/my/new") @POST public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } //String user = courseService.findSupervisor(email); courseService.signup(courseId, components, email, message); return Response.ok().build(); } @Path("/new") @POST public Response signup(@FormParam("userId")String userId, @FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("supervisorId")String supervisorId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.signup(userId, courseId, components, supervisorId); return Response.ok().build(); } @Path("/supervisor") @POST public Response signup(@FormParam("signupId")String signupId, @FormParam("supervisorId")String supervisorId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.setSupervisor(signupId, supervisorId); return Response.ok().build(); } @Path("/{id}") @GET @Produces("application/json") public Response getSignup(@PathParam("id") final String signupId) throws JsonGenerationException, JsonMappingException, IOException { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } CourseSignup signup = courseService.getCourseSignup(signupId); if (signup == null) { return Response.status(javax.ws.rs.core.Response.Status.NOT_FOUND).build(); } return Response.ok(objectMapper.writeValueAsString(signup)).build(); } @Path("/{id}") @POST // PUT Doesn't seem to make it through the portal :-( public void updateSignup(@PathParam("id") final String signupId, @FormParam("status") final Status status){ if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.setSignupStatus(signupId, status); } @Path("{id}/accept") @POST public Response accept(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.accept(signupId); return Response.ok().build(); } @Path("{id}/reject") @POST public Response reject(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.reject(signupId); return Response.ok().build(); } @Path("{id}/withdraw") @POST public Response withdraw(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.withdraw(signupId); return Response.ok().build(); } @Path("{id}/waiting") @POST public Response waiting(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.waiting(signupId); return Response.ok().build(); } @Path("{id}/approve") @POST public Response approve(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.approve(signupId); return Response.ok().build(); } @Path("{id}/confirm") @POST public Response confirm(@PathParam("id") final String signupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } courseService.confirm(signupId); return Response.ok().build(); } @Path("/course/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getCourseSignups(@PathParam("id") final String courseId, @QueryParam("status") final Status status) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } // All the pending return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { Set<Status> statuses = null; if (null != status) { statuses = Collections.singleton(status); } List<CourseSignup> signups = courseService.getCourseSignups(courseId, statuses); objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/count/course/signups/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public Response getCountCourseSignup(@PathParam("id") final String courseId, @QueryParam("status") final Status status) throws JsonGenerationException, JsonMappingException, IOException { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } // All the pending Set<Status> statuses = null; if (null != status) { statuses = Collections.singleton(status); } Integer signups = courseService.getCountCourseSignups(courseId, statuses); return Response.ok(objectMapper.writeValueAsString(signups)).build(); } @Path("/component/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getComponentSignups(@PathParam("id") final String componentId, @QueryParam("status") final Status status) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { Set<Status> statuses = null; if (null != status) { statuses = Collections.singleton(status); } List<CourseSignup> signups = courseService.getComponentSignups(componentId, statuses); objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/component/{id}.csv") @GET @Produces("text/comma-separated-values") public StreamingOutput getComponentSignupsCSV(@PathParam("id") final String componentId, @Context final HttpServletResponse response) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { List<CourseSignup> signups = courseService.getComponentSignups(componentId, null); response.addHeader("Content-disposition", "attachment; filename="+componentId+".csv"); // Force a download Writer writer = new OutputStreamWriter(output); CSVWriter csvWriter = new CSVWriter(writer); for(CourseSignup signup : signups) { Person user = signup.getUser(); csvWriter.writeln(new String[]{user.getName(), user.getEmail(), signup.getStatus().toString()}); } writer.flush(); } }; } @Path("/component/{id}.pdf") @GET @Produces("application/pdf") public StreamingOutput getComponentSignupsPDF(@PathParam("id") final String componentId, @Context final HttpServletResponse response) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { System.out.println("/rest/signup/component/"+componentId+"/pdf"); CourseComponent courseComponent = courseService.getCourseComponent(componentId); Collection<CourseGroup> courseGroups = courseService.getCourseGroupsByComponent(componentId); List<CourseSignup> signups = courseService.getComponentSignups( componentId, Collections.singleton(Status.CONFIRMED)); response.addHeader("Content-disposition", "attachment; filename="+componentId+".pdf"); // Force a download PDFWriter pdfWriter = new PDFWriter(output); pdfWriter.writeHead(courseGroups, courseComponent); pdfWriter.writeTableHead(); if (!signups.isEmpty()) { List<Person> persons = new ArrayList<Person>(); for (CourseSignup signup : signups) { persons.add(signup.getUser()); } Collections.sort(persons, new Comparator<Person>() { public int compare(Person p1,Person p2) { return p1.getLastName().compareTo(p2.getLastName()); } }); pdfWriter.writeTableBody(persons); } pdfWriter.writeTableFoot(); pdfWriter.close(); } }; } @Path("/component/{id}.xml") @GET @Produces(MediaType.TEXT_XML) public StreamingOutput syncComponent(@PathParam("id") final String componentId, @PathParam("status") final Status status) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { CourseComponent courseComponent = courseService.getCourseComponent(componentId); Set<Status> statuses = new HashSet<Status>(); if (null != status) { statuses = Collections.singleton(status); } else { statuses.add(Status.CONFIRMED); statuses.add(Status.WITHDRAWN); } try { List<CourseSignup> signups = courseService.getComponentSignups( componentId, statuses); Collections.sort(signups, new Comparator<CourseSignup>() { public int compare(CourseSignup s1,CourseSignup s2) { Person p1 = s1.getUser(); Person p2 = s2.getUser(); return p1.getLastName().compareTo(p2.getLastName()); } }); AttendanceWriter attendance = new AttendanceWriter(output); attendance.writeTeachingInstance(courseComponent, signups); attendance.close(); } catch (NotFoundException e) { throw new WebApplicationException(Response.Status.NOT_FOUND); } } }; } @Path("/attendance") @GET @Produces(MediaType.TEXT_XML) public StreamingOutput sync() { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { AttendanceWriter attendance = new AttendanceWriter(output); Collection<CourseComponent> courseComponents = courseService.getAllComponents(); for (CourseComponent courseComponent : courseComponents) { List<CourseSignup> signups = courseService.getComponentSignups( courseComponent.getId(), Collections.singleton(Status.CONFIRMED)); attendance.writeTeachingInstance(courseComponent, signups); } attendance.close(); } }; } @Path("/pending") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getPendingSignups() { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { List<CourseSignup> signups = courseService.getPendings(); objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/approve") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getApproveSignups() { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { List<CourseSignup> signups = courseService.getApprovals(); objectMapper.typedWriter(TypeFactory.collectionType(List.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/previous") @GET @Produces(MediaType.APPLICATION_JSON) public StreamingOutput getPreviousSignups(@QueryParam("userid") final String userId, @QueryParam("componentid") final String componentId, @QueryParam("groupid") final String groupId) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException { List<String> componentIds = Arrays.asList(componentId.split(",")); Set<CourseSignup> signups = new HashSet<CourseSignup>(); for (CourseSignup signup : courseService.getUserComponentSignups(userId, null)) { if (signup.getGroup().getId().equals(groupId)) { for (CourseComponent component : signup.getComponents()) { if (!componentIds.contains(component.getId())) { signups.add(signup); } } } } objectMapper.typedWriter(TypeFactory.collectionType(Set.class, CourseSignup.class)).writeValue(output, signups); } }; } @Path("/advance/{id}") @GET @Produces("text/html") public Response advanceGet(@PathParam("id") final String encoded) { String[] params = courseService.getCourseSignupFromEncrypted(encoded); for (int i=0; i<params.length; i++) { System.out.println("decoded parameter ["+params[i]+"]"); } CourseSignup signup = courseService.getCourseSignupAnyway(params[0]); Map<String, Object> model = new HashMap<String, Object>(); model.put("signup", signup); model.put("encoded", encoded); model.put("status", params[1]); return Response.ok(new Viewable("/static/advance", model)).build(); } @Path("/advance/{id}") @POST @Produces("text/html") public Response advancePost(@PathParam("id") final String encoded, @FormParam("formStatus") final String formStatus) { if (null == encoded) { return Response.noContent().build(); } String[] params = courseService.getCourseSignupFromEncrypted(encoded); for (int i=0; i<params.length; i++) { System.out.println("decoded parameter ["+params[i]+"]"); } String signupId = params[0]; //String status = params[1]; String placementId = params[2]; CourseSignup signup = courseService.getCourseSignupAnyway(signupId); if (null == signup) { return Response.noContent().build(); } switch (getIndex(new String[]{"accept", "approve", "confirm", "reject"}, formStatus.toLowerCase())) { case 0: courseService.accept(signupId, true, placementId); break; case 1: courseService.approve(signupId, true, placementId); break; case 2: courseService.confirm(signupId, true, placementId); break; case 3: courseService.reject(signupId, true, placementId); break; default: return Response.noContent().build(); } Map<String, Object> model = new HashMap<String, Object>(); model.put("signup", signup); return Response.ok(new Viewable("/static/ok", model)).build(); } protected int getIndex(String[] array, String value){ for(int i=0; i<array.length; i++){ if(array[i].equals(value)){ return i; } } return -1; } }
package se.sics.cooja.interfaces; import java.util.Collection; import java.util.Observable; import java.util.Observer; import javax.swing.JLabel; import javax.swing.JPanel; import org.apache.log4j.Logger; import org.jdom.Element; import se.sics.cooja.AddressMemory; import se.sics.cooja.ClassDescription; import se.sics.cooja.Mote; import se.sics.cooja.MoteInterface; import se.sics.cooja.MoteTimeEvent; import se.sics.cooja.Simulation; import se.sics.cooja.TimeEvent; /** * Read-only interface to IPv4 or IPv6 address. * * @author Fredrik Osterlind */ @ClassDescription("IP Address") public class IPAddress extends MoteInterface { private static Logger logger = Logger.getLogger(IPAddress.class); private AddressMemory moteMem; private static final int IPv6_MAX_ADDRESSES = 4; private int ipv6NetworkInterfaceAddressOffset; private int ipv6AddressStructSize; private boolean ipv6IsGlobal = false; private int ipv6AddressIndex = -1; public IPAddress(final Mote mote) { moteMem = (AddressMemory) mote.getMemory(); /* ipV6: Struct sizes and offsets */ int intLength = moteMem.getIntegerLength(); int longLength = 4; ipv6NetworkInterfaceAddressOffset /* net/uip-ds6.h:uip_ds6_netif_t */ = 4 /* link_mtu */ + align(1, intLength) /* cur_hop_limit */ + 4 /* base_reachable_time */ + 4 /* reachable_time */ + 4 /* retrans_timer */ + align(1, intLength) /* maxdadns */; ipv6AddressStructSize /* net/uip-ds6.h:uip_ds6_addr_t */ = align(1, 2) /* isused */ + 16 /* ipaddr, aligned on 16 bits */ + align(3, intLength) /* state + type + isinfinite */ + 2*longLength /* vlifetime */ + 2*longLength /* dadtimer */ + align(1, intLength) /* dadnscount */; ipv6AddressStructSize = align(ipv6AddressStructSize, intLength); /* Detect startup IP (only zeroes) */ TimeEvent updateWhenAddressReady = new MoteTimeEvent(mote, 0) { public void execute(long t) { if (!isVersion4() && !isVersion6()) { return; } String ipString = getIPString(); ipString = ipString.replace(".", ""); ipString = ipString.replace(":", ""); ipString = ipString.replace("0", ""); if (!ipString.isEmpty()) { setChanged(); notifyObservers(); return; } /* Postpone until IP has been set */ mote.getSimulation().scheduleEvent( this, mote.getSimulation().getSimulationTime() + Simulation.MILLISECOND); return; } }; updateWhenAddressReady.execute(0); } /** * Returns IP address string. * Supports both IPv4 and IPv6 addresses. * * @return IP address string */ public String getIPString() { if (isVersion4()) { String ipString = ""; byte[] ip = moteMem.getByteArray("uip_hostaddr", 4); for (int i=0; i < 3; i++) { ipString += (0xFF & ip[i]) + "."; } ipString += (0xFF & ip[3]); return ipString; } else if (isVersion6()) { String ipString = getUncompressedIPv6Address(); if (ipString != null) { ipString = compressIPv6Address(ipString); } return ipString; } return null; } public String compressIPv6Address(String ipString) { while (ipString.contains(":0000:")) { ipString = ipString.replaceAll(":0000:", "::"); } while (ipString.contains("0000")) { ipString = ipString.replaceAll("0000", "0"); } while (ipString.contains(":::")) { ipString = ipString.replaceAll(":::", "::"); } while (ipString.contains(":0")) { ipString = ipString.replaceAll(":0", ":"); } if (ipString.endsWith(":")) { ipString = ipString + "0"; } return ipString; } public String getUncompressedIPv6Address() { byte[] ip = null; /* TODO No need to copy the entire array! */ byte[] structData = moteMem.getByteArray("uip_ds6_if", ipv6NetworkInterfaceAddressOffset+IPv6_MAX_ADDRESSES*ipv6AddressStructSize); ipv6AddressIndex = -1; for (int addressIndex=0; addressIndex < IPv6_MAX_ADDRESSES; addressIndex++) { int offset = ipv6NetworkInterfaceAddressOffset+addressIndex*ipv6AddressStructSize; byte isUsed = structData[offset]; if (isUsed == 0) { continue; } byte[] addressData = new byte[16]; System.arraycopy( structData, offset+2/* ipaddr offset */, addressData, 0, 16); if (addressData[0] == (byte)0xFE && addressData[1] == (byte)0x80) { ipv6IsGlobal = false; } else { ipv6IsGlobal = true; } ip = addressData; ipv6AddressIndex = addressIndex; if (ipv6IsGlobal) { break; } } if (ip == null) { ip = new byte[16]; ipv6AddressIndex = -1; } String ipString = ""; int i=0; while (i < 14) { int val = (0xFF&ip[i+1]) + ((0xFF&ip[i])<<8); ipString += hex16ToString(val) + ":"; i+=2; } int val = (0xFF&ip[15]) + ((0xFF&ip[14])<<8); ipString += hex16ToString(val); return ipString; } /** * @return True if mote has an IPv4 address */ public boolean isVersion4() { return moteMem.variableExists("uip_hostaddr"); } /** * @return True if mote has an IPv6 address */ public boolean isVersion6() { return moteMem.variableExists("uip_ds6_if"); } public JPanel getInterfaceVisualizer() { JPanel panel = new JPanel(); final JLabel ipLabel = new JLabel(); Observer observer; this.addObserver(observer = new Observer() { public void update(Observable obs, Object obj) { if (isVersion4()) { ipLabel.setText("IPv4 address: " + getIPString()); } else if (isVersion6()) { ipLabel.setText((ipv6IsGlobal?"Global":"Local") + " IPv6 address(" + ipv6AddressIndex + "): " + getIPString()); } else { ipLabel.setText("Unknown IP"); } } }); observer.update(null, null); panel.add(ipLabel); panel.putClientProperty("intf_obs", observer); return panel; } public void releaseInterfaceVisualizer(JPanel panel) { Observer observer = (Observer) panel.getClientProperty("intf_obs"); if (observer == null) { logger.fatal("Error when releasing panel, observer is null"); return; } this.deleteObserver(observer); } public Collection<Element> getConfigXML() { return null; } public void setConfigXML(Collection<Element> configXML, boolean visAvailable) { } private static String hex16ToString(int data) { String s = Integer.toString(data & 0xffff, 16); if (s.length() < 4) { s = "0000".substring(0, 4 - s.length()) + s; } return s; } private static int align(int bytes, int alignment) { int size = (bytes/alignment)*alignment; while (size < bytes) { size += alignment; } return size; } }
//AUTEUR : CLAIRE DELORME //DESCRIPTION: //INFO : package model; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Pion { private String couleur; private int idPion; private Coord coord; private Map<Coord,Set<Coord>> modele = new HashMap<Coord,Set<Coord>>(); //FIXME comment se le faire donner par Jeu private static final boolean DEBUG = false; // Initialisation d'un pion public Pion(String couleur, int idPion, Coord coord) { this.couleur = couleur; this.idPion = idPion; this.coord = coord; } public boolean seDeplacer(int x, int y, De de) { // Fait se dplacer le pion if (isMoveOk(x,y,de)==true){ coord.x = x; coord.y = y; return true; } return false; } public boolean isMoveOk(int xFinal, int yFinal, De de) { Map<Coord,Set<Coord>> casesNonParcourues = new HashMap<>(modele); //toutes les cases du jeu non parcourues Set<Coord> coordoneesALEtapeActuelle = new HashSet<>(); if (true) System.out.println( String.format("Vérification du déplacement de %s cases en partant de %s", de.getNbAleatoire(), this.coord ) ); if (DEBUG) System.out.println("En utilisant la map suivante: " + modele); coordoneesALEtapeActuelle.add(this.coord); int etape=0; for (etape=0; etape<de.getNbAleatoire();etape++){ if (DEBUG) System.out.println("Etape N°" + etape); Set<Coord> etapesSuivante = new HashSet<Coord>(); for (Coord coordonneeDEtape : coordoneesALEtapeActuelle) { Set<Coord> casesVoisines = modele.get(coordonneeDEtape); if (DEBUG) System.out.println("Récupération des cases voisines de " + coordonneeDEtape + " => " + casesVoisines); for (Coord voisine : casesVoisines) { if (DEBUG) System.out.print("- la case voisine " + voisine + " "); if (casesNonParcourues.containsKey(voisine)) { if (DEBUG) System.out.print("n'a PAS"); etapesSuivante.add(voisine); } else { if (DEBUG) System.out.print("a"); } if (DEBUG) System.out.println(" déja été parcourue."); } if (DEBUG) System.out.println("Etapes suivantes possibles => " + etapesSuivante); casesNonParcourues.remove(coordonneeDEtape); } coordoneesALEtapeActuelle = etapesSuivante; } boolean ret = coordoneesALEtapeActuelle.contains(new Coord(xFinal, yFinal)); System.out.println("Destinations possibles:" + coordoneesALEtapeActuelle); System.out.println("Return:" + ret); return ret; } // Getters et Setters public String getCouleur() { return couleur; } public void setCouleur(String couleur) { this.couleur = couleur; } public int getIdPion() { return idPion; } public void setIdPion(int idPion) { this.idPion = idPion; } public int getX() { return coord.x; } public int getY() { return coord.y; } public void setX(int x) { this.coord.x = x; } public void setY(int y) { this.coord.y = y; } public Map<Coord, Set<Coord>> getModele() { return modele; } public void setModele(Map<Coord, Set<Coord>> modele) { this.modele = modele; System.out.println("Modele set to " + this.modele); } @Override public String toString() { return "Pion : couleur=" + couleur + ", idPion=" + idPion + ", coord=" + coord; } }
package jade.imtp.rmi; import java.net.InetAddress; import java.net.UnknownHostException; import java.rmi.*; import java.rmi.registry.*; import java.util.Iterator; import jade.util.leap.List; import jade.util.leap.ArrayList; import java.util.Map; import java.util.HashMap; import jade.core.*; import jade.lang.acl.ACLMessage; import jade.mtp.TransportAddress; /** * @author Giovanni Caire - Telecom Italia Lab */ public class RMIIMTPManager implements IMTPManager { private static class RemoteProxyRMI implements AgentProxy { private AgentContainerRMI ref; private AID receiver; // This needs to be restored whenever a RemoteProxyRMI object is // serialized. private transient RMIIMTPManager manager; public RemoteProxyRMI(AgentContainerRMI ac, AID recv) { ref = ac; receiver = recv; } public AID getReceiver() { return receiver; } public AgentContainer getRef() { return manager.getAdapter(ref); } public void dispatch(ACLMessage msg) throws NotFoundException, UnreachableException { try { ref.dispatch(msg, receiver); } catch (RemoteException re) { throw new UnreachableException("IMTP failure: [" + re.getMessage() + "]"); } catch (IMTPException imtpe) { throw new UnreachableException("IMTP failure: [" + imtpe.getMessage() + "]"); } } public void ping() throws UnreachableException { try { ref.ping(false); } catch (RemoteException re) { throw new UnreachableException("Unreachable remote object: [" + re.getMessage() + "]"); } catch (IMTPException imtpe) { throw new UnreachableException("Unreachable remote object: [" + imtpe.getMessage() + "]"); } } public void setMgr(RMIIMTPManager mgr) { manager = mgr; } } // End of RemoteProxyRMI class private static final int DEFAULT_RMI_PORT = 1099; private Profile myProfile; private String mainHost; private int mainPort; private String platformRMI; private MainContainer remoteMC; // Maps agent containers into their stubs private Map stubs; public RMIIMTPManager() { stubs = new HashMap(); } public void initialize(Profile p) throws IMTPException { try { myProfile = p; mainHost = myProfile.getParameter(Profile.MAIN_HOST); if (mainHost == null) { // Use the local host by default try { mainHost= InetAddress.getLocalHost().getHostName(); } catch(UnknownHostException uhe) { throw new IMTPException("Unknown main host"); } } mainPort = DEFAULT_RMI_PORT; String mainPortStr = myProfile.getParameter(Profile.MAIN_PORT); if (mainPortStr != null) { try { mainPort = Integer.parseInt(mainPortStr); } catch (NumberFormatException nfe) { // Do nothing. The DEFAULT_RMI_PORT is used } } platformRMI = "rmi://" + mainHost + ":" + mainPort + "/JADE"; } catch (ProfileException pe) { throw new IMTPException("Can't get main host and port", pe); } } public void remotize(AgentContainer ac) throws IMTPException { try { AgentContainerRMI acRMI = new AgentContainerRMIImpl(ac, this); stubs.put(ac, acRMI); } catch(RemoteException re) { throw new IMTPException("Failed to create the RMI container", re); } } /** * Get the RMIRegistry. If a registry is already active on this host * and the given portNumber, then that registry is returned, * otherwise a new registry is created and returned. * @param portNumber is the port on which the registry accepts requests * @param host host for the remote registry, if null the local host is used * @author David Bell (HP Palo Alto) **/ private Registry getRmiRegistry(String host, int portNumber) throws RemoteException { Registry rmiRegistry = null; // See if a registry already exists and // make sure we can really talk to it. try { rmiRegistry = LocateRegistry.getRegistry(host, portNumber); rmiRegistry.list(); } catch (Exception exc) { rmiRegistry = null; } // If rmiRegistry is null, then we failed to find an already running // instance of the registry, so let's create one. if (rmiRegistry == null) { //if (isLocalHost(host)) rmiRegistry = LocateRegistry.createRegistry(portNumber); //else //throw new java.net.UnknownHostException("cannot create RMI registry on a remote host"); } return rmiRegistry; } // END getRmiRegitstry() public void remotize(MainContainer mc) throws IMTPException { try { MainContainerRMI mcRMI = new MainContainerRMIImpl(mc, this); Registry theRegistry = getRmiRegistry(null,mainPort); Naming.bind(platformRMI, mcRMI); } catch(ConnectException ce) { // This one is thrown when trying to bind in an RMIRegistry that // is not on the current host System.out.println("ERROR: trying to bind to a remote RMI registry."); System.out.println("If you want to start a JADE main container:"); System.out.println(" Make sure the specified host name or IP address belongs to the local machine."); System.out.println(" Please use '-host' and/or '-port' options to setup JADE host and port."); System.out.println("If you want to start a JADE non-main container: "); System.out.println(" Use the '-container' option, then use '-host' and '-port' to specify the "); System.out.println(" location of the main container you want to connect to."); throw new IMTPException("RMI Binding error", ce); } catch(RemoteException re) { throw new IMTPException("Communication failure while starting JADE Runtime System. Check if the RMIRegistry CLASSPATH includes the RMI Stub classes of JADE.", re); } catch(Exception e) { throw new IMTPException("Problem starting JADE Runtime System.", e); } } /** Disconnects the given Agent Container and hides it from remote JVMs. */ public void unremotize(AgentContainer ac) throws IMTPException { try { AgentContainerRMIImpl impl = (AgentContainerRMIImpl)getRMIStub(ac); if(impl == null) throw new IMTPException("No RMI object for this agent container"); impl.unexportObject(impl, true); } catch(RemoteException re) { throw new IMTPException("RMI error during shutdown", re); } catch(ClassCastException cce) { throw new IMTPException("The RMI implementation is not locally available", cce); } } /** Disconnects the given Main Container and hides it from remote JVMs. */ public void unremotize(MainContainer mc) throws IMTPException { // Unbind the main container from RMI Registry // Unexport the RMI object } public AgentProxy createAgentProxy(AgentContainer ac, AID id) throws IMTPException { AgentContainerRMI acRMI = getRMIStub(ac); RemoteProxyRMI rp = new RemoteProxyRMI(acRMI, id); rp.setMgr(this); return rp; } public synchronized MainContainer getMain(boolean reconnect) throws IMTPException { // Look the remote Main Container up into the // RMI Registry. try { if(remoteMC == null || reconnect) { MainContainerRMI remoteMCRMI = (MainContainerRMI)Naming.lookup(platformRMI); remoteMC = new MainContainerAdapter(remoteMCRMI, this); } return remoteMC; } catch (Exception e) { throw new IMTPException("Exception in RMI Registry lookup", e); } } public void shutDown() { } public List getLocalAddresses() throws IMTPException { try { List l = new ArrayList(); // The port is meaningful only on the Main container TransportAddress addr = new RMIAddress(InetAddress.getLocalHost().getHostName(), String.valueOf(mainPort), null, null); l.add(addr); return l; } catch (Exception e) { throw new IMTPException("Exception in reading local addresses", e); } } AgentContainerRMI getRMIStub(AgentContainer ac) { return (AgentContainerRMI)stubs.get(ac); } AgentContainer getAdapter(AgentContainerRMI acRMI) { Iterator it = stubs.entrySet().iterator(); while(it.hasNext()) { Map.Entry e = (Map.Entry)it.next(); if(acRMI.equals(e.getValue())) return (AgentContainer)e.getKey(); } AgentContainer ac = new AgentContainerAdapter(acRMI, this); stubs.put(ac, acRMI); return ac; } void adopt(AgentProxy ap) throws IMTPException { try { RemoteProxyRMI rpRMI = (RemoteProxyRMI)ap; rpRMI.setMgr(this); } catch(ClassCastException cce) { throw new IMTPException("Cannot adopt this Remote Proxy", cce); } } }
package eu.mihosoft.vrl.v3d; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import eu.mihosoft.vrl.v3d.ext.quickhull3d.HullUtil; public class CSG { private List<Polygon> polygons; private static OptType defaultOptType = OptType.POLYGON_BOUND; private OptType optType = null; private CSG() {} /** * Constructs a CSG from a list of {@link Polygon} instances. * * @param polygons * polygons * @return a CSG instance */ public static CSG fromPolygons(List<Polygon> polygons) { CSG csg = new CSG(); csg.polygons = polygons; return csg; } /** * Constructs a CSG from the specified {@link Polygon} instances. * * @param polygons * polygons * @return a CSG instance */ public static CSG fromPolygons(Polygon... polygons) { return fromPolygons(Arrays.asList(polygons)); } @Override public CSG clone() { CSG csg = new CSG(); csg.setOptType(this.getOptType()); // sequential code // csg.polygons = new ArrayList<>(); // polygons.forEach((polygon) -> { // csg.polygons.add(polygon.clone()); Stream<Polygon> polygonStream; if (polygons.size() > 200) { polygonStream = polygons.parallelStream(); } else { polygonStream = polygons.stream(); } csg.polygons = polygonStream.map((Polygon p) -> p.clone()).collect(Collectors.toList()); return csg; } /** * * @return the polygons of this CSG */ public List<Polygon> getPolygons() { return polygons; } /** * Defines the CSg optimization type. * * @param type * optimization type * @return this CSG */ public CSG optimization(OptType type) { this.setOptType(type); return this; } public CSG union(CSG csg) { switch (getOptType()) { case CSG_BOUND: return _unionCSGBoundsOpt(csg); case POLYGON_BOUND: return _unionPolygonBoundsOpt(csg); default: // return _unionIntersectOpt(csg); return _unionNoOpt(csg); } } /** * Returns a csg consisting of the polygons of this csg and the specified csg. * * The purpose of this method is to allow fast union operations for objects * that do not intersect. * * <p> * <b>WARNING:</b> this method does not apply the csg algorithms. Therefore, * please ensure that this csg and the specified csg do not intersect. * * @param csg * csg * * @return a csg consisting of the polygons of this csg and the specified csg */ public CSG dumbUnion(CSG csg) { CSG result = this.clone(); CSG other = csg.clone(); result.polygons.addAll(other.polygons); return result; } /** * Returns the convex hull of this csg. * * @return the convex hull of this csg */ public CSG hull() { return HullUtil.hull(this); } /** * Returns the convex hull of this csg and the union of the specified csgs. * * @param csgs * csgs * @return the convex hull of this csg and the specified csgs */ public CSG hull(List<CSG> csgs) { CSG csgsUnion = new CSG(); csgsUnion.optType = optType; csgsUnion.polygons = this.clone().polygons; csgs.stream().forEach((csg) -> { csgsUnion.polygons.addAll(csg.clone().polygons); }); return csgsUnion.hull(); } /** * Returns the convex hull of this csg and the union of the specified csgs. * * @param csgs * csgs * @return the convex hull of this csg and the specified csgs */ public CSG hull(CSG... csgs) { return hull(Arrays.asList(csgs)); } private CSG _unionCSGBoundsOpt(CSG csg) { System.err.println("WARNING: using " + CSG.OptType.NONE + " since other optimization types missing for union operation."); return _unionIntersectOpt(csg); } private CSG _unionPolygonBoundsOpt(CSG csg) { List<Polygon> inner = new ArrayList<>(); List<Polygon> outer = new ArrayList<>(); Bounds bounds = csg.getBounds(); this.polygons.stream().forEach((p) -> { if (bounds.intersects(p.getBounds())) { inner.add(p); } else { outer.add(p); } }); List<Polygon> allPolygons = new ArrayList<>(); if (!inner.isEmpty()) { CSG innerCSG = CSG.fromPolygons(inner); allPolygons.addAll(outer); allPolygons.addAll(innerCSG._unionNoOpt(csg).polygons); } else { allPolygons.addAll(this.polygons); allPolygons.addAll(csg.polygons); } return CSG.fromPolygons(allPolygons).optimization(getOptType()); } /** * Optimizes for intersection. If csgs do not intersect create a new csg that * consists of the polygon lists of this csg and the specified csg. In this * case no further space partitioning is performed. * * @param csg * csg * @return the union of this csg and the specified csg */ private CSG _unionIntersectOpt(CSG csg) { boolean intersects = false; Bounds bounds = csg.getBounds(); for (Polygon p : polygons) { if (bounds.intersects(p.getBounds())) { intersects = true; break; } } List<Polygon> allPolygons = new ArrayList<>(); if (intersects) { return _unionNoOpt(csg); } else { allPolygons.addAll(this.polygons); allPolygons.addAll(csg.polygons); } return CSG.fromPolygons(allPolygons).optimization(getOptType()); } private CSG _unionNoOpt(CSG csg) { Node a = new Node(this.clone().polygons); Node b = new Node(csg.clone().polygons); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); return CSG.fromPolygons(a.allPolygons()).optimization(getOptType()); } public CSG difference(List<CSG> csgs) { if (csgs.isEmpty()) { return this.clone(); } CSG csgsUnion = csgs.get(0); for (int i = 1; i < csgs.size(); i++) { csgsUnion = csgsUnion.union(csgs.get(i)); } return difference(csgsUnion); } public CSG difference(CSG... csgs) { return difference(Arrays.asList(csgs)); } public CSG difference(CSG csg) { switch (getOptType()) { case CSG_BOUND: return _differenceCSGBoundsOpt(csg); case POLYGON_BOUND: return _differencePolygonBoundsOpt(csg); default: return _differenceNoOpt(csg); } } private CSG _differenceCSGBoundsOpt(CSG csg) { CSG b = csg; CSG a1 = this._differenceNoOpt(csg.getBounds().toCSG()); CSG a2 = this.intersect(csg.getBounds().toCSG()); return a2._differenceNoOpt(b)._unionIntersectOpt(a1).optimization(getOptType()); } private CSG _differencePolygonBoundsOpt(CSG csg) { List<Polygon> inner = new ArrayList<>(); List<Polygon> outer = new ArrayList<>(); Bounds bounds = csg.getBounds(); this.polygons.stream().forEach((p) -> { if (bounds.intersects(p.getBounds())) { inner.add(p); } else { outer.add(p); } }); CSG innerCSG = CSG.fromPolygons(inner); List<Polygon> allPolygons = new ArrayList<>(); allPolygons.addAll(outer); allPolygons.addAll(innerCSG._differenceNoOpt(csg).polygons); return CSG.fromPolygons(allPolygons).optimization(getOptType()); } private CSG _differenceNoOpt(CSG csg) { Node a = new Node(this.clone().polygons); Node b = new Node(csg.clone().polygons); a.invert(); a.clipTo(b); b.clipTo(a); b.invert(); b.clipTo(a); b.invert(); a.build(b.allPolygons()); a.invert(); CSG csgA = CSG.fromPolygons(a.allPolygons()).optimization(getOptType()); return csgA; } public CSG intersect(CSG csg) { Node a = new Node(this.clone().polygons); Node b = new Node(csg.clone().polygons); a.invert(); b.clipTo(a); b.invert(); a.clipTo(b); b.clipTo(a); a.build(b.allPolygons()); a.invert(); return CSG.fromPolygons(a.allPolygons()).optimization(getOptType()); } public CSG intersect(List<CSG> csgs) { if (csgs.isEmpty()) { return this.clone(); } CSG csgsUnion = csgs.get(0); for (int i = 1; i < csgs.size(); i++) { csgsUnion = csgsUnion.union(csgs.get(i)); } return intersect(csgsUnion); } public CSG intersect(CSG... csgs) { return intersect(Arrays.asList(csgs)); } /** * Returns this csg in STL string format. * * @return this csg in STL string format */ public String toStlString() { StringBuilder sb = new StringBuilder(); toStlString(sb); return sb.toString(); } /** * Returns this csg in STL string format. * * @param sb * string builder * * @return the specified string builder */ public StringBuilder toStlString(StringBuilder sb) { sb.append("solid v3d.csg\n"); this.polygons.stream().forEach( (Polygon p) -> { p.toStlString(sb); }); sb.append("endsolid v3d.csg\n"); return sb; } public ObjFile toObj() { StringBuilder objSb = new StringBuilder(); objSb.append("mtllib " + ObjFile.MTL_NAME); objSb.append("# Group").append("\n"); objSb.append("g v3d.csg\n"); class PolygonStruct { List<Integer> indices; public PolygonStruct(List<Integer> indices) { this.indices = indices; } } List<Vertex> vertices = new ArrayList<>(); List<PolygonStruct> indices = new ArrayList<>(); objSb.append("\n# Vertices\n"); for (Polygon p : polygons) { List<Integer> polyIndices = new ArrayList<>(); p.vertices.stream().forEach((v) -> { if (!vertices.contains(v)) { vertices.add(v); v.toObjString(objSb); polyIndices.add(vertices.size()); } else { polyIndices.add(vertices.indexOf(v) + 1); } }); indices.add(new PolygonStruct(polyIndices)); } objSb.append("\n# Faces").append("\n"); for (PolygonStruct ps : indices) { // we triangulate the polygon to ensure // compatibility with 3d printer software List<Integer> pVerts = ps.indices; int index1 = pVerts.get(0); for (int i = 0; i < pVerts.size() - 2; i++) { int index2 = pVerts.get(i + 1); int index3 = pVerts.get(i + 2); objSb.append("f ").append(index1).append(" ").append(index2).append(" ").append(index3) .append("\n"); } } objSb.append("\n# End Group v3d.csg").append("\n"); StringBuilder mtlSb = new StringBuilder(); return new ObjFile(objSb.toString(), mtlSb.toString()); } /** * Returns this csg in OBJ string format. * * @param sb * string builder * @return the specified string builder */ public StringBuilder toObjString(StringBuilder sb) { sb.append("# Group").append("\n"); sb.append("g v3d.csg\n"); List<Vertex> vertices = new ArrayList<>(); sb.append("\n# Vertices\n"); for (Polygon p : polygons) { List<Integer> polyIndices = new ArrayList<>(); p.vertices.stream().forEach((v) -> { if (!vertices.contains(v)) { vertices.add(v); v.toObjString(sb); polyIndices.add(vertices.size()); } else { polyIndices.add(vertices.indexOf(v) + 1); } }); } sb.append("\n# Faces").append("\n"); sb.append("\n# End Group v3d.csg").append("\n"); return sb; } /** * Returns this csg in OBJ string format. * * @return this csg in OBJ string format */ public String toObjString() { StringBuilder sb = new StringBuilder(); return toObjString(sb).toString(); } /** * Returns a transformed copy of this CSG. * * @param transform * the transform to apply * * @return a transformed copy of this CSG */ public CSG transformed(Transform transform) { if (polygons.isEmpty()) { return clone(); } List<Polygon> newpolygons = this.polygons.stream().map( p -> p.transformed(transform)).collect(Collectors.toList()); CSG result = CSG.fromPolygons(newpolygons).optimization(getOptType()); return result; } /** * Returns the bounds of this csg. * * @return bouds of this csg */ public Bounds getBounds() { if (polygons.isEmpty()) { return new Bounds(Vector3d.ZERO, Vector3d.ZERO); } double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double minZ = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; double maxZ = Double.NEGATIVE_INFINITY; for (Polygon p : getPolygons()) { for (int i = 0; i < p.vertices.size(); i++) { Vertex vert = p.vertices.get(i); if (vert.pos.x < minX) { minX = vert.pos.x; } if (vert.pos.y < minY) { minY = vert.pos.y; } if (vert.pos.z < minZ) { minZ = vert.pos.z; } if (vert.pos.x > maxX) { maxX = vert.pos.x; } if (vert.pos.y > maxY) { maxY = vert.pos.y; } if (vert.pos.z > maxZ) { maxZ = vert.pos.z; } } // end for vertices } // end for polygon return new Bounds( new Vector3d(minX, minY, minZ), new Vector3d(maxX, maxY, maxZ)); } /** * @return the optType */ private OptType getOptType() { return optType != null ? optType : defaultOptType; } /** * @param optType * the optType to set */ public static void setDefaultOptType(OptType optType) { defaultOptType = optType; } /** * @param optType * the optType to set */ public void setOptType(OptType optType) { this.optType = optType; } public static enum OptType { CSG_BOUND, POLYGON_BOUND, NONE } }
package io.compgen.cgpipe; import io.compgen.cgpipe.exceptions.ASTExecException; import io.compgen.cgpipe.exceptions.ASTParseException; import io.compgen.cgpipe.exceptions.ExitException; import io.compgen.cgpipe.exceptions.RunnerException; import io.compgen.cgpipe.parser.Parser; import io.compgen.cgpipe.parser.context.RootContext; import io.compgen.cgpipe.parser.variable.VarBool; import io.compgen.cgpipe.parser.variable.VarInt; import io.compgen.cgpipe.parser.variable.VarString; import io.compgen.cgpipe.parser.variable.VarValue; import io.compgen.cgpipe.runner.ExistingJob; import io.compgen.cgpipe.runner.JobDef; import io.compgen.cgpipe.runner.JobRunner; import io.compgen.cgpipe.support.SimpleFileLoggerImpl; import io.compgen.cmdline.MainBuilder; import io.compgen.cmdline.annotation.Command; import io.compgen.cmdline.annotation.Exec; import io.compgen.cmdline.annotation.Option; import io.compgen.cmdline.annotation.UnknownArgs; import io.compgen.cmdline.annotation.UnnamedArg; import io.compgen.cmdline.impl.AbstractCommand; import io.compgen.common.StringUtils; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; @Command(name="cgsub", desc="Dynamically submit jobs for multiple input files") public class CGSub extends AbstractCommand{ Map<String, VarValue> confVals = new HashMap<String, VarValue>(); private List<String> cmds = new ArrayList<String>(); private List<String> inputs = null; private String name = null; private int procs = -1; private String mem = null; private String walltime = null; private String stackMem = null; private String wd = null; private String stdout = null; private String stderr = null; private boolean dryrun = false; private List<String> dependencies = null; public CGSub() { } @UnknownArgs public void setUnknownArg(String k, String v) { confVals.put(k, VarValue.parseStringRaw(v)); } @UnnamedArg(name="commands -- input1 {input2...}") public void setArguments(List<String> args) { for (String arg: args) { if (inputs == null) { if (arg.equals(" inputs = new ArrayList<String>(); } else { cmds.add(arg); } } else { inputs.add(arg); } } } @Option(name="procs", charName="p", desc="Processors per job", defaultValue="1") public void setProcs(int procs) { this.procs = procs; } @Option(name="mem", charName="m", desc="Memory per job") public void setMem(String mem) { this.mem=mem; } @Option(name="walltime", charName="t", desc="Walltime per job", defaultValue="2:00:00") public void setWalltime(String walltime) { this.walltime = walltime; } @Option(name="stack", desc="Stack memory per job") public void setStackMem(String stackMem) { this.stackMem = stackMem; } @Option(name="wd", desc="Working directory", defaultValue=".", helpValue="dir") public void setWd(String wd) { this.wd = new File(wd).getAbsolutePath(); } @Option(name="name", charName="n", desc="Job name") public void setName(String name) { this.name = name; } @Option(name="stdout", desc="Write stdout to file/dir") public void setStdout(String stdout) { this.stdout = stdout; } @Option(name="stderr", desc="Write stderr to file/dir") public void setStderr(String stderr) { this.stderr = stderr; } @Option(name="dr", desc="Dry-run") public void setDryrun(boolean dryrun) { this.dryrun = dryrun; } @Option(name="deps", desc="Job dependencies (comma-delimited)") public void setDependencies(String deps) { this.dependencies = new ArrayList<String>(); for (String dep: deps.split(",")) { dependencies.add(dep); } } @Exec public void exec() { SimpleFileLoggerImpl.setSilent(true); JobRunner runner = null; confVals.put("job.procs", new VarInt(procs)); confVals.put("job.env", VarBool.TRUE); if (mem != null) { confVals.put("job.mem", new VarString(mem)); } if (stackMem != null) { confVals.put("job.stack", new VarString(stackMem)); } if (walltime != null) { confVals.put("job.walltime", new VarString(walltime)); } try { // Load config values from global config. RootContext root = new RootContext(); // Parse the default cgpiperc InputStream is = CGPipe.class.getClassLoader().getResourceAsStream("io/compgen/cgpipe/cgpiperc"); if (is != null) { Parser.exec("io/compgen/cgpipe/cgpiperc", is, root); } // Parse RC file if (CGPipe.RCFILE.exists()) { Parser.exec(CGPipe.RCFILE.getAbsolutePath(), root); } root.setOutputStream(null); root.update(confVals); runner = JobRunner.load(root, dryrun); if (inputs == null) { if (wd != null) { confVals.put("job.wd", new VarString(wd)); } if (stdout != null) { confVals.put("job.stdout", new VarString(stdout)); } if (stderr != null) { confVals.put("job.stderr", new VarString(stderr)); } JobDef jobdef = new JobDef(StringUtils.join(" ", cmds), confVals); if (dependencies != null) { for (String dep: dependencies) { jobdef.addDependency(new ExistingJob(dep)); } } if (name != null) { jobdef.setName(name); } else { jobdef.setName("cgsub"); } runner.submit(jobdef); } else { int i = 0; for (String input: inputs) { i++; List<String> inputcmds = new ArrayList<String>(); for (String cmd: cmds) { inputcmds.add(convertStringForInput(cmd, input)); } if (wd != null) { confVals.put("job.wd", new VarString(convertStringForInput(wd, input))); } if (stdout != null) { confVals.put("job.stdout", new VarString(convertStringForInput(stdout, input))); } if (stderr != null) { confVals.put("job.stderr", new VarString(convertStringForInput(stderr, input))); } JobDef jobdef = new JobDef(StringUtils.join(" ", inputcmds)+"\n", confVals); if (dependencies != null) { for (String dep: dependencies) { jobdef.addDependency(new ExistingJob(dep)); } } if (name != null) { String n = convertStringForInput(name, input); if (n.equals(name)) { jobdef.setName(n+"."+i); } else { jobdef.setName(n); } } else { jobdef.setName("cgsub."+i); } runner.submit(jobdef); } } runner.done(); } catch (ASTParseException | ASTExecException | RunnerException e) { if (runner != null) { runner.abort(); } if (e.getClass().equals(ExitException.class)) { System.exit(((ExitException) e).getReturnCode()); } System.out.println("CGSUB ERROR " + e.getMessage()); e.printStackTrace(); System.exit(1); } } protected String convertStringForInput(String str, String input) { Pattern p = Pattern.compile("^(.*)\\{(\\^.*)?\\}(.*)$"); Matcher m = p.matcher(str); while (m.matches()) { if (m.group(2) == null) { str = m.group(1)+input+m.group(3); } else { String suf = m.group(2).substring(1); if (input.endsWith(suf)) { str = m.group(1)+input.substring(0, input.length()-suf.length())+m.group(3); } else { str = m.group(1)+input+m.group(3); } } m = p.matcher(str); } return str; } public static void main(String[] args) throws Exception { new MainBuilder().runClass(CGSub.class, args); } }
package VASSAL.counters; import VASSAL.build.GameModule; import VASSAL.build.module.ObscurableOptions; import VASSAL.build.module.documentation.HelpFile; import VASSAL.command.ChangeTracker; import VASSAL.command.Command; import VASSAL.configure.ImageSelector; import VASSAL.configure.NamedHotKeyConfigurer; import VASSAL.configure.PieceAccessConfigurer; import VASSAL.configure.StringConfigurer; import VASSAL.configure.TranslatingStringEnumConfigurer; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.Resources; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.NamedKeyStroke; import VASSAL.tools.SequenceEncoder; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.InputEvent; import java.awt.geom.Area; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import net.miginfocom.swing.MigLayout; import org.apache.commons.lang3.ArrayUtils; public class Obscurable extends Decorator implements TranslatablePiece { public static final String ID = "obs;"; //$NON-NLS-1$// protected static final char INSET = 'I'; protected static final char BACKGROUND = 'B'; protected static final char PEEK = 'P'; protected static final char IMAGE = 'G'; protected static final char INSET2 = '2'; protected static final String DEFAULT_PEEK_COMMAND = Resources.getString("Editor.Obscurable.default_peek_command"); protected char obscureKey; protected NamedKeyStroke keyCommand; protected NamedKeyStroke peekKey; protected String imageName; protected String obscuredToOthersImage; protected String obscuredBy; protected ObscurableOptions obscuredOptions; protected String hideCommand = Resources.getString("Editor.Obscurable.default_mask_command"); protected String peekCommand = DEFAULT_PEEK_COMMAND; protected GamePiece obscuredToMeView; protected GamePiece obscuredToOthersView; protected boolean peeking; protected char displayStyle = INSET; // I = inset, B = background protected String maskName = "?"; protected PieceAccess access = PlayerAccess.getInstance(); protected KeyCommand[] commandsWithPeek; protected KeyCommand[] commandsWithoutPeek; protected KeyCommand hide; protected KeyCommand peek; protected String description = ""; public Obscurable() { this(ID + "M;", null); //$NON-NLS-1$// } public Obscurable(String type, GamePiece d) { mySetType(type); setInner(d); } @Override public void mySetState(String in) { final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(in, ';'); String token = sd.nextToken("null"); //$NON-NLS-1$// obscuredBy = "null".equals(token) ? null : token; //$NON-NLS-1$// token = sd.nextToken(""); obscuredOptions = (obscuredBy == null ? null : new ObscurableOptions(token)); } @Override public void mySetType(String in) { final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(in, ';'); st.nextToken(); keyCommand = st.nextNamedKeyStroke(null); imageName = st.nextToken(); obscuredToMeView = GameModule.getGameModule().createPiece(BasicPiece.ID + ";;" + imageName + ";;"); hideCommand = st.nextToken(hideCommand); if (st.hasMoreTokens()) { final String s = st.nextToken(String.valueOf(INSET)); displayStyle = s.charAt(0); switch (displayStyle) { case PEEK: if (s.length() > 1) { if (s.length() == 2) { peekKey = NamedKeyStroke.of(s.charAt(1), InputEvent.CTRL_DOWN_MASK); } else { peekKey = NamedHotKeyConfigurer.decode(s.substring(1)); } peeking = false; } else { peekKey = null; peeking = true; } break; case IMAGE: if (s.length() > 1) { obscuredToOthersImage = s.substring(1).intern(); obscuredToOthersView = GameModule.getGameModule().createPiece(BasicPiece.ID + ";;" + obscuredToOthersImage + ";;"); obscuredToMeView.setPosition(new Point()); } } } maskName = st.nextToken(maskName); access = PieceAccessConfigurer.decode(st.nextToken(null)); peekCommand = st.nextToken(DEFAULT_PEEK_COMMAND); description = st.nextToken(""); commandsWithPeek = null; hide = null; peek = null; } @Override public String myGetType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(keyCommand).append(imageName).append(hideCommand); switch (displayStyle) { case PEEK: if (peekKey == null) { se.append(displayStyle); } else { se.append(displayStyle + NamedHotKeyConfigurer.encode(peekKey)); } break; case IMAGE: se.append(displayStyle + obscuredToOthersImage); break; default: se.append(displayStyle); } se.append(maskName); se.append(PieceAccessConfigurer.encode(access)); se.append(peekCommand); se.append(description); return ID + se.getValue(); } @Override public String myGetState() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(obscuredBy == null ? "null" : obscuredBy); //$NON-NLS-1$// se.append((obscuredBy == null || obscuredOptions == null) ? "" : obscuredOptions.encodeOptions()); return se.getValue(); } @Override public Rectangle boundingBox() { if (obscuredToMe()) { return bBoxObscuredToMe(); } else if (obscuredToOthers()) { return bBoxObscuredToOthers(); } else { return piece.boundingBox(); } } @Override public Shape getShape() { if (obscuredToMe()) { return obscuredToMeView.getShape(); } else if (obscuredToOthers()) { switch (displayStyle) { case BACKGROUND: return obscuredToMeView.getShape(); case INSET: return piece.getShape(); case INSET2: return obscuredToMeView.getShape(); case PEEK: if (peeking && Boolean.TRUE.equals(getProperty(Properties.SELECTED))) { return piece.getShape(); } else { return obscuredToMeView.getShape(); } case IMAGE: final Area area = new Area(obscuredToOthersView.getShape()); final Shape innerShape = piece.getShape(); if (innerShape instanceof Area) { area.add((Area) innerShape); } else { area.add(new Area(innerShape)); } return area; default: return piece.getShape(); } } else { return piece.getShape(); } } public boolean obscuredToMe() { return !access.currentPlayerHasAccess(obscuredBy); } public boolean obscuredToOthers() { return obscuredBy != null; } @Override public void setProperty(Object key, Object val) { if (ID.equals(key)) { if (val instanceof String || val == null) { obscuredBy = (String) val; if ("null".equals(obscuredBy)) { //$NON-NLS-1$// obscuredBy = null; obscuredOptions = null; } } } else if (Properties.SELECTED.equals(key)) { if (!Boolean.TRUE.equals(val) && peekKey != null) { peeking = false; } super.setProperty(key, val); } else if (Properties.OBSCURED_TO_OTHERS.equals(key)) { String owner = null; if (Boolean.TRUE.equals(val)) { owner = access.getCurrentPlayerId(); } obscuredBy = owner; obscuredOptions = new ObscurableOptions(ObscurableOptions.getInstance().encodeOptions()); } else { super.setProperty(key, val); } } @Override public Object getProperty(Object key) { if (Properties.OBSCURED_TO_ME.equals(key)) { return obscuredToMe(); } else if (Properties.OBSCURED_TO_OTHERS.equals(key)) { return obscuredToOthers(); } else if (ID.equals(key)) { return obscuredBy; } else if (Properties.VISIBLE_STATE.equals(key)) { return myGetState() + isPeeking() + getProperty(Properties.SELECTED) + obscuredToMe() + piece.getProperty(key); } // FIXME: Access to Obscured properties // If piece is obscured to me, then mask any properties returned by // traits between this one and the innermost BasicPiece. Return directly // any properties normally handled by Decorator.getproperty() // Global Key Commands acting on Decks over-ride the masking by calling // setExposeMaskedProperties() // else if (obscuredToMe() && ! exposeMaskedProperties) { // if (Properties.KEY_COMMANDS.equals(key)) { // return getKeyCommands(); // else if (Properties.INNER.equals(key)) { // return piece; // else if (Properties.OUTER.equals(key)) { // return getOuter(); // else if (Properties.VISIBLE_STATE.equals(key)) { // return myGetState(); // else { // return ((BasicPiece) Decorator.getInnermost(this)).getPublicProperty(key); else { return super.getProperty(key); } } @Override public Object getLocalizedProperty(Object key) { if (obscuredToMe()) { return ((BasicPiece) Decorator.getInnermost(this)).getLocalizedPublicProperty(key); } else if (Properties.OBSCURED_TO_ME.equals(key)) { return obscuredToMe(); } else if (Properties.OBSCURED_TO_OTHERS.equals(key)) { return obscuredToOthers(); } else if (ID.equals(key)) { return obscuredBy; } else if (Properties.VISIBLE_STATE.equals(key)) { return myGetState() + isPeeking() + piece.getProperty(key); } else { return super.getLocalizedProperty(key); } } @Override public void draw(Graphics g, int x, int y, Component obs, double zoom) { if (obscuredToMe()) { drawObscuredToMe(g, x, y, obs, zoom); } else if (obscuredToOthers()) { drawObscuredToOthers(g, x, y, obs, zoom); } else { piece.draw(g, x, y, obs, zoom); } } protected void drawObscuredToMe(Graphics g, int x, int y, Component obs, double zoom) { obscuredToMeView.draw(g, x, y, obs, zoom); } protected void drawObscuredToOthers(Graphics g, int x, int y, Component obs, double zoom) { switch (displayStyle) { case BACKGROUND: obscuredToMeView.draw(g, x, y, obs, zoom); piece.draw(g, x, y, obs, zoom * .5); break; case INSET: piece.draw(g, x, y, obs, zoom); final Rectangle bounds = piece.getShape().getBounds(); final Rectangle obsBounds = obscuredToMeView.getShape().getBounds(); obscuredToMeView.draw(g, x - (int) (zoom * bounds.width / 2 - .5 * zoom * obsBounds.width / 2), y - (int) (zoom * bounds.height / 2 - .5 * zoom * obsBounds.height / 2), obs, zoom * 0.5); break; case INSET2: obscuredToMeView.draw(g, x, y, obs, zoom); final Rectangle bounds2 = piece.getShape().getBounds(); final Rectangle obsBounds2 = obscuredToMeView.getShape().getBounds(); piece.draw(g, x - (int) (0.4 * zoom * (obsBounds2.width - bounds2.width)), y - (int) (0.4 * zoom * (obsBounds2.height - bounds2.height)), obs, zoom * 0.8); break; case PEEK: if (peeking && Boolean.TRUE.equals(getProperty(Properties.SELECTED))) { piece.draw(g, x, y, obs, zoom); } else { obscuredToMeView.draw(g, x, y, obs, zoom); } break; case IMAGE: piece.draw(g, x, y, obs, zoom); obscuredToOthersView.draw(g, x, y, obs, zoom); } } /** Return true if the piece is currently being "peeked at" */ public boolean isPeeking() { return peeking; } protected Rectangle bBoxObscuredToMe() { return obscuredToMeView.boundingBox(); } protected Rectangle bBoxObscuredToOthers() { final Rectangle r; switch (displayStyle) { case BACKGROUND: r = bBoxObscuredToMe(); break; case IMAGE: r = piece.boundingBox(); r.add(obscuredToOthersView.boundingBox()); break; default: r = piece.boundingBox(); } return r; } @Override public String getLocalizedName() { String maskedName = maskName == null ? "?" : maskName; maskedName = getTranslation(maskedName); return getName(maskedName, true); } @Override public String getName() { final String maskedName = maskName == null ? "?" : maskName; return getName(maskedName, false); } protected String getName(String maskedName, boolean localized) { if (obscuredToMe()) { return maskedName; } else if (obscuredToOthers()) { return (localized ? piece.getLocalizedName() : piece.getName()) + "(" + maskedName + ")"; } else { return (localized ? piece.getLocalizedName() : piece.getName()); } } @Override public KeyCommand[] getKeyCommands() { if (obscuredToMe()) { final KeyCommand[] myC = myGetKeyCommands(); final KeyCommand[] c = (KeyCommand[]) Decorator.getInnermost(this).getProperty(Properties.KEY_COMMANDS); if (c == null) return myC; else return ArrayUtils.addAll(myC, c); } else { return super.getKeyCommands(); } } @Override public KeyCommand[] myGetKeyCommands() { final ArrayList<KeyCommand> l = new ArrayList<>(); final GamePiece outer = Decorator.getOutermost(this); // Hide Command if (keyCommand == null) { // Backwards compatibility with VASL classes keyCommand = NamedKeyStroke.of(obscureKey, InputEvent.CTRL_DOWN_MASK); } hide = new KeyCommand(hideCommand, keyCommand, outer, this); if (hideCommand.length() > 0 && isMaskable()) { l.add(hide); commandsWithoutPeek = new KeyCommand[] {hide}; } else { commandsWithoutPeek = KeyCommand.NONE; } // Peek Command peek = new KeyCommand(peekCommand, peekKey, outer, this); if (displayStyle == PEEK && peekKey != null && peekCommand.length() > 0) { l.add(peek); } commandsWithPeek = l.toArray(new KeyCommand[0]); return obscuredToOthers() && isMaskable() && displayStyle == PEEK && peekKey != null ? commandsWithPeek : commandsWithoutPeek; } /** * Return true if this piece can be masked/unmasked by the current player */ public boolean isMaskable() { // Check if piece is owned by us. Returns true if we own the piece, or if it // is not currently masked if (access.currentPlayerCanModify(obscuredBy)) { return true; } // Check ObscurableOptions in play when piece was Obscured if (obscuredOptions != null) { return obscuredOptions.isUnmaskable(obscuredBy); } // Fall-back, use current global ObscurableOptions return ObscurableOptions.getInstance().isUnmaskable(obscuredBy); } @Override public Command keyEvent(KeyStroke stroke) { if (!obscuredToMe()) { return super.keyEvent(stroke); } else if (isMaskable()) { return myKeyEvent(stroke); } else { return null; } } @Override public Command myKeyEvent(KeyStroke stroke) { Command retVal = null; myGetKeyCommands(); if (hide.matches(stroke)) { final ChangeTracker c = new ChangeTracker(this); if (obscuredToOthers() || obscuredToMe()) { obscuredBy = null; obscuredOptions = null; } else if (!obscuredToMe()) { obscuredBy = access.getCurrentPlayerId(); obscuredOptions = new ObscurableOptions(ObscurableOptions.getInstance().encodeOptions()); } retVal = c.getChangeCommand(); } else if (peek.matches(stroke)) { if (obscuredToOthers() && Boolean.TRUE.equals(getProperty(Properties.SELECTED))) { peeking = true; } } // For the "peek" display style with no key command (i.e. appears // face-up whenever selected). // It looks funny if we turn something face down but we can still see it. // Therefore, un-select the piece if turning it face down if (retVal != null && PEEK == displayStyle && peekKey == null && obscuredToOthers()) { // FIXME: This probably causes a race condition. Can we do this directly? final Runnable runnable = () -> KeyBuffer.getBuffer().remove(Decorator.getOutermost(this)); SwingUtilities.invokeLater(runnable); } return retVal; } @Override public String getDescription() { return buildDescription("Editor.Obscurable.trait_description", description); } @Override public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("Mask.html"); //$NON-NLS-1$// } @Override public PieceEditor getEditor() { return new Ed(this); } @Override public PieceI18nData getI18nData() { return getI18nData(new String[] {hideCommand, maskName, peekCommand}, new String[] { Resources.getString("Editor.Obscurable.mask_command"), Resources.getString("Editor.Obscurable.name_when_masked"), Resources.getString("Editor.Obscurable.peek_command")}); } /** * Return Property names exposed by this trait */ @Override public List<String> getPropertyNames() { final ArrayList<String> l = new ArrayList<>(); l.add(Properties.OBSCURED_TO_OTHERS); l.add(Properties.OBSCURED_TO_ME); return l; } @Override public boolean testEquals(Object o) { if (! (o instanceof Obscurable)) return false; final Obscurable c = (Obscurable) o; if (! Objects.equals(keyCommand, c.keyCommand)) return false; if (! Objects.equals(imageName, c.imageName)) return false; if (! Objects.equals(hideCommand, c.hideCommand)) return false; if (! Objects.equals(displayStyle, c.displayStyle)) return false; switch (displayStyle) { case PEEK: if (!Objects.equals(peekKey, c.peekKey)) return false; break; case IMAGE: if (!Objects.equals(obscuredToOthersImage, c.obscuredToOthersImage)) return false; break; default: break; } if (! Objects.equals(maskName, c.maskName)) return false; if (! Objects.equals(PieceAccessConfigurer.encode(access), PieceAccessConfigurer.encode(c.access))) return false; if (! Objects.equals(peekCommand, c.peekCommand)) return false; if (! Objects.equals(obscuredBy, c.obscuredBy)) return false; final boolean noOptions = obscuredBy == null || obscuredOptions == null; final boolean noOptions2 = c.obscuredBy == null || c.obscuredOptions == null; if (! Objects.equals(noOptions, noOptions2)) return false; if (!noOptions && !noOptions2) { return Objects.equals(obscuredOptions.encodeOptions(), c.obscuredOptions.encodeOptions()); } return true; } private static class Ed implements PieceEditor { private final ImageSelector picker; private final NamedHotKeyConfigurer obscureKeyInput; private final StringConfigurer obscureCommandInput, maskNameInput; private final TranslatingStringEnumConfigurer displayOption; private final NamedHotKeyConfigurer peekKeyInput; private final StringConfigurer peekCommandInput; private final TraitConfigPanel controls = new TraitConfigPanel(); private final String[] optionNames = {"B", "P", "I", "2", "U"}; // NON-NLS private final String[] optionKeys = { "Editor.Obscurable.background", "Editor.Obscurable.plain", "Editor.Obscurable.inset", "Editor.Obscurable.inset2", "Editor.Obscurable.use_image" }; private final char[] optionChars = {BACKGROUND, PEEK, INSET, INSET2, IMAGE}; private final ImageSelector imagePicker; private final PieceAccessConfigurer accessConfig; private final JPanel showDisplayOption; private final JLabel peekKeyLabel; private final JLabel peekCommandLabel; private final StringConfigurer descInput; public Ed(Obscurable p) { descInput = new StringConfigurer(p.description); descInput.setHintKey("Editor.description_hint"); controls.add("Editor.description_label", descInput); obscureCommandInput = new StringConfigurer(p.hideCommand); obscureCommandInput.setHintKey("Editor.menu_command_hint"); controls.add("Editor.menu_command", obscureCommandInput); obscureKeyInput = new NamedHotKeyConfigurer(p.keyCommand); controls.add("Editor.keyboard_command", obscureKeyInput); accessConfig = new PieceAccessConfigurer(p.access); controls.add("Editor.Obscurable.can_be_masked_by", accessConfig); picker = new ImageSelector(p.imageName, 512, 512); controls.add("Editor.Obscurable.view_when_masked", picker); maskNameInput = new StringConfigurer(p.maskName); maskNameInput.setHintKey("Editor.Obscurable.name_when_masked_hint"); controls.add("Editor.Obscurable.name_when_masked", maskNameInput); final JPanel displayPanel = new JPanel(new MigLayout("ins 0,hidemode 3", "[][][]")); // NON-NLS final JLabel displayLabel = new JLabel(Resources.getString("Editor.Obscurable.display_style")); displayLabel.setLabelFor(displayPanel); displayOption = new TranslatingStringEnumConfigurer(optionNames, optionKeys); for (int i = 0; i < optionNames.length; ++i) { if (p.displayStyle == optionChars[i]) { displayOption.setValue(optionNames[i]); break; } } controls.add(displayLabel); displayPanel.add(displayOption.getControls()); showDisplayOption = new JPanel() { private static final long serialVersionUID = 1L; @Override public Dimension getMinimumSize() { return new Dimension(60, 60); } @Override public Dimension getPreferredSize() { return new Dimension(60, 60); } @Override public void paint(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); char style = INSET; for (int i = 0; i < optionNames.length; ++i) { if (optionNames[i].equals(displayOption.getValueString())) { style = optionChars[i]; break; } } switch (style) { case BACKGROUND: g.setColor(Color.black); g.fillRect(0, 0, 60, 60); g.setColor(Color.white); g.fillRect(15, 15, 30, 30); break; case INSET: g.setColor(Color.white); g.fillRect(0, 0, 60, 60); g.setColor(Color.black); g.fillRect(0, 0, 30, 30); break; case INSET2: g.setColor(Color.black); g.fillRect(0, 0, 60, 60); g.setColor(Color.white); g.fillRect(10, 10, 40, 40); break; case PEEK: g.setColor(Color.black); g.fillRect(0, 0, 60, 60); break; } } }; displayPanel.add(showDisplayOption); imagePicker = new ImageSelector(p.obscuredToOthersImage, 512, 512); imagePicker.getControls().setVisible(p.displayStyle == IMAGE); displayPanel.add(imagePicker.getControls()); controls.add(displayPanel, "wrap"); // NON-NLS peekKeyLabel = new JLabel(Resources.getString("Editor.Obscurable.peek_keyboard_command")); peekKeyInput = new NamedHotKeyConfigurer(p.peekKey); peekKeyLabel.setVisible(p.displayStyle == PEEK); peekKeyInput.getControls().setVisible(p.displayStyle == PEEK); controls.add(peekKeyLabel, peekKeyInput); peekCommandLabel = new JLabel(Resources.getString("Editor.Obscurable.peek_menu_command")); peekCommandInput = new StringConfigurer(p.peekCommand); peekCommandInput.setHintKey("Editor.menu_command_hint"); peekCommandLabel.setVisible(p.displayStyle == PEEK); peekCommandInput.getControls().setVisible(p.displayStyle == PEEK); controls.add(peekCommandLabel, peekCommandInput); displayOption.addPropertyChangeListener(evt -> { showDisplayOption.repaint(); peekKeyLabel.setVisible(optionNames[1].equals(evt.getNewValue())); peekKeyInput.getControls().setVisible(optionNames[1].equals(evt.getNewValue())); peekCommandLabel.setVisible(optionNames[1].equals(evt.getNewValue())); peekCommandInput.getControls().setVisible(optionNames[1].equals(evt.getNewValue())); imagePicker.getControls().setVisible(optionNames[4].equals(evt.getNewValue())); showDisplayOption.setVisible(!optionNames[4].equals(evt.getNewValue())); repack(controls); }); } @Override public String getState() { return "null"; //$NON-NLS-1$// } @Override public String getType() { final SequenceEncoder se = new SequenceEncoder(';'); se.append(obscureKeyInput.getValueString()) .append(picker.getValueString()) .append(obscureCommandInput.getValueString()); char optionChar = INSET; for (int i = 0; i < optionNames.length; ++i) { if (optionNames[i].equals(displayOption.getValueString())) { optionChar = optionChars[i]; break; } } switch (optionChar) { case PEEK: final String valueString = peekKeyInput.getValueString(); if (valueString != null) { se.append(optionChar + valueString); } else { se.append(optionChar); } break; case IMAGE: se.append(optionChar + imagePicker.getValueString()); break; default: se.append(optionChar); } se.append(maskNameInput.getValueString()); se.append(accessConfig.getValueString()); se.append(peekCommandInput.getValueString()); se.append(descInput.getValueString()); return ID + se.getValue(); } @Override public Component getControls() { return controls; } } /** * @return a list of any Named KeyStrokes referenced in the Decorator, if any (for search) */ @Override public List<NamedKeyStroke> getNamedKeyStrokeList() { return Arrays.asList(keyCommand, peekKey); } /** * @return a list of any Menu Text strings referenced in the Decorator, if any (for search) */ @Override public List<String> getMenuTextList() { return List.of(hideCommand, peekCommand); } /** * @return a list of any Message Format strings referenced in the Decorator, if any (for search) */ @Override public List<String> getFormattedStringList() { return List.of(maskName); } @Override public void addLocalImageNames(Collection<String> s) { if (imageName != null) s.add(imageName); if (obscuredToOthersImage != null) s.add(obscuredToOthersImage); } }
package uk.ac.ebi.atlas.model; import com.google.common.collect.Sets; import org.apache.commons.collections.CollectionUtils; import org.springframework.context.annotation.Scope; import uk.ac.ebi.atlas.geneannotation.GeneNamesProvider; import javax.inject.Inject; import javax.inject.Named; import java.util.*; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; public class GeneProfile implements Iterable<Expression> { private String geneId; private GeneNamesProvider geneNamesProvider; private double maxExpressionLevel = 0; private double minExpressionLevel = Double.MAX_VALUE; private SortedMap<FactorValue, Expression> factorValueExpressions = new TreeMap<>(); private GeneProfile() { } public GeneProfile add(Expression expression) { // ToDo: this is wrong, this could lead to overriding certain expressions by reoccurring factor values for (FactorValue factorValue : expression.getAllFactorValues()) { factorValueExpressions.put(factorValue, expression); } updateProfileExpression(expression.getLevel()); return this; } public GeneProfile setGeneNamesProvider(GeneNamesProvider geneNamesProvider) { this.geneNamesProvider = geneNamesProvider; return this; } public String getGeneId() { return geneId; } public void setGeneId(String geneId) { this.geneId = geneId; } public int getSpecificity() { return factorValueExpressions.values().size(); } public Iterator<Expression> iterator() { return factorValueExpressions.values().iterator(); } public double getMaxExpressionLevel() { return maxExpressionLevel; } public double getMinExpressionLevel() { return minExpressionLevel; } private void updateProfileExpression(double level) { if (maxExpressionLevel < level) { maxExpressionLevel = level; } if (level < minExpressionLevel) { minExpressionLevel = level; } } public boolean isExpressedOnAnyOf(Set<FactorValue> factorValues) { checkArgument(CollectionUtils.isNotEmpty(factorValues)); return Sets.intersection(this.getAllFactorValues(), factorValues).size() > 0; } public double getAverageExpressionLevelOn(Set<FactorValue> factorValues) { if (CollectionUtils.isEmpty(factorValues)) { return 0D; } double expressionLevel = 0D; for (FactorValue factorValue : factorValues) { expressionLevel += getExpressionLevel(factorValue); } return expressionLevel / factorValues.size(); } public Set<FactorValue> getAllFactorValues() { return this.factorValueExpressions.keySet(); } public double getExpressionLevel(FactorValue factorValue) { Expression expression = factorValueExpressions.get(factorValue); return expression == null ? 0 : expression.getLevel(); } //we decided to lazy load rather then have an attribute because // not always the name is used public String getGeneName() { if (geneNamesProvider != null) { return geneNamesProvider.getGeneName(geneId); } return null; } public double getWeightedExpressionLevelOn(Set<FactorValue> selectedFactorValues, Set<FactorValue> allFactorValues) { if (allFactorValues.isEmpty()) { return getAverageExpressionLevelOn(selectedFactorValues); } return getAverageExpressionLevelOn(selectedFactorValues) - getAverageExpressionLevelOn(Sets.difference(allFactorValues, selectedFactorValues)); } @Named("geneProfileBuilder") @Scope("prototype") public static class Builder { private GeneNamesProvider geneNamesProvider; private GeneProfile geneProfile; private static double DEFAULT_CUTOFF_VALUE = 0D; private double cutoffValue = DEFAULT_CUTOFF_VALUE; protected Builder() { } @Inject protected void setGeneNamesProvider(GeneNamesProvider geneNamesProvider) { this.geneNamesProvider = geneNamesProvider; } public Builder forGeneId(String geneId) { this.geneProfile = new GeneProfile(); geneProfile.setGeneNamesProvider(geneNamesProvider); geneProfile.setGeneId(geneId); return this; } public Builder addExpression(Expression expression) { checkState(geneProfile != null, "Please invoke forGeneID before create"); if (expression.isGreaterThan(cutoffValue)) { geneProfile.add(expression); } return this; } public Builder withCutoff(double cutoff) { this.cutoffValue = cutoff; return this; } public GeneProfile create() { checkState(geneProfile != null, "Please invoke forGeneID before create"); return geneProfile; } public boolean containsExpressions() { return !geneProfile.factorValueExpressions.isEmpty(); } } }
package som.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import som.VM; import som.interpreter.Types; import som.vm.Bootstrap; import som.vmobjects.SClass; import som.vmobjects.SSymbol; @RunWith(Parameterized.class) public class BasicInterpreterTests { @Parameters public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { {"MethodCall", "test", 42, Long.class }, {"MethodCall", "test2", 42, Long.class }, {"NonLocalReturn", "test1", 42, Long.class }, {"NonLocalReturn", "test2", 43, Long.class }, {"NonLocalReturn", "test3", 3, Long.class }, {"NonLocalReturn", "test4", 42, Long.class }, {"NonLocalReturn", "test5", 22, Long.class }, {"Blocks", "arg1", 42, Long.class }, {"Blocks", "arg2", 77, Long.class }, {"Blocks", "argAndLocal", 8, Long.class }, {"Blocks", "argAndContext", 8, Long.class }, {"Return", "returnSelf", "Return", SClass.class }, {"Return", "returnSelfImplicitly", "Return", SClass.class }, {"Return", "noReturnReturnsSelf", "Return", SClass.class }, {"Return", "blockReturnsImplicitlyLastValue", 4, Long.class }, {"Return", "returnIntLiteral", 33, Long.class }, {"Return", "returnUnarySend", 33, Long.class }, {"IfTrueIfFalse", "test", 42, Long.class }, {"IfTrueIfFalse", "test2", 33, Long.class }, {"IfTrueIfFalse", "test3", 4, Long.class }, {"CompilerSimplification", "returnConstantSymbol", "constant", SSymbol.class }, {"CompilerSimplification", "returnConstantInt", 42, Long.class }, {"CompilerSimplification", "returnSelf", "CompilerSimplification", SClass.class }, {"CompilerSimplification", "returnSelfImplicitly", "CompilerSimplification", SClass.class }, {"CompilerSimplification", "testReturnArgumentN", 55, Long.class }, {"CompilerSimplification", "testReturnArgumentA", 44, Long.class }, {"CompilerSimplification", "testSetField", "foo", SSymbol.class }, {"CompilerSimplification", "testGetField", 40, Long.class }, {"Arrays", "testArrayCreation", "Array", Object.class }, {"Arrays", "testEmptyToInts", 3, Long.class }, {"Arrays", "testPutAllInt", 5, Long.class }, {"Arrays", "testPutAllNil", "Nil", Object.class }, {"Arrays", "testNewWithAll", 1, Long.class }, {"BlockInlining", "testNoInlining", 1, Long.class }, {"BlockInlining", "testOneLevelInlining", 1, Long.class }, {"BlockInlining", "testOneLevelInliningWithLocalShadowTrue", 2, Long.class }, {"BlockInlining", "testOneLevelInliningWithLocalShadowFalse", 1, Long.class }, {"BlockInlining", "testBlockNestedInIfTrue", 2, Long.class }, {"BlockInlining", "testBlockNestedInIfFalse", 42, Long.class }, {"BlockInlining", "testDeepNestedInlinedIfTrue", 3, Long.class }, {"BlockInlining", "testDeepNestedInlinedIfFalse", 42, Long.class }, {"BlockInlining", "testDeepNestedBlocksInInlinedIfTrue", 5, Long.class }, {"BlockInlining", "testDeepNestedBlocksInInlinedIfFalse", 43, Long.class }, {"BlockInlining", "testDeepDeepNestedTrue", 9, Long.class }, {"BlockInlining", "testDeepDeepNestedFalse", 43, Long.class }, {"BlockInlining", "testToDoNestDoNestIfTrue", 2, Long.class }, {"Lookup", "testClassMethodsNotBlockingOuterMethods", 42, Long.class }, {"Lookup", "testExplicitOuterInInitializer", 182, Long.class }, {"Lookup", "testImplicitOuterInInitializer", 182, Long.class }, {"Lookup", "testImplicitSend", 42, Long.class }, {"Lookup", "testSiblingLookupA", 42, Long.class }, {"Lookup", "testSiblingLookupB", 43, Long.class }, {"Lookup", "testNesting1", 91, Long.class }, {"Lookup", "testNesting2", 182, Long.class }, {"Lookup", "testNesting3", 364, Long.class }, {"Lookup", "testInner18", 999, Long.class }, {"SuperSends", "testSuperClassClause1A", 44, Long.class }, {"SuperSends", "testSuperClassClause1B", 88, Long.class }, {"SuperSends", "testSuperClassClause2A", 44, Long.class }, {"SuperSends", "testSuperClassClause2B", 88, Long.class }, {"SuperSends", "testSuperClassClause3A", 44, Long.class }, {"SuperSends", "testSuperClassClause3B", 88, Long.class }, {"SuperSends", "testSuperClassClause4A", 44, Long.class }, {"SuperSends", "testSuperClassClause4B", 88, Long.class }, {"OuterSends", "testOuterBindings1", 3, Long.class }, {"OuterSends", "testOuterBindings2", 2, Long.class }, {"OuterSends", "testOuterBindings3", 6, Long.class }, {"OuterSends", "testOuterSendLegalTargets", 666, Long.class }, {"ObjectCreation", "testNew", "ObjectCreation", Object.class }, {"ObjectCreation", "testImmutableRead", 3, Long.class }, {"ObjectCreation", "testImmutableReadInner", 42, Long.class }, {"Parser", "testOuterInKeyword", 32 * 32 * 32, Long.class }, {"Parser", "testOuterWithKeyword", 3 * 4, Long.class }, {"Parser", "testOuterInheritancePrefix", 32, Long.class }, {"Initializers", "testInit1", 42, Long.class }, {"Initializers", "testInit2", 42, Long.class }, }); } private final String testClass; private final String testSelector; private final Object expectedResult; private final Class<?> resultType; public BasicInterpreterTests(final String testClass, final String testSelector, final Object expectedResult, final Class<?> resultType) { this.testClass = testClass; this.testSelector = testSelector; this.expectedResult = expectedResult; this.resultType = resultType; } protected void assertEqualsSOMValue(final Object expectedResult, final Object actualResult) { if (resultType == Long.class) { long expected = (int) expectedResult; long actual = (long) actualResult; assertEquals(expected, actual); return; } if (resultType == SClass.class) { String expected = (String) expectedResult; String actual = ((SClass) actualResult).getName().getString(); assertEquals(expected, actual); return; } if (resultType == SSymbol.class) { String expected = (String) expectedResult; String actual = ((SSymbol) actualResult).getString(); assertEquals(expected, actual); return; } if (resultType == Object.class) { String objClassName = Types.getClassOf(actualResult).getName().getString(); assertEquals(expectedResult, objClassName); return; } fail("SOM Value handler missing"); } @Test public void testBasicInterpreterBehavior() { Bootstrap.loadPlatformAndKernelModule( "TestSuite/BasicInterpreterTests/" + testClass + ".som", VM.standardKernelFile); Bootstrap.initializeObjectSystem(); Object actualResult = Bootstrap.execute(testSelector); assertEqualsSOMValue(expectedResult, actualResult); } @Override public String toString() { return "BasicTest(" + testClass + ">>#" + testSelector + ")"; } }
package tv.ouya.demo.OuyaUnityApplication; import tv.ouya.console.api.*; import tv.ouya.console.api.OuyaController; import tv.ouya.sdk.*; import android.accounts.AccountManager; import android.app.Activity; import android.app.NativeActivity; import android.content.*; import android.content.res.Configuration; import android.graphics.PixelFormat; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.InputDevice; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import com.unity3d.player.UnityPlayer; import com.unity3d.player.UnityPlayerActivity; import com.unity3d.player.UnityPlayerProxyActivity; import java.io.InputStream; import java.io.IOException; import java.util.ArrayList; public class OuyaNativeActivity extends NativeActivity { protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code // UnityPlayer.init() should be called before attaching the view to a layout - it will load the native code. // UnityPlayer.quit() should be the last thing called - it will unload the native code. protected void onCreate (Bundle savedInstanceState) { Log.i("Unity", "***Starting OUYA Native Activity*********"); //make activity accessible to Unity IOuyaActivity.SetActivity(this); //make bundle accessible to Unity IOuyaActivity.SetSavedInstanceState(savedInstanceState); // load the raw resource for the application key try { InputStream inputStream = getResources().openRawResource(R.raw.key); byte[] applicationKey = new byte[inputStream.available()]; inputStream.read(applicationKey); inputStream.close(); IOuyaActivity.SetApplicationKey(applicationKey); } catch (IOException e) { e.printStackTrace(); } requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); getWindow().takeSurface(null); setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); getWindow().setFormat(PixelFormat.RGB_565); mUnityPlayer = new UnityPlayer(this); if (mUnityPlayer.getSettings ().getBoolean ("hide_status_bar", true)) getWindow ().setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); int glesMode = mUnityPlayer.getSettings().getInt("gles_mode", 1); boolean trueColor8888 = false; mUnityPlayer.init(glesMode, trueColor8888); View playerView = mUnityPlayer.getView(); setContentView(playerView); playerView.requestFocus(); // Create the UnityPlayer IOuyaActivity.SetUnityPlayer(mUnityPlayer); } /** * Broadcast listener to handle re-requesting the receipts when a user has re-authenticated */ private BroadcastReceiver mAuthChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { TestOuyaFacade test = IOuyaActivity.GetTestOuyaFacade(); if (null != test) { test.requestReceipts(); } } }; /** * Broadcast listener to handle menu appearing */ private BroadcastReceiver mMenuAppearingReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("Unity", "BroadcastReceiver intent=" + intent.getAction()); if(intent.getAction().equals(OuyaIntent.ACTION_MENUAPPEARING)) { //pause music, free up resources, etc. //invoke a unity callback Log.i("Unity", "BroadcastReceiver tell Unity we see the menu appearing"); UnityPlayer.UnitySendMessage("OuyaGameObject", "onMenuAppearing", ""); Log.i("Unity", "BroadcastReceiver notified Unity onMenuAppearing"); } } }; /** * Request an up to date list of receipts and start listening for any account changes * whilst the application is running. */ @Override public void onStart() { super.onStart(); // Register to receive notifications about account changes. This will re-query // the receipt list in order to ensure it is always up to date for whomever // is logged in. IntentFilter accountsChangedFilter = new IntentFilter(); accountsChangedFilter.addAction(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION); registerReceiver(mAuthChangeReceiver, accountsChangedFilter); IntentFilter menuAppearingFilter = new IntentFilter(); menuAppearingFilter.addAction(OuyaIntent.ACTION_MENUAPPEARING); registerReceiver(mMenuAppearingReceiver, menuAppearingFilter); } /** * Unregister the account change listener when the application is stopped. */ @Override public void onStop() { unregisterReceiver(mAuthChangeReceiver); unregisterReceiver(mMenuAppearingReceiver); super.onStop(); } /** * Check for the result from a call through to the authentication intent. If the authentication was * successful then re-try the purchase. */ @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if(resultCode == RESULT_OK) { TestOuyaFacade test = IOuyaActivity.GetTestOuyaFacade(); if (null != test) { switch (requestCode) { case TestOuyaFacade.GAMER_UUID_AUTHENTICATION_ACTIVITY_ID: test.fetchGamerUUID(); break; case TestOuyaFacade.PURCHASE_AUTHENTICATION_ACTIVITY_ID: test.restartInterruptedPurchase(); break; } } } } @Override protected void onSaveInstanceState(final Bundle outState) { TestOuyaFacade test = IOuyaActivity.GetTestOuyaFacade(); if (null != test) { test.onSaveInstanceState(outState); } } protected void onDestroy () { mUnityPlayer.quit(); super.onDestroy(); } // onPause()/onResume() must be sent to UnityPlayer to enable pause and resource recreation on resume. protected void onPause() { UnityPlayer.UnitySendMessage("OuyaGameObject", "onPause", ""); super.onPause(); mUnityPlayer.pause(); } protected void onResume() { UnityPlayer.UnitySendMessage("OuyaGameObject", "onResume", ""); super.onResume(); mUnityPlayer.resume(); } public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mUnityPlayer.configurationChanged(newConfig); } public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mUnityPlayer.windowFocusChanged(hasFocus); } public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_MULTIPLE) return mUnityPlayer.onKeyMultiple(event.getKeyCode(), event.getRepeatCount(), event); return super.dispatchKeyEvent(event); } @Override public boolean onKeyUp (int keyCode, KeyEvent event) { //Log.i("Unity", "onKeyUp keyCode=" + keyCode); if (keyCode == OuyaController.BUTTON_MENU) { Log.i("Unity", "BroadcastReceiver tell Unity we see the menu button up"); UnityPlayer.UnitySendMessage("OuyaGameObject", "onMenuButtonUp", ""); Log.i("Unity", "BroadcastReceiver notified Unity onMenuButtonUp"); return true; } return super.onKeyUp(keyCode, event); } }
package kata; import java.util.*; /** * Given a dictionary and a word, check if the word is typed by a stucked * keyboard. * * For example, a word "hello" in the dictionary can be typed with "helllllo" or * "heeeello" but not "heeeeelo". */ public class WordTypedByStuckKeys { public static List<String> DICT = List.of( "hello", "world", "cat", "dog", "bird", "green", "help", "great", "greet", "pool", "leet", "let"); static boolean wordTypedByStuckKeys(String str, List<String> dict) { TrieNode trie = TrieNode.build(dict); return trie.isInTrieForStucked(str); } /** * Stores a map of Map<Character, List<String>words> instead of a Trie */ static boolean wordTypedByStuckKeysWithMap(String str, List<String> dict) { Map<String, List<String>> simplified = buildMap(dict); String simplifiedString = simplifyString(str); List<String> matcheds = simplified.get(simplifiedString); if (matcheds == null) { return false; } char[] chars = str.toCharArray(); for (String matched: matcheds) { if (matchedSimplified(chars, 0, matched.toCharArray(), 0)) { return true; } } return false; } static Map<String, List<String>> buildMap(List<String> dict) { Map<String, List<String>> simplified = new HashMap<>(); for (String s: dict) { String newS = simplifyString(s); List<String> values = simplified.get(newS); if (values == null) { values = new ArrayList<>(); simplified.put(newS, values); } values.add(s); } return simplified; } static String simplifyString(String s) { int w = 1; char[] chars = s.toCharArray(); for (int r = 1; r < chars.length; r++) { if (chars[r] != chars[r - 1]) { chars[w] = chars[r]; w++; } } return new String(chars, 0, w); } static boolean matchedSimplified(char[] chars, int i, char[] tchars, int j) { if (i == chars.length && j == tchars.length) { return true; } if (i == chars.length || j == tchars.length) { return false; } if (chars[i] != tchars[j]) { return false; } return matchedSimplified(chars, i + 1, tchars, j) || matchedSimplified( chars, i + 1, tchars, j + 1); } public static void main(String args[]) { runSample("hellp", true); runSample("heeelo", false); runSample("bbbiirrdd", true); runSample("greeeeat", true); runSample("cad", false); runSample("green", true); runSample("aaaata", false); runSample("poolllll", true); runSample("leeet", true); runSample("let", true); } static void runSample(String s, boolean expected) { System.out.printf("%s = %s and %s (expected: %s)\n", s, wordTypedByStuckKeys(s, DICT), wordTypedByStuckKeysWithMap(s, DICT), expected); } static class TrieNode { Map<Character, TrieNode> children = new HashMap<>(); boolean isWord = false; static TrieNode build(List<String> strs) { TrieNode root = new TrieNode(); for (String s: strs) { TrieNode node = root; for (char c: s.toCharArray()) { if (node.children.containsKey(c)) { node = node.children.get(c); } else { TrieNode newNode = new TrieNode(); node.children.put(c, newNode); node = newNode; } } node.isWord = true; } return root; } boolean isInTrie(String s) { TrieNode n = this; for (char c: s.toCharArray()) { if (!n.children.containsKey(c)) { return false; } n = n.children.get(c); } return n.isWord; } boolean isInTrieForStucked(String s) { return isInTrieForStucked(s.toCharArray(), 0); } boolean isInTrieForStucked(char[] chars, int i) { if (i == chars.length) { return isWord; } char c = chars[i]; if (!children.containsKey(c)) { return false; } return isInTrieForStucked(chars, i + 1) || children.get(c).isInTrieForStucked(chars, i + 1); } } }
package edu.stuy.starlorn.util; import edu.stuy.starlorn.world.Path; import edu.stuy.starlorn.world.Wave; import edu.stuy.starlorn.world.Level; import edu.stuy.starlorn.entities.EnemyShip; public class Generator { public static Path generatePath(int numPoints) { Path p = new Path(); int screenWidth = 100; int screenHeight = 100; for (int i = 0; i < numPoints; i++) { int x = (int) (Math.random() * screenWidth); int y = (int) (Math.random() * screenHeight); p.addCoords(x, y); } return p; } public static Path generatePath() { return generatePath(10); } public static Wave generateWave(int dificulty) { Wave wave = new Wave(); int numEnemies = (int) (Math.random() * dificulty * dificulty); EnemyShip enemyType = generateEnemy(dificulty); Path path = generatePath(); wave.setPath(path); wave.setEnemyType(enemyType); wave.setNumEnemies(numEnemies); return wave; } public static Wave generateWave() { return generateWave(1); } public static Level generateLevel(int numWaves, int dificulty) { Level level = new Level(); for (int i = 0; i < numWaves; i++) { level.addWave(generateWave(dificulty)); } return level; } public static Level generateLevel() { return generateLevel(1, 1); } public static EnemyShip generateEnemy(int dificulty) { EnemyShip enemy = new EnemyShip(); Path path = generatePath(dificulty + 5); int damage = (int) (Math.random() * dificulty); int shotSpeed = (int) (Math.random() * dificulty); int health = (int) (Math.random() * dificulty * 10); int cooldown = (int) (Math.random() * (100 / dificulty) + 5); int cooldownRate = (int) (Math.random() * Math.log(dificulty)); // increase the cooldown rate logarithmically int movementSpeed = (int) (Math.random() * dificulty); enemy.setPath(path); enemy.setBaseDamage(damage); enemy.setBaseShotSpeed(shotSpeed); enemy.setMaxHealth(health); enemy.setCooldown(cooldown); enemy.setCooldownRate(cooldownRate); enemy.setMovementSpeed(movementSpeed); return enemy; } public static EnemyShip generateEnemy() { return generateEnemy(1); } }
package util; import java.io.IOException; import javafx.scene.image.Image; /** * * @author Rahul * */ public interface ILoadSave { /** * Load a resource from a given file and return Java object representation * * @param className * Java class object that is being loaded * @param filePath * that resource to be loaded from * @return Java class object */ public <T> T loadResource (Class className, String filePath); /** * Save a JSONable object to a library file * * @param object * that can be converted to JSON format * @param filePath * to which object should be saved * @throws IOException * in case of trouble reading */ public void save (JSONable object, String filePath) throws IOException; /** * Save an image to a particular file path * * @param image * @param filePath * @throws IOException */ public void saveImage (Image image, String filePath) throws IOException; /** * Load an image at given file path * * @param String * encoding of file path * @return Image object at that file path */ public Image loadImage (String filePath); }
package org.noear.weed; import org.noear.weed.cache.CacheUsing; import org.noear.weed.cache.ICacheController; import org.noear.weed.cache.ICacheService; import org.noear.weed.ext.Act1; import org.noear.weed.ext.Act2; import org.noear.weed.utils.StringUtils; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class DbTableQueryBase<T extends DbTableQueryBase> extends WhereBase<T> implements ICacheController<DbTableQueryBase> { String _table_raw; String _table; SQLBuilder _builder_bef; int _isLog=0; public DbTableQueryBase(DbContext context) { super(context); _builder_bef = new SQLBuilder(); } public T log(boolean isLog) { _isLog = isLog ? 1 : -1; return (T) this; } /** * build * */ @Deprecated public T expre(Act1<T> action){ action.run((T)this); return (T)this; } public T build(Act1<T> builder){ builder.run((T)this); return (T)this; } protected T table(String table) { // from if (table.startsWith(" _table = table.substring(1); _table_raw = _table; } else { _table_raw = table; if (table.indexOf('.') > 0) { _table = table; } else { if (WeedConfig.isUsingSchemaPrefix && _context.schema() != null) { _table = fmtObject(_context.schema() + "." + table); } else { _table = fmtObject(table); //"$." + table; } } } return (T) this; } /** SQL with * * db.table("user u") * .with("a","select type num from group by type") * .where("u.type in(select a.type) and u.type2 in (select a.type)") * .select("u.*") * .getMapList(); * */ public T with(String name, String code, Object... args) { if (_builder_bef.length() < 6) { _builder_bef.append(" WITH "); }else{ _builder_bef.append("," ); } _builder_bef.append(fmtColumn(name)) .append(" AS (") .append(code, args) .append(") "); return (T) this; } public T with(String name, SelectQ select) { if (_builder_bef.length() < 6) { _builder_bef.append(" WITH "); }else{ _builder_bef.append("," ); } _builder_bef.append(fmtColumn(name)) .append(" AS (") .append(select) .append(") "); return (T) this; } /** FROM */ public T from(String table){ _builder.append(" FROM ").append(fmtObject(table)); return (T)this; } private T join(String style, String table) { if (table.startsWith(" _builder.append(style).append(table.substring(1)); } else { if (WeedConfig.isUsingSchemaPrefix && _context.schema() != null) { _builder.append(style).append(fmtObject(_context.schema() + "." + table)); } else { _builder.append(style).append(fmtObject(table)); } } return (T) this; } /** SQL */ public T innerJoin(String table) { return join(" INNER JOIN ",table); } /** SQL */ public T leftJoin(String table) { return join(" LEFT JOIN ",table); } /** SQL */ public T rightJoin(String table) { return join(" RIGHT JOIN ",table); } public T append(String code, Object... args){ _builder.append(code, args); return (T)this; } public T on(String code) { _builder.append(" ON ").append(code); return (T)this; } public T onEq(String column1, String column2) { _builder.append(" ON ").append(fmtColumn(column1)).append("=").append(fmtColumn(column2)); return (T) this; } /** dataBuilder */ public long insert(Act1<IDataItem> dataBuilder) throws SQLException { DataItem item = new DataItem(); dataBuilder.run(item); return insert(item); } /** data */ public long insert(IDataItem data) throws SQLException { if (data == null || data.count() == 0) { return 0; } List<Object> args = new ArrayList<Object>(); StringBuilder sb = StringUtils.borrowBuilder(); sb.append(" INSERT INTO ").append(_table).append(" ("); data.forEach((key, value) -> { if(value==null) { if(_usingNull == false) { return; } } sb.append(fmtColumn(key)).append(","); }); sb.deleteCharAt(sb.length() - 1); sb.append(") "); sb.append("VALUES"); sb.append("("); data.forEach((key, value) -> { if (value == null) { if(_usingNull) { sb.append("null,"); //null } } else { if (value instanceof String) { String val2 = (String) value; if (isSqlExpr(val2)) { //SQL sb.append(val2.substring(1)).append(","); } else { sb.append("?,"); args.add(value); } } else { sb.append("?,"); args.add(value); } } }); sb.deleteCharAt(sb.length() - 1); sb.append(")"); _builder.clear(); _builder.append(StringUtils.releaseBuilder(sb), args.toArray()); return compile().insert(); } public long insertBy(IDataItem data, String conditionFields) throws SQLException{ String[] ff = conditionFields.split(","); if (ff.length == 0) { throw new RuntimeException("Please enter constraints"); } this.where("1=1"); for (String f : ff) { this.andEq(f, data.get(f)); } if (this.exists()) { return 0; } return insert(data); } public boolean insertList(List<DataItem> valuesList) throws SQLException { if (valuesList == null) { return false; } return insertList(valuesList.get(0), valuesList); } /** dataBuilder */ public <T> boolean insertList(Collection<T> valuesList, Act2<T,DataItem> dataBuilder) throws SQLException { List<DataItem> list2 = new ArrayList<>(); for (T values : valuesList) { DataItem item = new DataItem(); dataBuilder.run(values, item); list2.add(item); } if (list2.size() > 0) { return insertList(list2.get(0), list2); }else{ return false; } } protected <T extends GetHandler> boolean insertList(IDataItem cols, Collection<T> valuesList)throws SQLException { if (valuesList == null || valuesList.size() == 0) { return false; } if (cols == null || cols.count() == 0) { return false; } _context.dbDialect() .insertList(_context, _table, _builder, this::isSqlExpr, cols, valuesList); return compile().execute() > 0; } /** data, * * upsertBy * */ @Deprecated public void updateExt(IDataItem data, String conditionFields) throws SQLException { upsertBy(data, conditionFields); } /** data, * * upsertBy * */ @Deprecated public long upsert(IDataItem data, String conditionFields) throws SQLException { return upsertBy(data,conditionFields); } /** * data, * */ public long upsertBy(IDataItem data, String conditionFields) throws SQLException { String[] ff = conditionFields.split(","); if (ff.length == 0) { throw new RuntimeException("Please enter constraints"); } this.where("1=1"); for (String f : ff) { this.andEq(f, data.get(f)); } if (this.exists()) { for (String f : ff) { data.remove(f); } return this.update(data); } else { return this.insert(data); } } /** dataBuilder */ public int update(Act1<IDataItem> dataBuilder) throws SQLException { DataItem item = new DataItem(); dataBuilder.run(item); return update(item); } /** set */ public int update(IDataItem data) throws SQLException{ if (data == null || data.count() == 0) { return 0; } List<Object> args = new ArrayList<Object>(); StringBuilder sb = StringUtils.borrowBuilder(); sb.append("UPDATE ").append(_table).append(" SET "); data.forEach((key,value)->{ if(value==null) { if (_usingNull) { sb.append(fmtColumn(key)).append("=null,"); } return; } if (value instanceof String) { String val2 = (String)value; if (isSqlExpr(val2)) { sb.append(fmtColumn(key)).append("=").append(val2.substring(1)).append(","); } else { sb.append(fmtColumn(key)).append("=?,"); args.add(value); } } else { sb.append(fmtColumn(key)).append("=?,"); args.add(value); } }); sb.deleteCharAt(sb.length() - 1); _builder.backup(); _builder.insert(StringUtils.releaseBuilder(sb), args.toArray()); if(WeedConfig.isUpdateMustConditional && _builder.indexOf(" WHERE ")<0){ throw new RuntimeException("Lack of update condition!!!"); } int rst = compile().execute(); _builder.restore(); return rst; } public int delete() throws SQLException { StringBuilder sb = StringUtils.borrowBuilder(); sb.append("DELETE "); if(_builder.indexOf(" FROM ")<0){ sb.append(" FROM ").append(_table); }else{ sb.append(_table); } _builder.insert(StringUtils.releaseBuilder(sb)); if(WeedConfig.isDeleteMustConditional && _builder.indexOf(" WHERE ")<0){ throw new RuntimeException("Lack of delete condition!!!"); } return compile().execute(); } protected int limit_start, limit_size; /** SQL paging */ public T limit(int start, int size) { limit_start = start; limit_size = size; //_builder.append(" LIMIT " + start + "," + rows + " "); return (T)this; } protected int limit_top = 0; /** SQL top */ public T limit(int size) { limit_top = size; //_builder.append(" LIMIT " + rows + " "); return (T)this; } /** SQL paging */ public T paging(int start, int size) { limit_start = start; limit_size = size; //_builder.append(" LIMIT " + start + "," + rows + " "); return (T)this; } /** SQL top */ public T top(int size) { limit_top = size; //_builder.append(" LIMIT " + rows + " "); return (T)this; } public boolean exists() throws SQLException { int bak = limit_top; limit(1); select_do(" 1 ", false); limit(bak); DbQuery rst = compile(); if (_cache != null) { rst.cache(_cache); } _builder.restore(); return rst.getValue() != null; } String _hint = null; public T hint(String hint){ _hint = hint; return (T)this; } public long count() throws SQLException{ return count("COUNT(*)"); } public long count(String code) throws SQLException{ return select(code).getVariate().longValue(0l); } public IQuery select(String columns) { select_do(columns, true); DbQuery rst = compile(); if(_cache != null){ rst.cache(_cache); } _builder.restore(); return rst; } public SelectQ selectQ(String columns) { select_do(columns, true); return new SelectQ(_builder); } private void select_do(String columns, boolean doFormat) { _builder.backup(); //1. xxx... FROM table StringBuilder sb = new StringBuilder(_builder.builder.length() + 100); sb.append(" "); if (doFormat) { sb.append(fmtMutColumns(columns)).append(" FROM ").append(_table); } else { sb.append(columns).append(" FROM ").append(_table); } sb.append(_builder.builder); _builder.builder = sb; if (limit_top > 0) { _context.dbDialect().selectTop(_context, _table_raw, _builder, _orderBy, limit_top); } else if (limit_size > 0) { _context.dbDialect().selectPage(_context, _table_raw, _builder, _orderBy, limit_start, limit_size); } else { _builder.insert(0, "SELECT "); if (_orderBy != null) { _builder.append(_orderBy); } } //3.hint if (_hint != null) { sb.append(_hint); _builder.insert(0, _hint); } //4.whith if (_builder_bef.length() > 0) { _builder.insert(_builder_bef); } } protected DbTran _tran = null; public T tran(DbTran transaction) { _tran = transaction; return (T)this; } public T tran() { _tran = _context.tran(); return (T)this; } //DbQuery private DbQuery compile() { DbQuery temp = new DbQuery(_context).sql(_builder); _builder.clear(); if(_tran!=null) { temp.tran(_tran); } return temp.onCommandBuilt((cmd)->{ cmd.isLog = _isLog; cmd.tag = _table; }); } private boolean _usingNull = WeedConfig.isUsingValueNull; /** null */ public T usingNull(boolean isUsing){ _usingNull = isUsing; return (T)this; } private boolean _usingExpression = WeedConfig.isUsingValueExpression; /** $sql */ public T usingExpr(boolean isUsing){ _usingExpression = isUsing; return (T)this; } private boolean isSqlExpr(String txt) { if (_usingExpression == false) { return false; } if (txt.startsWith("$") && txt.indexOf(" ") < 0 && txt.length() < 100) { //100 return true; } else { return false; } } protected CacheUsing _cache = null; public T caching(ICacheService service) { _cache = new CacheUsing(service); return (T)this; } public T usingCache (boolean isCache) { _cache.usingCache(isCache); return (T)this; } public T usingCache (int seconds) { _cache.usingCache(seconds); return (T)this; } public T cacheTag(String tag) { _cache.cacheTag(tag); return (T)this; } }
package com.xpn.xwiki.api; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.fileupload.FileItem; import org.apache.commons.lang.StringUtils; import org.suigeneris.jrcs.diff.DifferentiationFailedException; import org.suigeneris.jrcs.diff.delta.Delta; import org.suigeneris.jrcs.rcs.Version; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.criteria.impl.RevisionCriteria; import com.xpn.xwiki.doc.AttachmentDiff; import com.xpn.xwiki.doc.MetaDataDiff; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiDocumentArchive; import com.xpn.xwiki.doc.XWikiLink; import com.xpn.xwiki.doc.XWikiLock; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ObjectDiff; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.plugin.fileupload.FileUploadPlugin; import com.xpn.xwiki.stats.impl.DocumentStats; import com.xpn.xwiki.util.TOCGenerator; import com.xpn.xwiki.util.Util; public class Document extends Api { protected XWikiDocument doc; protected boolean cloned = false; protected Object currentObj; public Document(XWikiDocument doc, XWikiContext context) { super(context); this.doc = doc; } /** * this function is accessible only if you have the programming rights give access to the priviledged API of the * Document */ public XWikiDocument getDocument() { if (hasProgrammingRights()) { return this.doc; } else { return null; } } protected XWikiDocument getDoc() { if (!this.cloned) { this.doc = (XWikiDocument) this.doc.clone(); this.cloned = true; } return this.doc; } /** * return the ID of the document. this ID is uniq accross the wiki. * * @return the id of the document */ public long getId() { return this.doc.getId(); } /** * return the name of a document. for exemple if the fullName of a document is "MySpace.Mydoc", the name is MyDoc * * @return the name of the document */ public String getName() { return this.doc.getName(); } /** * return the name of the space of the document for example if the fullName of a document is "MySpace.Mydoc", the * name is MySpace * * @return the name of the space of the document */ public String getSpace() { return this.doc.getSpace(); } /** * @return the name of the wiki where this document is stored. * @since XWiki Core 1.1.2, XWiki Core 1.2M2 */ public String getWiki() { return this.doc.getDatabase(); } /** * return the name of the space of the document for exemple if the fullName of a document is "MySpace.Mydoc", the * name is MySpace * * @deprecated use {@link #getSpace()} instead of this function */ @Deprecated public String getWeb() { return this.doc.getSpace(); } /** * return the fullName of a document if a document has for name "MyDoc" and space "MySpace", the fullname is * "MySpace.MyDoc" In a wiki, all the documents have a different fullName. */ public String getFullName() { return this.doc.getFullName(); } /** * @return the real full name of a document containing wiki name where document is stored. For document in "xwiki" * wiki, with name "MyDoc" and space "MySpace" the extended full name is "xwiki:MySpace.MyDoc". * @since XWiki Core 1.1.2, XWiki Core 1.2M2 */ public String getPrefixedFullName() { return (getWiki() != null ? getWiki() + ":" : "") + getFullName(); } public Version getRCSVersion() { return this.doc.getRCSVersion(); } /** * return a String with the version of the document. */ public String getVersion() { return this.doc.getVersion(); } /** * return a String with the previous version of the document. */ public String getPreviousVersion() { return this.doc.getPreviousVersion(); } /** * return the title of a document */ public String getTitle() { return this.doc.getTitle(); } /** * @return the document title. If a title has not been provided, look for a section title in the document's content * and if not found return the page name. The returned title is also interpreted which means it's allowed to * use Velocity, Groovy, etc syntax within a title. */ public String getDisplayTitle() { return this.doc.getDisplayTitle(getXWikiContext()); } public String getFormat() { return this.doc.getFormat(); } /** * return the name of the last author of the document */ public String getAuthor() { return this.doc.getAuthor(); } /** * return the name of the last author of the content of the document */ public String getContentAuthor() { return this.doc.getContentAuthor(); } /** * return the modification date */ public Date getDate() { return this.doc.getDate(); } /** * return the date of the last modification of the content */ public Date getContentUpdateDate() { return this.doc.getContentUpdateDate(); } /** * return the date of the creation of the document */ public Date getCreationDate() { return this.doc.getCreationDate(); } /** * return the name of the parent document */ public String getParent() { return this.doc.getParent(); } /** * return the name of the creator of the document */ public String getCreator() { return this.doc.getCreator(); } /** * return the content of the document */ public String getContent() { return this.doc.getContent(); } /** * return the language of the document if it's a traduction, otherwise, it return default */ public String getLanguage() { return this.doc.getLanguage(); } public String getTemplate() { return this.doc.getTemplate(); } /** * return the real language of the document */ public String getRealLanguage() throws XWikiException { return this.doc.getRealLanguage(getXWikiContext()); } /** * return the language of the default document */ public String getDefaultLanguage() { return this.doc.getDefaultLanguage(); } public String getDefaultTemplate() { return this.doc.getDefaultTemplate(); } /** * return the comment of the latest update of the document */ public String getComment() { return this.doc.getComment(); } public boolean isMinorEdit() { return this.doc.isMinorEdit(); } /** * Return the list of existing translations for this document. */ public List<String> getTranslationList() throws XWikiException { return this.doc.getTranslationList(getXWikiContext()); } /** * return the translated document's content if the wiki is multilingual, the language is first checked in the URL, * the cookie, the user profile and finally the wiki configuration if not, the language is the one on the wiki * configuration */ public String getTranslatedContent() throws XWikiException { return this.doc.getTranslatedContent(getXWikiContext()); } /** * return the translated content in the given language */ public String getTranslatedContent(String language) throws XWikiException { return this.doc.getTranslatedContent(language, getXWikiContext()); } /** * return the translated document in the given document */ public Document getTranslatedDocument(String language) throws XWikiException { return this.doc.getTranslatedDocument(language, getXWikiContext()).newDocument(getXWikiContext()); } /** * return the tranlated Document if the wiki is multilingual, the language is first checked in the URL, the cookie, * the user profile and finally the wiki configuration if not, the language is the one on the wiki configuration */ public Document getTranslatedDocument() throws XWikiException { return this.doc.getTranslatedDocument(getXWikiContext()).newDocument(getXWikiContext()); } /** * return the content of the document rendererd */ public String getRenderedContent() throws XWikiException { return this.doc.getRenderedContent(getXWikiContext()); } /** * @param text the text to render * @return the given text rendered in the context of this document * @deprecated since 1.6M1 use {@link #getRenderedContent(String, String)} */ @Deprecated public String getRenderedContent(String text) throws XWikiException { return this.doc.getRenderedContent(text, getXWikiContext()); } /** * @param text the text to render * @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0") * @return the given text rendered in the context of this document using the passed Syntax * @since 1.6M1 */ public String getRenderedContent(String text, String syntaxId) throws XWikiException { return this.doc.getRenderedContent(text, syntaxId, getXWikiContext()); } /** * return a escaped version of the content of this document */ public String getEscapedContent() throws XWikiException { return this.doc.getEscapedContent(getXWikiContext()); } /** * return the archive of the document in a string format */ public String getArchive() throws XWikiException { return this.doc.getDocumentArchive(getXWikiContext()).getArchive(getXWikiContext()); } /** * this function is accessible only if you have the programming rights return the archive of the document */ public XWikiDocumentArchive getDocumentArchive() throws XWikiException { if (hasProgrammingRights()) { return this.doc.getDocumentArchive(getXWikiContext()); } return null; } /** * @return true if the document is a new one (ie it has never been saved) or false otherwise */ public boolean isNew() { return this.doc.isNew(); } /** * return the URL of download for the the given attachment name * * @param filename the name of the attachment * @return A String with the URL */ public String getAttachmentURL(String filename) { return this.doc.getAttachmentURL(filename, "download", getXWikiContext()); } /** * return the URL of the given action for the the given attachment name * * @return A string with the URL */ public String getAttachmentURL(String filename, String action) { return this.doc.getAttachmentURL(filename, action, getXWikiContext()); } /** * return the URL of the given action for the the given attachment name with "queryString" parameters * * @param queryString parameters added to the URL */ public String getAttachmentURL(String filename, String action, String queryString) { return this.doc.getAttachmentURL(filename, action, queryString, getXWikiContext()); } /** * return the URL for accessing to the archive of the attachment "filename" at the version "version" */ public String getAttachmentRevisionURL(String filename, String version) { return this.doc.getAttachmentRevisionURL(filename, version, getXWikiContext()); } /** * return the URL for accessing to the archive of the attachment "filename" at the version "version" and with the * given queryString parameters */ public String getAttachmentRevisionURL(String filename, String version, String querystring) { return this.doc.getAttachmentRevisionURL(filename, version, querystring, getXWikiContext()); } /** * return the URL of this document in view mode */ public String getURL() { return this.doc.getURL("view", getXWikiContext()); } /** * return the URL of this document with the given action */ public String getURL(String action) { return this.doc.getURL(action, getXWikiContext()); } /** * return the URL of this document with the given action and queryString as parameters */ public String getURL(String action, String querystring) { return this.doc.getURL(action, querystring, getXWikiContext()); } /** * return the full URL of the document */ public String getExternalURL() { return this.doc.getExternalURL("view", getXWikiContext()); } /** * return the full URL of the document for the given action */ public String getExternalURL(String action) { return this.doc.getExternalURL(action, getXWikiContext()); } public String getExternalURL(String action, String querystring) { return this.doc.getExternalURL(action, querystring, getXWikiContext()); } public String getParentURL() throws XWikiException { return this.doc.getParentURL(getXWikiContext()); } public Class getxWikiClass() { BaseClass bclass = this.doc.getxWikiClass(); if (bclass == null) { return null; } else { return new Class(bclass, getXWikiContext()); } } public Class[] getxWikiClasses() { List<BaseClass> list = this.doc.getxWikiClasses(getXWikiContext()); if (list == null) { return null; } Class[] result = new Class[list.size()]; for (int i = 0; i < list.size(); i++) { result[i] = new Class(list.get(i), getXWikiContext()); } return result; } public int createNewObject(String classname) throws XWikiException { return getDoc().createNewObject(classname, getXWikiContext()); } public Object newObject(String classname) throws XWikiException { int nb = createNewObject(classname); return getObject(classname, nb); } public boolean isFromCache() { return this.doc.isFromCache(); } public int getObjectNumbers(String classname) { return this.doc.getObjectNumbers(classname); } public Map<String, Vector<Object>> getxWikiObjects() { Map<String, Vector<BaseObject>> map = this.doc.getxWikiObjects(); Map<String, Vector<Object>> resultmap = new HashMap<String, Vector<Object>>(); for (String name : map.keySet()) { Vector<BaseObject> objects = map.get(name); if (objects != null) { resultmap.put(name, getObjects(objects)); } } return resultmap; } protected Vector<Object> getObjects(Vector<BaseObject> objects) { Vector<Object> result = new Vector<Object>(); if (objects == null) { return result; } for (BaseObject bobj : objects) { if (bobj != null) { result.add(newObjectApi(bobj, getXWikiContext())); } } return result; } public Vector<Object> getObjects(String classname) { Vector<BaseObject> objects = this.doc.getObjects(classname); return getObjects(objects); } public Object getFirstObject(String fieldname) { try { BaseObject obj = this.doc.getFirstObject(fieldname, getXWikiContext()); if (obj == null) { return null; } else { return newObjectApi(obj, getXWikiContext()); } } catch (Exception e) { return null; } } public Object getObject(String classname, String key, String value, boolean failover) { try { BaseObject obj = this.doc.getObject(classname, key, value, failover); if (obj == null) { return null; } else { return newObjectApi(obj, getXWikiContext()); } } catch (Exception e) { return null; } } /** * Select a subset of objects from a given class, filtered on a "key = value" criteria. * * @param classname The type of objects to return. * @param key The name of the property used for filtering. * @param value The required value. * @return A Vector of {@link Object objects} matching the criteria. If no objects are found, or if the key is an * empty String, then an empty vector is returned. */ public Vector<Object> getObjects(String classname, String key, String value) { Vector<Object> result = new Vector<Object>(); if (StringUtils.isBlank(key) || value == null) { return getObjects(classname); } try { Vector<BaseObject> allObjects = this.doc.getObjects(classname); if (allObjects == null || allObjects.size() == 0) { return result; } else { for (BaseObject obj : allObjects) { if (obj != null) { BaseProperty prop = (BaseProperty) obj.get(key); if (prop == null || prop.getValue() == null) { continue; } if (value.equals(prop.getValue().toString())) { result.add(newObjectApi(obj, getXWikiContext())); } } } } } catch (Exception e) { } return result; } public Object getObject(String classname, String key, String value) { try { BaseObject obj = this.doc.getObject(classname, key, value); if (obj == null) { return null; } else { return newObjectApi(obj, getXWikiContext()); } } catch (Exception e) { return null; } } public Object getObject(String classname) { return getObject(classname, false); } /** * get the object of the given className. If there is no object of this className and the create parameter at true, * the object is created. */ public Object getObject(String classname, boolean create) { try { BaseObject obj = this.doc.getObject(classname, create, getXWikiContext()); if (obj == null) { return null; } else { return newObjectApi(obj, getXWikiContext()); } } catch (Exception e) { return null; } } public Object getObject(String classname, int nb) { try { BaseObject obj = this.doc.getObject(classname, nb); if (obj == null) { return null; } else { return newObjectApi(obj, getXWikiContext()); } } catch (Exception e) { return null; } } private Object newObjectApi(BaseObject obj, XWikiContext context) { return obj.newObjectApi(obj, context); } public String getXMLContent() throws XWikiException { String xml = this.doc.getXMLContent(getXWikiContext()); return getXWikiContext().getUtil().substitute( "s/<email>.*?<\\/email>/<email>********<\\/email>/goi", getXWikiContext().getUtil().substitute("s/<password>.*?<\\/password>/<password>********<\\/password>/goi", xml)); } public String toXML() throws XWikiException { if (hasProgrammingRights()) { return this.doc.toXML(getXWikiContext()); } else { return ""; } } public org.dom4j.Document toXMLDocument() throws XWikiException { if (hasProgrammingRights()) { return this.doc.toXMLDocument(getXWikiContext()); } else { return null; } } public Version[] getRevisions() throws XWikiException { return this.doc.getRevisions(getXWikiContext()); } public String[] getRecentRevisions() throws XWikiException { return this.doc.getRecentRevisions(5, getXWikiContext()); } public String[] getRecentRevisions(int nb) throws XWikiException { return this.doc.getRecentRevisions(nb, getXWikiContext()); } /** * Get document versions matching criterias like author, minimum creation date, etc. * * @param criteria criteria used to match versions * @return a list of matching versions */ public List<String> getRevisions(RevisionCriteria criteria) throws XWikiException { return this.doc.getRevisions(criteria, this.context); } /** * Get information about a document version : author, date, etc. * * @param version the version you want to get information about * @return a new RevisionInfo object */ public RevisionInfo getRevisionInfo(String version) throws XWikiException { return new RevisionInfo(this.doc.getRevisionInfo(version, getXWikiContext()), getXWikiContext()); } public List<Attachment> getAttachmentList() { List<Attachment> apis = new ArrayList<Attachment>(); for (XWikiAttachment attachment : this.doc.getAttachmentList()) { apis.add(new Attachment(this, attachment, getXWikiContext())); } return apis; } public Vector<Object> getComments() { return getComments(true); } public Vector<Object> getComments(boolean asc) { return getObjects(this.doc.getComments(asc)); } public void use(Object object) { this.currentObj = object; } public void use(String className) { this.currentObj = getObject(className); } public void use(String className, int nb) { this.currentObj = getObject(className, nb); } public String getActiveClass() { if (this.currentObj == null) { return null; } else { return this.currentObj.getName(); } } public String displayPrettyName(String fieldname) { if (this.currentObj == null) { return this.doc.displayPrettyName(fieldname, getXWikiContext()); } else { return this.doc.displayPrettyName(fieldname, this.currentObj.getBaseObject(), getXWikiContext()); } } public String displayPrettyName(String fieldname, Object obj) { if (obj == null) { return ""; } return this.doc.displayPrettyName(fieldname, obj.getBaseObject(), getXWikiContext()); } public String displayPrettyName(String fieldname, boolean showMandatory) { if (this.currentObj == null) { return this.doc.displayPrettyName(fieldname, showMandatory, getXWikiContext()); } else { return this.doc.displayPrettyName(fieldname, showMandatory, this.currentObj.getBaseObject(), getXWikiContext()); } } public String displayPrettyName(String fieldname, boolean showMandatory, Object obj) { if (obj == null) { return ""; } return this.doc.displayPrettyName(fieldname, showMandatory, obj.getBaseObject(), getXWikiContext()); } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before) { if (this.currentObj == null) { return this.doc.displayPrettyName(fieldname, showMandatory, before, getXWikiContext()); } else { return this.doc.displayPrettyName(fieldname, showMandatory, before, this.currentObj.getBaseObject(), getXWikiContext()); } } public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, Object obj) { if (obj == null) { return ""; } return this.doc.displayPrettyName(fieldname, showMandatory, before, obj.getBaseObject(), getXWikiContext()); } public String displayTooltip(String fieldname) { if (this.currentObj == null) { return this.doc.displayTooltip(fieldname, getXWikiContext()); } else { return this.doc.displayTooltip(fieldname, this.currentObj.getBaseObject(), getXWikiContext()); } } public String displayTooltip(String fieldname, Object obj) { if (obj == null) { return ""; } return this.doc.displayTooltip(fieldname, obj.getBaseObject(), getXWikiContext()); } public String display(String fieldname) { if (this.currentObj == null) { return this.doc.display(fieldname, getXWikiContext()); } else { return this.doc.display(fieldname, this.currentObj.getBaseObject(), getXWikiContext()); } } public String display(String fieldname, String mode) { if (this.currentObj == null) { return this.doc.display(fieldname, mode, getXWikiContext()); } else { return this.doc.display(fieldname, mode, this.currentObj.getBaseObject(), getXWikiContext()); } } public String display(String fieldname, String mode, String prefix) { if (this.currentObj == null) { return this.doc.display(fieldname, mode, prefix, getXWikiContext()); } else { return this.doc.display(fieldname, mode, prefix, this.currentObj.getBaseObject(), getXWikiContext()); } } public String display(String fieldname, Object obj) { if (obj == null) { return ""; } return this.doc.display(fieldname, obj.getBaseObject(), getXWikiContext()); } public String display(String fieldname, String mode, Object obj) { if (obj == null) { return ""; } return this.doc.display(fieldname, mode, obj.getBaseObject(), getXWikiContext()); } public String display(String fieldname, String mode, String prefix, Object obj) { if (obj == null) { return ""; } return this.doc.display(fieldname, mode, prefix, obj.getBaseObject(), getXWikiContext()); } public String displayForm(String className, String header, String format) { return this.doc.displayForm(className, header, format, getXWikiContext()); } public String displayForm(String className, String header, String format, boolean linebreak) { return this.doc.displayForm(className, header, format, linebreak, getXWikiContext()); } public String displayForm(String className) { return this.doc.displayForm(className, getXWikiContext()); } public String displayRendered(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) throws XWikiException { if ((pclass == null) || (object == null)) { return ""; } return this.doc.displayRendered(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext()); } public String displayView(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) { if ((pclass == null) || (object == null)) { return ""; } return this.doc.displayView(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext()); } public String displayEdit(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) { if ((pclass == null) || (object == null)) { return ""; } return this.doc.displayEdit(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext()); } public String displayHidden(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object) { if ((pclass == null) || (object == null)) { return ""; } return this.doc.displayHidden(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext()); } public List<String> getIncludedPages() { return this.doc.getIncludedPages(getXWikiContext()); } public List<String> getIncludedMacros() { return this.doc.getIncludedMacros(getXWikiContext()); } public List<String> getLinkedPages() { return this.doc.getLinkedPages(getXWikiContext()); } public Attachment getAttachment(String filename) { XWikiAttachment attach = this.doc.getAttachment(filename); if (attach == null) { return null; } else { return new Attachment(this, attach, getXWikiContext()); } } public List<Delta> getContentDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getContentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getContentDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getContentDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CONTENT_ERROR, "Error while making content diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<Delta> getXMLDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getXMLDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getXMLDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getXMLDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_XML_ERROR, "Error while making xml diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<Delta> getRenderedContentDiff(Document origdoc, Document newdoc) throws XWikiException, DifferentiationFailedException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getRenderedContentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getRenderedContentDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc .getName()), getXWikiContext()); } return this.doc.getRenderedContentDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_RENDERED_ERROR, "Error while making rendered diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<MetaDataDiff> getMetaDataDiff(Document origdoc, Document newdoc) throws XWikiException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getMetaDataDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getMetaDataDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getMetaDataDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_METADATA_ERROR, "Error while making meta data diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<List<ObjectDiff>> getObjectDiff(Document origdoc, Document newdoc) throws XWikiException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getObjectDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getObjectDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getObjectDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_OBJECT_ERROR, "Error while making meta object diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<List<ObjectDiff>> getClassDiff(Document origdoc, Document newdoc) throws XWikiException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getClassDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getClassDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getClassDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CLASS_ERROR, "Error while making class diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<AttachmentDiff> getAttachmentDiff(Document origdoc, Document newdoc) throws XWikiException { try { if ((origdoc == null) && (newdoc == null)) { return Collections.emptyList(); } if (origdoc == null) { return this.doc.getAttachmentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc, getXWikiContext()); } if (newdoc == null) { return this.doc.getAttachmentDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext()); } return this.doc.getAttachmentDiff(origdoc.doc, newdoc.doc, getXWikiContext()); } catch (Exception e) { java.lang.Object[] args = {(origdoc != null) ? origdoc.getFullName() : null, (origdoc != null) ? origdoc.getVersion() : null, (newdoc != null) ? newdoc.getVersion() : null}; List list = new ArrayList(); XWikiException xe = new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_ATTACHMENT_ERROR, "Error while making attachment diff of {0} between version {1} and version {2}", e, args); String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext()); list.add(errormsg); return list; } } public List<Delta> getLastChanges() throws XWikiException, DifferentiationFailedException { return this.doc.getLastChanges(getXWikiContext()); } public DocumentStats getCurrentMonthPageStats(String action) { return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getDocMonthStats(this.doc.getFullName(), action, new Date(), getXWikiContext()); } public DocumentStats getCurrentMonthWebStats(String action) { return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getDocMonthStats(this.doc.getSpace(), action, new Date(), getXWikiContext()); } public List getCurrentMonthRefStats() throws XWikiException { return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getRefMonthStats(this.doc.getFullName(), new Date(), getXWikiContext()); } public boolean checkAccess(String right) { try { return getXWikiContext().getWiki().checkAccess(right, this.doc, getXWikiContext()); } catch (XWikiException e) { return false; } } public boolean hasAccessLevel(String level) { try { return getXWikiContext().getWiki().getRightService().hasAccessLevel(level, getXWikiContext().getUser(), this.doc.getFullName(), getXWikiContext()); } catch (Exception e) { return false; } } @Override public boolean hasAccessLevel(String level, String user) { try { return getXWikiContext().getWiki().getRightService().hasAccessLevel(level, user, this.doc.getFullName(), getXWikiContext()); } catch (Exception e) { return false; } } public boolean getLocked() { try { XWikiLock lock = this.doc.getLock(getXWikiContext()); if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) { return true; } else { return false; } } catch (Exception e) { return false; } } public String getLockingUser() { try { XWikiLock lock = this.doc.getLock(getXWikiContext()); if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) { return lock.getUserName(); } else { return ""; } } catch (XWikiException e) { return ""; } } public Date getLockingDate() { try { XWikiLock lock = this.doc.getLock(getXWikiContext()); if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) { return lock.getDate(); } else { return null; } } catch (XWikiException e) { return null; } } public java.lang.Object get(String classOrFieldName) { if (this.currentObj != null) { return this.doc.display(classOrFieldName, this.currentObj.getBaseObject(), getXWikiContext()); } BaseObject object = this.doc.getFirstObject(classOrFieldName, getXWikiContext()); if (object != null) { return this.doc.display(classOrFieldName, object, getXWikiContext()); } return this.doc.getObject(classOrFieldName); } public java.lang.Object getValue(String fieldName) { Object object; if (this.currentObj == null) { object = new Object(this.doc.getFirstObject(fieldName, getXWikiContext()), getXWikiContext()); } else { object = this.currentObj; } return getValue(fieldName, object); } public java.lang.Object getValue(String fieldName, Object object) { if (object != null) { try { return ((BaseProperty) object.getBaseObject().safeget(fieldName)).getValue(); } catch (NullPointerException e) { return null; } } return null; } public String getTextArea() { return com.xpn.xwiki.XWiki.getTextArea(this.doc.getContent(), getXWikiContext()); } /** * Returns data needed for a generation of Table of Content for this document. * * @param init an intial level where the TOC generation should start at * @param max maximum level TOC is generated for * @param numbered if should generate numbering for headings * @return a map where an heading (title) ID is the key and value is another map with two keys: text, level and * numbering */ public Map getTOC(int init, int max, boolean numbered) { getXWikiContext().put("tocNumbered", new Boolean(numbered)); return TOCGenerator.generateTOC(getContent(), init, max, numbered, getXWikiContext()); } public String getTags() { return this.doc.getTags(getXWikiContext()); } public List<String> getTagList() { return this.doc.getTagsList(getXWikiContext()); } public List getTagsPossibleValues() { return this.doc.getTagsPossibleValues(getXWikiContext()); } public void insertText(String text, String marker) throws XWikiException { if (hasAccessLevel("edit")) { getDoc().insertText(text, marker, getXWikiContext()); } } @Override public boolean equals(java.lang.Object arg0) { if (!(arg0 instanceof Document)) { return false; } Document d = (Document) arg0; return d.getXWikiContext().equals(getXWikiContext()) && this.doc.equals(d.doc); } public List<String> getBacklinks() throws XWikiException { return this.doc.getBacklinks(getXWikiContext()); } public List<XWikiLink> getLinks() throws XWikiException { return this.doc.getLinks(getXWikiContext()); } public String getDefaultEditURL() throws XWikiException { return this.doc.getDefaultEditURL(getXWikiContext()); } public String getEditURL(String action, String mode) throws XWikiException { return this.doc.getEditURL(action, mode, getXWikiContext()); } public String getEditURL(String action, String mode, String language) { return this.doc.getEditURL(action, mode, language, getXWikiContext()); } public boolean isCurrentUserCreator() { return this.doc.isCurrentUserCreator(getXWikiContext()); } public boolean isCurrentUserPage() { return this.doc.isCurrentUserPage(getXWikiContext()); } public boolean isCurrentLocalUserPage() { return this.doc.isCurrentLocalUserPage(getXWikiContext()); } public boolean isCreator(String username) { return this.doc.isCreator(username); } public void set(String fieldname, java.lang.Object value) { Object obj; if (this.currentObj != null) { obj = this.currentObj; } else { obj = getFirstObject(fieldname); } set(fieldname, value, obj); } public void set(String fieldname, java.lang.Object value, Object obj) { if (obj == null) { return; } obj.set(fieldname, value); } public void setTitle(String title) { getDoc().setTitle(title); } public void setCustomClass(String customClass) { getDoc().setCustomClass(customClass); } public void setParent(String parent) { getDoc().setParent(parent); } public void setContent(String content) { getDoc().setContent(content); } public void setSyntaxId(String syntaxId) { getDoc().setSyntaxId(syntaxId); } public void setDefaultTemplate(String dtemplate) { getDoc().setDefaultTemplate(dtemplate); } public void setComment(String comment) { getDoc().setComment(comment); } public void setMinorEdit(boolean isMinor) { getDoc().setMinorEdit(isMinor); } public void save() throws XWikiException { save("", false); } public void save(String comment) throws XWikiException { save(comment, false); } public void save(String comment, boolean minorEdit) throws XWikiException { if (hasAccessLevel("edit")) { saveDocument(comment, minorEdit); } else { java.lang.Object[] args = {this.doc.getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access denied in edit mode on document {0}", null, args); } } public void saveWithProgrammingRights() throws XWikiException { saveWithProgrammingRights("", false); } public void saveWithProgrammingRights(String comment) throws XWikiException { saveWithProgrammingRights(comment, false); } public void saveWithProgrammingRights(String comment, boolean minorEdit) throws XWikiException { if (hasProgrammingRights()) { saveDocument(comment, minorEdit); } else { java.lang.Object[] args = {this.doc.getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access denied with no programming rights document {0}", null, args); } } protected void saveDocument(String comment, boolean minorEdit) throws XWikiException { XWikiDocument doc = getDoc(); doc.setAuthor(this.context.getUser()); if (doc.isNew()) { doc.setCreator(this.context.getUser()); } getXWikiContext().getWiki().saveDocument(doc, comment, minorEdit, getXWikiContext()); this.cloned = false; } public com.xpn.xwiki.api.Object addObjectFromRequest() throws XWikiException { // Call to getDoc() ensures that we are working on a clone() return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(getXWikiContext()), getXWikiContext()); } public com.xpn.xwiki.api.Object addObjectFromRequest(String className) throws XWikiException { return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, getXWikiContext()), getXWikiContext()); } public List<Object> addObjectsFromRequest(String className) throws XWikiException { return addObjectsFromRequest(className, ""); } public com.xpn.xwiki.api.Object addObjectFromRequest(String className, String prefix) throws XWikiException { return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, prefix, getXWikiContext()), getXWikiContext()); } public List<Object> addObjectsFromRequest(String className, String prefix) throws XWikiException { List<BaseObject> objs = getDoc().addObjectsFromRequest(className, prefix, getXWikiContext()); List<Object> wrapped = new ArrayList<Object>(); for (BaseObject object : objs) { wrapped.add(new com.xpn.xwiki.api.Object(object, getXWikiContext())); } return wrapped; } public com.xpn.xwiki.api.Object updateObjectFromRequest(String className) throws XWikiException { return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, getXWikiContext()), getXWikiContext()); } public List<Object> updateObjectsFromRequest(String className) throws XWikiException { return updateObjectsFromRequest(className, ""); } public com.xpn.xwiki.api.Object updateObjectFromRequest(String className, String prefix) throws XWikiException { return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, prefix, getXWikiContext()), getXWikiContext()); } public List<Object> updateObjectsFromRequest(String className, String prefix) throws XWikiException { List<BaseObject> objs = getDoc().updateObjectsFromRequest(className, prefix, getXWikiContext()); List<Object> wrapped = new ArrayList<Object>(); for (BaseObject object : objs) { wrapped.add(new com.xpn.xwiki.api.Object(object, getXWikiContext())); } return wrapped; } public boolean isAdvancedContent() { return this.doc.isAdvancedContent(); } public boolean isProgrammaticContent() { return this.doc.isProgrammaticContent(); } public boolean removeObject(Object obj) { return getDoc().removeObject(obj.getBaseObject()); } public boolean removeObjects(String className) { return getDoc().removeObjects(className); } /** * Remove document from the wiki. Reinit <code>cloned</code>. * * @throws XWikiException */ protected void deleteDocument() throws XWikiException { getXWikiContext().getWiki().deleteDocument(this.doc, getXWikiContext()); this.cloned = false; } public void delete() throws XWikiException { if (hasAccessLevel("delete")) { deleteDocument(); } else { java.lang.Object[] args = {this.doc.getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access denied in edit mode on document {0}", null, args); } } public void deleteWithProgrammingRights() throws XWikiException { if (hasProgrammingRights()) { deleteDocument(); } else { java.lang.Object[] args = {this.doc.getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access denied with no programming rights document {0}", null, args); } } public String getVersionHashCode() { return this.doc.getVersionHashCode(getXWikiContext()); } public int addAttachments() throws XWikiException { return addAttachments(null); } public int addAttachments(String fieldName) throws XWikiException { if (!hasAccessLevel("edit")) { java.lang.Object[] args = {this.doc.getFullName()}; throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED, "Access denied in edit mode on document {0}", null, args); } XWiki xwiki = getXWikiContext().getWiki(); FileUploadPlugin fileupload = (FileUploadPlugin) xwiki.getPlugin("fileupload", getXWikiContext()); List<FileItem> fileuploadlist = fileupload.getFileItems(getXWikiContext()); List<XWikiAttachment> attachments = new ArrayList<XWikiAttachment>(); // adding attachment list to context so we find the names this.context.put("addedAttachments", attachments); int nb = 0; if (fileuploadlist == null) { return 0; } for (FileItem item : fileuploadlist) { String name = item.getFieldName(); if (fieldName != null && !fieldName.equals(name)) { continue; } if (item.isFormField()) { continue; } byte[] data = fileupload.getFileItemData(name, getXWikiContext()); String filename; String fname = fileupload.getFileName(name, getXWikiContext()); int i = fname.lastIndexOf("\\"); if (i == -1) { i = fname.lastIndexOf("/"); } filename = fname.substring(i + 1); filename = filename.replaceAll("\\+", " "); if ((data != null) && (data.length > 0)) { XWikiAttachment attachment = this.doc.addAttachment(filename, data, getXWikiContext()); getDoc().saveAttachmentContent(attachment, getXWikiContext()); // commenting because this was already done by addAttachment // getDoc().getAttachmentList().add(attachment); attachments.add(attachment); nb++; } } if (nb > 0) { getXWikiContext().getWiki().saveDocument(getDoc(), getXWikiContext()); this.cloned = false; } return nb; } public Attachment addAttachment(String fileName, InputStream iStream) { try { return new Attachment(this, this.doc.addAttachment(fileName, iStream, getXWikiContext()), getXWikiContext()); } catch (XWikiException e) { // TODO Log the error and let the user know about it } catch (IOException e) { // TODO Log the error and let the user know about it } return null; } public Attachment addAttachment(String fileName, byte[] data) { try { return new Attachment(this, this.doc.addAttachment(fileName, data, getXWikiContext()), getXWikiContext()); } catch (XWikiException e) { // TODO Log the error and let the user know about it } return null; } public boolean validate() throws XWikiException { return this.doc.validate(getXWikiContext()); } public boolean validate(String[] classNames) throws XWikiException { return this.doc.validate(classNames, getXWikiContext()); } /** * Retrieves the validation script associated with this document, a Velocity script that is executed when validating * the document data. * * @return A <code>String</code> representation of the validation script, or an empty string if there is no such * script. */ public String getValidationScript() { return getDoc().getValidationScript(); } /** * Sets a new validation script for this document, a Velocity script that is executed when validating the document * data. * * @param validationScript The new validation script, which can be an empty string or <code>null</code> if the * script should be removed. */ public void setValidationScript(String validationScript) { getDoc().setValidationScript(validationScript); } /** * @deprecated use {@link #rename(String)} instead */ @Deprecated public void renameDocument(String newDocumentName) throws XWikiException { rename(newDocumentName); } /** * Rename the current document and all the backlinks leading to it. See * {@link #renameDocument(String, java.util.List)} for more details. * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @throws XWikiException in case of an error */ public void rename(String newDocumentName) throws XWikiException { this.doc.rename(newDocumentName, getXWikiContext()); } /** * @deprecated use {@link #rename(String, java.util.List)} instead */ @Deprecated public void renameDocument(String newDocumentName, List<String> backlinkDocumentNames) throws XWikiException { rename(newDocumentName, backlinkDocumentNames); } /** * Rename the current document and all the links pointing to it in the list of passed backlink documents. The * renaming algorithm takes into account the fact that there are several ways to write a link to a given page and * all those forms need to be renamed. For example the following links all point to the same page: * <ul> * <li>[Page]</li> * <li>[Page?param=1]</li> * <li>[currentwiki:Page]</li> * <li>[CurrentSpace.Page]</li> * </ul> * <p> * Note: links without a space are renamed with the space added. * </p> * * @param newDocumentName the new document name. If the space is not specified then defaults to the current space. * @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the * new renamed document. * @throws XWikiException in case of an error */ public void rename(String newDocumentName, List<String> backlinkDocumentNames) throws XWikiException { this.doc.rename(newDocumentName, backlinkDocumentNames, getXWikiContext()); } /** * Allow to easily access any revision of a document * * @param revision version to access * @return Document object * @throws XWikiException */ public Document getDocumentRevision(String revision) throws XWikiException { return new Document(this.context.getWiki().getDocument(this.doc, revision, this.context), this.context); } /** * Allow to easily access the previous revision of a document * * @return Document * @throws XWikiException */ public Document getPreviousDocument() throws XWikiException { return getDocumentRevision(getPreviousVersion()); } /** * @return is document most recent. false if and only if there are older versions of this document. */ public boolean isMostRecent() { return this.doc.isMostRecent(); } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return this.doc.toString(); } /** * @return the Syntax id representing the syntax used for the current document. For example "xwiki/1.0" represents * the first version XWiki syntax while "xwiki/2.0" represents version 2.0 of the XWiki Syntax. */ public String getSyntaxId() { return this.doc.getSyntaxId(); } /** * Convert the current document content from its current syntax to the new syntax passed as parameter. * * @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc) * @throws XWikiException if an exception occurred during the conversion process */ public boolean convertSyntax(String targetSyntaxId) throws XWikiException { try { this.doc.convertSyntax(targetSyntaxId); } catch (Exception ex) { return false; } return true; } }
package agents; import city.City; import city.DropoffPoint; import jade.core.Agent; import jade.wrapper.AgentController; import jade.wrapper.ContainerController; import jade.wrapper.StaleProxyException; import javafx.beans.binding.ObjectExpression; import utils.misc.Shift; import java.util.logging.Level; import java.util.logging.Logger; public class TaxiCompany extends Agent { int totalTaxis; int totalCalls; City city; public TaxiCompany(City city){ this.city = city; totalTaxis = 0; totalCalls = 0; String[] arg = {"-gui", "-agents" ,"test:AgentTest"}; jade.Boot.main(arg); } public void addTaxi(DropoffPoint point, Shift shift){ Object[] params = {this.city,point,shift}; ContainerController cc = getContainerController(); try { AgentController new_agent = cc.createNewAgent("smith" + totalTaxis, "agents.Taxi", params); new_agent.start(); } catch (StaleProxyException ex) { Logger.getLogger(TaxiCompany.class.getName()).log(Level.SEVERE, null, ex); } } public void generateSampleTaxis(){ //Gene for(int i=1;i<=4;i++){ this.addTaxi(new DropoffPoint(this.city.taxiCenter),Shift.TIME_3AM_TO_1PM); } for(int i=1;i<=4;i++){ this.addTaxi(new DropoffPoint(this.city.taxiCenter),Shift.TIME_6PM_TO_4AM); } for(int i=1;i<=4;i++){ this.addTaxi(new DropoffPoint(this.city.taxiCenter),Shift.TIME_9AM_TO_7PM); } } public void startAction(){ } }
package com.jom; import cern.colt.list.tdouble.DoubleArrayList; import cern.colt.list.tint.IntArrayList; import cern.colt.matrix.tdouble.DoubleMatrix1D; import cern.colt.matrix.tdouble.DoubleMatrix2D; import cern.colt.matrix.tint.IntFactory1D; import cern.colt.matrix.tint.IntMatrix1D; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map.Entry; public abstract class Expression { protected final OptimizationProblem model; protected final int numVarIds; //protected ExpressionCurvatureInfo curvature; protected _INTERNAL_AffineExpressionCoefs affineExp; protected int numScalarExpressions; protected int numDim; // reshaping can change this protected int[] size; // reshaping can change this private DoubleMatrixND cachedValueIfConstant; Expression(OptimizationProblem model) { this.model = model; this.numVarIds = model.getNumScalarDecisionVariables(); this.cachedValueIfConstant = null; this.affineExp = null; this.numDim = -1; this.numScalarExpressions = -1; this.size = null; } /* A constant scalar */ Expression(OptimizationProblem model, double constant) { this(model, new DoubleMatrixND(constant)); } /* A linear expression */ Expression(OptimizationProblem model, _INTERNAL_AffineExpressionCoefs affineExpression) { this.model = model; this.numVarIds = model.getNumScalarDecisionVariables(); this.size = affineExpression.getSize(); this.numScalarExpressions = IntMatrixND.prod(size); this.numDim = this.size.length; this.cachedValueIfConstant = null; if (this.numVarIds != affineExpression.getNumVarIds()) throw new JOMException("Wrong number of columns in coefs matrix"); if (this.numScalarExpressions != affineExpression.getNumScalarExpressions()) throw new JOMException("Wrong number of rows in coefs matrix"); this.affineExp = affineExpression; if (size.length < 2) throw new JOMException("1-D vectors are not allowed. Try row vectors or column vectors"); } /* General constructor to be called by overriding classes */ Expression(OptimizationProblem model, int[] size, _INTERNAL_AffineExpressionCoefs affineExpression) { this.model = model; this.numVarIds = model.getNumScalarDecisionVariables(); this.size = Arrays.copyOf(size, size.length); this.numScalarExpressions = IntMatrixND.prod(size); this.numDim = size.length; this.cachedValueIfConstant = null; this.affineExp = affineExpression; if (size.length < 2) throw new JOMException("1-D vectors are not allowed. Try row vectors or column vectors"); } /* A decision variable (and thus linear) */ Expression(OptimizationProblem model, _INTERNAL_DecisionVariableArray dv) { this(model, dv.getVarIds()); } /* A constant expression */ Expression(OptimizationProblem model, DoubleMatrixND constant) { this.model = model; this.numVarIds = model.getNumScalarDecisionVariables(); this.size = constant.getSize().toArray(); this.numScalarExpressions = IntMatrixND.prod(size); this.numDim = this.size.length; this.cachedValueIfConstant = constant.copy(); this.affineExp = new _INTERNAL_AffineExpressionCoefs(model, size, constant.elements().toArray()); if (size.length < 2) throw new JOMException("1-D vectors are not allowed. Try row vectors or column vectors"); } /* An array or subarray of decision variables */ Expression(OptimizationProblem model, IntMatrixND varIds) { this.model = model; this.numVarIds = model.getNumScalarDecisionVariables(); this.size = varIds.getSize().toArray(); this.numScalarExpressions = IntMatrixND.prod(size); this.numDim = this.size.length; this.cachedValueIfConstant = null; this.affineExp = new _INTERNAL_AffineExpressionCoefs(model, varIds); if (size.length < 2) throw new JOMException("1-D vectors are not allowed. Try row vectors or column vectors"); } static String toStringLinearScalarExpression(OptimizationProblem model, DoubleMatrix1D row) { double constant = row.get((int) row.size() - 1); String s = "" + constant; DoubleMatrix1D lCoefs = row.viewPart(0, (int) row.size() - 1); IntArrayList indexes = new IntArrayList(); DoubleArrayList values = new DoubleArrayList(); lCoefs.getNonZeros(indexes, values); indexes.trimToSize(); values.trimToSize(); for (int cont = 0; cont < indexes.size(); cont++) { int varId = indexes.get(cont); double coef = values.get(cont); _INTERNAL_DecisionVariableArray varInfo = model.getVarInfo(varId); String varName = varInfo.getName(); int indexInVariable = varId - varInfo.getFirstVarId(); IntMatrix1D subindexesInVariable = IntMatrixND.ind2sub(indexInVariable, varInfo.getSize()); s = s + " + " + coef + "" + varName + Arrays.toString(subindexesInVariable.toArray()); } return s; } /** Evaluates this expression. The expression should be a constant: do not depend from the decision variables * @return an array with the same size as the expression, with the values evaluated in each cell */ public final DoubleMatrixND evaluateConstant() { if (!this.isConstant()) throw new JOMException("The expression is not constant"); if (cachedValueIfConstant != null) return cachedValueIfConstant.copy(); this.cachedValueIfConstant = this.evaluate_internal(new double[this.numVarIds]); return cachedValueIfConstant.copy(); } /** Evaluates this expression, in the point provided by the decision variables. For those variables for which value is not provided, zeros are * assumed. * @param varNameVarValuePairs An even number of parameters, first in each pair is a String with the variable name, second a DoubleMatrixND * object with its value * @return an array with the same size as the expression, with the values evaluated in each cell */ public final DoubleMatrixND evaluate(Object... varNameVarValuePairs) { if (varNameVarValuePairs.length % 2 != 0) throw new JOMException("Wrong number of parameters"); double[] x = new double[this.model.getNumScalarDecisionVariables()]; for (int cont = 0; cont < varNameVarValuePairs.length / 2; cont++) { if (!(varNameVarValuePairs[cont * 2] instanceof String)) throw new JOMException("Variable name must be a String"); if (!(varNameVarValuePairs[cont * 2 + 1] instanceof DoubleMatrixND)) throw new JOMException("Value name must be a DoubleMatrixND " + "object"); String varName = (String) varNameVarValuePairs[cont * 2]; DoubleMatrixND val = (DoubleMatrixND) varNameVarValuePairs[cont * 2 + 1]; _INTERNAL_DecisionVariableArray dv = this.model.getDecisionVariable(varName); if (dv == null) throw new JOMException("Unknown decision variable name"); if (!dv.getSize().equals(val.getSize())) throw new JOMException("Wrong size of variable: '" + varName + "'"); double[] data = val.elements().toArray(); System.arraycopy(data, 0, x, dv.getFirstVarId(), data.length); } return this.evaluate_internal(x); } /** Evaluates the given cell in this expression. The expression should be a constant: do not depend from the decision variables * @param cellIndex Index of the constants that will be evaluated. * @return an array with the same size as the expression, with the values evaluated in each cell */ public final double evaluateConstant(int cellIndex) { if (!this.isConstant()) throw new JOMException("The expression is not constant"); return this.evaluate_internal(new double[this.numVarIds]).get(cellIndex); } final DoubleMatrix2D evaluateJacobian_internal(double[] valuesDVs) { if (!this.isLinear()) return this.nl_evaluateJacobian(valuesDVs); else return this.affineExp.getJacobian(); } /** Evaluates the jacobian of this expression, in the point provided by the decision variables. For those variables for which value is not * provided, zeros are assumed. * @param varNameVarValuePairs An even number of parameters, first in each pair is a String with the variable name, second a DoubleMatrixND * object with its value * @return a DoubleMatrix2D array representing the jacobian matrix, with one row for each cell in the expression (in the position of its linear * index), and one column per decision variable */ public final DoubleMatrix2D evaluateJacobian(Object... varNameVarValuePairs) { if (varNameVarValuePairs.length % 2 != 0) throw new JOMException("Wrong number of parameters"); double[] x = new double[this.model.getNumScalarDecisionVariables()]; for (int cont = 0; cont < varNameVarValuePairs.length / 2; cont++) { if (!(varNameVarValuePairs[cont * 2] instanceof String)) throw new JOMException("Variable name must be a String"); if (!(varNameVarValuePairs[cont * 2 + 1] instanceof DoubleMatrixND)) throw new JOMException("Value name must be a DoubleMatrixND " + "object"); String varName = (String) varNameVarValuePairs[cont * 2]; DoubleMatrixND val = (DoubleMatrixND) varNameVarValuePairs[cont * 2 + 1]; _INTERNAL_DecisionVariableArray dv = this.model.getDecisionVariable(varName); if (dv == null) throw new JOMException("Unknown decision variable name"); if (!dv.getSize().equals(val.getSize())) throw new JOMException("Wrong size of variable: " + varName); double[] data = val.elements().toArray(); System.arraycopy(data, 0, x, dv.getFirstVarId(), data.length); } return this.evaluateJacobian_internal(x); } /** Returns the number of dimensions in this expression * @return the number of dimensions */ public final int getNumDim() { return this.numDim; } /** Returns the number of cells (scalar expressions) inside this arrayed expression * @return the number of cells */ public final int getNumScalarExpressions() { return this.numScalarExpressions; } /** Returns true if the expression has two dimensions, and is a row (1xS) or column (Sx1) array. Returns false otherwise * @return true or false as stated above */ final boolean isRowOrColumn2DExpression() { if (this.numDim != 2) return false; return ((this.size[0] == 1) || (this.size[1] == 1)); } /** Returns true if the expression has two dimensions, and is a 1x1 expression (a scalar) * @return true or false as stated above */ public final boolean isScalar() { return ((this.numScalarExpressions == 1) && (this.numDim == 2)); } /** Returns true if the expression has two dimensions, is a 1x1 expression (a scalar), and also is constant (does not depend on the decision * variables) * @return true or false as stated above */ final boolean isScalarConstant() { return (isScalar() && isConstant()); } /** Resizes the array. The new size must have the same number of cells as the old one. The cell in index i in the old array has the same index * in the new. Cell values are NOT copied. * @param newSize the new size of the array */ final void reshape(int[] newSize) { if (IntMatrixND.prod(newSize) != this.numScalarExpressions) throw new JOMException("Reshaping an expression cannot change its number of elements"); this.size = newSize; this.numDim = this.size.length; if (this.affineExp != null) this.affineExp.reshape(newSize); } /** Returns the size of the array. The size array produced is a copy. * @return Array size. The i-th element in size indicates the size of the array in the corresponding dimension. */ public final int[] size() { return this.size; } /* A formatted String with information of the expression * * @see java.lang.Object#toString() */ @Override public String toString() { String s = "Expression " + ((this.isLinear()) ? "(linear)" : "(not linear)") + " size: " + Arrays.toString(size) + " (" + this.numScalarExpressions + " scalar expressions) , number variables " + "model: " + numVarIds + "\n"; if (!this.isLinear()) return s; for (int contCell = 0; contCell < this.numScalarExpressions; contCell++) { IntMatrix1D coord = IntMatrixND.ind2sub(contCell, IntFactory1D.dense.make(size)); s = s + " Cell " + Arrays.toString(coord.toArray()) + ": "; s = s + this.affineExp.getCellConstantCoef(contCell); LinkedHashMap<Integer, Double> c = this.affineExp.getScalarExpressionLinearCoefs(contCell); if (c != null) for (Entry<Integer, Double> e : c.entrySet()) { int thisActiveVarId = e.getKey(); double coef = e.getValue(); _INTERNAL_DecisionVariableArray vSet = model.getVarInfo(thisActiveVarId); int indexInVariable = thisActiveVarId - vSet.getFirstVarId(); IntMatrix1D coordInVariableThisCoef = IntMatrixND.ind2sub(indexInVariable, vSet.getSize()); s = s + " + " + coef + " * " + vSet.getName() + Arrays.toString(coordInVariableThisCoef.toArray()); } s = s + "\n"; } return s; } /* tries to evaluate the expression to a number if out of domain somewhere, or not numbers => exception */ /* This implementation works for linear function. To be overriden for other expressions */ final DoubleMatrixND evaluate_internal(double[] valuesDVs) { if (!this.isLinear()) return this.nl_evaluate(valuesDVs); // not lineal return this.affineExp.evaluate(valuesDVs); // linear } /** Returns the optimization problem object that is the framework where this expression was created * @return the optimization problem object */ public final OptimizationProblem getModel() { return model; } final int[] getSize() { return this.size; } final _INTERNAL_AffineExpressionCoefs getAffineExpression() { return this.affineExp; } void resize(int[] size) { this.size = size; this.numDim = size.length; this.numScalarExpressions = IntMatrixND.prod(size); if (this.numScalarExpressions < 0) throw new JOMException("Wrong size of Expression object"); // maybe because of a big number greater than Integer.MAX_VALUE creates this } /* TO BE IMPLEMENTED BY THE SUBCLASSES. CALLED WHEN THE EXPRESSION IS NOT LINEAR */ abstract DoubleMatrixND nl_evaluate(double[] valuesDVs); abstract DoubleMatrix2D nl_evaluateJacobian(double[] valuesDVs); abstract boolean isLinear(); abstract boolean isConstant(); abstract LinkedHashMap<Integer, HashSet<Integer>> nl_getActiveVarIds(); final LinkedHashMap<Integer, HashSet<Integer>> getActiveVarIds() { if (this.isLinear()) return this.affineExp.getNonZeroLinearCoefsCols(); else return this.nl_getActiveVarIds(); } }
package edu.pdx.spi; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import edu.pdx.spi.verticles.Deploy; import io.vertx.core.DeploymentOptions; import io.vertx.core.Verticle; import io.vertx.core.Vertx; import io.vertx.core.file.OpenOptions; import io.vertx.core.json.JsonObject; import java.io.IOException; import java.nio.file.*; final class Options { @JsonProperty String vertxHost; @JsonProperty Integer vertxPort; @JsonProperty Boolean sstore; @JsonProperty String sstoreClientHost; @JsonProperty Integer sstoreClientPort; @JsonProperty Boolean bigDawg; @JsonProperty String bigDawgRequestUrl; @JsonProperty int bigDawgRequestPort; @JsonProperty String bigDawgPollUrl; @JsonProperty int bigDawgPollPort; public Options() { this.vertxHost = "localhost"; this.vertxPort = 9999; this.sstore = false; this.sstoreClientHost = "localhost"; this.sstoreClientPort = 6000; this.bigDawg = false; this.bigDawgRequestUrl = ""; this.bigDawgRequestPort = 8080; this.bigDawgPollUrl = ""; this.bigDawgPollPort = 8080; } @Override public String toString() { return "Options{" + "vertxHost='" + vertxHost + '\'' + ", vertxPort=" + vertxPort + ", sstore=" + sstore + ", sstoreClientHost='" + sstoreClientHost + '\'' + ", sstoreClientPort=" + sstoreClientPort + ", bigDawg=" + bigDawg + ", bigDawgRequestUrl='" + bigDawgRequestUrl + '\'' + ", bigDawgRequestPort=" + bigDawgRequestPort + ", bigDawgPollUrl='" + bigDawgPollUrl + '\'' + ", bigDawgPollPort=" + bigDawgPollPort + '}'; } } public class Runner { public static void main(final String... args) { ObjectMapper om = new ObjectMapper(); DeploymentOptions deploymentOptions = new DeploymentOptions(); Options options = null; Path configFile = Paths.get("settings.json"); if (Files.exists(configFile)) { System.out.println("Found config"); try { options = om.readValue(Files.readAllBytes(configFile), Options.class); System.out.println(options); } catch (IOException e) { System.out.println("Error reading from local config. Using default."); } } else { options = new Options(); try { Files.write(configFile, om.writeValueAsBytes(options), StandardOpenOption.CREATE, StandardOpenOption.WRITE); } catch (IOException e) { System.out.println("Error writing new default config file."); } } Vertx vtx = Vertx.vertx(); Verticle deploy = new Deploy(); System.out.println("Starting deployment..."); try { vtx.deployVerticle(deploy, deploymentOptions.setConfig(new JsonObject(om.writeValueAsString(options)))); } catch (JsonProcessingException e) { System.out.println(e); } } }
package galvin; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; public final class StringUtils extends org.apache.commons.lang3.StringUtils { private StringUtils() { } public static String addLeadingZeroIfNecessary( int integer ) { if( integer < 10 ) { return "0" + integer; } else { return "" + integer; } } public static String appendIfNecessary( String target, String append ) { if( target.endsWith( append ) ) { return target; } else { return target + append; } } public static String capitalize( String word ) { if( word.length() > 0 ) { return word.substring( 0, 1 ).toUpperCase() + word.substring( 1, word.length() ); } else { return ""; } } public static String cat( List<String> strings ) { StringBuilder result = new StringBuilder(); if( strings != null ) { for( int i = 0; i < strings.size(); i++ ) { result.append( strings.get( i ) ); if( i + 1 < strings.size() ) { result.append( "\n" ); } } } return result.toString(); } public static String cat( String[] strings ) { StringBuilder result = new StringBuilder(); if( strings != null ) { for( int i = 0; i < strings.length; i++ ) { result.append( strings[i] ); if( i + 1 < strings.length ) { result.append( "\n" ); } } } return result.toString(); } public static String cat( String[] strings, String delimiter ) { StringBuilder result = new StringBuilder(); if( strings != null ) { for( int i = 0; i < strings.length; i++ ) { result.append( strings[i] ); if( i + 1 < strings.length ) { result.append( delimiter ); } } } return result.toString(); } public static String camelCase( String string ) { StringBuilder builder = new StringBuilder( string.length() ); string = string.toLowerCase(); boolean whitespaceMode = true; for( char c : string.toCharArray() ) { if( whitespaceMode ) { if( !Character.isWhitespace( c ) ) { c = Character.toUpperCase( c ); whitespaceMode = false; } } else { if( Character.isWhitespace( c ) ) { whitespaceMode = true; } } builder.append( c ); } return builder.toString(); } public static boolean contains( String[] array, String target ){ for( String string : array ){ if( target.equals( string ) ){ return true; } } return false; } public static String csv( Collection<String> strings ) { StringBuilder builder = new StringBuilder(); Iterator<String> iterator = strings.iterator(); while( iterator.hasNext() ) { String string = iterator.next(); builder.append( string ); if( iterator.hasNext() ) { builder.append( ", " ); } } return builder.toString(); } public static boolean isEmpty( String string ) { return empty( string ); } public static boolean empty( String string ) { return string == null || string.trim().length() == 0; } public static String getOrdinal( int number ) { String numberText = "" + number; if( number == 11 || number == 12 || number == 13 ) { return "th"; } else if( numberText.endsWith( "1" ) ) { return "st"; } else if( numberText.endsWith( "2" ) ) { return "nd"; } else if( numberText.endsWith( "3" ) ) { return "rd"; } else { return "th"; } } public static String markup( String text, String markup ) { return markup( text, markup, markup ); } public static String markup( String text, String startMarkup, String endMarkup ) { StringBuilder builder = new StringBuilder( startMarkup ); builder.append( text ); builder.append( endMarkup ); return builder.toString(); } public static String neverNull( String string ) { return ( string == null ? "" : string ); } public static String padTo( String string, int length ){ StringBuilder result = new StringBuilder(length); result.append(string); int diff = length - string.length(); for(int i = 0; i < diff; i++ ){ result.append( " " ); } return result.toString(); } public static String replaceAll( String target, String oldText, String newText ) { return replaceAll( target, oldText, newText, false ); } public static String replaceAll( String target, String oldText, String newText, boolean ignorCase ) { if( target != null && oldText != null && newText != null ) { StringBuilder result = new StringBuilder( target ); replaceAll( result, oldText, newText ); return result.toString(); } else { return target; } } public static String replaceAll( StringBuilder target, String oldText, String newText ) { replaceAll( target, oldText, newText, false ); return target.toString(); } public static int replaceAll( StringBuilder target, String oldText, String newText, boolean ignorCase ) { int count = 0; if( target != null && oldText != null && newText != null ) { if( ignorCase ) { StringBuilder noCaseTarget = new StringBuilder( target.toString().toLowerCase() ); String noCaseOldText = oldText.toLowerCase(); int index = noCaseTarget.indexOf( noCaseOldText ); while( index != -1 ) { count++; int endIndex = index + oldText.length(); target.replace( index, endIndex, newText ); noCaseTarget.replace( index, endIndex, newText ); endIndex = index + newText.length(); index = noCaseTarget.indexOf( noCaseOldText, endIndex ); } } else { int index = target.indexOf( oldText ); while( index != -1 ) { count++; int endIndex = index + oldText.length(); target.replace( index, endIndex, newText ); endIndex = index + newText.length(); index = target.indexOf( oldText, endIndex ); } } } return count; } public static String reverseChars( String target ) { byte[] bytes = target.getBytes(); byte[] result = new byte[ bytes.length ]; for( int i = 0; i < bytes.length; i++ ) { result[( bytes.length - i - 1 )] = bytes[i]; } return new String( result ); } public static String rot13( String s ) { //'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' //'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM' if( s != null ) { if( s.length() > 0 ) { int length = s.length(); StringBuilder buffer = new StringBuilder( length ); for( int i = 0; i < length; i++ ) { char c = s.charAt( i ); if( c >= 'a' && c <= 'z' ) { c += 13; if( c > 'z' ) { c -= 26; } } else if( c >= 'A' && c <= 'Z' ) { c += 13; if( c > 'Z' ) { c -= 26; } } buffer.insert( i, c ); } return buffer.toString(); } } return s; } /** * Like ROT13, but it also encodes numeric characters. * 1234567890 * will become * 6789012345 */ public static String rot135( String s ) { if( s != null ) { s = rot13( s ); int length = s.length(); StringBuilder buffer = new StringBuilder( length ); for( int i = 0; i < length; i++ ) { char c = s.charAt( i ); if( c >= '0' && c <= '4' ) { c += 5; } else if( c >= '5' && c <= '9' ) { c -= 5; } buffer.insert( i, c ); } return buffer.toString(); } return s; } public static String sideBySide( String left, String right ){ final String separator = " | "; String[] one = left.split( "\n" ); String[] two = right.split( "\n" ); int lineCount = Math.max(one.length, two.length); int longestLine = 0; for( String line : one ){ longestLine = Math.max(longestLine, line.length() ); } for( String line : two ){ longestLine = Math.max(longestLine, line.length() ); } int length = longestLine * lineCount * 2; length += (separator.length()+1) * lineCount; StringBuilder result = new StringBuilder(length); for( int i = 0; i < lineCount; i++ ){ String a = padTo( i < one.length ? one[i] : "", longestLine ); String b = padTo( i < two.length ? two[i] : "", longestLine ); result.append(a); result.append(separator); result.append(b); result.append("\n"); } return result.toString(); } public static String spacesToTabs( String text, int spacesPerTab ) { if( text != null && text.length() > 0 && spacesPerTab > 0 ) { String spaces = ""; for( int i = 0; i < spacesPerTab; i++ ) { spaces += " "; } return replaceAll( text, spaces, "\t" ); } return text; } public static String tabsToSpaces( String text, int spacesPerTab ) { if( text != null && text.length() > 0 && spacesPerTab > 0 ) { String spaces = ""; for( int i = 0; i < spacesPerTab; i++ ) { spaces += " "; } return replaceAll( text, "\t", spaces ); } return text; } public static String[] tokenize( String target, String delimiter ) { List tokens = new ArrayList(); int lastIndex = 0; int index = 0; while( index > -1 ) { index = target.indexOf( delimiter, lastIndex ); if( index != -1 ) { String token = target.substring( lastIndex, index ); lastIndex = index + delimiter.length(); tokens.add( token ); } else { String token = target.substring( lastIndex, target.length() ); if( token.length() != 0 ) { tokens.add( token ); } } } int numTokens = tokens.size(); String[] result = new String[ numTokens ]; for( int i = 0; i < numTokens; i++ ) { result[i] = (String)tokens.get( i ); } return result; } public static List<String> tokenizeToList( String target, String delimiter ) { List<String> result = new ArrayList(); String[] tokens = tokenize( target, delimiter ); result.addAll( Arrays.asList( tokens ) ); return result; } public static String[] toArray( List target ) { return toStringArray( target ); } public static String[] toStringArray( List target ) { int size = target.size(); String[] result = new String[ size ]; for( int i = 0; i < size; i++ ) { result[i] = target.get( i ).toString(); } return result; } }
package javax.time; import java.io.Serializable; /** * An instantaneous point on the time-line. * <p> * The Java Time Framework models time as a series of instantaneous events, * known as instants, along a single time-line. This class represents one * of those instants. * <p> * Each instant is theoretically an instantaneous event, however for practicality * a precision of nanoseconds has been chosen. * <p> * An instant is always defined with respect to a well-defined fixed point in time, * known as the epoch. The Java Time Framework uses the standard Java epoch of * 1970-01-01T00:00:00Z. * * @author Stephen Colebourne */ public final class Instant implements Comparable<Instant>, Serializable { // TODO: Minus methods (as per plus methods) // TODO: Duration class integration // TODO: Leap seconds (document or implement) // TODO: Serialized format // TODO: Evaluate hashcode // TODO: Optimise to 2 private subclasses (second/nano & millis) // TODO: Consider BigDecimal /** * Constant for nanos per second. */ private static final int NANOS_PER_SECOND = 1000000000; /** * Serialization version id. */ private static final long serialVersionUID = -9114640809030911667L; /** * The number of seconds from the epoch of 1970-01-01T00:00:00Z. */ private final long epochSeconds; /** * The number of nanoseconds, later along the time-line, from the seconds field. * This is always positive, and never exceeds 999,999,999. */ private final int nanoOfSecond; /** * Factory method to create an instance of Instant using seconds from the * epoch of 1970-01-01T00:00:00Z with a zero nanosecond fraction. * * @param epochSeconds the number of seconds from the epoch of 1970-01-01T00:00:00Z * @return the created Instant */ public static Instant instant(long epochSeconds) { return new Instant(epochSeconds, 0); } public static Instant instant(long epochSeconds, int nanoOfSecond) { if (nanoOfSecond < 0) { throw new IllegalArgumentException("NanoOfSecond must be positive but was " + nanoOfSecond); } if (nanoOfSecond > 999999999) { throw new IllegalArgumentException("NanoOfSecond must not be more than 999,999,999 but was " + nanoOfSecond); } return new Instant(epochSeconds, nanoOfSecond); } public static Instant millisInstant(long epochMillis) { if (epochMillis < 0) { epochMillis++; long epochSeconds = epochMillis / 1000; int millis = ((int) (epochMillis % 1000)); // 0 to -999 millis = 999 + millis; // 0 to 999 return new Instant(epochSeconds - 1, millis * 1000000); } return new Instant(epochMillis / 1000, ((int) (epochMillis % 1000)) * 1000000); } public static Instant millisInstant(long epochMillis, int nanoOfMillisecond) { if (nanoOfMillisecond < 0) { throw new IllegalArgumentException("NanoOfMillisecond must be positive but was " + nanoOfMillisecond); } if (nanoOfMillisecond > 999999) { throw new IllegalArgumentException("NanoOfMillisecond must not be more than 999,999 but was " + nanoOfMillisecond); } if (epochMillis < 0) { epochMillis++; long epochSeconds = epochMillis / 1000; int millis = ((int) (epochMillis % 1000)); // 0 to -999 millis = 999 + millis; // 0 to 999 return new Instant(epochSeconds - 1, millis * 1000000 + nanoOfMillisecond); } return new Instant(epochMillis / 1000, ((int) (epochMillis % 1000)) * 1000000 + nanoOfMillisecond); } /** * Constructs an instance of Instant using seconds from the epoch of * 1970-01-01T00:00:00Z and nanosecond fraction of second. * * @param epochSeconds the number of seconds from the epoch * @param nanoOfSecond the nanoseconds within the second, must be positive */ private Instant(long epochSeconds, int nanoOfSecond) { super(); this.epochSeconds = epochSeconds; this.nanoOfSecond = nanoOfSecond; } /** * Gets the number of seconds from the epoch of 1970-01-01T00:00:00Z. * <p> * Instants on the time-line after the epoch are positive, earlier are negative. * * @return the seconds from the epoch */ public long getEpochSeconds() { return epochSeconds; } /** * Gets the number of nanoseconds, later along the time-line, from the start * of the second returned by {@link #getEpochSeconds()}. * * @return the nanoseconds within the second, always positive, never exceeds 999,999,999 */ public int getNanoOfSecond() { return nanoOfSecond; } /** * Returns a copy of this Instant with the specified duration added. * <p> * This instance is immutable and unaffected by this method call. * * @param duration the duration to add, not null * @return a new updated Instant */ public Instant plus(Duration duration) { long secsToAdd = duration.getEpochSeconds(); int nanosToAdd = duration.getNanoOfSecond(); if (secsToAdd == 0 && nanosToAdd == 0) { return this; } long secs = MathUtils.safeAdd(epochSeconds, secsToAdd); if (nanosToAdd == 0) { return new Instant(secs, nanoOfSecond); } int nos = nanoOfSecond + nanosToAdd; if (nos > NANOS_PER_SECOND) { nos -= NANOS_PER_SECOND; MathUtils.safeAdd(secs, 1); } return new Instant(secs, nos); } /** * Returns a copy of this Instant with the specified number of seconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param secondsToAdd the seconds to add * @return a new updated Instant */ public Instant plusSeconds(long secondsToAdd) { if (secondsToAdd == 0) { return this; } return new Instant(MathUtils.safeAdd(epochSeconds, secondsToAdd) , nanoOfSecond); } /** * Returns a copy of this Instant with the specified number of nanoseconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param millisToAdd the milliseconds to add * @return a new updated Instant */ public Instant plusMillis(long millisToAdd) { if (millisToAdd == 0) { return this; } long secondsToAdd = millisToAdd / 1000; // add: 0 to 999,000,000, subtract: 0 to -999,000,000 int nos = ((int) (millisToAdd % 1000)) * 1000000; // add: 0 to 0 to 1998,999,999, subtract: -999,000,000 to 999,999,999 nos += nanoOfSecond; if (nos < 0) { nos += NANOS_PER_SECOND; // subtract: 1,000,000 to 999,999,999 secondsToAdd } else if (nos >= NANOS_PER_SECOND) { nos -= NANOS_PER_SECOND; // add: 1 to 998,999,999 secondsToAdd++; } return new Instant(MathUtils.safeAdd(epochSeconds, secondsToAdd) , nos); } /** * Returns a copy of this Instant with the specified number of nanoseconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param nanosToAdd the nanoseconds to add * @return a new updated Instant */ public Instant plusNanos(long nanosToAdd) { if (nanosToAdd == 0) { return this; } long secondsToAdd = nanosToAdd / NANOS_PER_SECOND; // add: 0 to 999,999,999, subtract: 0 to -999,999,999 int nos = (int) (nanosToAdd % NANOS_PER_SECOND); // add: 0 to 0 to 1999,999,998, subtract: -999,999,999 to 999,999,999 nos += nanoOfSecond; if (nos < 0) { nos += NANOS_PER_SECOND; // subtract: 1 to 999,999,999 secondsToAdd } else if (nos >= NANOS_PER_SECOND) { nos -= NANOS_PER_SECOND; // add: 1 to 999,999,999 secondsToAdd++; } return new Instant(MathUtils.safeAdd(epochSeconds, secondsToAdd) , nos); } /** * Compares this Instant to another. * * @param otherInstant the other instant to compare to, not null * @return the comparator value, negative if less, postive if greater * @throws NullPointerException if otherInstant is null */ public int compareTo(Instant otherInstant) { int cmp = MathUtils.safeCompare(epochSeconds, otherInstant.epochSeconds); if (cmp != 0) { return cmp; } return MathUtils.safeCompare(nanoOfSecond, otherInstant.nanoOfSecond); } /** * Is this Instant after the specified one. * * @param otherInstant the other instant to compare to, not null * @return true if this instant is after the specified instant * @throws NullPointerException if otherInstant is null */ public boolean isAfter(Instant otherInstant) { return compareTo(otherInstant) > 0; } /** * Is this Instant before the specified one. * * @param otherInstant the other instant to compare to, not null * @return true if this instant is before the specified instant * @throws NullPointerException if otherInstant is null */ public boolean isBefore(Instant otherInstant) { return compareTo(otherInstant) < 0; } /** * Is this Instant equal to that specified. * * @param otherInstant the other instant, null returns false * @return true if the other instant is equal to this one */ @Override public boolean equals(Object otherInstant) { if (this == otherInstant) { return true; } if (otherInstant instanceof Instant) { Instant other = (Instant) otherInstant; return this.epochSeconds == other.epochSeconds && this.nanoOfSecond == other.nanoOfSecond; } return false; } /** * A hashcode for this Instant. * * @return a suitable hashcode */ @Override public int hashCode() { return ((int) (epochSeconds ^ (epochSeconds >>> 32))) + 51 * nanoOfSecond; } /** * A string representation of this Instant using ISO-8601 representation. * <p> * The format of the returned string will be <code>yyyy-MM-ddTHH:mm:ss.SSSSSSSSSZ</code>. * * @return an ISO-8601 represntation of this Instant */ @Override public String toString() { // TODO return "TODO"; } }
package leetcode; public class Problem65 { public boolean isNumber(String s) { return s.matches("\\s*(?:-|\\+)?(\\d+|(?:\\d+\\.\\d*)|(?:\\d*\\.\\d+))(e(?:-|\\+)?\\d+)?\\s*"); } private static void test(boolean actual, boolean expected) { if (actual != expected) { throw new RuntimeException("Wrong!"); } } public static void main(String[] args) { Problem65 prob = new Problem65(); test(prob.isNumber("0"), true); // true test(prob.isNumber("123.45"), true); // true test(prob.isNumber(" 0.1"), true); // true test(prob.isNumber("abc"), false); // false test(prob.isNumber("1 a"), false); // false test(prob.isNumber("2e10"), true); // true test(prob.isNumber("1.2e10"), true); // true test(prob.isNumber("1.2e-10"), true); // true test(prob.isNumber(".1"), true); // true test(prob.isNumber(""), false); // false test(prob.isNumber("e9"), false); // false test(prob.isNumber("1.21.2"), false); // false test(prob.isNumber("1.2e1.2"), false); // false test(prob.isNumber("3."), true); // true test(prob.isNumber("."), false); // false test(prob.isNumber("-12."), true); // true test(prob.isNumber("-.234"), true); // true test(prob.isNumber("-2.2e3.4"), false); // false test(prob.isNumber("-2.2e-3.4"), false); // false test(prob.isNumber("+.8"), true); // true test(prob.isNumber(" 005047e+6"), true); // true } }
package mutslam; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.accumulo.minicluster.MiniAccumuloCluster; import org.apache.accumulo.minicluster.MiniAccumuloConfig; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.MiniDFSCluster; public class MiniRunner { public static void main(String[] args) throws Exception { MiniDFSCluster dfscluster = new MiniDFSCluster.Builder(new Configuration()).build(); //System.out.println(dfscluster.getURI()); MiniAccumuloConfig macConfig = new MiniAccumuloConfig(new File(args[0]), "secret"); Map<String, String> site = new HashMap<String, String>(); // instance.volumes was not working, and the following does not seem to work either site.put("instance.dfs.uri", dfscluster.getURI().toString()); macConfig.setSiteConfig(site); System.out.println(site); MiniAccumuloCluster mac = new MiniAccumuloCluster(macConfig); mac.start(); System.out.println("instance.zookeeper.host="+mac.getZooKeepers()); System.out.println("instance.name="+mac.getInstanceName()); System.out.println("user.name=root"); System.out.println("user.password=secret"); } }
package org.joda.time; import java.util.HashMap; public class Pool { private static Pool myInstance; private HashMap<Integer, Object> instances; private Pool() { this.instances = new HashMap<Integer, Object>(); } public static Pool getInstance() { if (myInstance == null) { myInstance = new Pool(); } return myInstance; } public void add(int numeral, Days day) { instances.put(new Integer(numeral), day); } public Object getInstance(int numeral){ Object instance = instances.get(new Integer(numeral)); if (instance == null) { return null; } return instance; } public static Days getDays(int numeral) { } }
package utils; import java.io.PrintWriter; import java.io.StringWriter; /** * * @author nick */ public class ErrorManager { private final static String newLine = "\n"; public static void send(Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); print(newLine + sw.toString()); } public static void print(String msg) { LogManager.writeAndPrint(msg + "\n\nExit\n"); LogManager.close(); System.exit(1); } }
package org.neo4j.backup; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import static org.neo4j.helpers.collection.MapUtil.stringMap; import static org.neo4j.kernel.Config.ENABLE_ONLINE_BACKUP; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.neo4j.com.ComException; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.index.Index; import org.neo4j.index.impl.lucene.LuceneDataSource; import org.neo4j.kernel.AbstractGraphDatabase; import org.neo4j.kernel.Config; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.test.DbRepresentation; import org.neo4j.test.subprocess.SubProcess; public class TestBackup { private final String serverPath = "target/var/serverdb"; private final String otherServerPath = serverPath + "2"; private final String backupPath = "target/var/backuedup-serverdb"; @Before public void before() throws Exception { FileUtils.deleteDirectory( new File( serverPath ) ); FileUtils.deleteDirectory( new File( otherServerPath ) ); FileUtils.deleteDirectory( new File( backupPath ) ); } // TODO MP: What happens if the server database keeps growing, virtually making the files endless? @Test public void makeSureFullFailsWhenDbExists() throws Exception { createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); createInitialDataSet( backupPath ); try { backup.full( backupPath ); fail( "Shouldn't be able to do full backup into existing db" ); } catch ( Exception e ) { // good } shutdownServer( server ); } @Test public void makeSureIncrementalFailsWhenNoDb() throws Exception { createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); try { backup.incremental( backupPath ); fail( "Shouldn't be able to do incremental backup into non-existing db" ); } catch ( Exception e ) { // Good } shutdownServer( server ); } @Test public void fullThenIncremental() throws Exception { DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); DbRepresentation furtherRepresentation = addMoreData( serverPath ); server = startServer( serverPath ); backup.incremental( backupPath ); assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); } @Test public void makeSureStoreIdIsEnforced() throws Exception { // Create data set X on server A DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); // Grab initial backup from server A OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); // Create data set X+Y on server B createInitialDataSet( otherServerPath ); addMoreData( otherServerPath ); server = startServer( otherServerPath ); // Try to grab incremental backup from server B. // Data should be OK, but store id check should prevent that. try { backup.incremental( backupPath ); fail( "Shouldn't work" ); } catch ( ComException e ) { // Good } shutdownServer( server ); // Just make sure incremental backup can be received properly from // server A, even after a failed attempt from server B DbRepresentation furtherRepresentation = addMoreData( serverPath ); server = startServer( serverPath ); backup.incremental( backupPath ); assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); } private ServerInterface startServer( String path ) throws Exception { /* ServerProcess server = new ServerProcess(); try { server.startup( Pair.of( path, "true" ) ); } catch ( Throwable e ) { // TODO Auto-generated catch block throw new RuntimeException( e ); } */ ServerInterface server = new EmbeddedServer( path, "true" ); server.awaitStarted(); return server; } private void shutdownServer( ServerInterface server ) throws Exception { server.shutdown(); Thread.sleep( 1000 ); } private DbRepresentation addMoreData( String path ) { GraphDatabaseService db = startGraphDatabase( path ); Transaction tx = db.beginTx(); Node node = db.createNode(); node.setProperty( "backup", "Is great" ); db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( "LOVES" ) ); tx.success(); tx.finish(); DbRepresentation result = DbRepresentation.of( db ); db.shutdown(); return result; } private GraphDatabaseService startGraphDatabase( String path ) { return new EmbeddedGraphDatabase( path, stringMap( Config.KEEP_LOGICAL_LOGS, "true" ) ); } private DbRepresentation createInitialDataSet( String path ) { GraphDatabaseService db = startGraphDatabase( path ); Transaction tx = db.beginTx(); Node node = db.createNode(); node.setProperty( "myKey", "myValue" ); db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( "KNOWS" ) ); tx.success(); tx.finish(); DbRepresentation result = DbRepresentation.of( db ); db.shutdown(); return result; } @Test public void multipleIncrementals() throws Exception { GraphDatabaseService db = new EmbeddedGraphDatabase( serverPath, stringMap( ENABLE_ONLINE_BACKUP, "true" ) ); Index<Node> index = db.index().forNodes( "yo" ); OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); long lastCommittedTxForLucene = getLastCommittedTx( backupPath ); for ( int i = 0; i < 5; i++ ) { Transaction tx = db.beginTx(); Node node = db.createNode(); index.add( node, "key", "value" + i ); tx.success(); tx.finish(); backup.incremental( backupPath ); assertEquals( lastCommittedTxForLucene+i+1, getLastCommittedTx( backupPath ) ); } db.shutdown(); } private long getLastCommittedTx( String path ) { GraphDatabaseService db = new EmbeddedGraphDatabase( path ); try { XaDataSource ds = ((AbstractGraphDatabase)db).getConfig().getTxModule().getXaDataSourceManager().getXaDataSource( LuceneDataSource.DEFAULT_NAME ); return ds.getLastCommittedTxId(); } finally { db.shutdown(); } } @Ignore( "Not fixed yet - Fails on Mac OS X (only?)" ) @Test public void shouldRetainFileLocksAfterFullBackupOnLiveDatabase() throws Exception { GraphDatabaseService db = new EmbeddedGraphDatabase( serverPath, stringMap( ENABLE_ONLINE_BACKUP, "true" ) ); try { assertStoreIsLocked( serverPath ); OnlineBackup.from( "localhost" ).full( backupPath ); assertStoreIsLocked( serverPath ); } finally { db.shutdown(); } } private static void assertStoreIsLocked( String path ) { StartupChecker proc = new LockProcess().start( path ); try { assertFalse( "Could start up database, store is not locked", proc.startupOk() ); } finally { SubProcess.stop( proc ); } } public interface StartupChecker { boolean startupOk(); } @SuppressWarnings( "serial" ) private static class LockProcess extends SubProcess<StartupChecker, String> implements StartupChecker { private volatile Object state; @Override public boolean startupOk() { Object result; do { result = state; } while ( result == null ); return !( state instanceof Exception ); } @Override protected void startup( String path ) throws Throwable { GraphDatabaseService db; try { db = new EmbeddedGraphDatabase( path ); } catch ( TransactionFailureException ex ) { state = ex; return; } db.shutdown(); state = new Object(); } } }
package org.pentaho.di.core; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.regex.Pattern; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaAndData; import org.pentaho.di.core.row.ValueMetaInterface; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.XMLInterface; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; /** This class describes a condition in a general meaning. A condition can either be<p> <p> 1) Atomic (a=10, B='aa')<p> 2) Composite ( NOT Condition1 AND Condition2 OR Condition3 )<p> <p> If the nr of atomic conditions is 0, the condition is atomic, otherwise it's Composit.<p> Precedence doesn't exist. Conditions are evaluated in the order in which they are found.<p> A condition can be negated or not.<p> <p> @author Matt @since 8-06-2004 */ public class Condition implements Cloneable, XMLInterface { public static final String[] operators = new String[] { "-", "OR", "AND", "NOT", "OR NOT", "AND NOT", "XOR" }; public static final int OPERATOR_NONE = 0; public static final int OPERATOR_OR = 1; public static final int OPERATOR_AND = 2; public static final int OPERATOR_NOT = 3; public static final int OPERATOR_OR_NOT = 4; public static final int OPERATOR_AND_NOT = 5; public static final int OPERATOR_XOR = 6; public static final String[] functions = new String[] { "=", "<>", "<", "<=", ">", ">=", "REGEXP", "IS NULL", "IS NOT NULL", "IN LIST", "CONTAINS", "STARTS WITH", "ENDS WITH" }; public static final int FUNC_EQUAL = 0; public static final int FUNC_NOT_EQUAL = 1; public static final int FUNC_SMALLER = 2; public static final int FUNC_SMALLER_EQUAL = 3; public static final int FUNC_LARGER = 4; public static final int FUNC_LARGER_EQUAL = 5; public static final int FUNC_REGEXP = 6; public static final int FUNC_NULL = 7; public static final int FUNC_NOT_NULL = 8; public static final int FUNC_IN_LIST = 9; public static final int FUNC_CONTAINS = 10; public static final int FUNC_STARTS_WITH = 11; public static final int FUNC_ENDS_WITH = 12; // These parameters allow for: // value = othervalue // value = 'A' // NOT value = othervalue private long id; private boolean negate; private int operator; private String left_valuename; private int function; private String right_valuename; private ValueMetaAndData right_exact; private long id_right_exact; private int left_fieldnr; private int right_fieldnr; private ArrayList list; private String right_string; public Condition() { list = new ArrayList(); this.operator = OPERATOR_NONE; this.negate = false; left_fieldnr = -2; right_fieldnr = -2; id=-1L; } public Condition(String valuename, int function, String valuename2, ValueMetaAndData exact) { this(); this.left_valuename = valuename; this.function = function; this.right_valuename = valuename2; this.right_exact = exact; clearFieldPositions(); } public Condition(int operator, String valuename, int function, String valuename2, ValueMetaAndData exact) { this(); this.operator = operator; this.left_valuename = valuename; this.function = function; this.right_valuename = valuename2; this.right_exact = exact; clearFieldPositions(); } public Condition(boolean negate, String valuename, int function, String valuename2, ValueMetaAndData exact) { this(valuename, function, valuename2, exact); this.negate = negate; } /** * Returns the database ID of this Condition if a repository was used before. * * @return the ID of the db connection. */ public long getID() { return id; } /** * Set the database ID for this Condition in the repository. * @param id The ID to set on this condition. * */ public void setID(long id) { this.id = id; } public Object clone() { Condition retval = null; retval = new Condition(); retval.negate = negate; retval.operator = operator; if (isComposite()) { for (int i=0;i<nrConditions();i++) { Condition c = getCondition(i); Condition cCopy = (Condition)c.clone(); retval.addCondition(cCopy); } } else { retval.negate = negate; retval.left_valuename = left_valuename; retval.operator = operator; retval.right_valuename = right_valuename; retval.function = function; if (right_exact!=null) { retval.right_exact = (ValueMetaAndData) right_exact.clone(); } else { retval.right_exact = null; } } return retval; } public void setOperator(int operator) { this.operator = operator; } public int getOperator() { return operator; } public String getOperatorDesc() { return Const.rightPad(operators[operator], 7); } public static final int getOperator(String description) { if (description==null) return OPERATOR_NONE; for (int i=1;i<operators.length;i++) { if (operators[i].equalsIgnoreCase(Const.trim(description))) return i; } return OPERATOR_NONE; } public static final String[] getOperators() { String retval[] = new String[operators.length-1]; for (int i=1;i<operators.length;i++) { retval[i-1] = operators[i]; } return retval; } public static final String[] getRealOperators() { return new String[] { "OR", "AND", "OR NOT", "AND NOT", "XOR" }; } public void setLeftValuename(String left_valuename) { this.left_valuename = left_valuename; } public String getLeftValuename() { return left_valuename; } public int getFunction() { return function; } public void setFunction( int function ) { this.function = function; } public String getFunctionDesc() { return functions[function]; } public static final int getFunction(String description) { for (int i=1;i<functions.length;i++) { if (functions[i].equalsIgnoreCase(Const.trim(description))) return i; } return FUNC_EQUAL; } public void setRightValuename(String right_valuename) { this.right_valuename = right_valuename; } public String getRightValuename() { return right_valuename; } public void setRightExact(ValueMetaAndData right_exact) { this.right_exact = right_exact; } public ValueMetaAndData getRightExact() { return right_exact; } public String getRightExactString() { if (right_exact == null) return null; return right_exact.toString(); } /** * Get the id of the RightExact Value in the repository * @return The id of the RightExact Value in the repository */ public long getRightExactID() { return id_right_exact; } /** * Set the database ID for the RightExact Value in the repository. * @param id_right_exact The ID to set on this Value. * */ public void setRightExactID(long id_right_exact) { this.id_right_exact = id_right_exact; } public boolean isAtomic() { return list.size()==0; } public boolean isComposite() { return list.size()!=0; } public boolean isNegated() { return negate; } public void setNegated(boolean negate) { this.negate = negate; } public void negate() { setNegated(!isNegated()); } /** * A condition is empty when the condition is atomic and no left field is specified. */ public boolean isEmpty() { return (isAtomic() && left_valuename==null); } /** * We cache the position of a value in a row. * If ever we want to change the rowtype, we need to * clear these cached field positions... */ public void clearFieldPositions() { left_fieldnr = -1; right_fieldnr = -1; } // Evaluate the condition... public boolean evaluate(RowMetaInterface rowMeta, Object[] r) { // Start of evaluate boolean retval = false; // If we have 0 items in the list, evaluate the current condition // Otherwise, evaluate all sub-conditions try { if (isAtomic()) { // Get fieldnrs left value // Check out the fieldnrs if we don't have them... if (left_valuename!=null && left_valuename.length()>0 && left_fieldnr<-1) left_fieldnr = rowMeta.indexOfValue(left_valuename); // Get fieldnrs right value if (right_valuename!=null && right_valuename.length()>0 && right_fieldnr<-1) right_fieldnr = rowMeta.indexOfValue(right_valuename); // Get fieldnrs left field ValueMetaInterface fieldMeta = null; Object field=null; if (left_fieldnr>=0) { fieldMeta = rowMeta.getValueMeta(left_fieldnr); field = r[left_fieldnr]; if (field==null) { throw new KettleException("Unable to find field ["+left_valuename+"] in the input row!"); } } // Get fieldnrs right exact ValueMetaInterface fieldMeta2 = right_exact!=null ? right_exact.getValueMeta() : null; Object field2 = right_exact!=null ? right_exact.getValueData() : null; if (field2==null && right_fieldnr>=0) { fieldMeta2 = rowMeta.getValueMeta(right_fieldnr); field2 = r[right_fieldnr]; if (field2==null) { throw new KettleException("Unable to find field ["+right_valuename+"] in the input row!"); } } if (field==null) { throw new KettleException("Unable to find value for field ["+left_valuename+"] in the input row!"); } if (field2==null && function!=FUNC_NULL && function!=FUNC_NOT_NULL) { throw new KettleException("Unable to find value for field ["+right_valuename+"] in the input row!"); } // Evaluate switch(function) { case FUNC_EQUAL : retval = (fieldMeta.compare(field, fieldMeta2, field2)==0); break; case FUNC_NOT_EQUAL : retval = (fieldMeta.compare(field, fieldMeta2, field2)!=0); break; case FUNC_SMALLER : retval = (fieldMeta.compare(field, fieldMeta2, field2)< 0); break; case FUNC_SMALLER_EQUAL : retval = (fieldMeta.compare(field, fieldMeta2, field2)<=0); break; case FUNC_LARGER : retval = (fieldMeta.compare(field, fieldMeta2, field2)> 0); break; case FUNC_LARGER_EQUAL : retval = (fieldMeta.compare(field, fieldMeta2, field2)>=0); break; case FUNC_REGEXP : if (fieldMeta.isNull(field) || field2==null) { retval = false; } else { retval = Pattern.matches(fieldMeta2.getString(field), fieldMeta.getString(field)); } break; case FUNC_NULL : retval = (fieldMeta.isNull(field)); break; case FUNC_NOT_NULL : retval = (!fieldMeta.isNull(field)); break; case FUNC_IN_LIST : String list[] = Const.splitString(fieldMeta2.getString(field2), ';'); retval = Const.indexOfString(fieldMeta.getString(field), list)>=0; break; case FUNC_CONTAINS : retval = fieldMeta.getString(field)!=null?fieldMeta.getString(field).indexOf(fieldMeta2.getString(field2))>=0:false; break; case FUNC_STARTS_WITH : retval = fieldMeta.getString(field)!=null?fieldMeta.getString(field).startsWith(fieldMeta2.getString(field2)):false; break; case FUNC_ENDS_WITH : String string = fieldMeta.getString(field); if (!Const.isEmpty(string)) { if (right_string==null && field2!=null) right_string=fieldMeta2.getString(field2); if (right_string!=null) { retval = string.endsWith(fieldMeta2.getString(field2)); } else { retval = false; } } else { retval = false; } // retval = fieldMeta.getString(field)!=null?fieldMeta.getString(field).endsWith(fieldMeta2.getString(field2)):false; break; default: break; } // Only NOT makes sense, the rest doesn't, so ignore!!!! // Optionally negate if (isNegated()) retval=!retval; } else { // Composite : get first Condition cb0 = (Condition)list.get(0); retval = cb0.evaluate(rowMeta, r); // Loop over the conditions listed below. for (int i=1;i<list.size();i++) { // Composite : evaluate Condition cb = (Condition)list.get(i); boolean cmp = cb.evaluate(rowMeta, r); switch (cb.getOperator()) { case Condition.OPERATOR_OR : retval = retval || cmp; break; case Condition.OPERATOR_AND : retval = retval && cmp; break; case Condition.OPERATOR_OR_NOT : retval = retval || ( !cmp ); break; case Condition.OPERATOR_AND_NOT : retval = retval && ( !cmp ); break; case Condition.OPERATOR_XOR : retval = retval ^ cmp; break; default: break; } } // Composite: optionally negate if (isNegated()) retval=!retval; } } catch(Exception e) { throw new RuntimeException("Unexpected error evaluation condition ["+toString()+"]", e); } return retval; } public void addCondition(Condition cb) { if (isAtomic() && getLeftValuename()!=null) { /* Copy current atomic setup... * */ Condition current = new Condition(getLeftValuename(), getFunction(), getRightValuename(), getRightExact()); current.setNegated(isNegated()); setNegated(false); list.add(current); } else // Set default operator if not on first position... if (isComposite() && list.size()>0 && cb.getOperator()==OPERATOR_NONE) { cb.setOperator(OPERATOR_AND); } list.add( cb ); } public void addCondition(int idx, Condition cb) { if (isAtomic() && getLeftValuename()!=null) { /* Copy current atomic setup... * */ Condition current = new Condition(getLeftValuename(), getFunction(), getRightValuename(), getRightExact()); current.setNegated(isNegated()); setNegated(false); list.add(current); } else // Set default operator if not on first position... if (isComposite() && idx>0 && cb.getOperator()==OPERATOR_NONE) { cb.setOperator(OPERATOR_AND); } list.add(idx, cb ); } public void removeCondition(int nr) { if (isComposite()) { Condition c = (Condition)list.get(nr); list.remove(nr); // Nothing left or only one condition left: move it to the parent: make it atomic. boolean moveUp = isAtomic() || nrConditions()==1; if (nrConditions()==1) c=getCondition(0); if (moveUp) { setLeftValuename(c.getLeftValuename()); setFunction(c.getFunction()); setRightValuename(c.getRightValuename()); setRightExact(c.getRightExact()); setNegated(c.isNegated()); } } } public int nrConditions() { return list.size(); } public Condition getCondition(int i) { return (Condition)list.get(i); } public void setCondition(int i, Condition subCondition) { list.set(i, subCondition); } public String toString() { return toString(0, true, true); } public String toString(int level, boolean show_negate, boolean show_operator) { String retval=""; if (isAtomic()) { //retval+="<ATOMIC "+level+", "+show_negate+", "+show_operator+">"; for (int i=0;i<level;i++) retval+=" "; if (show_operator && getOperator()!=OPERATOR_NONE) { retval += getOperatorDesc()+" "; } else { retval+=" "; } // Atomic is negated? if (isNegated() && ( show_negate || level>0 )) { retval+="NOT ( "; } else { retval+=" "; } retval+=left_valuename+" "+getFunctionDesc(); if (function != FUNC_NULL && function != FUNC_NOT_NULL) { if ( right_valuename != null ) { retval+=" "+right_valuename; } else { retval+=" ["+( getRightExactString()==null?"":getRightExactString() )+"]"; } } if (isNegated() && ( show_negate || level>0 )) retval+=" )"; retval+=Const.CR; } else { //retval+="<COMP "+level+", "+show_negate+", "+show_operator+">"; // Group is negated? if (isNegated() && (show_negate || level>0)) { for (int i=0;i<level;i++) retval+=" "; retval+="NOT"+Const.CR; } // Group is preceded by an operator: if (getOperator()!=OPERATOR_NONE && (show_operator || level>0)) { for (int i=0;i<level;i++) retval+=" "; retval+=getOperatorDesc()+Const.CR; } for (int i=0;i<level;i++) retval+=" "; retval+="("+Const.CR; for (int i=0;i<list.size();i++) { Condition cb = (Condition)list.get(i); retval+=cb.toString(level+1, true, i>0); } for (int i=0;i<level;i++) retval+=" "; retval+=")"+Const.CR; } return retval; } public String getXML() { return getXML(0); } public String getXML(int level) { String retval=""; String indent1 = Const.rightPad(" ", level); String indent2 = Const.rightPad(" ", level+1); String indent3 = Const.rightPad(" ", level+2); retval+= indent1+"<condition>"+Const.CR; retval+=indent2+XMLHandler.addTagValue("negated", isNegated()); if (getOperator()!=OPERATOR_NONE) { retval+=indent2+XMLHandler.addTagValue("operator", Const.rtrim(getOperatorDesc())); } if (isAtomic()) { retval+=indent2+XMLHandler.addTagValue("leftvalue", getLeftValuename()); retval+=indent2+XMLHandler.addTagValue("function", getFunctionDesc()); retval+=indent2+XMLHandler.addTagValue("rightvalue", getRightValuename()); if (getRightExact()!=null) { retval+=indent2+getRightExact().getXML(); } } else { retval+=indent2+"<conditions>"+Const.CR; for (int i=0;i<nrConditions();i++) { Condition c = getCondition(i); retval+=c.getXML(level+2); } retval+=indent3+"</conditions>"+Const.CR; } retval+=indent2+"</condition>"+Const.CR; return retval; } /** * Build a new condition using an XML Document Node * @param condnode * @throws KettleXMLException */ public Condition(Node condnode) throws KettleXMLException { this(); list = new ArrayList(); try { String str_negated = XMLHandler.getTagValue(condnode, "negated"); setNegated( "Y".equalsIgnoreCase(str_negated) ); String str_operator = XMLHandler.getTagValue(condnode, "operator"); setOperator( getOperator( str_operator ) ); Node conditions = XMLHandler.getSubNode(condnode, "conditions"); int nrconditions = XMLHandler.countNodes(conditions, "condition"); if (nrconditions==0) // ATOMIC! { setLeftValuename( XMLHandler.getTagValue(condnode, "leftvalue") ); setFunction( getFunction(XMLHandler.getTagValue(condnode, "function") ) ); setRightValuename( XMLHandler.getTagValue(condnode, "rightvalue") ); Node exactnode = XMLHandler.getSubNode(condnode, ValueMetaAndData.XML_TAG); if (exactnode!=null) { ValueMetaAndData exact = new ValueMetaAndData(exactnode); setRightExact(exact); } } else { for (int i=0;i<nrconditions;i++) { Node subcondnode = XMLHandler.getSubNodeByNr(conditions, "condition", i); Condition c = new Condition(subcondnode); addCondition(c); } } } catch(Exception e) { throw new KettleXMLException("Unable to create condition using xml: "+Const.CR+condnode, e); } } /* * TODO: re-enable repository support * * Read a condition from the repository. * @param rep The repository to read from * @param id_condition The condition id * @throws KettleException if something goes wrong. * public Condition(Repository rep, long id_condition) throws KettleException { this(); list = new ArrayList(); try { Row r = rep.getCondition(id_condition); if (r!=null) { negate = r.getBoolean("NEGATED", false); operator = getOperator( r.getString("OPERATOR", null) ); id = r.getInteger("ID_CONDITION", -1L); long subids[] = rep.getSubConditionIDs(id); if (subids.length==0) { left_valuename = r.getString("LEFT_NAME", null); function = getFunction( r.getString("CONDITION_FUNCTION", null) ); right_valuename = r.getString("RIGHT_NAME", null); long id_value = r.getInteger("ID_VALUE_RIGHT", -1L); if (id_value>0) { Value v = new Value(rep, id_value); right_exact = v; } } else { for (int i=0;i<subids.length;i++) { addCondition( new Condition(rep, subids[i]) ); } } } else { throw new KettleException("Condition with id_condition="+id_condition+" could not be found in the repository"); } } catch(KettleDatabaseException dbe) { throw new KettleException("Error loading condition from the repository (id_condition="+id_condition+")", dbe); } } public long saveRep(Repository rep) throws KettleException { return saveRep(0L, rep); } public long saveRep(long id_condition_parent, Repository rep) throws KettleException { try { id = rep.insertCondition( id_condition_parent, this ); for (int i=0;i<nrConditions();i++) { Condition subc = getCondition(i); subc.saveRep(getID(), rep); } return getID(); } catch(KettleDatabaseException dbe) { throw new KettleException("Error saving condition to the repository.", dbe); } } */ public String[] getUsedFields() { Hashtable fields = new Hashtable(); getUsedFields(fields); String retval[] = new String[fields.size()]; Enumeration keys = fields.keys(); int i=0; while (keys.hasMoreElements()) { retval[i] = (String)keys.nextElement(); i++; } return retval; } public void getUsedFields(Hashtable fields) { if (isAtomic()) { if (getLeftValuename()!=null) fields.put(getLeftValuename(), "-"); if (getRightValuename()!=null) fields.put(getRightValuename(), "-"); } else { for (int i=0;i<nrConditions();i++) { Condition subc = getCondition(i); subc.getUsedFields(fields); } } } }
package jolie.net; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.server.rpc.RPC; import com.google.gwt.user.server.rpc.RPCRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jolie.Interpreter; import jolie.lang.Constants; import jolie.lang.NativeType; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.http.json.JsonUtils; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.OperationTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import joliex.gwt.client.JolieService; import joliex.gwt.server.JolieGWTConverter; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * HTTP protocol implementation * @author Fabrizio Montesi * 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status codes */ public class HttpProtocol extends CommProtocol { private static final byte[] NOT_IMPLEMENTED_HEADER = "HTTP/1.1 501 Not Implemented".getBytes(); private static final int DEFAULT_STATUS_CODE = 200; private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303; private static final Map< Integer, String > statusCodeDescriptions = new HashMap< Integer, String >(); private static final Set< Integer > locationRequiredStatusCodes = new HashSet< Integer >(); static { locationRequiredStatusCodes.add( 301 ); locationRequiredStatusCodes.add( 302 ); locationRequiredStatusCodes.add( 303 ); locationRequiredStatusCodes.add( 307 ); locationRequiredStatusCodes.add( 308 ); } static { // Initialise the HTTP Status code map. statusCodeDescriptions.put( 100,"Continue" ); statusCodeDescriptions.put( 101,"Switching Protocols" ); statusCodeDescriptions.put( 102,"Processing" ); statusCodeDescriptions.put( 200,"OK" ); statusCodeDescriptions.put( 201,"Created" ); statusCodeDescriptions.put( 202,"Accepted" ); statusCodeDescriptions.put( 203,"Non-Authoritative Information" ); statusCodeDescriptions.put( 204,"No Content" ); statusCodeDescriptions.put( 205,"Reset Content" ); statusCodeDescriptions.put( 206,"Partial Content" ); statusCodeDescriptions.put( 207,"Multi-Status" ); statusCodeDescriptions.put( 208,"Already Reported" ); statusCodeDescriptions.put( 226,"IM Used" ); statusCodeDescriptions.put( 300,"Multiple Choices" ); statusCodeDescriptions.put( 301,"Moved Permanently" ); statusCodeDescriptions.put( 302,"Found" ); statusCodeDescriptions.put( 303,"See Other" ); statusCodeDescriptions.put( 304,"Not Modified" ); statusCodeDescriptions.put( 305,"Use Proxy" ); statusCodeDescriptions.put( 306,"Reserved" ); statusCodeDescriptions.put( 307,"Temporary Redirect" ); statusCodeDescriptions.put( 308,"Permanent Redirect" ); statusCodeDescriptions.put( 400,"Bad Request" ); statusCodeDescriptions.put( 401,"Unauthorized" ); statusCodeDescriptions.put( 402,"Payment Required" ); statusCodeDescriptions.put( 403,"Forbidden" ); statusCodeDescriptions.put( 404,"Not Found" ); statusCodeDescriptions.put( 405,"Method Not Allowed" ); statusCodeDescriptions.put( 406,"Not Acceptable" ); statusCodeDescriptions.put( 407,"Proxy Authentication Required" ); statusCodeDescriptions.put( 408,"Request Timeout" ); statusCodeDescriptions.put( 409,"Conflict" ); statusCodeDescriptions.put( 410,"Gone" ); statusCodeDescriptions.put( 411,"Length Required" ); statusCodeDescriptions.put( 412,"Precondition Failed" ); statusCodeDescriptions.put( 413,"Request Entity Too Large" ); statusCodeDescriptions.put( 414,"Request-URI Too Long" ); statusCodeDescriptions.put( 415,"Unsupported Media Type" ); statusCodeDescriptions.put( 416,"Requested Range Not Satisfiable" ); statusCodeDescriptions.put( 417,"Expectation Failed" ); statusCodeDescriptions.put( 422,"Unprocessable Entity" ); statusCodeDescriptions.put( 423,"Locked" ); statusCodeDescriptions.put( 424,"Failed Dependency" ); statusCodeDescriptions.put( 426,"Upgrade Required" ); statusCodeDescriptions.put( 427,"Unassigned" ); statusCodeDescriptions.put( 428,"Precondition Required" ); statusCodeDescriptions.put( 429,"Too Many Requests" ); statusCodeDescriptions.put( 430,"Unassigned" ); statusCodeDescriptions.put( 431,"Request Header Fields Too Large" ); statusCodeDescriptions.put( 500,"Internal Server Error" ); statusCodeDescriptions.put( 501,"Not Implemented" ); statusCodeDescriptions.put( 502,"Bad Gateway" ); statusCodeDescriptions.put( 503,"Service Unavailable" ); statusCodeDescriptions.put( 504,"Gateway Timeout" ); statusCodeDescriptions.put( 505,"HTTP Version Not Supported" ); statusCodeDescriptions.put( 507,"Insufficient Storage" ); statusCodeDescriptions.put( 508,"Loop Detected" ); statusCodeDescriptions.put( 509,"Unassigned" ); statusCodeDescriptions.put( 510,"Not Extended" ); statusCodeDescriptions.put( 511,"Network Authentication Required" ); } private static class Parameters { private static final String DEBUG = "debug"; private static final String COOKIES = "cookies"; private static final String METHOD = "method"; private static final String ALIAS = "alias"; private static final String MULTIPART_HEADERS = "multipartHeaders"; private static final String CONCURRENT = "concurrent"; private static final String USER_AGENT = "userAgent"; private static final String HOST = "host"; private static final String HEADERS = "headers"; private static final String STATUS_CODE = "statusCode"; private static final String REDIRECT = "redirect"; private static final String DEFAULT_OPERATION = "default"; private static class MultiPartHeaders { private static final String FILENAME = "filename"; } } private static class Headers { private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; public final static String CRLF = new String( new char[] { 13, 10 } ); public String name() { return "http"; } public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); } private void valueToDocument( Value value, Node node, Document doc ) { node.appendChild( doc.createTextNode( value.strValue() ) ); Element currentElement; for( Entry< String, ValueVector > entry : value.children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { for( Value val : entry.getValue() ) { currentElement = doc.createElement( entry.getKey() ); node.appendChild( currentElement ); Map< String, ValueVector > attrs = jolie.xml.XmlUtils.getAttributesOrNull( val ); if ( attrs != null ) { for( Entry< String, ValueVector > attrEntry : attrs.entrySet() ) { currentElement.setAttribute( attrEntry.getKey(), attrEntry.getValue().first().strValue() ); } } valueToDocument( val, currentElement, doc ); } } } } public String getMultipartHeaderForPart( String operationName, String partName ) { if ( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if ( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if ( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----Jol13H77p77Bound4r155"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if ( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if ( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if ( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if ( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if ( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if ( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( CRLF ); } } } } private String encoding = null; private String requestFormat = null; private void send_appendQuerystring( Value value, String charset, StringBuilder headerBuilder ) throws IOException { if ( value.children().isEmpty() == false ) { headerBuilder.append( '?' ); for( Entry< String, ValueVector > entry : value.children().entrySet() ) { for( Value v : entry.getValue() ) { headerBuilder .append( entry.getKey() ) .append( '=' ) .append( URLEncoder.encode( v.strValue(), charset ) ) .append( '&' ); } } } } private void send_appendJsonQueryString( CommMessage message, String charset, StringBuilder headerBuilder ) throws IOException { if ( message.value().hasChildren() == false ) { headerBuilder.append( "?=" ); JsonUtils.valueToJsonString( message.value(), getSendType( message ), headerBuilder ); } } private void send_appendParsedAlias( String alias, Value value, String charset, StringBuilder headerBuilder ) throws IOException { int offset = 0; ArrayList<String> aliasKeys = new ArrayList<String>(); String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { if ( m.group( 1 ) == null ) { // We have to use URLEncoder currKey = alias.substring( m.start() + 2, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), charset ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), charset ); aliasKeys.add( currKey ); } } else { // We have to insert the string raw currKey = alias.substring( m.start() + 3, m.end() - 1 ); if ( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); aliasKeys.add( currKey ); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); offset += currStrValue.length() - 3 - currKey.length(); } // removing used keys for( int k = 0; k < aliasKeys.size(); k++ ) { value.children().remove( aliasKeys.get( k ) ); } headerBuilder.append( result ); } private String getCharset() { String charset = "UTF-8"; if ( hasParameter( "charset" ) ) { charset = getStringParameter( "charset" ); } return charset; } private String send_getFormat() { String format = "xml"; if ( inInputPort && requestFormat != null ) { format = requestFormat; requestFormat = null; } else if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = ""; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if ( inInputPort == false && method == Method.GET ) { // We are building a GET request return ret; } if ( "xml".equals( format ) ) { Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + (( inInputPort ) ? "Response" : "") ); doc.appendChild( root ); if ( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); valueToDocument( message.fault().value(), faultElement, doc ); } else { valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); ret.contentType = "text/xml"; } else if ( "binary".equals( format ) ) { if ( message.value().isByteArray() ) { ret.content = (ByteArray) message.value().valueObject(); ret.contentType = "application/octet-stream"; } } else if ( "html".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); ret.contentType = "text/html"; } else if ( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if ( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( CRLF ); builder.append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ); boolean isBinary = false; if ( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) { Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS ); if ( specOpParam.hasChildren( "partName" ) ) { ValueVector partNames = specOpParam.getChildren( "partName" ); for( int p = 0; p < partNames.size(); p++ ) { if ( partNames.get( p ).hasChildren( "part" ) ) { if ( partNames.get( p ).getFirstChild( "part" ).strValue().equals( entry.getKey() ) ) { isBinary = true; if ( partNames.get( p ).hasChildren( "filename" ) ) { builder.append( "; filename=\"" ).append( partNames.get( p ).getFirstChild( "filename" ).strValue() ).append( "\"" ); } if ( partNames.get( p ).hasChildren( "contentType" ) ) { builder.append( CRLF ).append( "Content-Type:" ).append( partNames.get( p ).getFirstChild( "contentType" ).strValue() ); } } } } } } builder.append( CRLF ).append( CRLF ); if ( isBinary ) { bStream.write( builder.toString().getBytes( charset ) ); bStream.write( entry.getValue().first().byteArrayValue().getBytes() ); builder.delete( 0, builder.length() - 1 ); builder.append( CRLF ); } else { builder.append( entry.getValue().first().strValue() ).append( CRLF ); } } } builder.append( "--" + BOUNDARY + "--" ); bStream.write( builder.toString().getBytes( charset )); ret.content = new ByteArray( bStream.toByteArray() ); } else if ( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); Entry< String, ValueVector > entry; StringBuilder builder = new StringBuilder(); while( it.hasNext() ) { entry = it.next(); builder.append( entry.getKey() ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), "UTF-8" ) ); if ( it.hasNext() ) { builder.append( '&' ); } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if ( "text/x-gwt-rpc".equals( format ) ) { ret.contentType = "text/x-gwt-rpc"; try { if ( message.isFault() ) { ret.content = new ByteArray( RPC.encodeResponseForFailure( JolieService.class.getMethods()[0], JolieGWTConverter.jolieToGwtFault( message.fault() ) ).getBytes( charset ) ); } else { joliex.gwt.client.Value v = new joliex.gwt.client.Value(); JolieGWTConverter.jolieToGwtValue( message.value(), v ); ret.content = new ByteArray( RPC.encodeResponseForSuccess( JolieService.class.getMethods()[0], v ).getBytes( charset ) ); } } catch( SerializationException e ) { throw new IOException( e ); } } else if ( "json".equals( format ) || "application/json".equals( format ) ) { ret.contentType = "application/json"; StringBuilder jsonStringBuilder = new StringBuilder(); if ( message.isFault() ) { Value jolieJSONFault = Value.create(); jolieJSONFault.getFirstChild( "jolieFault" ).getFirstChild( "faultName" ).setValue( message.fault().faultName() ); if ( message.fault().value().hasChildren() ) { jolieJSONFault.getFirstChild( "jolieFault" ).getFirstChild( "data" ).deepCopy( message.fault().value() ); } JsonUtils.valueToJsonString( jolieJSONFault, getSendType( message ), jsonStringBuilder ); } else { JsonUtils.valueToJsonString( message.value(), getSendType( message ), jsonStringBuilder ); } ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } else if ( "raw".equals( format ) ) { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } return ret; } private boolean isLocationNeeded( int statusCode ) { return locationRequiredStatusCodes.contains( statusCode ); } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { int statusCode = DEFAULT_STATUS_CODE; String statusDescription = null; if( hasParameter( Parameters.STATUS_CODE ) ) { statusCode = getIntParameter( Parameters.STATUS_CODE ); if ( !statusCodeDescriptions.containsKey( statusCode ) ) { Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which is not in the HTTP specifications." ); statusDescription = "Internal Server Error"; } else if ( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) { // if statusCode is a redirection code, location parameter is needed Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which expects a redirect parameter but the latter is not set." ); } } else if ( hasParameter( Parameters.REDIRECT ) ) { statusCode = DEFAULT_REDIRECTION_STATUS_CODE; } if ( statusDescription == null ) { statusDescription = statusCodeDescriptions.get( statusCode ); } headerBuilder.append( "HTTP/1.1 " + statusCode + " " + statusDescription + CRLF ); // if redirect has been set, the redirect location parameter is set if ( hasParameter( Parameters.REDIRECT ) ) { headerBuilder.append( "Location: " + getStringParameter( Parameters.REDIRECT ) + CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: Jolie" ).append( CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if ( hasParameter( "cacheControl" ) ) { Value cacheControl = getParameterFirstValue( "cacheControl" ); if ( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if ( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( CRLF ); } } private void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { if ( uri.getPath().length() < 1 || uri.getPath().charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( uri.getPath() ); String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); if ( alias.isEmpty() ) { headerBuilder.append( message.operationName() ); } else { send_appendParsedAlias( alias, message.value(), charset, headerBuilder ); } if ( method == Method.GET ) { boolean jsonFormat = false; if ( getParameterFirstValue( "method" ).hasChildren( "queryFormat" ) ) { if ( getParameterFirstValue( "method" ).getFirstChild( "queryFormat" ).strValue().equals( "json" ) ) { jsonFormat = true; send_appendJsonQueryString( message, charset, headerBuilder ); } } if ( !jsonFormat ) { send_appendQuerystring( message.value(), charset, headerBuilder ); } } } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if ( message.value().hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value().getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); //String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); userpass = encoder.encode( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( CRLF ); } } private void send_appendHeader( CommMessage message, StringBuilder headerBuilder ) { Value v = getParameterFirstValue( "addHeader" ); if ( v != null ) { if ( v.hasChildren("header") ) { for( Value head : v.getChildren("header") ) { String header = head.strValue() + ": " + head.getFirstChild( "value" ).strValue(); headerBuilder.append( header ).append( CRLF ); } } } } private Method send_getRequestMethod( CommMessage message ) throws IOException { try { Method method = hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ? Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ).toUpperCase() ) : hasParameter( Parameters.METHOD ) ? Method.fromString( getStringParameter( Parameters.METHOD ).toUpperCase() ) : Method.POST; return method; } catch( Method.UnsupportedMethodException e ) { throw new IOException( e ); } } private void send_appendRequestHeaders( CommMessage message, Method method, StringBuilder headerBuilder, String charset ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, headerBuilder, charset ); headerBuilder.append( " HTTP/1.1" + CRLF ); headerBuilder.append( "Host: " + uri.getHost() + CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); if ( checkBooleanParameter( "compression", true ) ) { headerBuilder.append( "Accept-Encoding: gzip, deflate" + CRLF ); } send_appendHeader( message, headerBuilder ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) throws IOException { String param; if ( checkBooleanParameter( "keepAlive", true ) == false || channel().toBeClosed() ) { channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" + CRLF ); } if ( checkBooleanParameter( Parameters.CONCURRENT, true ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.id() ).append( CRLF ); } if ( encodedContent.content != null ) { String contentType = getStringParameter( "contentType" ); if ( contentType.length() > 0 ) { encodedContent.contentType = contentType; } headerBuilder.append( "Content-Type: " + encodedContent.contentType ); if ( charset != null ) { headerBuilder.append( "; charset=" + charset.toLowerCase() ); } headerBuilder.append( CRLF ); param = getStringParameter( "contentTransferEncoding" ); if ( !param.isEmpty() ) { headerBuilder.append( "Content-Transfer-Encoding: " + param + CRLF ); } String contentDisposition = getStringParameter( "contentDisposition" ); if ( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " + encodedContent.contentDisposition + CRLF ); } boolean compression = ( encoding != null ) && checkBooleanParameter( "compression", true ); String compressionTypes = getStringParameter( "compressionTypes", "text/html text/css text/plain text/xml text/x-js application/json application/javascript" ); if ( !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) { compression = false; } if ( compression ) { if ( encoding.contains( "gzip" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); GZIPOutputStream outStream = new GZIPOutputStream( baOutStream ); outStream.write( encodedContent.content.getBytes() ); outStream.close(); encodedContent.content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: gzip" + CRLF ); } else if ( encoding.contains( "deflate" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); DeflaterOutputStream outStream = new DeflaterOutputStream( baOutStream ); outStream.write( encodedContent.content.getBytes() ); outStream.close(); encodedContent.content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: deflate" + CRLF ); } } headerBuilder.append( "Content-Length: " + (encodedContent.content.size()) + CRLF ); //headerBuilder.append( "Content-Length: " + (encodedContent.content.size() + 2) + CRLF ); } else { headerBuilder.append( "Content-Length: 0" + CRLF ); } } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent ) { if ( checkBooleanParameter( "debug" ) ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ); debugSB.append( header ); if ( getParameterVector( "debug" ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString() ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } } public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = getCharset(); String format = send_getFormat(); EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); StringBuilder headerBuilder = new StringBuilder(); if ( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); } else { // We're sending a notification or a solicit send_appendRequestHeaders( message, method, headerBuilder, charset ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( CRLF ); send_logDebugInfo( headerBuilder, encodedContent ); inputId = message.operationName(); /*if ( charset == null ) { charset = "UTF8"; }*/ ostream.write( headerBuilder.toString().getBytes( charset ) ); if ( encodedContent.content != null ) { ostream.write( encodedContent.content.getBytes() ); //ostream.write( CRLF.getBytes( charset ) ); } } private void parseXML( HttpMessage message, Value value ) throws IOException { try { if ( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value ); } } catch( ParserConfigurationException pce ) { throw new IOException( pce ); } catch( SAXException saxe ) { throw new IOException( saxe ); } } private static void parseJson( HttpMessage message, Value value, boolean strictEncoding ) throws IOException { JsonUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ) ), value, strictEncoding ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), "UTF8" ); String[] pair; for( String item : line.split( "&" ) ) { pair = item.split( "=", 2 ); value.getChildren( pair[0] ).first().setValue( URLDecoder.decode( pair[1], charset ) ); } } private void parseMultiPartFormData( HttpMessage message, Value value ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private static String parseGWTRPC( HttpMessage message, Value value ) throws IOException { RPCRequest request = RPC.decodeRequest( new String( message.content(), "UTF8" ) ); String operationName = (String)request.getParameters()[0]; joliex.gwt.client.Value requestValue = (joliex.gwt.client.Value)request.getParameters()[1]; JolieGWTConverter.gwtToJolieValue( requestValue, value ); return operationName; } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if ( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if ( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if ( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); type = cookieConfig.hasChildren( "type" ) ? cookieConfig.getFirstChild( "type" ).strValue() : "string"; recv_assignCookieValue( cookie.value(), v, type ); } } /*currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue );*/ } } } private void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if ( NativeType.INT == type ) { try { value.setValue( new Integer( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.LONG == type ) { try { value.setValue( new Long( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if ( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if ( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if ( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if ( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if ( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if ( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if ( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value headers = null; if ( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) { headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS ); } else if ( hasParameter( Parameters.HEADERS ) ) { headers = getParameterFirstValue( Parameters.HEADERS ); } if ( headers != null ) { for( String headerName : headers.children().keySet() ) { String headerAlias = headers.getFirstChild( headerName ).strValue(); headerName = headerName.replace( "_", "-" ); decodedMessage.value.getFirstChild( headerAlias ).setValue( message.getPropertyOrEmptyString( headerName ) ); } } } private static void recv_parseQueryString( HttpMessage message, Value value ) { Map< String, Integer > indexes = new HashMap< String, Integer >(); String queryString = message.requestPath() == null ? "" : message.requestPath(); String[] kv = queryString.split( "\\?" ); Integer index; if ( kv.length > 1 ) { queryString = kv[1]; String[] params = queryString.split( "&" ); for( String param : params ) { kv = param.split( "=", 2 ); if ( kv.length > 1 ) { index = indexes.get( kv[0] ); if ( index == null ) { index = 0; indexes.put( kv[0], index ); } value.getChildren( kv[0] ).get( index ).setValue( kv[1] ); indexes.put( kv[0], index + 1 ); } } } } /* * Prints debug information about a received message */ private void recv_logDebugInfo( HttpMessage message ) { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Receiving:\n" ); debugSB.append( "HTTP Code: " + message.statusCode() + "\n" ); debugSB.append( "Resource: " + message.requestPath() + "\n" ); debugSB.append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { debugSB.append( '\t' + entry.getKey() + ": " + entry.getValue() + '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { debugSB.append( "\tset-cookie: " + cookie.toString() + '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { debugSB.append( "\tcookie: " + entry.getKey() + '=' + entry.getValue() + '\n' ); } if ( getParameterFirstValue( "debug" ).getFirstChild( "showContent" ).intValue() > 0 && message.content() != null ) { debugSB.append( "--> Message content\n" ); debugSB.append( new String( message.content() ) ); } Interpreter.getInstance().logInfo( debugSB.toString() ); } private void recv_parseRequestFormat( HttpMessage message ) throws IOException { requestFormat = null; String type = message.getPropertyOrEmptyString( "content-type" ).split( ";" )[0]; if ( "text/x-gwt-rpc".equals( type ) ) { requestFormat = "text/x-gwt-rpc"; } else if ( "application/json".equals( type ) ) { requestFormat = "application/json"; } } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String charset ) throws IOException { String format = "xml"; if ( hasParameter( "format" ) ) { format = getStringParameter( "format" ); } String type = message.getProperty( "content-type" ).split( ";" )[0]; if ( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content() ) ); } else if ( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if ( "text/xml".equals( type ) ) { parseXML( message, decodedMessage.value ); } else if ( "text/x-gwt-rpc".equals( type ) ) { decodedMessage.operationName = parseGWTRPC( message, decodedMessage.value ); } else if ( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if ( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) || "application/zip".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if ( "application/json".equals( type ) || "json".equals( format ) ) { boolean strictEncoding = checkStringParameter( "json_encoding", "strict" ); parseJson( message, decodedMessage.value, strictEncoding ); } else if ( "xml".equals( format ) || "rest".equals( format ) ) { parseXML( message, decodedMessage.value ); } else { decodedMessage.value.setValue( new String( message.content() ) ); } } private String getDefaultOperation( HttpMessage.Type t ) { if ( hasParameter( Parameters.DEFAULT_OPERATION ) ) { Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION ); String method = t == HttpMessage.Type.GET ? "get" : t == HttpMessage.Type.HEAD ? "head" : t == HttpMessage.Type.POST ? "post" : t == HttpMessage.Type.PUT ? "put" : t == HttpMessage.Type.DELETE ? "delete" : null; if ( method == null || dParam.hasChildren( method ) == false ) { return dParam.strValue(); } else { return dParam.getFirstChild( method ).strValue(); } } return null; } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if ( decodedMessage.operationName == null ) { String requestPath = message.requestPath().split( "\\?" )[0]; decodedMessage.operationName = requestPath; Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( decodedMessage.operationName ); if ( m.find() ) { int resourceStart = m.end(); if ( m.find() ) { decodedMessage.resourcePath = requestPath.substring( resourceStart - 1, m.start() ); decodedMessage.operationName = requestPath.substring( m.end(), requestPath.length() ); } } } if ( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getDefaultOperation( message.type() ); if ( defaultOpId != null ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); if ( message.userAgent() != null ) { decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() ); } Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if ( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser.getPartPropertiesSet() ) { if ( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if ( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForGenericHeader( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage ); if ( message.userAgent() != null && hasParameter( Parameters.USER_AGENT ) ) { getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() ); } if ( getParameterVector( Parameters.HOST ) != null ) { getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_ID; } private void recv_checkForStatusCode( HttpMessage message ) { if ( hasParameter( Parameters.STATUS_CODE ) ) { getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() ); } } public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpMessage message = new HttpParser( istream ).parse(); if ( message.isSupported() == false ) { ostream.write( NOT_IMPLEMENTED_HEADER ); ostream.write( CRLF.getBytes() ); ostream.write( CRLF.getBytes() ); ostream.flush(); return null; } if ( message.getProperty( "connection" ) != null ) { HttpUtils.recv_checkForChannelClosing( message, channel() ); } else { channel().setToBeClosed( checkBooleanParameter( "keepAlive", true ) == false ); } if ( checkBooleanParameter( Parameters.DEBUG ) ) { recv_logDebugInfo( message ); } recv_checkForStatusCode( message ); String charset = getCharset(); encoding = message.getProperty( "accept-encoding" ); recv_parseRequestFormat( message ); if ( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, charset ); } if ( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if ( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) {} } } if ( message.isResponse() ) { recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, null ); } else if ( message.isError() == false ) { if ( message.isGet() ) { recv_parseQueryString( message, decodedMessage.value ); } recv_checkReceivingOperation( message, decodedMessage ); recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if ( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && (channel().parentPort().getInterface().containsOperation( retVal.operationName() ) || channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null) ) { try { // The message is for this service boolean hasInput = false; OneWayTypeDescription oneWayTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asOneWayTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); } if ( oneWayTypeDescription != null ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { hasInput = false; RequestResponseTypeDescription rrTypeDescription = null; if ( channel().parentInputPort() != null ) { if ( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ).getOperationTypeDescription().asRequestResponseTypeDescription(); hasInput = true; } } if ( !hasInput ) { Interface iface = channel().parentPort().getInterface(); rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); } if ( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if ( faultType != null ) { faultType.cast( retVal.value() ); } } else { if ( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } private Type getSendType( CommMessage message ) throws IOException { Type ret = null; if ( channel().parentPort() == null ) { throw new IOException( "Could not retrieve communication port for HTTP protocol" ); } OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH ); if ( opDesc == null ) { throw new IOException( "Operation " + message.operationName() + " not declared in port interface for HTTP protocol" ); } if ( opDesc.asOneWayTypeDescription() != null ) { if ( message.isFault() ) { ret = Type.UNDEFINED; } else { OneWayTypeDescription ow = opDesc.asOneWayTypeDescription(); ret = ow.requestType(); } } else if ( opDesc.asRequestResponseTypeDescription() != null ) { RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription(); if ( message.isFault() ) { ret = rr.getFaultType( message.fault().faultName() ); if ( ret == null ) { ret = Type.UNDEFINED; } } else { ret = ( inInputPort ) ? rr.responseType() : rr.requestType(); } } else { throw new IOException( "Internal error" ); } return ret; } }
package aQute.lib.deployer; import java.io.*; import java.security.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import aQute.bnd.header.*; import aQute.bnd.osgi.*; import aQute.bnd.service.*; import aQute.bnd.version.*; import aQute.lib.io.*; import aQute.service.reporter.*; public class FileRepo implements Plugin, RepositoryPlugin, Refreshable, RegistryPlugin { public final static String LOCATION = "location"; public final static String READONLY = "readonly"; public final static String NAME = "name"; File[] EMPTY_FILES = new File[0]; protected File root; Registry registry; boolean canWrite = true; Pattern REPO_FILE = Pattern.compile("([-a-zA-z0-9_\\.]+)-([0-9\\.]+|latest)\\.(jar|lib)"); Reporter reporter; boolean dirty; String name; public FileRepo() {} public FileRepo(String name, File location, boolean canWrite) { this.name = name; this.root = location; this.canWrite = canWrite; } protected void init() throws Exception { // for extensions } public void setProperties(Map<String,String> map) { String location = map.get(LOCATION); if (location == null) throw new IllegalArgumentException("Location must be set on a FileRepo plugin"); root = new File(location); String readonly = map.get(READONLY); if (readonly != null && Boolean.valueOf(readonly).booleanValue()) canWrite = false; name = map.get(NAME); } /** * Get a list of URLs to bundles that are constrained by the bsn and * versionRange. */ private File[] get(String bsn, String versionRange) throws Exception { init(); // If the version is set to project, we assume it is not // for us. A project repo will then get it. if (versionRange != null && versionRange.equals("project")) return null; // Check if the entry exists File f = new File(root, bsn); if (!f.isDirectory()) return null; // The version range we are looking for can // be null (for all) or a version range. VersionRange range; if (versionRange == null || versionRange.equals("latest")) { range = new VersionRange("0"); } else range = new VersionRange(versionRange); // Iterator over all the versions for this BSN. // Create a sorted map over the version as key // and the file as URL as value. Only versions // that match the desired range are included in // this list. File instances[] = f.listFiles(); SortedMap<Version,File> versions = new TreeMap<Version,File>(); for (int i = 0; i < instances.length; i++) { Matcher m = REPO_FILE.matcher(instances[i].getName()); if (m.matches() && m.group(1).equals(bsn)) { String versionString = m.group(2); Version version; if (versionString.equals("latest")) version = new Version(Integer.MAX_VALUE); else version = new Version(versionString); if (range.includes(version) || versionString.equals(versionRange)) versions.put(version, instances[i]); } } File[] files = versions.values().toArray(EMPTY_FILES); if ("latest".equals(versionRange) && files.length > 0) { return new File[] { files[files.length - 1] }; } return files; } public boolean canWrite() { return canWrite; } protected PutResult putArtifact(File tmpFile, PutOptions options) throws Exception { assert (tmpFile != null); assert (options != null); Jar jar = null; try { init(); dirty = true; jar = new Jar(tmpFile); Manifest manifest = jar.getManifest(); if (manifest == null) throw new IllegalArgumentException("No manifest in JAR: " + jar); String bsn = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_SYMBOLICNAME); if (bsn == null) throw new IllegalArgumentException("No Bundle SymbolicName set"); Parameters b = Processor.parseHeader(bsn, null); if (b.size() != 1) throw new IllegalArgumentException("Multiple bsn's specified " + b); for (String key : b.keySet()) { bsn = key; if (!Verifier.SYMBOLICNAME.matcher(bsn).matches()) throw new IllegalArgumentException("Bundle SymbolicName has wrong format: " + bsn); } String versionString = manifest.getMainAttributes().getValue(Analyzer.BUNDLE_VERSION); Version version; if (versionString == null) version = new Version(); else version = new Version(versionString); if (reporter != null) reporter.trace("bsn=%s version=%s", bsn, version); File dir = new File(root, bsn); if (!dir.mkdirs()) { throw new IOException("Could not create directory " + dir); } String fName = bsn + "-" + version.getWithoutQualifier() + ".jar"; File file = new File(dir, fName); boolean renamed = false; PutResult result = new PutResult(); if (reporter != null) reporter.trace("updating %s ", file.getAbsolutePath()); if (!file.exists() || file.lastModified() < jar.lastModified()) { if (file.exists()) { IO.delete(file); } IO.rename(tmpFile, file); renamed = true; result.artifact = file.toURI(); if (reporter != null) reporter.progress(-1, "updated " + file.getAbsolutePath()); fireBundleAdded(jar, file); } else { if (reporter != null) { reporter.progress(-1, "Did not update " + jar + " because repo has a newer version"); reporter.trace("NOT Updating " + fName + " (repo is newer)"); } } File latest = new File(dir, bsn + "-latest.jar"); boolean latestExists = latest.exists() && latest.isFile(); boolean latestIsOlder = latestExists && (latest.lastModified() < jar.lastModified()); if ((options.createLatest && !latestExists) || latestIsOlder) { if (latestExists) { IO.delete(latest); } if (!renamed) { IO.rename(tmpFile, latest); } else { IO.copy(file, latest); } result.latest = latest.toURI(); } return result; } finally { if (jar != null) { jar.close(); } } } /* a straight copy of this method lives in LocalIndexedRepo */ public PutResult put(InputStream stream, PutOptions options) throws Exception { /* both parameters are required */ if ((stream == null) || (options == null)) { throw new IllegalArgumentException("No stream and/or options specified"); } /* determine if the put is allowed */ if (!canWrite) { throw new IOException("Repository is read-only"); } /* the root directory of the repository has to be a directory */ if (!root.isDirectory()) { throw new IOException("Repository directory " + root + " is not a directory"); } /* determine if the artifact needs to be verified */ boolean verifyFetch = (options.digest != null); boolean verifyPut = !options.allowArtifactChange; /* determine which digests are needed */ boolean needFetchDigest = verifyFetch || verifyPut; boolean needPutDigest = verifyPut || options.generateDigest; /* * setup a new stream that encapsulates the stream and calculates (when * needed) the digest */ DigestInputStream dis = new DigestInputStream(stream, MessageDigest.getInstance("SHA-1")); dis.on(needFetchDigest); File tmpFile = null; try { /* * copy the artifact from the (new/digest) stream into a temporary * file in the root directory of the repository */ tmpFile = IO.createTempFile(root, "put", ".bnd"); IO.copy(dis, tmpFile); /* get the digest if available */ byte[] disDigest = needFetchDigest ? dis.getMessageDigest().digest() : null; /* verify the digest when requested */ if (verifyFetch && !MessageDigest.isEqual(options.digest, disDigest)) { throw new IOException("Retrieved artifact digest doesn't match specified digest"); } /* put the artifact into the repository (from the temporary file) */ PutResult r = putArtifact(tmpFile, options); /* calculate the digest when requested */ if (needPutDigest && (r.artifact != null)) { MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); IO.copy(new File(r.artifact), sha1); r.digest = sha1.digest(); } /* verify the artifact when requested */ if (verifyPut && (r.digest != null) && !MessageDigest.isEqual(disDigest, r.digest)) { File f = new File(r.artifact); if (f.exists()) { IO.delete(f); } throw new IOException("Stored artifact digest doesn't match specified digest"); } return r; } finally { if (tmpFile != null && tmpFile.exists()) { IO.delete(tmpFile); } } } protected void fireBundleAdded(Jar jar, File file) { if (registry == null) return; List<RepositoryListenerPlugin> listeners = registry.getPlugins(RepositoryListenerPlugin.class); for (RepositoryListenerPlugin listener : listeners) { try { listener.bundleAdded(this, jar, file); } catch (Exception e) { if (reporter != null) reporter.warning("Repository listener threw an unexpected exception: %s", e); } } } public void setLocation(String string) { root = new File(string); if (!root.isDirectory()) throw new IllegalArgumentException("Invalid repository directory"); } public void setReporter(Reporter reporter) { this.reporter = reporter; } public List<String> list(String regex) throws Exception { init(); Instruction pattern = null; if (regex != null) pattern = new Instruction(regex); List<String> result = new ArrayList<String>(); if (root == null) { if (reporter != null) reporter.error("FileRepo root directory is not set."); } else { File[] list = root.listFiles(); if (list != null) { for (File f : list) { if (!f.isDirectory()) continue; // ignore non-directories String fileName = f.getName(); if (fileName.charAt(0) == '.') continue; // ignore hidden files if (pattern == null || pattern.matches(fileName)) result.add(fileName); } } else if (reporter != null) reporter.error("FileRepo root directory (%s) does not exist", root); } return result; } public List<Version> versions(String bsn) throws Exception { init(); File dir = new File(root, bsn); if (dir.isDirectory()) { String versions[] = dir.list(); List<Version> list = new ArrayList<Version>(); for (String v : versions) { Matcher m = REPO_FILE.matcher(v); if (m.matches()) { String version = m.group(2); if (version.equals("latest")) version = Integer.MAX_VALUE + ""; list.add(new Version(version)); } } return list; } return null; } public String toString() { return String.format("%-40s r/w=%s", root.getAbsolutePath(), canWrite()); } public File getRoot() { return root; } public boolean refresh() { if (dirty) { dirty = false; return true; } return false; } public String getName() { if (name == null) { return toString(); } return name; } public Jar get(String bsn, Version v) throws Exception { init(); File bsns = new File(root, bsn); File version = new File(bsns, bsn + "-" + v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + ".jar"); if (version.exists()) return new Jar(version); return null; } public File get(String bsn, String version, Strategy strategy, Map<String,String> properties) throws Exception { if (version == null) version = "0.0.0"; if (strategy == Strategy.EXACT) { VersionRange vr = new VersionRange(version); if (vr.isRange()) return null; if (vr.getHigh().getMajor() == Integer.MAX_VALUE) version = "latest"; File file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".jar"); if (file.isFile()) return file; file = IO.getFile(root, bsn + "/" + bsn + "-" + version + ".lib"); if (file.isFile()) return file; return null; } File[] files = get(bsn, version); if (files == null || files.length == 0) return null; if (files.length >= 0) { switch (strategy) { case LOWEST : return files[0]; case HIGHEST : return files[files.length - 1]; case EXACT : // TODO break; } } return null; } public void setRegistry(Registry registry) { this.registry = registry; } public String getLocation() { return root.toString(); } }
package br.pucrs.ap3.graphs; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * Grafo no-dirigido (Directed graph - Digrafo). * * @author marco.mangan@pucrs.br * */ public abstract class AbstractGraph { protected int[][] m; public AbstractGraph(int size) { if (size <= 0) throw new IllegalArgumentException("Size must be 1 or more."); m = new int[size + 1][size + 1]; } @Override public String toString() { String r = " "; for (int j = 1; j < m.length; j++) { r += j + " "; } r += "\n"; r += " +"; for (int j = 1; j < m.length; j++) { r += " } r += "\n"; for (int i = 1; i < m.length; i++) { r += i + " | "; for (int j = 1; j < m.length; j++) { r += m[i][j] + " "; } r += "\n"; } return r; } public void addEdge(int i, int j) { addEdge(i, j, 1); } public abstract void addEdge(int i, int j, int value); protected void checkNode(int i) { if (i <= 0 || i >= m.length) throw new IllegalArgumentException("Invalid node:" + i); } public List<Integer> getNext(int i) { checkNode(i); List<Integer> r = new ArrayList<Integer>(); for (int j = 1; j < m.length; j++) { if (m[i][j] != 0) r.add(j); } return r; } // enum { private static final int WHITE = 10; private static final int GRAY = 20; private static final int BLACK = 30; public List<Integer> breadth(int s) { List<Integer> r = new ArrayList<>(); checkNode(s); // 1 - 7 // TODO trocar para enum! int color[] = new int[m.length]; int d[] = new int[m.length]; int p[] = new int[m.length]; for (int u = 1; u < color.length; u++) { color[u] = WHITE; d[u] = 1000; p[u] = -1; } color[s] = GRAY; d[s] = 0; p[s] = -1; // 8, 9 List<Integer> Q = new LinkedList<Integer>(); Q.add(s); while (!Q.isEmpty()) { int u = Q.remove(0); for (Integer v : getNext(u)) { if (color[v] == WHITE) { color[v] = GRAY; d[v] = d[u] + 1; p[v] = u; Q.add(v); } } color[u] = BLACK; r.add(u); } // System.out.println(Arrays.toString(d)); // System.out.println(Arrays.toString(p)); return r; } public List<Integer> depth(int s) { checkNode(s); List<Integer> r = new ArrayList<>(); depth0(s, r); return r; } private void depth0(int s, List<Integer> r) { r.add(s); for (Integer v : getNext(s)) if (!r.contains(v)) depth0(v, r); } private int counter; private int[] color; private int[] discovery; private int[] finish; public List<Integer> topological() { counter = 1; color = new int[m.length]; discovery = new int[m.length]; finish = new int[m.length]; for (int u = 1; u < color.length; u++) { color[u] = WHITE; discovery[u] = -1; finish[u] = -1; } List<Integer> sorted = new ArrayList<>(); for (int u = 1; u < color.length; u++) { if (color[u] == WHITE) { topological0(u, sorted); } } return sorted; } private void topological0(int node, List<Integer> sorted) { sorted.add(node); color[node] = GRAY; discovery[node] = counter; counter++; for (Integer adjacentNode : getNext(node)) { if (!sorted.contains(adjacentNode)) { topological0(adjacentNode, sorted); } } color[node] = BLACK; finish[node] = counter; counter++; } }
package ccw.launching; import java.io.File; import java.io.IOException; import java.net.URL; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.launching.JavaLaunchDelegate; import ccw.CCWPlugin; public class ClojureLaunchDelegate extends JavaLaunchDelegate { private ILaunch launch; @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { int port = LaunchUtils.getLaunchServerReplPort(launch); launch.setAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_LISTEN, Integer.toString(port)); launch.setAttribute(LaunchUtils.ATTR_PROJECT_NAME, configuration.getAttribute(LaunchUtils.ATTR_PROJECT_NAME, (String) null)); if (port == -1) { try { launch.setAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_FILE_PORT, File.createTempFile(LaunchUtils.SERVER_FILE_PORT_PREFIX, LaunchUtils.SERVER_FILE_PORT_SUFFFIX).getAbsolutePath()); } catch (IOException e) { throw new CoreException(Status.CANCEL_STATUS); // TODO do better than that ? } } this.launch = launch; super.launch(configuration, mode, launch, monitor); } @Override public String getVMArguments(ILaunchConfiguration configuration) throws CoreException { int port = LaunchUtils.getLaunchServerReplPort(launch); StringBuilder sb = new StringBuilder(); sb.append(" -D" + "clojure.remote.server.port" + "=" + Integer.toString(port)); if (port == -1) { sb.append(" -D" + LaunchUtils.ATTR_CLOJURE_SERVER_FILE_PORT + "=" + launch.getAttribute(LaunchUtils.ATTR_CLOJURE_SERVER_FILE_PORT)); } sb.append(" " + super.getVMArguments(configuration)); return sb.toString(); } @Override public String getProgramArguments(ILaunchConfiguration configuration) throws CoreException { String userProgramArguments = super.getProgramArguments(configuration); if (configuration.getAttribute(LaunchUtils.ATTR_CLOJURE_INSTALL_REPL, true)) { String filesToLaunchArguments = LaunchUtils.getFilesToLaunchAsCommandLineList(configuration, false); // Add serverrepl as a file to launch to install a remote server try { URL serverReplBundleUrl = CCWPlugin.getDefault().getBundle().getResource("ccw/debug/serverrepl.clj"); URL serverReplFileUrl = FileLocator.toFileURL(serverReplBundleUrl); String serverRepl = serverReplFileUrl.getFile(); filesToLaunchArguments = "-i " + '\"' + serverRepl + "\" " + filesToLaunchArguments // doesn't work + "-e \"(doseq [[v b] {(var *print-length*) 10000, (var *print-level*) 100}] (var-set v b))\" "; ; } catch (IOException e) { e.printStackTrace(); } return filesToLaunchArguments + " --repl " + userProgramArguments; } else { String filesToLaunchArguments = LaunchUtils.getFilesToLaunchAsCommandLineList(configuration, true); return filesToLaunchArguments + userProgramArguments; } } }
package ru.job4j.start; import ru.job4j.models.Item; //import java.util.Arrays; import java.util.Scanner; /** * class StartUI. */ public class StartUI { /** * Input object. */ private Input input; /** * Constructor. * @param input - Input object */ StartUI(Input input) { this.input = input; } /** * Method for all calculate in program. */ public void init() { Tracker tracker = new Tracker(); Scanner in = new Scanner(System.in); //ConsoleInput input = new ConsoleInput(); String s = new String(); for (;;) { System.out.print("0. Add new item\n1. Show all items\n2. Edit item\n3. Delete item\n4. Find item by id\n5. Find items by name\n6. Exit program\nSelect: "); s = in.next(); if (s.equals(String.valueOf(0))) { System.out.print("Enter your name: "); String name = input.ask(); System.out.print("Enter task's description: "); String desc = input.ask(); System.out.print("Enter current date: "); long create = input.askDate(); Item it1 = new Item(name, desc, create); tracker.add(it1); } if (s.equals(String.valueOf(3))) { System.out.print("Enter your name: "); String name = input.ask(); System.out.print("Enter task's description: "); String desc = input.ask(); System.out.print("Enter current date: "); long create = input.askDate(); Item temp = null; boolean b = false; for (int i = 0; i < tracker.findAll().length; i++) { if (name.equals(tracker.findAll()[i].getName()) && desc.equals(tracker.findAll()[i].getDescription()) && create == tracker.findAll()[i].getCreate()) { temp = tracker.findAll()[i]; b = true; break; } } if (b) { tracker.delete(temp); System.out.println("Done"); } else { System.out.println("You entered incorrect value!"); } } if (s.equals(String.valueOf(1))) { if (tracker.findAll().length != 0) { System.out.println("Your items:"); for (int i = 0; i < tracker.findAll().length; i++) { System.out.println(String.format("%s %s %s %s", tracker.findAll()[i].getName(), tracker.findAll()[i].getDescription(), tracker.findAll()[i].getCreate(), tracker.findAll()[i].getId())); //System.out.println(tracker.findAll()[i].getName() + " " + tracker.findAll()[i].getDescription() + " " + tracker.findAll()[i].getCreate() + " " + tracker.findAll()[i].getId()); } } else { System.out.println("Nothing to display"); } } if (s.equals(String.valueOf(2))) { System.out.print("Enter item's id to replace: "); String id = input.ask(); boolean b = true; for (int i = 0; i < tracker.findAll().length; i++) { if (tracker.findAll()[i].getId().equals(id)) { System.out.print("Enter new name: "); tracker.findAll()[i].setName(input.ask()); System.out.print("Enter new description: "); tracker.findAll()[i].setDescription(input.ask()); System.out.print("Enter new date: "); tracker.findAll()[i].setCreate(input.askDate()); b = false; //tracker.update(new Item(name, desc, create)); break; } } if (b) { System.out.println("You entered incorrect value!"); } /*for (int i = 0; i < tracker.findAll().length; i++) { if (tracker.findAll()[i].getId().equals(id)) { tracker.findAll()[i] = temp; break; } }*/ } if (s.equals(String.valueOf(4))) { System.out.print("Enter ID: "); String temp = input.ask(); /*boolean b = true; for(int i=0; i<tracker.findAll().length; i++) { if(tracker.findAll()[i].getId().equals(temp)) { System.out.println("Your request:"); System.out.println(tracker.findAll()[i].getName() + " " + tracker.findAll()[i].getDescription() + " " + tracker.findAll()[i].getCreate() + " " + tracker.findAll()[i].getId()); b = false; break; } } if (b) { System.out.println("You entered incorrect value!"); }*/ Item it = tracker.findById(temp); if (it != null) { System.out.println(String.format("%s %s %s %s", it.getName(), it.getDescription(), it.getCreate(), it.getId())); /*System.out.println(it.getName() + " " + it.getDescription() + " " + it.getCreate() + " " + it.getId());*/ } else { System.out.println("You entered incorrect value!"); } } if (s.equals(String.valueOf(5))) { System.out.print("Enter your name: "); String name = input.ask(); for (int i = 0; i < tracker.findByName(name).length; i++) { System.out.println(String.format("%s %s %s %s", tracker.findByName(name)[i].getName(), tracker.findByName(name)[i].getDescription(), tracker.findByName(name)[i].getCreate(), tracker.findByName(name)[i].getId())); //System.out.println(tracker.findByName(name)[i].getName() + " " + tracker.findByName(name)[i].getDescription() + " " + tracker.findByName(name)[i].getCreate() + " " + tracker.findByName(name)[i].getId()); } } if (s.equals(String.valueOf(6))) { System.out.println("Bye!"); break; } if (!(s.equals("0") || s.equals("1") || s.equals("2") || s.equals("3") || s.equals("4") || s.equals("5") || s.equals("6"))) { System.out.println("Incorrect input! Try again"); continue; } } } /** * method main. * @param args - arguments */ public static void main(String[] args) { String[] array = {"0", "1", "2", "3", "4", "5", "6"}; StartUI obj = new StartUI(new ConsoleInput()/*StubInput(array)*/); obj.init(); } }
package de.fau.mad.clickdummy; import java.util.ArrayList; import com.example.kobold.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class DataAdapter extends ArrayAdapter<DataHolder> { private Activity myContext; ArrayList<DataHolder> theData; public DataAdapter(Activity context, int textViewResourceId, DataHolder[] objects, ArrayList<DataHolder> allData) { super(context, textViewResourceId, objects); myContext = context; theData = allData; } // We keep this ViewHolder object to save time. It's quicker than findViewById() when repainting. static class ViewHolder { protected DataHolder data; protected TextView text; protected EditText text2; protected Spinner spin; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; // Check to see if this row has already been painted once. if (convertView == null) { // If it hasn't, set up everything: LayoutInflater inflator = myContext.getLayoutInflater(); view = inflator.inflate(R.layout.initialrow, null); // Make a new ViewHolder for this row, and modify its data and spinner: final ViewHolder viewHolder = new ViewHolder(); viewHolder.text = (TextView) view.findViewById(R.id.text); viewHolder.text2 = (EditText) view.findViewById(R.id.text2); //viewHolder.text.setText("TEST"); viewHolder.data = new DataHolder(myContext); viewHolder.spin = (Spinner) view.findViewById(R.id.spin); viewHolder.spin.setAdapter(viewHolder.data.getAdapter()); // Used to handle events when the user changes the Spinner selection: viewHolder.spin.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { viewHolder.data.setSelected(arg2); viewHolder.text.setText(viewHolder.data.getText()); if(viewHolder.data.getText().equals("Ordner")){ MainActivity ma = (MainActivity) myContext; ma.addItemList(); ma.allData.remove(viewHolder.data); } else if(arg0.getItemAtPosition(arg2).toString().equals("Text")){ viewHolder.text2.setVisibility(View.VISIBLE); // arg1.findViewById(R.id.listView_items).invalidate(); // viewHolder.text2.setText(arg1.getId()); Toast.makeText(myContext, myContext.getResources().getResourceEntryName(((View) arg1.getParent().getParent().getParent()).getId()), Toast.LENGTH_LONG).show(); // ((ListView) arg1.getParent()).getLayoutParams().height = LinearLayout.LayoutParams.MATCH_PARENT; // this.notifyDataSetChanged(); ((ListView) arg1.getParent().getParent().getParent()).invalidate(); } else{ viewHolder.text2.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); // Update the TextView to reflect what's in the Spinner viewHolder.text.setText(viewHolder.data.getText()); view.setTag(viewHolder); Log.d("DBGINF", viewHolder.text.getText() + ""); } else { view = convertView; } // This is what gets called every time the ListView refreshes ViewHolder holder = (ViewHolder) view.getTag(); holder.text.setText(getItem(position).getText()); holder.text2.setText("test"); holder.spin.setSelection(getItem(position).getSelected()); return view; } }
package org.spine3.base; import com.google.common.base.Converter; /** * Serves as converter from {@code I} to {@code String} with an associated * reverse function from {@code String} to {@code I}. * * <p>It is used for converting back and forth between the different * representations of the same information. * * @author Alexander Yevsyukov * @see #convert(Object) * @see #reverse() */ public abstract class Stringifier<I> extends Converter<I, String> { }
package bisq.core.app; import bisq.core.btc.BaseCurrencyNetwork; import bisq.core.btc.BtcOptionKeys; import bisq.core.btc.UserAgent; import bisq.core.dao.DaoOptionKeys; import bisq.core.exceptions.BisqException; import bisq.core.filter.FilterManager; import bisq.network.NetworkOptionKeys; import bisq.network.p2p.network.ConnectionConfig; import bisq.common.CommonOptionKeys; import bisq.common.app.Version; import bisq.common.crypto.KeyStorage; import bisq.common.storage.Storage; import bisq.common.util.Utilities; import org.bitcoinj.core.NetworkParameters; import org.springframework.core.env.Environment; import org.springframework.core.env.JOptCommandLinePropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.ResourcePropertySource; import joptsimple.OptionSet; import org.apache.commons.lang3.StringUtils; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import ch.qos.logback.classic.Level; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; @Slf4j public class BisqEnvironment extends StandardEnvironment { // Static public static void setDefaultAppName(String defaultAppName) { DEFAULT_APP_NAME = defaultAppName; } public static String DEFAULT_APP_NAME = "Bisq"; public static final String DEFAULT_USER_DATA_DIR = defaultUserDataDir(); public static final String DEFAULT_APP_DATA_DIR = appDataDir(DEFAULT_USER_DATA_DIR, DEFAULT_APP_NAME); public static final String LOG_LEVEL_DEFAULT = Level.INFO.levelStr; public static final String BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME = "bisqCommandLineProperties"; public static final String BISQ_APP_DIR_PROPERTY_SOURCE_NAME = "bisqAppDirProperties"; public static final String BISQ_DEFAULT_PROPERTY_SOURCE_NAME = "bisqDefaultProperties"; private static String staticAppDataDir; public static String getStaticAppDataDir() { return staticAppDataDir; } @SuppressWarnings("SameReturnValue") public static BaseCurrencyNetwork getDefaultBaseCurrencyNetwork() { return BaseCurrencyNetwork.BTC_MAINNET; } protected static BaseCurrencyNetwork baseCurrencyNetwork = getDefaultBaseCurrencyNetwork(); public static NetworkParameters getParameters() { return getBaseCurrencyNetwork().getParameters(); } public static BaseCurrencyNetwork getBaseCurrencyNetwork() { return baseCurrencyNetwork; } private static String defaultUserDataDir() { if (Utilities.isWindows()) return System.getenv("APPDATA"); else if (Utilities.isOSX()) return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toString(); else // *nix return Paths.get(System.getProperty("user.home"), ".local", "share").toString(); } private static String appDataDir(String userDataDir, String appName) { //TODO fix for changing app name form bisq to Bisq (add dir renamed as well) final String newAppName = "Bisq"; if (appName.equals(newAppName)) { final String oldAppName = "bisq"; Path oldPath = Paths.get(Paths.get(userDataDir, oldAppName).toString());// bisq Path newPath = Paths.get(Paths.get(userDataDir, appName).toString());//Bisq File oldDir = new File(oldPath.toString()); // bisq File newDir = new File(newPath.toString()); //Bisq try { if (Files.exists(oldPath) && oldDir.getCanonicalPath().endsWith(oldAppName)) { if (Files.exists(newPath) && newDir.getCanonicalPath().endsWith(newAppName)) { // we have both bisq and Bisq and rename Bisq to Bisq_backup File newDirBackup = new File(newDir.toString() + "_backup"); // Bisq log.info("Rename Bisq data dir {} to {}", newPath.toString(), newDirBackup.toString()); if (!newDir.renameTo(newDirBackup)) throw new RuntimeException("Cannot rename dir"); log.info("Rename old data dir {} to {}", oldDir.toString(), newPath.toString()); if (!oldDir.renameTo(newDir)) throw new RuntimeException("Cannot rename dir"); } else { log.info("Rename old data dir {} to {}", oldDir.toString(), newPath.toString()); if (!oldDir.renameTo(newDir)) throw new RuntimeException("Cannot rename dir"); } } } catch (IOException e) { e.printStackTrace(); } } return Paths.get(userDataDir, appName).toString(); } // Util to set isDaoActivated to true if either set as program argument or we run testnet or regtest. // Can be removed once DAO is live. public static boolean isDaoActivated(Environment environment) { Boolean daoActivatedFromOptions = environment.getProperty(DaoOptionKeys.DAO_ACTIVATED, Boolean.class, true); BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork(); return daoActivatedFromOptions || !baseCurrencyNetwork.isMainnet(); } // Instance fields protected final ResourceLoader resourceLoader = new DefaultResourceLoader(); protected final String appName; protected final String userDataDir; @Getter protected final String appDataDir; protected final String btcNetworkDir, userAgent; protected final String logLevel, providers; @Getter @Setter protected boolean isBitcoinLocalhostNodeRunning; @Getter protected String desktopWithHttpApi, desktopWithGrpcApi; @Getter protected List<String> bannedSeedNodes, bannedBtcNodes, bannedPriceRelayNodes; protected final String btcNodes, seedNodes, ignoreDevMsg, useDevPrivilegeKeys, useDevMode, useTorForBtc, rpcUser, rpcPassword, rpcHost, rpcPort, rpcBlockNotificationPort, rpcBlockNotificationHost, dumpBlockchainData, fullDaoNode, banList, dumpStatistics, maxMemory, socks5ProxyBtcAddress, torRcFile, torRcOptions, externalTorControlPort, externalTorPassword, externalTorCookieFile, socks5ProxyHttpAddress, useAllProvidedNodes, numConnectionForBtc, genesisTxId, genesisBlockHeight, genesisTotalSupply, referralId, daoActivated, msgThrottlePerSec, msgThrottlePer10Sec, sendMsgThrottleTrigger, sendMsgThrottleSleep, ignoreLocalBtcNode; protected final boolean externalTorUseSafeCookieAuthentication, torStreamIsolation; public BisqEnvironment(OptionSet options) { this(new JOptCommandLinePropertySource(BISQ_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull( options))); } @SuppressWarnings("ConstantConditions") public BisqEnvironment(PropertySource commandLineProperties) { //CommonOptionKeys logLevel = getProperty(commandLineProperties, CommonOptionKeys.LOG_LEVEL_KEY, LOG_LEVEL_DEFAULT); useDevMode = getProperty(commandLineProperties, CommonOptionKeys.USE_DEV_MODE, ""); //AppOptionKeys userDataDir = getProperty(commandLineProperties, AppOptionKeys.USER_DATA_DIR_KEY, DEFAULT_USER_DATA_DIR); appName = getProperty(commandLineProperties, AppOptionKeys.APP_NAME_KEY, DEFAULT_APP_NAME); appDataDir = getProperty(commandLineProperties, AppOptionKeys.APP_DATA_DIR_KEY, appDataDir(userDataDir, appName)); staticAppDataDir = appDataDir; desktopWithHttpApi = getProperty(commandLineProperties, AppOptionKeys.DESKTOP_WITH_HTTP_API, "false"); desktopWithGrpcApi = getProperty(commandLineProperties, AppOptionKeys.DESKTOP_WITH_GRPC_API, "false"); ignoreDevMsg = getProperty(commandLineProperties, AppOptionKeys.IGNORE_DEV_MSG_KEY, ""); useDevPrivilegeKeys = getProperty(commandLineProperties, AppOptionKeys.USE_DEV_PRIVILEGE_KEYS, ""); referralId = getProperty(commandLineProperties, AppOptionKeys.REFERRAL_ID, ""); dumpStatistics = getProperty(commandLineProperties, AppOptionKeys.DUMP_STATISTICS, ""); maxMemory = getProperty(commandLineProperties, AppOptionKeys.MAX_MEMORY, ""); providers = getProperty(commandLineProperties, AppOptionKeys.PROVIDERS, ""); //NetworkOptionKeys seedNodes = getProperty(commandLineProperties, NetworkOptionKeys.SEED_NODES_KEY, ""); banList = getProperty(commandLineProperties, NetworkOptionKeys.BAN_LIST, ""); socks5ProxyBtcAddress = getProperty(commandLineProperties, NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS, ""); socks5ProxyHttpAddress = getProperty(commandLineProperties, NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS, ""); torRcFile = getProperty(commandLineProperties, NetworkOptionKeys.TORRC_FILE, ""); torRcOptions = getProperty(commandLineProperties, NetworkOptionKeys.TORRC_OPTIONS, ""); externalTorControlPort = getProperty(commandLineProperties, NetworkOptionKeys.EXTERNAL_TOR_CONTROL_PORT, ""); externalTorPassword = getProperty(commandLineProperties, NetworkOptionKeys.EXTERNAL_TOR_PASSWORD, ""); externalTorCookieFile = getProperty(commandLineProperties, NetworkOptionKeys.EXTERNAL_TOR_COOKIE_FILE, ""); externalTorUseSafeCookieAuthentication = commandLineProperties.containsProperty(NetworkOptionKeys.EXTERNAL_TOR_USE_SAFECOOKIE); torStreamIsolation = commandLineProperties.containsProperty(NetworkOptionKeys.TOR_STREAM_ISOLATION); msgThrottlePerSec = getProperty(commandLineProperties, NetworkOptionKeys.MSG_THROTTLE_PER_SEC, String.valueOf(ConnectionConfig.MSG_THROTTLE_PER_SEC)); msgThrottlePer10Sec = getProperty(commandLineProperties, NetworkOptionKeys.MSG_THROTTLE_PER_10_SEC, String.valueOf(ConnectionConfig.MSG_THROTTLE_PER_10_SEC)); sendMsgThrottleTrigger = getProperty(commandLineProperties, NetworkOptionKeys.SEND_MSG_THROTTLE_TRIGGER, String.valueOf(ConnectionConfig.SEND_MSG_THROTTLE_TRIGGER)); sendMsgThrottleSleep = getProperty(commandLineProperties, NetworkOptionKeys.SEND_MSG_THROTTLE_SLEEP, String.valueOf(ConnectionConfig.SEND_MSG_THROTTLE_SLEEP)); //DaoOptionKeys rpcUser = getProperty(commandLineProperties, DaoOptionKeys.RPC_USER, ""); rpcPassword = getProperty(commandLineProperties, DaoOptionKeys.RPC_PASSWORD, ""); rpcHost = getProperty(commandLineProperties, DaoOptionKeys.RPC_HOST, ""); rpcPort = getProperty(commandLineProperties, DaoOptionKeys.RPC_PORT, ""); rpcBlockNotificationPort = getProperty(commandLineProperties, DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT, ""); rpcBlockNotificationHost = getProperty(commandLineProperties, DaoOptionKeys.RPC_BLOCK_NOTIFICATION_HOST, ""); dumpBlockchainData = getProperty(commandLineProperties, DaoOptionKeys.DUMP_BLOCKCHAIN_DATA, ""); fullDaoNode = getProperty(commandLineProperties, DaoOptionKeys.FULL_DAO_NODE, ""); genesisTxId = getProperty(commandLineProperties, DaoOptionKeys.GENESIS_TX_ID, ""); genesisBlockHeight = getProperty(commandLineProperties, DaoOptionKeys.GENESIS_BLOCK_HEIGHT, "-1"); genesisTotalSupply = getProperty(commandLineProperties, DaoOptionKeys.GENESIS_TOTAL_SUPPLY, "-1"); daoActivated = getProperty(commandLineProperties, DaoOptionKeys.DAO_ACTIVATED, "true"); //BtcOptionKeys btcNodes = getProperty(commandLineProperties, BtcOptionKeys.BTC_NODES, ""); useTorForBtc = getProperty(commandLineProperties, BtcOptionKeys.USE_TOR_FOR_BTC, ""); userAgent = getProperty(commandLineProperties, BtcOptionKeys.USER_AGENT, "Bisq"); useAllProvidedNodes = getProperty(commandLineProperties, BtcOptionKeys.USE_ALL_PROVIDED_NODES, "false"); numConnectionForBtc = getProperty(commandLineProperties, BtcOptionKeys.NUM_CONNECTIONS_FOR_BTC, "9"); ignoreLocalBtcNode = getProperty(commandLineProperties, BtcOptionKeys.IGNORE_LOCAL_BTC_NODE, "false"); MutablePropertySources propertySources = getPropertySources(); propertySources.addFirst(commandLineProperties); try { propertySources.addLast(getAppDirProperties()); final String bannedPriceRelayNodesAsString = getProperty(FilterManager.BANNED_PRICE_RELAY_NODES, ""); bannedPriceRelayNodes = !bannedPriceRelayNodesAsString.isEmpty() ? Arrays.asList(StringUtils.deleteWhitespace(bannedPriceRelayNodesAsString).split(",")) : null; final String bannedSeedNodesAsString = getProperty(FilterManager.BANNED_SEED_NODES, ""); bannedSeedNodes = !bannedSeedNodesAsString.isEmpty() ? Arrays.asList(StringUtils.deleteWhitespace(bannedSeedNodesAsString).split(",")) : new ArrayList<>(); final String bannedBtcNodesAsString = getProperty(FilterManager.BANNED_BTC_NODES, ""); bannedBtcNodes = !bannedBtcNodesAsString.isEmpty() ? Arrays.asList(StringUtils.deleteWhitespace(bannedBtcNodesAsString).split(",")) : null; baseCurrencyNetwork = BaseCurrencyNetwork.valueOf(getProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK, getDefaultBaseCurrencyNetwork().name()).toUpperCase()); btcNetworkDir = Paths.get(appDataDir, baseCurrencyNetwork.name().toLowerCase()).toString(); File btcNetworkDirFile = new File(btcNetworkDir); if (!btcNetworkDirFile.exists()) //noinspection ResultOfMethodCallIgnored btcNetworkDirFile.mkdir(); // btcNetworkDir used in defaultProperties propertySources.addLast(defaultProperties()); } catch (Exception ex) { throw new BisqException(ex); } } public void saveBaseCryptoNetwork(BaseCurrencyNetwork baseCurrencyNetwork) { BisqEnvironment.baseCurrencyNetwork = baseCurrencyNetwork; setProperty(BtcOptionKeys.BASE_CURRENCY_NETWORK, baseCurrencyNetwork.name()); } public void saveBannedSeedNodes(@Nullable List<String> bannedNodes) { setProperty(FilterManager.BANNED_SEED_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes)); } public void saveBannedBtcNodes(@Nullable List<String> bannedNodes) { setProperty(FilterManager.BANNED_BTC_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes)); } public void saveBannedPriceRelayNodes(@Nullable List<String> bannedNodes) { setProperty(FilterManager.BANNED_PRICE_RELAY_NODES, bannedNodes == null ? "" : String.join(",", bannedNodes)); } protected void setProperty(String key, String value) { try { Resource resource = getAppDirPropertiesResource(); File file = resource.getFile(); Properties properties = new Properties(); if (file.exists()) { Object propertiesObject = getAppDirProperties().getSource(); if (propertiesObject instanceof Properties) { properties = (Properties) propertiesObject; } else { log.warn("propertiesObject not instance of Properties"); } } if (!value.isEmpty()) properties.setProperty(key, value); else properties.remove(key); log.debug("properties=" + properties); try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { properties.store(fileOutputStream, null); } catch (IOException e1) { log.error(e1.toString()); e1.printStackTrace(); throw new RuntimeException(e1); } } catch (Exception e2) { log.error(e2.toString()); e2.printStackTrace(); throw new RuntimeException(e2); } } public boolean getIgnoreLocalBtcNode() { return ignoreLocalBtcNode.equalsIgnoreCase("true"); } private Resource getAppDirPropertiesResource() { String location = String.format("file:%s/bisq.properties", appDataDir); return resourceLoader.getResource(location); } PropertySource<?> getAppDirProperties() throws Exception { Resource resource = getAppDirPropertiesResource(); if (!resource.exists()) return new PropertySource.StubPropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME); return new ResourcePropertySource(BISQ_APP_DIR_PROPERTY_SOURCE_NAME, resource); } private String getProperty (PropertySource properties, String propertyKey, String defaultValue) { return properties.containsProperty(propertyKey) ? (String) properties.getProperty(propertyKey) : defaultValue; } private PropertySource<?> defaultProperties() { return new PropertiesPropertySource(BISQ_DEFAULT_PROPERTY_SOURCE_NAME, new Properties() { { setProperty(CommonOptionKeys.LOG_LEVEL_KEY, logLevel); setProperty(CommonOptionKeys.USE_DEV_MODE, useDevMode); setProperty(NetworkOptionKeys.SEED_NODES_KEY, seedNodes); setProperty(NetworkOptionKeys.BAN_LIST, banList); setProperty(NetworkOptionKeys.TOR_DIR, Paths.get(btcNetworkDir, "tor").toString()); setProperty(NetworkOptionKeys.NETWORK_ID, String.valueOf(baseCurrencyNetwork.ordinal())); setProperty(NetworkOptionKeys.SOCKS_5_PROXY_BTC_ADDRESS, socks5ProxyBtcAddress); setProperty(NetworkOptionKeys.SOCKS_5_PROXY_HTTP_ADDRESS, socks5ProxyHttpAddress); setProperty(NetworkOptionKeys.TORRC_FILE, torRcFile); setProperty(NetworkOptionKeys.TORRC_OPTIONS, torRcOptions); setProperty(NetworkOptionKeys.EXTERNAL_TOR_CONTROL_PORT, externalTorControlPort); setProperty(NetworkOptionKeys.EXTERNAL_TOR_PASSWORD, externalTorPassword); setProperty(NetworkOptionKeys.EXTERNAL_TOR_COOKIE_FILE, externalTorCookieFile); if (externalTorUseSafeCookieAuthentication) setProperty(NetworkOptionKeys.EXTERNAL_TOR_USE_SAFECOOKIE, "true"); if (torStreamIsolation) setProperty(NetworkOptionKeys.TOR_STREAM_ISOLATION, "true"); setProperty(NetworkOptionKeys.MSG_THROTTLE_PER_SEC, msgThrottlePerSec); setProperty(NetworkOptionKeys.MSG_THROTTLE_PER_10_SEC, msgThrottlePer10Sec); setProperty(NetworkOptionKeys.SEND_MSG_THROTTLE_TRIGGER, sendMsgThrottleTrigger); setProperty(NetworkOptionKeys.SEND_MSG_THROTTLE_SLEEP, sendMsgThrottleSleep); setProperty(AppOptionKeys.APP_DATA_DIR_KEY, appDataDir); setProperty(AppOptionKeys.DESKTOP_WITH_HTTP_API, desktopWithHttpApi); setProperty(AppOptionKeys.DESKTOP_WITH_GRPC_API, desktopWithGrpcApi); setProperty(AppOptionKeys.IGNORE_DEV_MSG_KEY, ignoreDevMsg); setProperty(AppOptionKeys.USE_DEV_PRIVILEGE_KEYS, useDevPrivilegeKeys); setProperty(AppOptionKeys.REFERRAL_ID, referralId); setProperty(AppOptionKeys.DUMP_STATISTICS, dumpStatistics); setProperty(AppOptionKeys.APP_NAME_KEY, appName); setProperty(AppOptionKeys.MAX_MEMORY, maxMemory); setProperty(AppOptionKeys.USER_DATA_DIR_KEY, userDataDir); setProperty(AppOptionKeys.PROVIDERS, providers); setProperty(DaoOptionKeys.RPC_USER, rpcUser); setProperty(DaoOptionKeys.RPC_PASSWORD, rpcPassword); setProperty(DaoOptionKeys.RPC_HOST, rpcHost); setProperty(DaoOptionKeys.RPC_PORT, rpcPort); setProperty(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_PORT, rpcBlockNotificationPort); setProperty(DaoOptionKeys.RPC_BLOCK_NOTIFICATION_HOST, rpcBlockNotificationHost); setProperty(DaoOptionKeys.DUMP_BLOCKCHAIN_DATA, dumpBlockchainData); setProperty(DaoOptionKeys.FULL_DAO_NODE, fullDaoNode); setProperty(DaoOptionKeys.GENESIS_TX_ID, genesisTxId); setProperty(DaoOptionKeys.GENESIS_BLOCK_HEIGHT, genesisBlockHeight); setProperty(DaoOptionKeys.GENESIS_TOTAL_SUPPLY, genesisTotalSupply); setProperty(DaoOptionKeys.DAO_ACTIVATED, daoActivated); setProperty(BtcOptionKeys.BTC_NODES, btcNodes); setProperty(BtcOptionKeys.USE_TOR_FOR_BTC, useTorForBtc); setProperty(BtcOptionKeys.WALLET_DIR, btcNetworkDir); setProperty(BtcOptionKeys.USER_AGENT, userAgent); setProperty(BtcOptionKeys.USE_ALL_PROVIDED_NODES, useAllProvidedNodes); setProperty(BtcOptionKeys.NUM_CONNECTIONS_FOR_BTC, numConnectionForBtc); setProperty(BtcOptionKeys.IGNORE_LOCAL_BTC_NODE, ignoreLocalBtcNode); setProperty(UserAgent.NAME_KEY, appName); setProperty(UserAgent.VERSION_KEY, Version.VERSION); setProperty(Storage.STORAGE_DIR, Paths.get(btcNetworkDir, "db").toString()); setProperty(KeyStorage.KEY_STORAGE_DIR, Paths.get(btcNetworkDir, "keys").toString()); } }); } }
package ch.trick17.betterchecks; import static ch.trick17.betterchecks.Exceptions.illegalArgumentException; import static ch.trick17.betterchecks.Exceptions.illegalStateException; import java.net.URL; import java.util.Collection; import ch.trick17.betterchecks.fluent.CollectionCheck; import ch.trick17.betterchecks.fluent.DoubleCheck; import ch.trick17.betterchecks.fluent.FluentChecks; import ch.trick17.betterchecks.fluent.IntCheck; import ch.trick17.betterchecks.fluent.LongCheck; import ch.trick17.betterchecks.fluent.NumberCheck; import ch.trick17.betterchecks.fluent.ObjectArrayCheck; import ch.trick17.betterchecks.fluent.ObjectCheck; import ch.trick17.betterchecks.fluent.PrimitiveArrayCheck; import ch.trick17.betterchecks.fluent.StringCheck; import ch.trick17.betterchecks.fluent.UrlCheck; public abstract class Check { /* * Simple checks */ public static void arguments(final boolean condition, final String message) { if(!condition) throw illegalArgumentException(message); } public static void state(final boolean condition, final String message) { if(!condition) throw illegalStateException(message); } /* * Fluent argument checks */ /** * Returns a generic {@link ObjectCheck} which can be use to check basic * properties of all objects, e.g. {@link ObjectCheck#isNotNull()} or * {@link ObjectCheck#isInstanceOf(Class)}. * * @param argument * The argument to check * @return A check object with the argument "imprinted" * @see ObjectCheck */ public static ObjectCheck that(final Object argument) { return FluentChecks.getObjectCheck(ObjectCheck.class, argument); } /** * Returns a {@link StringCheck} which can be use to check various * properties of a {@link String}, e.g. {@link StringCheck#hasLength(int)} * or {@link StringCheck#contains(CharSequence)}. * * @param argument * The String argument to check * @return A check object with the argument "imprinted" * @see StringCheck */ public static StringCheck that(final String argument) { return FluentChecks.getObjectCheck(StringCheck.class, argument); } /** * Returns a {@link ObjectArrayCheck} which can be use to check various * properties of an object array (<code>Object[]</code>), e.g. * {@link ObjectArrayCheck#hasLength(int)} or * {@link ObjectArrayCheck#containsNoNull()}. * <p> * Note that since arrays are covariant in Java, any type of array (e.g. * <code>String[]</code> or <code>Date[]</code>) is accepted by this method. * The only exception are arrays of primitive types (e.g. <code>int[]</code> * ), which have their own <code>that(...)</code> methods. * * @param argument * The object array argument to check * @return A check object with the argument "imprinted" * @see ObjectArrayCheck */ public static ObjectArrayCheck that(final Object[] argument) { return FluentChecks.getObjectCheck(ObjectArrayCheck.class, argument); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>boolean[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final boolean[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>byte[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final byte[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>char[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final char[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>double[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final double[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>float[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final float[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>int[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final int[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>long[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final long[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link PrimitiveArrayCheck} which can be use to check various * properties of a primitive array (e.g. <code>int[]</code>), e.g. * {@link PrimitiveArrayCheck#hasLength(int)} or * {@link PrimitiveArrayCheck#isNotEmpty()}. * * @param argument * The <code>short[]</code> array argument to check * @return A check object with the argument "imprinted" * @see PrimitiveArrayCheck */ public static PrimitiveArrayCheck that(final short[] argument) { return FluentChecks.getPrimitiveArrayCheck(argument, argument != null ? argument.length : -1); } /** * Returns a {@link CollectionCheck} which can be use to check various * properties of a {@link Collection}, e.g. * {@link CollectionCheck#hasSize(int)} or * {@link CollectionCheck#containsNoNull()}. * * @param argument * The Collection argument to check * @return A check object with the argument "imprinted" * @see CollectionCheck */ public static CollectionCheck that(final Collection<?> argument) { return FluentChecks.<Collection<?>, CollectionCheck> getObjectCheck( CollectionCheck.class, argument); } // IMPROVE: Create MapCheck /** * Returns a {@link NumberCheck} which can be use to check various * properties of a {@link Number}, e.g. {@link NumberCheck#isPositive()} or * {@link NumberCheck#isBetween(Number, Number)}. * <p> * Note that this method is (should be) only used for numbers other than the * ones corresponding to the primitive type numbers ( * <code>byte, short, int, long, float, double</code>). Those types have * their own <code>that(...)</code> method and check classes with specific * features. Also, they do not require any boxing or unboxing. * * @param argument * The Number argument to check * @return A check object with the argument "imprinted" * @see NumberCheck */ public static NumberCheck that(final Number argument) { return FluentChecks.getObjectCheck(NumberCheck.class, argument); } /** * Returns an {@link UrlCheck} which can be use to check various properties * of an {@link URL}, e.g. {@link UrlCheck#hasProtocol(String)}. * <p> * Note that the typical use case is to obtain a UrlCheck via the * {@link StringCheck#isUrlWhich()} method which "converts" a * {@link StringCheck} to an UrlCheck. * * @param argument * The URL argument to check * @return A check object with the argument "imprinted" * @see UrlCheck */ public static UrlCheck that(final URL argument) { return FluentChecks.getObjectCheck(UrlCheck.class, argument); } /** * Returns an {@link IntCheck} which can be use to check various properties * of an <code>int</code>, e.g. {@link IntCheck#isPositive()}, * {@link IntCheck#isBetween(int, int)} or * {@link IntCheck#isValidIndex(Object[])}. * <p> * This method is (should be) also used for <code>short</code> and * <code>byte</code> arguments as there is no (need for a) separate check * class for them. * * @param argument * The <code>int</code> argument to check * @return A check object with the argument "imprinted" * @see IntCheck */ public static IntCheck that(final int argument) { return FluentChecks.getIntCheck(argument); } /** * Returns a {@link LongCheck} which can be use to check various properties * of a <code>long</code>, e.g. {@link LongCheck#isPositive()} or * {@link LongCheck#isBetween(long, long)}. * * @param argument * The <code>long</code> argument to check * @return A check object with the argument "imprinted" * @see LongCheck */ public static LongCheck that(final long argument) { return FluentChecks.getLongCheck(argument); } /** * Returns a {@link DoubleCheck} which can be use to check various * properties of an <code>double</code>, e.g. * {@link DoubleCheck#isPositive()}, * {@link DoubleCheck#isBetween(double, double)} or * {@link DoubleCheck#isNotNaN()}. * <p> * This method is (should be) also used for <code>float</code> arguments as * there is no (need for a) separate check class for them. * * @param argument * The <code>double</code> argument to check * @return A check object with the argument "imprinted" * @see DoubleCheck */ public static DoubleCheck that(final double argument) { return FluentChecks.getDoubleCheck(argument); } }
package com.segment.analytics; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.squareup.tape.FileObjectQueue; import com.squareup.tape.InMemoryObjectQueue; import com.squareup.tape.ObjectQueue; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import static android.os.Process.THREAD_PRIORITY_BACKGROUND; import static com.segment.analytics.Logger.OWNER_SEGMENT; import static com.segment.analytics.Logger.VERB_ENQUEUE; import static com.segment.analytics.Logger.VERB_FLUSH; import static com.segment.analytics.Utils.isConnected; import static com.segment.analytics.Utils.isNullOrEmpty; import static com.segment.analytics.Utils.panic; import static com.segment.analytics.Utils.quitThread; import static com.segment.analytics.Utils.toISO8601Date; /** * The actual service that posts data to Segment's servers. * * @since 2.3 */ class Segment { static final int REQUEST_ENQUEUE = 0; static final int REQUEST_FLUSH = 1; private static final String SEGMENT_THREAD_NAME = Utils.THREAD_PREFIX + "Segment"; private static final String TASK_QUEUE_FILE_NAME = "payload-task-queue-"; final Context context; final ObjectQueue<BasePayload> queue; final SegmentHTTPApi segmentHTTPApi; final int queueSize; final int flushInterval; final Stats stats; final Handler handler; final HandlerThread segmentThread; final Logger logger; final Map<String, Boolean> integrations; Segment(Context context, int queueSize, int flushInterval, SegmentHTTPApi segmentHTTPApi, ObjectQueue<BasePayload> queue, Map<String, Boolean> integrations, Stats stats, Logger logger) { this.context = context; this.queueSize = queueSize; this.segmentHTTPApi = segmentHTTPApi; this.queue = queue; this.stats = stats; this.logger = logger; this.integrations = integrations; this.flushInterval = flushInterval * 1000; segmentThread = new HandlerThread(SEGMENT_THREAD_NAME, THREAD_PRIORITY_BACKGROUND); segmentThread.start(); handler = new SegmentHandler(segmentThread.getLooper(), this); rescheduleFlush(); } static synchronized Segment create(Context context, int queueSize, int flushInterval, SegmentHTTPApi segmentHTTPApi, Map<String, Boolean> integrations, String tag, Stats stats, Logger logger) { File parent = context.getFilesDir(); ObjectQueue<BasePayload> queue; try { if (!parent.exists()) parent.mkdirs(); File queueFile = new File(parent, TASK_QUEUE_FILE_NAME + tag); queue = new FileObjectQueue<BasePayload>(queueFile, new PayloadConverter()); } catch (IOException e) { logger.error(OWNER_SEGMENT, Logger.VERB_INITIALIZE, null, e, "Unable to initialize disk queue with tag %s in directory %s," + "falling back to memory queue.", tag, parent.getAbsolutePath()); queue = new InMemoryObjectQueue<BasePayload>(); } return new Segment(context, queueSize, flushInterval, segmentHTTPApi, queue, integrations, stats, logger); } void dispatchEnqueue(final BasePayload payload) { handler.sendMessage(handler.obtainMessage(REQUEST_ENQUEUE, payload)); } void performEnqueue(BasePayload payload) { logger.debug(OWNER_SEGMENT, VERB_ENQUEUE, payload.id(), "queueSize: %s", queue.size()); try { queue.add(payload); } catch (Exception e) { logger.error(OWNER_SEGMENT, VERB_ENQUEUE, payload.id(), e, "payload: %s", payload); return; } // Check if we've reached the maximum queue size if (queue.size() >= queueSize) { performFlush(); } } void dispatchFlush() { handler.sendMessage(handler.obtainMessage(REQUEST_FLUSH)); } void performFlush() { if (queue.size() != 0 && isConnected(context)) { boolean batch = true; final List<BasePayload> payloads = new ArrayList<BasePayload>(queue.size()); try { queue.setListener(new ObjectQueue.Listener<BasePayload>() { @Override public void onAdd(ObjectQueue<BasePayload> queue, BasePayload entry) { payloads.add(entry); } @Override public void onRemove(ObjectQueue<BasePayload> queue) { } }); queue.setListener(null); } catch (Exception e) { logger.error(OWNER_SEGMENT, VERB_FLUSH, "Could not read queue. Flushing messages individually.", e, String.format("queue: %s", queue)); batch = false; } if (batch) { int count = payloads.size(); try { segmentHTTPApi.upload(new BatchPayload(payloads, integrations)); stats.dispatchFlush(count); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < count; i++) { queue.remove(); } } catch (IOException e) { logger.error(OWNER_SEGMENT, VERB_FLUSH, "Unable to flush messages.", e, "events: %s", count); } } else { // There was an error reading the queue, so we'll try to flush the payloads one at a time while (queue.size() > 0) { try { BasePayload payload = queue.peek(); try { segmentHTTPApi.upload( new BatchPayload(Collections.singletonList(payload), integrations)); stats.dispatchFlush(1); queue.remove(); } catch (IOException e) { logger.error(OWNER_SEGMENT, VERB_FLUSH, "Unable to dispatchFlush payload.", e, "payload: %s", payload); } } catch (Exception e) { // This is an unrecoverable error, we can't read the entry from disk logger.error(OWNER_SEGMENT, VERB_FLUSH, "Unable to read payload.", e, "queue: %s", queue); queue.remove(); } } } } rescheduleFlush(); } private void rescheduleFlush() { handler.removeMessages(REQUEST_FLUSH); handler.sendMessageDelayed(handler.obtainMessage(REQUEST_FLUSH), flushInterval); } void shutdown() { quitThread(segmentThread); } static class BatchPayload extends JsonMap { /** * The sent timestamp is an ISO-8601-formatted string that, if present on a message, can be * used to correct the original timestamp in situations where the local clock cannot be * trusted, for example in our mobile libraries. The sentAt and receivedAt timestamps will be * assumed to have occurred at the same time, and therefore the difference is the local clock * skew. */ private static final String SENT_AT_KEY = "sentAt"; /** * A dictionary of integration names that the message should be proxied to. 'All' is a special * name that applies when no key for a specific integration is found, and is case-insensitive. */ private static final String INTEGRATIONS_KEY = "integrations"; BatchPayload(List<BasePayload> batch, Map<String, Boolean> integrations) { put("batch", batch); put(INTEGRATIONS_KEY, integrations); put(SENT_AT_KEY, toISO8601Date(new Date())); } } private static class SegmentHandler extends Handler { private final Segment segment; SegmentHandler(Looper looper, Segment segment) { super(looper); this.segment = segment; } @Override public void handleMessage(final Message msg) { switch (msg.what) { case REQUEST_ENQUEUE: BasePayload payload = (BasePayload) msg.obj; segment.performEnqueue(payload); break; case REQUEST_FLUSH: segment.performFlush(); break; default: panic("Unknown dispatcher message." + msg.what); } } } static class PayloadConverter implements FileObjectQueue.Converter<BasePayload> { static final Charset UTF_8 = Charset.forName("UTF-8"); @Override public BasePayload from(byte[] bytes) throws IOException { String json = new String(bytes, UTF_8); if (isNullOrEmpty(json)) { throw new IOException("Cannot deserialize payload from empty byte array."); } return new BasePayload(json); } @Override public void toStream(BasePayload payload, OutputStream bytes) throws IOException { String json = payload.toString(); if (isNullOrEmpty(json)) { throw new IOException("Cannot serialize payload : " + payload); } OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bytes, UTF_8); outputStreamWriter.write(json); outputStreamWriter.close(); } } }
package de.otto.jlineup.config; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import de.otto.jlineup.browser.Browser; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public final class Config { public static final String LINEUP_CONFIG_DEFAULT_PATH = "./lineup.json"; public static final String EXAMPLE_URL = "https: public static final int DEFAULT_WARMUP_BROWSER_CACHE_TIME = 0; public static final int DEFAULT_REPORT_FORMAT = 2; static final Browser.Type DEFAULT_BROWSER = Browser.Type.PHANTOMJS; static final float DEFAULT_MAX_DIFF = 0; public static final int DEFAULT_WINDOW_HEIGHT = 800; static final float DEFAULT_GLOBAL_WAIT_AFTER_PAGE_LOAD = 0f; public static final int DEFAULT_WINDOW_WIDTH = 800; static final String DEFAULT_PATH = "/"; static final int DEFAULT_MAX_SCROLL_HEIGHT = 100000; static final int DEFAULT_WAIT_AFTER_PAGE_LOAD = 0; static final int DEFAULT_WAIT_AFTER_SCROLL = 0; static final int DEFAULT_WAIT_FOR_NO_ANIMATION_AFTER_SCROLL = 0; static final int DEFAULT_WAIT_FOR_FONTS_TIME = 0; static final int DEFAULT_THREADS = 1; static final int DEFAULT_PAGELOAD_TIMEOUT = 120; static final int DEFAULT_SCREENSHOT_RETRIES = 0; static final int DEFAULT_GLOBAL_TIMEOUT = 600; public final Map<String, UrlConfig> urls; public final Browser.Type browser; @SerializedName(value = "wait-after-page-load", alternate = "async-wait") public final Float globalWaitAfterPageLoad; @SerializedName(value = "page-load-timeout") public final int pageLoadTimeout; @SerializedName("window-height") public final Integer windowHeight; @SerializedName("report-format") public final Integer reportFormat; @SerializedName("screenshot-retries") public final int screenshotRetries; @SerializedName("threads") public int threads; @SerializedName("timeout") public final int globalTimeout; @SerializedName("debug") public final boolean debug; @SerializedName("log-to-file") public final boolean logToFile; private final static Gson gson = new Gson(); /* Used by GSON to set default values */ public Config() { this(configBuilder()); } private Config(Builder builder) { urls = builder.urls; browser = builder.browser; globalWaitAfterPageLoad = builder.globalWaitAfterPageLoad; pageLoadTimeout = builder.pageLoadTimeout; windowHeight = builder.windowHeight; threads = builder.threads; screenshotRetries = builder.screenshotRetries; reportFormat = builder.reportFormat; globalTimeout = builder.globalTimeout; debug = builder.debug; logToFile = builder.logToFile; } @Override public String toString() { return "Config{" + "urls=" + urls + ", browser=" + browser + ", globalWaitAfterPageLoad=" + globalWaitAfterPageLoad + ", pageLoadTimeout=" + pageLoadTimeout + ", windowHeight=" + windowHeight + ", reportFormat=" + reportFormat + ", screenshotRetries=" + screenshotRetries + ", threads=" + threads + ", globalTimeout=" + globalTimeout + ", debug=" + debug + ", logToFile=" + logToFile + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Config config = (Config) o; if (pageLoadTimeout != config.pageLoadTimeout) return false; if (screenshotRetries != config.screenshotRetries) return false; if (threads != config.threads) return false; if (globalTimeout != config.globalTimeout) return false; if (debug != config.debug) return false; if (logToFile != config.logToFile) return false; if (urls != null ? !urls.equals(config.urls) : config.urls != null) return false; if (browser != config.browser) return false; if (globalWaitAfterPageLoad != null ? !globalWaitAfterPageLoad.equals(config.globalWaitAfterPageLoad) : config.globalWaitAfterPageLoad != null) return false; if (windowHeight != null ? !windowHeight.equals(config.windowHeight) : config.windowHeight != null) return false; return reportFormat != null ? reportFormat.equals(config.reportFormat) : config.reportFormat == null; } @Override public int hashCode() { int result = urls != null ? urls.hashCode() : 0; result = 31 * result + (browser != null ? browser.hashCode() : 0); result = 31 * result + (globalWaitAfterPageLoad != null ? globalWaitAfterPageLoad.hashCode() : 0); result = 31 * result + pageLoadTimeout; result = 31 * result + (windowHeight != null ? windowHeight.hashCode() : 0); result = 31 * result + (reportFormat != null ? reportFormat.hashCode() : 0); result = 31 * result + screenshotRetries; result = 31 * result + threads; result = 31 * result + globalTimeout; result = 31 * result + (debug ? 1 : 0); result = 31 * result + (logToFile ? 1 : 0); return result; } public static Config defaultConfig() { return defaultConfig(EXAMPLE_URL); } public static Config defaultConfig(String url) { return configBuilder().withUrls(ImmutableMap.of(url, new UrlConfig())).build(); } public static Builder configBuilder() { return new Builder(); } public static Config exampleConfig() { return configBuilder() .withUrls(ImmutableMap.of("http: new UrlConfig( ImmutableList.of("/","someOtherPath"), DEFAULT_MAX_DIFF, ImmutableList.of( new Cookie("exampleCookieName", "exampleValue", "http: ), ImmutableMap.of("live", "www"), ImmutableMap.of("exampleLocalStorageKey", "value"), ImmutableMap.of("exampleSessionStorageKey", "value"), ImmutableList.of(600,800,1000), DEFAULT_MAX_SCROLL_HEIGHT, DEFAULT_WAIT_AFTER_PAGE_LOAD, DEFAULT_WAIT_AFTER_SCROLL, DEFAULT_WAIT_FOR_NO_ANIMATION_AFTER_SCROLL, DEFAULT_WARMUP_BROWSER_CACHE_TIME, "console.log('This is JavaScript!')", DEFAULT_WAIT_FOR_FONTS_TIME ))) .build(); } public static Config readConfig(final Parameters parameters) throws FileNotFoundException { return Config.readConfig(parameters.getWorkingDirectory(), parameters.getConfigFile()); } public static Config readConfig(final String workingDir, final String configFileName) throws FileNotFoundException { List<String> searchPaths = new ArrayList<>(); Path configFilePath = Paths.get(workingDir + "/" + configFileName); searchPaths.add(configFilePath.toString()); if (!Files.exists(configFilePath)) { configFilePath = Paths.get(configFileName); searchPaths.add(configFilePath.toString()); if (!Files.exists(configFilePath)) { configFilePath = Paths.get(LINEUP_CONFIG_DEFAULT_PATH); searchPaths.add(configFilePath.toString()); if (!Files.exists(configFilePath)) { String cwd = Paths.get(".").toAbsolutePath().normalize().toString(); throw new FileNotFoundException("Config file not found. Search locations were: " + Arrays.toString(searchPaths.toArray()) + " - working dir: " + cwd); } } } BufferedReader br = new BufferedReader(new FileReader(configFilePath.toString())); return gson.fromJson(br, Config.class); } public static final class Builder { private Map<String, UrlConfig> urls = null; private Browser.Type browser = DEFAULT_BROWSER; private float globalWaitAfterPageLoad = DEFAULT_GLOBAL_WAIT_AFTER_PAGE_LOAD; private int pageLoadTimeout = DEFAULT_PAGELOAD_TIMEOUT; private int windowHeight = DEFAULT_WINDOW_HEIGHT; private int reportFormat = DEFAULT_REPORT_FORMAT; private int screenshotRetries = DEFAULT_SCREENSHOT_RETRIES; private int threads = DEFAULT_THREADS; private int globalTimeout = DEFAULT_GLOBAL_TIMEOUT; private boolean debug = false; private boolean logToFile = false; private Builder() { } public Builder withUrls(Map<String, UrlConfig> val) { urls = val; return this; } public Builder withBrowser(Browser.Type val) { browser = val; return this; } public Builder withGlobalWaitAfterPageLoad(float val) { globalWaitAfterPageLoad = val; return this; } public Builder withPageLoadTimeout(int val) { pageLoadTimeout = val; return this; } public Builder withWindowHeight(int val) { windowHeight = val; return this; } public Builder withReportFormat(int val) { reportFormat = val; return this; } public Builder withScreenshotRetries(int val) { screenshotRetries = val; return this; } public Builder withThreads(int val) { threads = val; return this; } public Builder withDebug(boolean val) { debug = val; return this; } public Builder withLogToFile(boolean val) { logToFile = val; return this; } public Builder withGlobalTimeout(int val) { globalTimeout = val; return this; } public Config build() { return new Config(this); } } }
package jenkins.util; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.model.Computer; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.slaves.ComputerListener; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import jenkins.security.MasterToSlaveCallable; import jenkins.util.io.OnMaster; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Centralizes calls to {@link System#getProperty(String)} and related calls. * This allows us to get values not just from environment variables but also from * the {@link ServletContext}, so properties like {@code hudson.DNSMultiCast.disabled} * can be set in {@code context.xml} and the app server's boot script does not * have to be changed. * * <p>This should be used to obtain hudson/jenkins "app"-level parameters * (e.g. {@code hudson.DNSMultiCast.disabled}), but not for system parameters * (e.g. {@code os.name}). * * <p>If you run multiple instances of Jenkins in the same virtual machine and wish * to obtain properties from {@code context.xml}, make sure these Jenkins instances use * different ClassLoaders. Tomcat, for example, does this automatically. If you do * not use different ClassLoaders, the values of properties specified in * {@code context.xml} is undefined. * * <p>Property access is logged on {@link Level#CONFIG}. Note that some properties * may be accessed by Jenkins before logging is configured properly, so early access to * some properties may not be logged. * * <p>While it looks like it on first glance, this cannot be mapped to {@link EnvVars}, * because {@link EnvVars} is only for build variables, not Jenkins itself variables. * * @since TODO */ @SuppressFBWarnings(value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Currently Jenkins instance may have one ond only one context") public class SystemProperties { @FunctionalInterface private interface Handler { @CheckForNull String getString(String key); } private static final Handler NULL_HANDLER = key -> null; private static @NonNull Handler handler = NULL_HANDLER; // declared in WEB-INF/web.xml @Restricted(NoExternalUse.class) public static final class Listener implements ServletContextListener, OnMaster { /** * Called by the servlet container to initialize the {@link ServletContext}. */ @Override public void contextInitialized(ServletContextEvent event) { ServletContext theContext = event.getServletContext(); handler = key -> { if (StringUtils.isNotBlank(key)) { try { return theContext.getInitParameter(key); } catch (SecurityException ex) { // Log exception and go on LOGGER.log(Level.CONFIG, "Access to the property {0} is prohibited", key); } } return null; }; } @Override public void contextDestroyed(ServletContextEvent event) { handler = NULL_HANDLER; } } private static final Set<String> ALLOW_ON_AGENT = Collections.synchronizedSet(new HashSet<>()); /** * Mark a key whose value should be made accessible in agent JVMs. * * @param key Property key to be explicitly allowed */ public static void allowOnAgent(String key) { ALLOW_ON_AGENT.add(key); } @Extension @Restricted(NoExternalUse.class) public static final class AgentCopier extends ComputerListener { @Override public void preOnline(Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException { channel.call(new CopySystemProperties()); } private static final class CopySystemProperties extends MasterToSlaveCallable<Void, RuntimeException> { private static final long serialVersionUID = 1; private final Map<String, String> snapshot; CopySystemProperties() { // Take a snapshot of those system properties and context variables available on the master at the time the agent starts which have been whitelisted for that purpose. snapshot = new HashMap<>(); for (String key : ALLOW_ON_AGENT) { snapshot.put(key, getString(key)); } LOGGER.log(Level.FINE, "taking snapshot of {0}", snapshot); } @Override public Void call() throws RuntimeException { handler = new CopiedHandler(snapshot); return null; } } private static final class CopiedHandler implements Handler { private final Map<String, String> snapshot; CopiedHandler(Map<String, String> snapshot) { this.snapshot = snapshot; } @Override public String getString(String key) { return snapshot.get(key); } } } /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(SystemProperties.class.getName()); private SystemProperties() {} @CheckForNull public static String getString(String key) { return getString(key, null); } public static String getString(String key, @CheckForNull String def) { return getString(key, def, Level.CONFIG); } public static String getString(String key, @CheckForNull String def, Level logLevel) { String value = System.getProperty(key); // keep passing on any exceptions if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (system): {0} => {1}", new Object[] {key, value}); } return value; } value = handler.getString(key); if (value != null) { if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (context): {0} => {1}", new Object[]{key, value}); } return value; } value = def; if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property (default): {0} => {1}", new Object[] {key, value}); } return value; } /** * Returns {@code true} if the system property * named by the argument exists and is equal to the string * {@code "true"}. If the system property does not exist, return * {@code "false"}. if a property by this name exists in the {@link ServletContext} * and is equal to the string {@code "true"}. * * This behaves just like {@link Boolean#getBoolean(java.lang.String)}, except that it * also consults the {@link ServletContext}'s "init" parameters. * * @param name the system property name. * @return the {@code boolean} value of the system property. */ public static boolean getBoolean(String name) { return getBoolean(name, false); } /** * Returns {@code true} if the system property * named by the argument exists and is equal to the string * {@code "true"}, or a default value. If the system property does not exist, return * {@code "true"} if a property by this name exists in the {@link ServletContext} * and is equal to the string {@code "true"}. If that property does not * exist either, return the default value. * * This behaves just like {@link Boolean#getBoolean(java.lang.String)} with a default * value, except that it also consults the {@link ServletContext}'s "init" parameters. * * @param name the system property name. * @param def a default value. * @return the {@code boolean} value of the system property. */ public static boolean getBoolean(String name, boolean def) { String v = getString(name); if (v != null) { return Boolean.parseBoolean(v); } return def; } /** * Returns {@link Boolean#TRUE} if the named system property exists and is equal to the string {@code "true} * (ignoring case), returns {@link Boolean#FALSE} if the system property exists and doesn't equal {@code "true} * otherwise returns {@code null} if the named system property does not exist. * * @param name the system property name. * @return {@link Boolean#TRUE}, {@link Boolean#FALSE} or {@code null} * @since 2.16 */ @CheckForNull public static Boolean optBoolean(String name) { String v = getString(name); return v == null ? null : Boolean.parseBoolean(v); } /** * Determines the integer value of the system property with the * specified name. * * This behaves just like {@link Integer#getInteger(java.lang.String)}, except that it * also consults the {@link ServletContext}'s "init" parameters. * * @param name property name. * @return the {@code Integer} value of the property. */ @CheckForNull public static Integer getInteger(String name) { return getInteger(name, null); } /** * Determines the integer value of the system property with the * specified name, or a default value. * * This behaves just like {@code Integer.getInteger(String,Integer)}, except that it * also consults the {@code ServletContext}'s "init" parameters. If neither exist, * return the default value. * * @param name property name. * @param def a default value. * @return the {@code Integer} value of the property. * If the property is missing, return the default value. * Result may be {@code null} only if the default value is {@code null}. */ public static Integer getInteger(String name, Integer def) { return getInteger(name, def, Level.CONFIG); } /** * Determines the integer value of the system property with the * specified name, or a default value. * * This behaves just like {@code Integer.getInteger(String,Integer)}, except that it * also consults the {@code ServletContext}'s "init" parameters. If neither exist, * return the default value. * * @param name property name. * @param def a default value. * @param logLevel the level of the log if the provided system property name cannot be decoded into Integer. * @return the {@code Integer} value of the property. * If the property is missing, return the default value. * Result may be {@code null} only if the default value is {@code null}. */ public static Integer getInteger(String name, Integer def, Level logLevel) { String v = getString(name); if (v != null) { try { return Integer.decode(v); } catch (NumberFormatException e) { // Ignore, fallback to default if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property. Value is not integer: {0} => {1}", new Object[] {name, v}); } } } return def; } /** * Determines the long value of the system property with the * specified name. * * This behaves just like {@link Long#getLong(java.lang.String)}, except that it * also consults the {@link ServletContext}'s "init" parameters. * * @param name property name. * @return the {@code Long} value of the property. */ @CheckForNull public static Long getLong(String name) { return getLong(name, null); } /** * Determines the integer value of the system property with the * specified name, or a default value. * * This behaves just like {@code Long.getLong(String,Long)}, except that it * also consults the {@link ServletContext}'s "init" parameters. If neither exist, * return the default value. * * @param name property name. * @param def a default value. * @return the {@code Long} value of the property. * If the property is missing, return the default value. * Result may be {@code null} only if the default value is {@code null}. */ public static Long getLong(String name, Long def) { return getLong(name, def, Level.CONFIG); } /** * Determines the integer value of the system property with the * specified name, or a default value. * * This behaves just like {@link Long#getLong(String, Long)}, except that it * also consults the {@link ServletContext}'s "init" parameters. If neither exist, * return the default value. * * @param name property name. * @param def a default value. * @param logLevel the level of the log if the provided system property name cannot be decoded into Long. * @return the {@code Long} value of the property. * If the property is missing, return the default value. * Result may be {@code null} only if the default value is {@code null}. */ public static Long getLong(String name, Long def, Level logLevel) { String v = getString(name); if (v != null) { try { return Long.decode(v); } catch (NumberFormatException e) { // Ignore, fallback to default if (LOGGER.isLoggable(logLevel)) { LOGGER.log(logLevel, "Property. Value is not long: {0} => {1}", new Object[] {name, v}); } } } return def; } }
package nl.eernie.jmoribus; import nl.eernie.jmoribus.exception.UnableToParseStoryException; import nl.eernie.jmoribus.model.Scenario; import nl.eernie.jmoribus.model.Step; import nl.eernie.jmoribus.model.StepType; import nl.eernie.jmoribus.model.Story; import nl.eernie.jmoribus.parser.ParseableStory; import nl.eernie.jmoribus.parser.StoryParser; import org.junit.Test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mock; public class ParserTest { @Test public void testParse() throws IOException { InputStream fileInputStream = getClass().getResourceAsStream("/test.story"); ParseableStory parseableStory = new ParseableStory(fileInputStream, "test.story"); Story story = StoryParser.parseStory(parseableStory); assertEquals("test.story", story.getUniqueIdentifier()); assertEquals("Some awsome title", story.getTitle()); assertEquals("In order to realize a named business value" + System.lineSeparator() + " As a explicit system actor" + System.lineSeparator() + " I want to gain some beneficial outcome which furthers the goal", story.getFeature().getContent()); assertSame(story, story.getFeature().getStory()); assertEquals(1, story.getScenarios().size()); Scenario scenario = story.getScenarios().get(0); assertEquals("scenario description", scenario.getTitle()); assertSame(story, scenario.getStory()); assertEquals(4, scenario.getSteps().size()); Step step = scenario.getSteps().remove(0); assertStep(StepType.GIVEN, "a system state", scenario, 12, step); step = scenario.getSteps().remove(0); assertStep(StepType.WHEN, "I do something", scenario, 13, step); step = scenario.getSteps().remove(0); assertStep(StepType.THEN, "system is in a different state", scenario, 16, step); step = scenario.getSteps().remove(0); assertStep(StepType.THEN, "another assertion", scenario, 17, step); } private void assertStep(StepType type, String stepString, Scenario scenario, int lineNumber, Step step) { assertSame(scenario, step.getStepContainer()); assertEquals(type, step.getStepType()); assertEquals(stepString, step.getFirstStepLine().getText()); assertEquals(lineNumber, step.getLineNumber()); } @Test public void testMultipleScenarioParse() throws IOException { InputStream fileInputStream = getClass().getResourceAsStream("/multiScenario.story"); ParseableStory parseableStory = new ParseableStory(fileInputStream, "test.story"); Story story = StoryParser.parseStory(parseableStory); assertEquals(6, story.getScenarios().size()); } @Test public void testMultipleStories() throws IOException { List<ParseableStory> parseableStories = new ArrayList<>(3); InputStream fileInputStream = getClass().getResourceAsStream("/multiScenario.story"); parseableStories.add(new ParseableStory(fileInputStream, "MultiScenarioTitle")); fileInputStream = getClass().getResourceAsStream("/test2.story"); parseableStories.add(new ParseableStory(fileInputStream, "testTitle")); fileInputStream = getClass().getResourceAsStream("/referring/referring.story"); parseableStories.add(new ParseableStory(fileInputStream, "PrologueTest")); List<Story> stories = StoryParser.parseStories(parseableStories); assertEquals(3, stories.size()); assertEquals("MultiScenarioTitle", stories.get(0).getTitle()); } @SuppressWarnings("unchecked") @Test(expected = UnableToParseStoryException.class) public void testUnparsableStory() throws IOException { FileInputStream fileInputStream = mock(FileInputStream.class); when(fileInputStream.read()).thenThrow(IOException.class); ParseableStory parseableStory = new ParseableStory(fileInputStream, "typo.story"); StoryParser.parseStory(parseableStory); } }
package ts.nodejs; import java.io.File; import java.util.ArrayList; import java.util.List; import ts.TypeScriptException; import ts.utils.FileUtils; /** * Abstract class for node.js process. * */ public abstract class AbstractNodejsProcess implements INodejsProcess { /** * The node.js base dir. If null, it uses installed node.js */ protected final File nodejsFile; /** * The project dir where tsconfig.json is hosted. */ protected final File projectDir; private final INodejsLaunchConfiguration launchConfiguration; /** * Process listeners. */ protected final List<INodejsProcessListener> listeners; public AbstractNodejsProcess(File nodejsFile, File projectDir) throws TypeScriptException { this(nodejsFile, projectDir, null); } /** * Nodejs process constructor. * * @param nodejsFile * the node.exe file. * @param projectDir * the project base dir where tsconfig.json is hosted. * @throws TernException */ public AbstractNodejsProcess(File nodejsFile, File projectDir, INodejsLaunchConfiguration launchConfiguration) throws TypeScriptException { this.projectDir = checkProjectDir(projectDir); this.nodejsFile = checkNodejsFile(nodejsFile); this.listeners = new ArrayList<INodejsProcessListener>(); this.launchConfiguration = launchConfiguration; } private File checkProjectDir(File projectDir) throws TypeScriptException { if (projectDir == null) { throw new TypeScriptException("project directory cannot be null"); } if (!projectDir.exists()) { throw new TypeScriptException("Cannot find project directory " + FileUtils.getPath(projectDir)); } return projectDir; } private File checkNodejsFile(File nodejsFile) throws TypeScriptException { if (nodejsFile == null) { // node.js file cannot be null. In this case it uses installed // node.js return null; } if (!nodejsFile.exists()) { throw new TypeScriptException("Cannot find node file " + FileUtils.getPath(nodejsFile)); } return nodejsFile; } protected List<String> createNodeArgs() { if (launchConfiguration == null) { return null; } return launchConfiguration.createNodeArgs(); } /** * return the project dir where tsconfig.json is hosted. * * @return */ public File getProjectDir() { return projectDir; } /** * Add the given process listener. * * @param listener */ public void addProcessListener(INodejsProcessListener listener) { synchronized (listeners) { listeners.add(listener); } } /** * Remove the given process listener. * * @param listener */ public void removeProcessListener(INodejsProcessListener listener) { synchronized (listeners) { listeners.remove(listener); } } /** * Notify start process. */ protected void notifyCreateProcess(List<String> commands, File projectDir) { synchronized (listeners) { for (INodejsProcessListener listener : listeners) { listener.onCreate(this, commands, projectDir); } } } /** * Notify start process. * * @param startTime * time when node.js process is started. */ protected void notifyStartProcess(long startTime) { synchronized (listeners) { for (INodejsProcessListener listener : listeners) { listener.onStart(this); } } } /** * Notify stop process. */ protected void notifyStopProcess() { synchronized (listeners) { for (INodejsProcessListener listener : listeners) { listener.onStop(this); } } } /** * Notify data process. * * @param jsonObject */ protected void notifyMessage(String message) { synchronized (listeners) { for (INodejsProcessListener listener : listeners) { listener.onMessage(this, message); } } } /** * Notify error process. */ protected void notifyErrorProcess(String line) { synchronized (listeners) { for (INodejsProcessListener listener : listeners) { listener.onError(AbstractNodejsProcess.this, line); } } } }
package mockit.coverage; import java.io.*; import mockit.coverage.reporting.*; import mockit.coverage.output.*; final class OutputFileGenerator extends Thread { private final String outputFormat; private final String outputDir; private final String[] sourceDirs; private String[] classPath; OutputFileGenerator(String outputFormat, String outputDir, String[] sourceDirs) { this.outputDir = outputDir; this.sourceDirs = sourceDirs; String format = outputFormat.length() > 0 ? outputFormat : outputFormatFromClasspath(); if (format.length() == 0) { format = "html-nocp"; } this.outputFormat = format; } private String outputFormatFromClasspath() { classPath = System.getProperty("java.class.path").split(File.pathSeparator); String result = ""; if (availableInTheClasspath("xmlbasic")) { result = "xml-nocp"; } else if (availableInTheClasspath("xmlfull")) { result = "xml"; } if (availableInTheClasspath("htmlbasic")) { result += "html-nocp"; } else if (availableInTheClasspath("htmlfull")) { result += "html"; } return result; } private boolean availableInTheClasspath(String jarFileNameSuffix) { String desiredJarFile = "jmockit-coverage-" + jarFileNameSuffix + ".jar"; for (String cpEntry : classPath) { if (cpEntry.endsWith(desiredJarFile)) { return true; } } return false; } boolean isOutputToBeGenerated() { return outputFormat.length() > 0; } boolean isWithCallPoints() { return outputFormat.contains("xml") && !outputFormat.contains("xml-nocp") || outputFormat.contains("html") && !outputFormat.contains("html-nocp"); } @Override public void run() { CoverageData coverageData = CoverageData.instance(); try { generateXMLOutputFileIfRequested(coverageData); generateHTMLReportIfRequested(coverageData); } catch (IOException e) { throw new RuntimeException(e); } } private void generateXMLOutputFileIfRequested(CoverageData coverageData) throws IOException { if (outputFormat.contains("xml-nocp")) { new BasicXmlWriter(coverageData).writeToXmlFile(outputDir); } else if (outputFormat.contains("xml")) { new FullXmlWriter(coverageData).writeToXmlFile(outputDir); } } private void generateHTMLReportIfRequested(CoverageData coverageData) throws IOException { if (outputFormat.contains("html-nocp")) { new BasicCoverageReport(outputDir, sourceDirs, coverageData).generate(); } else if (outputFormat.contains("html")) { new FullCoverageReport(outputDir, sourceDirs, coverageData).generate(); } } }
package com.psddev.dari.db; import java.io.IOException; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer; import org.apache.solr.client.solrj.request.UpdateRequest; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.MoreLikeThisParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.Profiler; import com.psddev.dari.util.PullThroughValue; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SettingsException; import com.psddev.dari.util.Stats; import com.psddev.dari.util.UuidUtils; public class SolrDatabase extends AbstractDatabase<SolrServer> { public static final String DEFAULT_COMMIT_WITHIN_SETTING = "dari/solrDefaultCommitWithin"; public static final String SERVER_URL_SUB_SETTING = "serverUrl"; public static final String READ_SERVER_URL_SUB_SETTING = "readServerUrl"; public static final String COMMIT_WITHIN_SUB_SETTING = "commitWithin"; public static final String VERSION_SUB_SETTING = "version"; public static final String SAVE_DATA_SUB_SETTING = "saveData"; public static final double DEFAULT_COMMIT_WITHIN = 0.0; public static final String ID_FIELD = "id"; public static final String TYPE_ID_FIELD = "typeId"; public static final String DATA_FIELD = "data"; public static final String FIELDS_FIELD = "_t__fields"; public static final String ALL_FIELD = "all"; public static final String SCORE_FIELD = "score"; public static final String SUGGESTION_FIELD = "_e_suggestField"; public static final String SCORE_EXTRA = "solr.score"; public static final String NORMALIZED_SCORE_EXTRA = "solr.normalizedScore"; private static final int INITIAL_FETCH_SIZE = 100; private static final Logger LOGGER = LoggerFactory.getLogger(SolrDatabase.class); private static final Pattern UUID_PATTERN = Pattern.compile("([A-Fa-f0-9]{8})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{4})-([A-Fa-f0-9]{12})"); private static final String SHORT_NAME = "Solr"; private static final Stats STATS = new Stats(SHORT_NAME); private static final String ADD_STATS_OPERATION = "Add"; private static final String COMMIT_STATS_OPERATION = "Commit"; private static final String DELETE_STATS_OPERATION = "Delete"; private static final String QUERY_STATS_OPERATION = "Query"; private static final String ADD_PROFILER_EVENT = SHORT_NAME + " " + ADD_STATS_OPERATION; private static final String COMMIT_PROFILER_EVENT = SHORT_NAME + " " + COMMIT_STATS_OPERATION; private static final String DELETE_PROFILER_EVENT = SHORT_NAME + " " + DELETE_STATS_OPERATION; private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION; private volatile SolrServer server; private volatile SolrServer readServer; private volatile Double commitWithin; private volatile String version; private volatile boolean saveData = true; /** Returns the underlying Solr server. */ public SolrServer getServer() { return server; } /** Sets the underlying Solr server. */ public void setServer(SolrServer server) { this.server = server; schema.invalidate(); } /** Returns the underlying Solr read server. */ public SolrServer getReadServer() { return readServer; } /** Sets the underlying Solr read server. */ public void setReadServer(SolrServer readServer) { this.readServer = readServer; schema.invalidate(); } public Double getCommitWithin() { return commitWithin; } public double getEffectiveCommitWithin() { Double commitWithin = getCommitWithin(); if (commitWithin == null) { commitWithin = Settings.get(Double.class, DEFAULT_COMMIT_WITHIN_SETTING); if (commitWithin == null) { commitWithin = DEFAULT_COMMIT_WITHIN; } } return commitWithin; } public void setCommitWithin(Double newCommitWithin) { commitWithin = newCommitWithin; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public boolean isSaveData() { return saveData; } public void setSaveData(boolean saveData) { this.saveData = saveData; } private static class SolrSchema { public final int version; private SolrField defaultType; private final Map<String, SolrField> types = new HashMap<String, SolrField>(); public SolrSchema(int version) { this.version = version; } public void setDefaultField(SolrField defaultType) { this.defaultType = defaultType; } public void mapFields(SolrField type, String... internalTypes) { if (internalTypes != null) { for (String internalType : internalTypes) { types.put(internalType, type); } } } public SolrField getField(String internalType) { SolrField type = types.get(internalType); return type != null ? type : defaultType; } } private static class SolrField { public final String facetPrefix; public final String searchPrefix; public final String sortPrefix; public final Set<String> addPrefixes; public final Set<String> setPrefixes; public SolrField(String facetPrefix, String searchPrefix, String sortPrefix, boolean allMultiValued) { this.facetPrefix = facetPrefix; this.searchPrefix = searchPrefix; this.sortPrefix = sortPrefix; Set<String> addPrefixes = new HashSet<String>(); addPrefixes.add(facetPrefix); addPrefixes.add(searchPrefix); Set<String> setPrefixes = new HashSet<String>(); setPrefixes.add(sortPrefix); if (allMultiValued) { setPrefixes.removeAll(addPrefixes); } else { addPrefixes.removeAll(setPrefixes); } this.addPrefixes = Collections.unmodifiableSet(addPrefixes); this.setPrefixes = Collections.unmodifiableSet(setPrefixes); } public SolrField(String facetPrefix, String searchPrefix, String sortPrefix) { this(facetPrefix, searchPrefix, sortPrefix, false); } } private final transient PullThroughValue<SolrSchema> schema = new PullThroughValue<SolrSchema>() { @Override protected SolrSchema produce() { Exception error = query("*:*"); if (error != null) { throw new IllegalStateException("Solr server isn't available!", error); } SolrSchema schema; if (query("_e_test:1") == null) { schema = new SolrSchema(10); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); schema.mapFields(new SolrField("_g_", "_g_", "_g_"), ObjectField.LOCATION_TYPE); } else if (query("_query_:\"{!geofilt pt=0.0,0.0 sfield=_g_test d=1}\"") == null) { schema = new SolrSchema(9); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); schema.mapFields(new SolrField("_g_", "_g_", "_g_"), ObjectField.LOCATION_TYPE); } else if (query("_sl_test:1") == null) { schema = new SolrSchema(8); schema.setDefaultField(new SolrField("_sl_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } else if (query("_ss_test:1") == null) { schema = new SolrSchema(7); schema.setDefaultField(new SolrField("_s_", "_t_", "_ss_")); schema.mapFields(new SolrField("_b_", "_b_", "_bs_"), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_ds_"), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_ls_"), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_us_"), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } else { schema = new SolrSchema(6); schema.setDefaultField(new SolrField("_s_", "_t_", "_s_")); schema.mapFields(new SolrField("_b_", "_b_", "_b_", true), ObjectField.BOOLEAN_TYPE); schema.mapFields(new SolrField("_d_", "_d_", "_d_", true), ObjectField.NUMBER_TYPE); schema.mapFields(new SolrField("_l_", "_l_", "_l_", true), ObjectField.DATE_TYPE); schema.mapFields(new SolrField("_u_", "_u_", "_u_", true), ObjectField.RECORD_TYPE, ObjectField.UUID_TYPE); } LOGGER.info("Using Solr schema version [{}]", schema.version); return schema; } private Exception query(String query) { SolrServer server = openReadConnection(); SolrQuery solrQuery = new SolrQuery(query); solrQuery.setRows(0); try { server.query(solrQuery); return null; } catch (SolrServerException ex) { return ex; } } }; private SolrField getSolrField(String internalType) { return schema.get().getField(internalType); } private Query.MappedKey mapFullyDenormalizedKey(Query<?> query, String key) { Query.MappedKey mappedKey = query.mapDenormalizedKey(getEnvironment(), key); if (mappedKey.hasSubQuery()) { throw new Query.NoFieldException(query.getGroup(), key); } else { return mappedKey; } } public SolrQuery buildQueryFacetByField(Query<?> query, String field) { SolrQuery solrQuery = buildQuery(query); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, field); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).searchPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, field); } solrQuery.setFacet(true); solrQuery.addFacetField(solrField); return solrQuery; } /** Builds a Solr query based on the given {@code query}. */ public SolrQuery buildQuery(Query<?> query) { SolrQuery solrQuery = new SolrQuery(); StringBuilder queryBuilder = new StringBuilder(); Predicate predicate = query.getPredicate(); if (predicate != null) { appendPredicate(query, queryBuilder, predicate); } Query<?> facetedQuery = query.getFacetQuery(); if (facetedQuery != null) { StringBuilder fq = new StringBuilder(); appendPredicate(facetedQuery, fq, query.getPredicate()); solrQuery.addFacetQuery(fq.toString()); solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); } Map<String, Object> facetedFields = query.getFacetedFields(); if (facetedFields.size() > 0) { boolean facet = false; for(String field : facetedFields.keySet()) { Object value = facetedFields.get(field); if (value != null) { Predicate p = new ComparisonPredicate(PredicateParser.EQUALS_ANY_OPERATOR, false, field, ObjectUtils.to(Iterable.class, value)); StringBuilder filter = new StringBuilder(); appendPredicate(query, filter, p); solrQuery.addFilterQuery(filter.toString()); } else { Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, field); solrQuery.addFacetField(getSolrField(mappedKey.getInternalType()).facetPrefix + mappedKey.getIndexKey(null)); facet = true; } } if (facet) { solrQuery.setFacetMinCount(1); solrQuery.setFacet(true); } } if (!query.isFromAll()) { Set<ObjectType> types = query.getConcreteTypes(getEnvironment()); if (!isAllTypes(types)) { if (types.isEmpty()) { if (queryBuilder.length() > 0) { queryBuilder.insert(0, '('); queryBuilder.append(") && "); } queryBuilder.append("-*:*"); } else { if (queryBuilder.length() > 0) { queryBuilder.insert(0, '('); queryBuilder.append(") && "); } queryBuilder.append("typeId:("); for (UUID typeId : query.getConcreteTypeIds(this)) { queryBuilder.append(Static.escapeValue(typeId)); queryBuilder.append(" || "); } queryBuilder.setLength(queryBuilder.length() - 4); queryBuilder.append(")"); } } } if (queryBuilder.length() < 1) { queryBuilder.append("*:*"); } StringBuilder sortBuilder = new StringBuilder(); for (Sorter sorter : query.getSorters()) { String operator = sorter.getOperator(); boolean isAscending = Sorter.ASCENDING_OPERATOR.equals(operator); if (isAscending || Sorter.DESCENDING_OPERATOR.equals(operator)) { String queryKey = (String) sorter.getOptions().get(0); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, queryKey); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).sortPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, queryKey); } solrQuery.addSortField(solrField, isAscending ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc); continue; } else if (Sorter.RELEVANT_OPERATOR.equals(operator)) { Predicate sortPredicate = (Predicate) sorter.getOptions().get(1); double boost = ObjectUtils.to(double.class, sorter.getOptions().get(0)); if (boost < 0.0) { boost = -boost; sortPredicate = new CompoundPredicate(PredicateParser.NOT_OPERATOR, Arrays.asList(sortPredicate)); } solrQuery.addSortField(SCORE_FIELD, SolrQuery.ORDER.desc); sortBuilder.append("("); appendPredicate(query, sortBuilder, sortPredicate); sortBuilder.append(")^"); sortBuilder.append(boost); sortBuilder.append(" || "); continue; } else if (schema.get().version >= 9) { boolean closest = Sorter.CLOSEST_OPERATOR.equals(operator); if (closest || Sorter.FARTHEST_OPERATOR.equals(operator)) { Location location = (Location) sorter.getOptions().get(1); Query.MappedKey mappedKey = mapFullyDenormalizedKey(query, (String) sorter.getOptions().get(0)); String internalType = mappedKey.getInternalType(); String oldField = solrQuery.get("sfield"); String newField = getSolrField(internalType).sortPrefix + mappedKey.getIndexKey(null); if (oldField == null) { solrQuery.set("sfield", newField); } else if (!oldField.equals(newField)) { throw new IllegalArgumentException("Can't query against more than one location at a time!"); } StringBuilder geoBuilder = new StringBuilder(); geoBuilder.append("geodist("); geoBuilder.append(location.getX()); geoBuilder.append(","); geoBuilder.append(location.getY()); geoBuilder.append(")"); solrQuery.setSortField(geoBuilder.toString(), closest ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc); continue; } } throw new UnsupportedSorterException(this, sorter); } if (sortBuilder.length() > 0) { queryBuilder.insert(0, "("); queryBuilder.append(") && ("); queryBuilder.append(sortBuilder); queryBuilder.append("*:*)"); } solrQuery.setQuery(queryBuilder.toString()); return solrQuery; } /** * Transforms and appends the given {@code predicate} to the given * {@code queryBuilder}. */ private void appendPredicate(Query<?> query, StringBuilder queryBuilder, Predicate predicate) { if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; String operator = compoundPredicate.getOperator(); CompoundOperator solrOperator = COMPOUND_OPERATORS.get(operator); if (solrOperator != null) { List<Predicate> children = compoundPredicate.getChildren(); if (children.isEmpty()) { queryBuilder.append("*:*"); } else { solrOperator.appendCompound(this, query, queryBuilder, children); } return; } } else if (predicate instanceof ComparisonPredicate) { ComparisonPredicate comparisonPredicate = (ComparisonPredicate) predicate; String queryKey = comparisonPredicate.getKey(); Query.MappedKey mappedKey = query.mapDenormalizedKey(getEnvironment(), queryKey); String solrField = SPECIAL_FIELDS.get(mappedKey); if (solrField == null) { String internalType = mappedKey.getInternalType(); if (internalType != null) { solrField = getSolrField(internalType).searchPrefix + mappedKey.getIndexKey(null); } } if (solrField == null) { throw new UnsupportedIndexException(this, queryKey); } String operator = comparisonPredicate.getOperator(); ComparisonOperator solrOperator = COMPARISON_OPERATORS.get(operator); if (solrOperator != null) { List<Object> values; Query<?> valueQuery = mappedKey.getSubQueryWithComparison(comparisonPredicate); if (valueQuery == null) { values = comparisonPredicate.resolveValues(this); } else { values = new ArrayList<Object>(); for (Object item : readPartial( valueQuery, 0, Settings.getOrDefault(int.class, "dari/subQueryResolveLimit", 100)). getItems()) { values.add(State.getInstance(item).getId()); } } solrOperator.appendComparison(queryBuilder, solrField, values); return; } } throw new UnsupportedPredicateException(this, predicate); } private final Map<String, CompoundOperator> COMPOUND_OPERATORS; { Map<String, CompoundOperator> m = new HashMap<String, CompoundOperator>(); m.put(PredicateParser.AND_OPERATOR, new StandardCompoundOperator("&&")); m.put(PredicateParser.OR_OPERATOR, new StandardCompoundOperator("||")); m.put(PredicateParser.NOT_OPERATOR, new CompoundOperator() { @Override protected void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children) { queryBuilder.append("(*:*"); for (Predicate child : children) { queryBuilder.append(" && -("); database.appendPredicate(query, queryBuilder, child); queryBuilder.append(")"); } queryBuilder.append(")"); } }); COMPOUND_OPERATORS = m; } private abstract class CompoundOperator { protected abstract void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children); } private class StandardCompoundOperator extends CompoundOperator { private final String join; public StandardCompoundOperator(String join) { this.join = join; } protected void appendCompound( SolrDatabase database, Query<?> query, StringBuilder queryBuilder, List<Predicate> children) { for (Predicate child : children) { queryBuilder.append("("); database.appendPredicate(query, queryBuilder, child); queryBuilder.append(") "); queryBuilder.append(join); queryBuilder.append(" "); } queryBuilder.setLength(queryBuilder.length() - join.length() - 2); } } private final Map<Query.MappedKey, String> SPECIAL_FIELDS; { Map<Query.MappedKey, String> m = new HashMap<Query.MappedKey, String>(); m.put(Query.MappedKey.ID, ID_FIELD); m.put(Query.MappedKey.TYPE, TYPE_ID_FIELD); m.put(Query.MappedKey.ANY, ALL_FIELD); SPECIAL_FIELDS = m; } private final Map<String, ComparisonOperator> COMPARISON_OPERATORS; { Map<String, ComparisonOperator> m = new HashMap<String, ComparisonOperator>(); m.put(PredicateParser.EQUALS_ANY_OPERATOR, new ExactMatchOperator(false, true)); m.put(PredicateParser.NOT_EQUALS_ALL_OPERATOR, new ExactMatchOperator(true, false)); m.put(PredicateParser.MATCHES_ANY_OPERATOR, new FullTextMatchOperator(false, true)); m.put(PredicateParser.MATCHES_ALL_OPERATOR, new FullTextMatchOperator(false, false)); m.put(PredicateParser.STARTS_WITH_OPERATOR, new MatchOperator(false, true) { @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { comparisonBuilder.append(escapeValue(value)); comparisonBuilder.append("*"); } }); m.put(PredicateParser.LESS_THAN_OPERATOR, new RangeOperator("{* TO ", "}")); m.put(PredicateParser.LESS_THAN_OR_EQUALS_OPERATOR, new RangeOperator("[* TO ", "]")); m.put(PredicateParser.GREATER_THAN_OPERATOR, new RangeOperator("{", " TO *}")); m.put(PredicateParser.GREATER_THAN_OR_EQUALS_OPERATOR, new RangeOperator("[", " TO *]")); COMPARISON_OPERATORS = m; } private abstract class ComparisonOperator { private final boolean isNegate; private final boolean isAny; private final String join; public ComparisonOperator(boolean isNegate, boolean isAny, String join) { this.isNegate = isNegate; this.isAny = isAny; this.join = join; } public void appendComparison( StringBuilder queryBuilder, String solrField, List<Object> values) { StringBuilder comparisonBuilder = new StringBuilder(); for (Object value : values) { if (ObjectUtils.isBlank(value)) { comparisonBuilder.append("(*:* && -*:*)"); } else { addValue(comparisonBuilder, solrField, value); } comparisonBuilder.append(join); } if (comparisonBuilder.length() > 0) { comparisonBuilder.setLength(comparisonBuilder.length() - 4); if (isNegate) { queryBuilder.append("(*:* && -"); } // field:(...) queryBuilder.append(changeSolrField(solrField)); queryBuilder.append(":("); queryBuilder.append(comparisonBuilder); queryBuilder.append(")"); if (isNegate) { queryBuilder.append(")"); } } else if (isAny) { queryBuilder.append("(*:* && -*:*)"); } else { queryBuilder.append("*:*"); } } protected abstract void addValue(StringBuilder comparisonBuilder, String solrField, Object value); protected String changeSolrField(String solrField) { return solrField.startsWith("_t_") ? (schema.get().version >= 8 ? "_sl_" : "_s_") + solrField.substring(3) : solrField; } protected String escapeValue(Object value) { String escaped = Static.escapeValue(value); if (escaped != null && schema.get().version >= 8) { escaped = escaped.trim().toLowerCase(Locale.ENGLISH); } return escaped; } } private abstract class MatchOperator extends ComparisonOperator { public MatchOperator(boolean isNegate, boolean isAny) { super(isNegate, isAny, isNegate ? (isAny ? " && " : " || ") : (isAny ? " || " : " && ")); } @Override protected void addValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (value == Query.MISSING_VALUE) { if (solrField.startsWith("_g_")) { comparisonBuilder.append("(*:* && -[-90,-180 TO 90,180])"); } else { comparisonBuilder.append("(*:* && -[* TO *])"); } } else { addNonMissingValue(comparisonBuilder, solrField, value); } } protected abstract void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value); } private class ExactMatchOperator extends MatchOperator { public ExactMatchOperator(boolean isNegate, boolean isAny) { super(isNegate, isAny); } @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (value instanceof Region) { List<Location> locations = ((Region) value).getLocations(); double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for (Location location : locations) { double x = location.getX(); double y = location.getY(); if (minX > x) { minX = x; } else if (maxX < x) { maxX = x; } if (minY > y) { minY = y; } else if (maxY < y) { maxY = y; } } comparisonBuilder.append('['); comparisonBuilder.append(minX); comparisonBuilder.append(','); comparisonBuilder.append(minY); comparisonBuilder.append(" TO "); comparisonBuilder.append(maxX); comparisonBuilder.append(','); comparisonBuilder.append(maxY); comparisonBuilder.append(']'); } else { comparisonBuilder.append(escapeValue(value)); } } } private final static char[] UUID_WORD_CHARS = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; private static String uuidToWord(UUID uuid) { if (uuid == null) { return null; } byte[] bytes = UuidUtils.toBytes(uuid); int bytesLength = bytes.length; int wordLast = bytesLength * 2; byte currentByte; char[] word = new char[wordLast + 1]; for (int byteIndex = 0, hexIndex = 0; byteIndex < bytesLength; ++ byteIndex, ++ hexIndex) { currentByte = bytes[byteIndex]; word[hexIndex] = UUID_WORD_CHARS[(currentByte & 0xf0) >> 4]; ++ hexIndex; word[hexIndex] = UUID_WORD_CHARS[(currentByte & 0x0f)]; } word[wordLast] = 'z'; return new String(word); } private class FullTextMatchOperator extends MatchOperator { public FullTextMatchOperator(boolean isNegate, boolean isAny) { super(isNegate, isAny); } @Override protected void addNonMissingValue(StringBuilder comparisonBuilder, String solrField, Object value) { if (ALL_FIELD.equals(solrField)) { if ("*".equals(value)) { comparisonBuilder.append("*:*"); return; } else { UUID valueUuid = ObjectUtils.to(UUID.class, value); if (valueUuid != null) { comparisonBuilder.append(uuidToWord(valueUuid)); return; } } } String valueString = value.toString(); int valueStringLength = valueString.length(); if (valueStringLength == 0) { comparisonBuilder.append("(*:* && -*:*)"); } else { String escapedValue = escapeValue(valueString).toLowerCase(Locale.ENGLISH); if (valueString.length() == 1) { comparisonBuilder.append(escapedValue); } else { comparisonBuilder.append("("); comparisonBuilder.append(escapedValue); comparisonBuilder.append(" || "); comparisonBuilder.append(escapedValue); comparisonBuilder.append("*)"); } } } @Override protected String changeSolrField(String solrField) { return solrField; } } private class RangeOperator extends ComparisonOperator { private final String prefix; private final String suffix; public RangeOperator(String prefix, String suffix) { super(false, true, " || "); this.prefix = prefix; this.suffix = suffix; } @Override protected void addValue(StringBuilder comparisonBuilder, String solrField, Object value) { String valueString = value.toString(); if (schema.get().version >= 8) { valueString = valueString.trim().toLowerCase(Locale.ENGLISH); } comparisonBuilder.append(prefix); comparisonBuilder.append("\""); comparisonBuilder.append(valueString.replaceAll("([\\\\\"])", "\\\\$1")); comparisonBuilder.append("\""); comparisonBuilder.append(suffix); } } public SolrQuery buildSimilarQuery(Object object) { State state = State.getInstance(object); SolrQuery solrQuery = new SolrQuery(); solrQuery.setQueryType("/mlt"); solrQuery.set(MoreLikeThisParams.SIMILARITY_FIELDS, ALL_FIELD); solrQuery.set(MoreLikeThisParams.MIN_WORD_LEN, 2); solrQuery.set(MoreLikeThisParams.BOOST, true); StringBuilder streamBody = new StringBuilder(); addToStreamBody(streamBody, state.getSimpleValues()); solrQuery.set(CommonParams.STREAM_BODY, streamBody.toString()); solrQuery.add(CommonParams.FQ, "-id:" + state.getId()); return solrQuery; } private void addToStreamBody(StringBuilder streamBody, Object value) { if (value == null || value instanceof Boolean) { } else if (value instanceof Iterable) { for (Object item : (Iterable<?>) value) { addToStreamBody(streamBody, item); } } else if (value instanceof Map) { for (Object item : ((Map<?, ?>) value).values()) { addToStreamBody(streamBody, item); } } else { streamBody.append(value); streamBody.append(" "); } } /** * Queries the underlying Solr server with the given {@code query} * and options from the given {@code query}. */ public QueryResponse queryWithOptions(SolrQuery solrQuery, Query<?> query) { if (query != null && query.isReferenceOnly()) { solrQuery.setFields(ID_FIELD, TYPE_ID_FIELD); } else { solrQuery.setFields("*", SCORE_FIELD); } Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT); try { return openReadConnection().query(solrQuery, SolrRequest.METHOD.POST); } catch (SolrServerException ex) { throw new DatabaseException(this, String.format( "Unable to read from the Solr server using [%s]!", solrQuery), ex); } finally { double duration = timer.stop(QUERY_STATS_OPERATION); Profiler.Static.stopThreadEvent(solrQuery); LOGGER.debug( "Read from the Solr server using [{}] in [{}]ms", solrQuery, duration); } } /** * Queries the underlying Solr server with the given * {@code solrQuery}. */ public QueryResponse query(SolrQuery solrQuery) { return queryWithOptions(solrQuery, null); } /** * Queries the underlying Solr server for a partial list of objects * that match the given {@code solrQuery} with the options from * the given {@code query}. */ public <T> SolrPaginatedResult<T> queryPartialWithOptions(SolrQuery solrQuery, Query<T> query) { QueryResponse response = queryWithOptions(solrQuery, query); SolrDocumentList documents = response.getResults(); long count = 0; List<T> objects = new ArrayList<T>(); if (documents != null) { count = documents.getNumFound(); for (SolrDocument document : documents) { objects.add(createSavedObjectWithDocument(document, documents, query)); } } return new SolrPaginatedResult<T>( solrQuery.getStart(), solrQuery.getRows(), count, objects, response.getLimitingFacets(), query != null ? query.getClass() : null, Settings.isDebug() ? solrQuery : null); } /** * Queries the underlying Solr server for a partial list of objects * that match the given {@code solrQuery}. */ public SolrPaginatedResult<Object> queryPartial(SolrQuery solrQuery) { return queryPartialWithOptions(solrQuery, null); } /** * Creates a previously saved object using the given {@code document}. */ private <T> T createSavedObjectWithDocument( SolrDocument document, SolrDocumentList documents, Query<T> query) { T object = createSavedObject(document.get(TYPE_ID_FIELD), document.get(ID_FIELD), query); State objectState = State.getInstance(object); if (!objectState.isReferenceOnly()) { String data = (String) document.get(DATA_FIELD); if (ObjectUtils.isBlank(data)) { Object original = objectState.getDatabase().readFirst(Query.from(Object.class).where("_id = ?", objectState.getId())); if (original != null) { objectState.putAll(State.getInstance(original).getValues()); } } else { @SuppressWarnings("unchecked") Map<String, Object> values = (Map<String, Object>) ObjectUtils.fromJson(data); objectState.putAll(values); } } Map<String, Object> extras = objectState.getExtras(); Object score = document.get(SCORE_FIELD); extras.put(SCORE_EXTRA, score); Float maxScore = documents.getMaxScore(); if (maxScore != null && score instanceof Number) { extras.put(NORMALIZED_SCORE_EXTRA, ((Number) score).floatValue() / maxScore); } // Set up Metric fields ObjectType type = objectState.getType(); if (type != null) { for (ObjectField field : type.getFields()) { if (field.as(MetricDatabase.FieldData.class).isMetricValue()) { objectState.putByPath(field.getInternalName(), new Metric(objectState, field.getInternalName())); } } } return swapObjectType(query, object); } /** Commits all pending writes in the underlying Solr server. */ public void commit() { doCommit(openConnection()); } private void doCommit(SolrServer server) { try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(COMMIT_PROFILER_EVENT); try { server.commit(); } finally { double duration = timer.stop(COMMIT_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr commit time: [{}]ms", duration); } } catch (Exception ex) { throw new DatabaseException(this, "Can't commit to Solr!", ex); } } @Override protected void doInitialize(String settingsKey, Map<String, Object> settings) { String url = ObjectUtils.to(String.class, settings.get(SERVER_URL_SUB_SETTING)); if (ObjectUtils.isBlank(url)) { throw new SettingsException( settingsKey + "/" + SERVER_URL_SUB_SETTING, "No Solr server URL!"); } try { setServer(new CommonsHttpSolrServer(url)); String readUrl = ObjectUtils.to(String.class, settings.get(READ_SERVER_URL_SUB_SETTING)); if (!ObjectUtils.isBlank(readUrl)) { setReadServer(new CommonsHttpSolrServer(readUrl)); } } catch (MalformedURLException ex) { throw new SettingsException( settingsKey + "/" + SERVER_URL_SUB_SETTING, String.format("[%s] is not a valid URL!", url)); } setCommitWithin(ObjectUtils.to(Double.class, settings.get(COMMIT_WITHIN_SUB_SETTING))); setVersion(ObjectUtils.to(String.class, settings.get(VERSION_SUB_SETTING))); Boolean saveData = ObjectUtils.to(Boolean.class, settings.get(SAVE_DATA_SUB_SETTING)); if (saveData != null) { setSaveData(saveData); } } @Override public SolrServer openConnection() { return getServer(); } @Override protected SolrServer doOpenReadConnection() { SolrServer server = getReadServer(); return server != null ? server : getServer(); } @Override public void closeConnection(SolrServer server) { } @Override public <T> List<T> readAll(Query<T> query) { // Solr sometimes throws an OutOfMemoryError when the limit // is too large, so read all using 2 separate queries. SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(INITIAL_FETCH_SIZE); PaginatedResult<T> result = queryPartialWithOptions(solrQuery, query); int count = (int) result.getCount(); List<T> all = new ArrayList<T>(count); all.addAll(result.getItems()); if (count > INITIAL_FETCH_SIZE) { solrQuery.setStart(INITIAL_FETCH_SIZE); solrQuery.setRows(count - INITIAL_FETCH_SIZE); all.addAll(queryPartialWithOptions(solrQuery, query).getItems()); } return all; } @Override public long readCount(Query<?> query) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(0); SolrDocumentList documents = queryWithOptions(solrQuery, query).getResults(); return documents != null ? documents.getNumFound() : 0L; } @Override public <T> T readFirst(Query<T> query) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart(0); solrQuery.setRows(1); SolrDocumentList documents = queryWithOptions(solrQuery, query).getResults(); if (documents != null) { for (SolrDocument document : documents) { return createSavedObjectWithDocument(document, documents, query); } } return null; } @Override public Date readLastUpdate(Query<?> query) { throw new UnsupportedOperationException(); } @Override public <T> PaginatedResult<T> readPartial(Query<T> query, long offset, int limit) { SolrQuery solrQuery = buildQuery(query); solrQuery.setStart((int) offset); solrQuery.setRows(limit); return queryPartialWithOptions(solrQuery, query); } @Override public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) { if (fields == null || fields.length != 1) { return super.readPartialGrouped(query, offset, limit, fields); } SolrQuery solrQuery = buildQueryFacetByField(query, fields[0]); solrQuery.setStart(0); solrQuery.setRows(0); solrQuery.setFacetMinCount(1); List<Grouping<T>> groupings = new ArrayList<Grouping<T>>(); QueryResponse response = queryWithOptions(solrQuery, query); for (FacetField facetField : response.getFacetFields()) { List<FacetField.Count> values = facetField.getValues(); if (values == null) { continue; } for (FacetField.Count value : facetField.getValues()) { Object key = value.getName(); ObjectField field = mapFullyDenormalizedKey(query, fields[0]).getField(); if (field != null) { key = StateValueUtils.toJavaValue(query.getDatabase(), null, field, field.getInternalItemType(), key); } groupings.add(new SolrGrouping<T>(Arrays.asList(key), query, fields, value.getCount())); } } return new PaginatedResult<Grouping<T>>(offset, limit, groupings); } /** Solr-specific implementation of {@link Grouping}. */ private class SolrGrouping<T> extends AbstractGrouping<T> { private long count; public SolrGrouping(List<Object> keys, Query<T> query, String[] fields, long count) { super(keys, query, fields); this.count = count; } @Override protected Aggregate createAggregate(String field) { throw new UnsupportedOperationException(); } @Override public long getCount() { return count; } } @Override public void deleteByQuery(Query<?> query) { try { SolrServer server = openConnection(); server.deleteByQuery(buildQuery(query).getQuery()); doCommit(server); } catch (Exception ex) { throw new DatabaseException(this, String.format( "Can't delete documents matching [%s] from Solr!", query), ex); } } @Override protected void commitTransaction(SolrServer server, boolean isImmediate) { if (isImmediate && getEffectiveCommitWithin() <= 0.0) { doCommit(openConnection()); } } private void processUpdate( SolrServer server, UpdateRequest update, boolean isImmediate) throws IOException, SolrServerException { if (isImmediate) { double commitWithin = getEffectiveCommitWithin(); if (commitWithin > 0.0) { update.setCommitWithin((int) (commitWithin * 1000)); } } update.process(server); } @Override protected void doSaves(SolrServer server, boolean isImmediate, List<State> states) { Set<String> databaseGroups = getGroups(); List<SolrInputDocument> documents = new ArrayList<SolrInputDocument>(); for (State state : states) { ObjectType type = state.getType(); if (type != null) { boolean savable = false; for (String typeGroup : type.getGroups()) { if (databaseGroups.contains(typeGroup)) { savable = true; break; } } if (!savable) { continue; } } else { // skip processing States with no typeId continue; } Map<String, Object> stateValues = state.getSimpleValues(); SolrInputDocument document = new SolrInputDocument(); StringBuilder allBuilder = new StringBuilder(); documents.add(document); document.setField(ID_FIELD, state.getId()); document.setField(TYPE_ID_FIELD, state.getVisibilityAwareTypeId()); if (isSaveData()) { document.setField(DATA_FIELD, ObjectUtils.toJson(stateValues)); } if (schema.get().version >= 10) { Set<String> typeAheadFields = type.as(TypeModification.class).getTypeAheadFields(); Map<String, List<String>> typeAheadFieldsMap = type.as(TypeModification.class).getTypeAheadFieldsMap(); if (!typeAheadFields.isEmpty()) { for (String typeAheadField : typeAheadFields) { String value = ObjectUtils.to(String.class, state.getValue(typeAheadField)); // Hack for a client. if (!ObjectUtils.isBlank(value)) { value = value.replaceAll("\\{", "").replaceAll("\\}", ""); document.setField(SUGGESTION_FIELD, value); } } } if (!typeAheadFieldsMap.isEmpty()) { for (Map.Entry<String, List<String>> entry : typeAheadFieldsMap.entrySet()) { String typeAheadField = entry.getKey(); List<String> targetFields = entry.getValue(); String value = ObjectUtils.to(String.class, state.getValue(typeAheadField)); if (!ObjectUtils.isBlank(targetFields)) { for (String targetField : targetFields) { if (!ObjectUtils.isBlank(value)) { value = value.replaceAll("\\{", "").replaceAll("\\}", ""); document.setField("_e_" + targetField, value); } } } } } } for (Map.Entry<String, Object> entry : stateValues.entrySet()) { String fieldName = entry.getKey(); ObjectField field = state.getField(fieldName); if (field == null) { continue; } String uniqueName = field.getUniqueName(); addDocumentValues( document, allBuilder, field, uniqueName, entry.getValue()); } document.setField(ALL_FIELD, allBuilder.toString()); } int documentsSize = documents.size(); if (documentsSize == 0) { return; } try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(ADD_PROFILER_EVENT, documentsSize); try { UpdateRequest update = new UpdateRequest(); update.add(documents); processUpdate(server, update, isImmediate); } finally { double duration = timer.stop(ADD_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr add: [{}], Time: [{}]ms", documentsSize, duration); } } catch (Exception ex) { throw new DatabaseException(this, String.format( "Can't add [%s] documents to Solr!", documentsSize), ex); } } // Adds all items within the given {@code value} to the given // {@code document} at the given {@code name}. private void addDocumentValues( SolrInputDocument document, StringBuilder allBuilder, ObjectField field, String name, Object value) { if (value == null) { return; } if (value instanceof List) { for (Object item : (List<?>) value) { addDocumentValues(document, allBuilder, field, name, item); } return; } if (value instanceof Recordable) { value = ((Recordable) value).getState().getSimpleValues(); } if (value instanceof Map) { Map<?, ?> valueMap = (Map<?, ?>) value; if (schema.get().version >= 9 && field.getInternalItemType().equals(ObjectField.LOCATION_TYPE)) { if (valueMap.containsKey("x") && valueMap.containsKey("y")) { value = valueMap.get("x") + "," + valueMap.get("y"); } else { return; } } else { UUID valueTypeId = ObjectUtils.to(UUID.class, valueMap.get(StateValueUtils.TYPE_KEY)); if (valueTypeId == null) { for (Object item : valueMap.values()) { addDocumentValues(document, allBuilder, field, name, item); } return; } else { UUID valueId = ObjectUtils.to(UUID.class, valueMap.get(StateValueUtils.REFERENCE_KEY)); if (valueId == null) { allBuilder.append(valueTypeId).append(' '); ObjectType valueType = getEnvironment().getTypeById(valueTypeId); if (valueType != null) { for (Map.Entry<?, ?> entry : valueMap.entrySet()) { String subName = entry.getKey().toString(); ObjectField subField = valueType.getField(subName); if (subField != null) { addDocumentValues( document, allBuilder, subField, name + "/" + subName, entry.getValue()); } } } return; } else { value = valueId; Set<ObjectField> denormFields = field.getEffectiveDenormalizedFields(getEnvironment().getTypeById(valueTypeId)); if (denormFields != null) { State valueState = State.getInstance(Query.from(Object.class).where("_id = ?", valueId).first()); if (valueState != null) { Map<String, Object> valueValues = valueState.getSimpleValues(); for (ObjectField denormField : denormFields) { String denormFieldName = denormField.getInternalName(); addDocumentValues( document, allBuilder, denormField, name + "/" + denormFieldName, valueValues.get(denormFieldName)); } } } } } } } String trimmed = value.toString().trim(); Matcher uuidMatcher = UUID_PATTERN.matcher(trimmed); int uuidLast = 0; while (uuidMatcher.find()) { allBuilder.append(trimmed.substring(uuidLast, uuidMatcher.start())); uuidLast = uuidMatcher.end(); String word = uuidToWord(ObjectUtils.to(UUID.class, uuidMatcher.group(0))); if (word != null) { allBuilder.append(word); } } allBuilder.append(trimmed.substring(uuidLast)); allBuilder.append(' '); if (value instanceof String && schema.get().version >= 8) { value = ((String) value).trim().toLowerCase(Locale.ENGLISH); } SolrField solrField = getSolrField(field.getInternalItemType()); for (String prefix : solrField.addPrefixes) { document.addField(prefix + name, value); } for (String prefix : solrField.setPrefixes) { document.setField(prefix + name, value); } } @Override protected void doDeletes(SolrServer server, boolean isImmediate, List<State> states) { List<String> idStrings = new ArrayList<String>(); for (State state : states) { idStrings.add(state.getId().toString()); } int statesSize = states.size(); try { Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(DELETE_PROFILER_EVENT, statesSize); try { UpdateRequest update = new UpdateRequest(); update.deleteById(idStrings); processUpdate(openConnection(), update, isImmediate); } finally { double duration = timer.stop(DELETE_STATS_OPERATION); Profiler.Static.stopThreadEvent(); LOGGER.debug("Solr delete: [{}], Time: [{}]ms", statesSize, duration); } } catch (Exception ex) { throw new DatabaseException(this, String.format( "Can't delete [%s] documents from Solr!", statesSize), ex); } } /** {@link SolrDatabase} utility methods. */ public static final class Static { private static final Pattern ESCAPE_PATTERN = Pattern.compile("([-+&|!(){}\\[\\]^\"~*?:\\\\\\s])"); private Static() { } /** * Escapes the given {@code value} so that it's safe to use * in a Solr query. * * @param value If {@code null}, returns {@code null}. */ public static final String escapeValue(Object value) { return value != null ? ESCAPE_PATTERN.matcher(value.toString()).replaceAll("\\\\$1") : null; } /** * Returns the Solr search result score associated with the given * {@code object}. * * @return May be {@code null} if the score isn't available. */ public static Float getScore(Object object) { return (Float) State.getInstance(object).getExtra(SCORE_EXTRA); } /** * Returns the normalized Solr search result score, in a scale of * {@code 0.0} to {@code 1.0}, associated with the given * {@code object}. * * @return May be {@code null} if the score isn't available. */ public static Float getNormalizedScore(Object object) { return (Float) State.getInstance(object).getExtra(NORMALIZED_SCORE_EXTRA); } } /** * Specifies all fields that are stored for type-ahead from an * instance of the target type. */ @Documented @Inherited @ObjectType.AnnotationProcessorClass(TypeAheadFieldsProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface TypeAheadFields { String[] value() default { }; TypeAheadFieldsMapping[] mappings() default { }; } public @interface TypeAheadFieldsMapping { String field(); String[] solrFields(); } private static class TypeAheadFieldsProcessor implements ObjectType.AnnotationProcessor<TypeAheadFields> { @Override public void process(ObjectType type, TypeAheadFields annotation) { Map <String, List<String>> typeAheadFieldsMap = new HashMap<String, List<String>>(); for (TypeAheadFieldsMapping mapping : annotation.mappings()) { List<String> fields = Arrays.asList(mapping.solrFields()); typeAheadFieldsMap.put(mapping.field(), fields); } Collections.addAll(type.as(TypeModification.class).getTypeAheadFields(), annotation.value()); type.as(TypeModification.class).setTypeAheadFieldsMap(typeAheadFieldsMap); } } @TypeModification.FieldInternalNamePrefix("solr.") public static class TypeModification extends Modification<ObjectType> { private Set<String> typeAheadFields; private Map<String, List<String>> typeAheadFieldsMap; public Set<String> getTypeAheadFields() { if (typeAheadFields == null) { typeAheadFields = new HashSet<String>(); } return typeAheadFields; } public void setTypeAheadFields(Set<String> typeAheadFields) { this.typeAheadFields = typeAheadFields; } public Map<String, List<String>> getTypeAheadFieldsMap() { if (null == typeAheadFieldsMap) { typeAheadFieldsMap = new HashMap<String, List<String>>(); } return typeAheadFieldsMap; } public void setTypeAheadFieldsMap(Map<String, List<String>> typeAheadFieldsMap) { this.typeAheadFieldsMap = typeAheadFieldsMap; } } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public static final String MAXIMUM_DOCUMENTS_SETTING = "maximumDocuments"; /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public static final String MAXIMUM_TIME_SETTING = "maximumTime"; /** @deprecated Use {@link #SERVER_URL_SUB_SETTING} instead. */ @Deprecated public static final String SERVER_URL_SETTING = SERVER_URL_SUB_SETTING; /** @deprecated Use {@link #READ_SERVER_URL_SUB_SETTING} instead. */ @Deprecated public static final String READ_SERVER_URL_SETTING = READ_SERVER_URL_SUB_SETTING; /** @deprecated Use {@link Static#escapeValue} instead. */ @Deprecated public static final String quoteValue(Object value) { return Static.escapeValue(String.valueOf(value)); } /** @deprecated Use {@link Static#getScore} instead. */ @Deprecated public static Float getScore(Object object) { return (Float) State.getInstance(object).getExtra(SCORE_EXTRA); } /** @deprecated Use {@link Static#getNormalizedScore} instead. */ @Deprecated public static Float getNormalizedScore(Object object) { return (Float) State.getInstance(object).getExtra(NORMALIZED_SCORE_EXTRA); } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public Long getMaximumDocuments() { return null; } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void setMaximumDocuments(Long maximumDocuments) { } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public Long getMaximumTime() { return null; } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void setMaximumTime(Long maximumTime) { } /** @deprecated Use {@link #buildQuery} instead. */ @Deprecated public SolrQuery buildSolrQuery(Query<?> query) { return buildQuery(query); } /** @deprecated Use {@link #commit} instead. */ @Deprecated public void commitImmediately() { commit(); } /** @deprecated Use the auto commit feature native to Solr instead. */ @Deprecated public void commitEventually() { } }
import java.io.IOException; import com.itextpdf.text.DocumentException; class Main { public static void main(String[] args) throws IOException, DocumentException { com.itextpdf.text.pdf.PdfReader.unethicalreading = true; if( args.length!=2 && args.length!=3) { System.err.println("Usage:"); System.err.println(" java -jar scrivepdftools.jar add-verification-pages config.json optional-input.pdf"); System.err.println(" java -jar scrivepdftools.jar find-texts config.json optional-input.pdf"); System.err.println(" java -jar scrivepdftools.jar extract-texts config.json optional-input.pdf"); System.err.println(""); System.err.println("scrivepdftools uses the following products:"); System.err.println(" iText by Bruno Lowagie, iText Group NV "); System.err.println(" snakeyaml"); } else { String input = null; if( args.length == 3 ) { input = args[2]; } if( args[0].equals("add-verification-pages")) { AddVerificationPages.execute(args[1], input); } else if( args[0].equals("find-texts")) { FindTexts.execute(args[1], input); } else if( args[0].equals("extract-texts")) { ExtractTexts.execute(args[1], input); } else { System.err.println("Uknown verb " + args[0]); } } } }
import MovementAndImageAPI.src.ImageUpdater; import MovementAndImageAPI.src.Turtle; import MovementAndImageAPI.src.TurtleHandler; import parser.Parser; import javafx.application.Application; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Main extends Application { private static final int SCREEN_WIDTH = 1000; private static final int SCREEN_HEIGHT = 700; private static final int DISPLAY_WIDTH = 1000; private static final int DISPLAY_HEIGHT = 600; private Scene myScene; private Canvas myBackDisplay; private Canvas myFrontDisplay; private Button BGColorButton; private Button RefGridButton; private Button HelpPageButton; private GraphicsContext gcBack; private GraphicsContext gcFront; private String userInput; private Parser myParser; /** * the JavaFX thread entry point. Creates the Stage and scene. */ @Override public void start (Stage primaryStage) { try { Group root = new Group(); Pane pane = new Pane(); BorderPane bpane = new BorderPane(); myScene = new Scene(root, SCREEN_WIDTH, SCREEN_HEIGHT); //Add back display canvas myBackDisplay = new Canvas(DISPLAY_WIDTH, DISPLAY_HEIGHT); gcBack = myBackDisplay.getGraphicsContext2D(); pane.getChildren().add(myBackDisplay); //Add front display canvas myFrontDisplay = new Canvas(DISPLAY_WIDTH, DISPLAY_HEIGHT); gcFront = myFrontDisplay.getGraphicsContext2D(); pane.getChildren().add(myFrontDisplay); //Setting display positions myBackDisplay.toBack(); myFrontDisplay.toFront(); //Setting pane(containing the displays) to the center of the borderpane. bpane.setCenter(pane); // Add Feature buttons on top bpane.setTop(addFeatureButtons(bpane, primaryStage, pane)); //adding parser? not sure now this works...! myParser = new Parser(null); // Add textbox at bottom (temporary) TextField textBox = new TextField(""); bpane.setBottom(textBox); sendUserInput(textBox); //adding imageUpdater ImageUpdater frontImageUpdater = new ImageUpdater(myFrontDisplay); //adding my turtle TurtleHandler testTurtle = new TurtleHandler(frontImageUpdater); testTurtle.updateImage("/images/turtle.png"); //(test) turtle knows how to move -- YESSS // testTurtle.updateTurtleAbsoluteLocation(new Point2D(50,0)); // Setting up layers root.getChildren().add(bpane); primaryStage.setScene(myScene); primaryStage.show(); } catch (Exception e) { e.printStackTrace(); } } /** * Adds features. */ public Node addFeatureButtons (BorderPane bpane, Stage primaryStage, Pane pane) { HBox featureButtons = new HBox(); BGColorFeature BGColor = new BGColorFeature(); ChoiceBox BGColorChoices = BGColor.makeColorChoices(gcBack,DISPLAY_WIDTH,DISPLAY_HEIGHT); bpane.getChildren().add(BGColorChoices); BGColorButton = BGColor.makeButton("Show Background Color Options", event->BGColorChoices.show()); //should fix this for canvas RefGridFeature RefGrid = new RefGridFeature(); RefGridButton = RefGrid.makeButton("RefGrid On/Off", event -> RefGrid.showReferenceGrid(RefGridButton, pane, DISPLAY_WIDTH, DISPLAY_HEIGHT)); HelpPageFeature HelpPage = new HelpPageFeature(); HelpPageButton = HelpPage.makeButton("Help Page", event -> HelpPage.openHelpPage(HelpPageButton, bpane)); featureButtons.getChildren().addAll(BGColorButton, RefGridButton, HelpPageButton); return featureButtons; } /** * Tells the parser to parse the userInput String * (determined by whatever was typed in the TextField) * @param userInput the user input * @return returns true if XMLparser can parse the userInput (which means the userInput is valid) * returns false otherwise. */ public boolean sendUserInput(TextField textBox){ boolean validInput = false; textBox.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle (KeyEvent key) { if (key.getCode() == KeyCode.ENTER) { userInput = textBox.getText(); //i need to send this userInput to the parser. System.out.println(userInput); // //i need to check if this userInput is valid... using the parser. // if (userInput is a valid input){ // validInput = true; textBox.clear(); } } }); return validInput; } // /** // * Displays a list of valid commands (valid userInputs that the XMLparser could parse) // * @param userInput the user input // */ // public void showPreviousCommands(String userInput){ /** * the main entry point for the program. * * @param args */ public static void main (String[] args) { launch(args); } }
package demos.components; import com.jfoenix.controls.JFXChipView; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public final class ChipViewDemo extends Application { @Override public void start(Stage stage) { JFXChipView<String> chipView = new JFXChipView<>(); chipView.getChips().addAll("WEF", "WWW", "JD"); chipView.getSuggestions().addAll("HELLO", "TROLL", "WFEWEF", "WEF"); chipView.setStyle("-fx-background-color: WHITE;"); StackPane pane = new StackPane(); pane.getChildren().add(chipView); StackPane.setMargin(chipView, new Insets(100)); pane.setStyle("-fx-background-color:GRAY;"); final Scene scene = new Scene(pane, 500, 500); // scene.getStylesheets().add(TagAreaDemo.class.getResource("/css/jfoenix-components.css").toExternalForm()); stage.setTitle("JFX Button Demo"); stage.setScene(scene); stage.show(); // ScenicView.show(scene); } public static void main(String[] args) { launch(args); } }
public class View { private Player player; public View (Player p) { player=p; } public void update() { System.out.println("The current player has a health of " + player.getHealth());//TODO System.out.println("The player has the following items"); for (Item item : player.getInventory(null)) { System.out.println(item.getDescription()); } System.out.println("The player is in room " + player.getCurrentRoom().getLongDescription()); } }
//FILE: GUIUtils.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // Arthur Edelstein, arthuredelstein@gmail.com // 100X Imaging Inc, 2009 // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.utils; import com.swtdesigner.SwingResourceManager; import ij.WindowManager; import ij.gui.ImageWindow; import java.awt.*; import java.awt.event.*; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import java.util.prefs.Preferences; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.text.JTextComponent; public class GUIUtils { private static String DIALOG_POSITION = "dialogPosition"; public static void setComboSelection(JComboBox cb, String sel){ ActionListener[] listeners = cb.getActionListeners(); for (int i=0; i<listeners.length; i++) cb.removeActionListener(listeners[i]); cb.setSelectedItem(sel); for (int i=0; i<listeners.length; i++) cb.addActionListener(listeners[i]); } public static void replaceComboContents(JComboBox cb, String[] items) { // remove listeners ActionListener[] listeners = cb.getActionListeners(); for (int i=0; i<listeners.length; i++) cb.removeActionListener(listeners[i]); if (cb.getItemCount() > 0) cb.removeAllItems(); // add contents for (int i=0; i<items.length; i++){ cb.addItem(items[i]); } // restore listeners for (int i=0; i<listeners.length; i++) cb.addActionListener(listeners[i]); } /* * This takes care of a Java bug that would throw several exceptions when a Projector device * is attached in Windows. */ public static void preventDisplayAdapterChangeExceptions() { try { if (JavaUtils.isWindows()) { // Check that we are in windows. //Dynamically load sun.awt.Win32GraphicsEnvironment, because it seems to be missing from //the Mac OS X JVM. ClassLoader cl = ClassLoader.getSystemClassLoader (); Class<?> envClass = cl.loadClass("sun.awt.Win32GraphicsEnvironment"); //Get the current local graphics environment. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); //Send notification that display may have changed, so that display count is updated. envClass.getDeclaredMethod("displayChanged").invoke(envClass.cast(ge)); } } catch (Exception e) { ReportingUtils.logError(e); } } public static void setClickCountToStartEditing(JTable table, int count) { for (int columnIndex = 0; columnIndex < table.getColumnCount(); ++columnIndex) { TableCellEditor cellEditor = table.getColumnModel().getColumn(columnIndex).getCellEditor(); if (cellEditor instanceof DefaultCellEditor) { ((DefaultCellEditor) cellEditor).setClickCountToStart(count); } } } public static void stopEditingOnLosingFocus(final JTable table) { table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); } public static boolean isLocationInScreenBounds(Point location) { // Check if the location is in the bounds of one of the graphics devices. GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices(); Rectangle graphicsConfigurationBounds = new Rectangle(); // Iterate over the graphics devices. for (int j = 0; j < graphicsDevices.length; j++) { // Get the bounds of the device. GraphicsDevice graphicsDevice = graphicsDevices[j]; graphicsConfigurationBounds.setRect(graphicsDevice.getDefaultConfiguration().getBounds()); // Is the location in this bounds? graphicsConfigurationBounds.setRect(graphicsConfigurationBounds.x, graphicsConfigurationBounds.y, graphicsConfigurationBounds.width, graphicsConfigurationBounds.height); if (graphicsConfigurationBounds.contains(location.x, location.y)) { // The location is in this screengraphics. return true; } } // We could not find a device that contains the given point. return false; } public static void recallPosition(final Window win) { Preferences prefs = Preferences.userNodeForPackage(win.getClass()); Point dialogPosition = JavaUtils.getObjectFromPrefs(prefs, DIALOG_POSITION, (Point) null); if (dialogPosition == null || !isLocationInScreenBounds(dialogPosition)) { Dimension screenDims = JavaUtils.getScreenDimensions(); dialogPosition = new Point((screenDims.width - win.getWidth()) / 2, (screenDims.height - win.getHeight()) / 2); } win.setLocation(dialogPosition); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { storePosition(win); } }); } private static void storePosition(final Window win) { Preferences prefs = Preferences.userNodeForPackage(win.getClass()); JavaUtils.putObjectInPrefs(prefs, DIALOG_POSITION, win.getLocation()); } public static void registerImageFocusListener(final ImageFocusListener listener) { AWTEventListener awtEventListener = new AWTEventListener() { private ImageWindow currentImageWindow_ = null; @Override public void eventDispatched(AWTEvent event) { if (event instanceof WindowEvent) { if (0 != (event.getID() & WindowEvent.WINDOW_GAINED_FOCUS)) { if (event.getSource() instanceof ImageWindow) { ImageWindow focusedWindow = WindowManager.getCurrentWindow(); if (currentImageWindow_ != focusedWindow) { //if (focusedWindow.isVisible() && focusedWindow instanceof ImageWindow) { listener.focusReceived(focusedWindow); currentImageWindow_ = focusedWindow; } } } } } }; Toolkit.getDefaultToolkit().addAWTEventListener(awtEventListener, AWTEvent.WINDOW_FOCUS_EVENT_MASK); } /* * Wraps SwingUtilities.invokeAndWait so that if it is being called * from the EDT, then the runnable is simply run. */ public static void invokeAndWait(Runnable r) throws InterruptedException, InvocationTargetException { if (SwingUtilities.isEventDispatchThread()) { r.run(); } else { SwingUtilities.invokeAndWait(r); } } /* * Wraps SwingUtilities.invokeLater so that if it is being called * from the EDT, then the runnable is simply run. */ public static void invokeLater(Runnable r) throws InterruptedException, InvocationTargetException { if (SwingUtilities.isEventDispatchThread()) { r.run(); } else { SwingUtilities.invokeLater(r); } } /* * Attach properly formatted tooltip text to the specified * JComponent. */ public static void setToolTipText(JComponent component, String toolTipText) { if (JavaUtils.isMac()) {// running on a mac component.setToolTipText(toolTipText); } else { component.setToolTipText(TooltipTextMaker.addHTMLBreaksForTooltip(toolTipText)); } } /* * Add an icon from the "org/micromanager/icons/ folder with * given file name, to specified the button or menu. */ public static void setIcon(AbstractButton component, String iconFileName) { component.setIcon(SwingResourceManager.getIcon( org.micromanager.MMStudioMainFrame.class, "/org/micromanager/icons/" + iconFileName)); } /////////////////////// MENU ITEM UTILITY METHODS /////////// /* * Add a menu to the specified menu bar. */ public static JMenu createMenuInMenuBar(final JMenuBar menuBar, final String menuName) { final JMenu menu = new JMenu(); menu.setText(menuName); menuBar.add(menu); return menu; } /* * Add a menu item to the specified parent menu. */ public static JMenuItem addMenuItem(final JMenu parentMenu, JMenuItem menuItem, final String menuItemToolTip, final Runnable menuActionRunnable) { if (menuItemToolTip != null) { setToolTipText(menuItem, menuItemToolTip); } if (menuActionRunnable != null) { menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ignoreEvent) { menuActionRunnable.run(); } }); } parentMenu.add(menuItem); return menuItem; } /* * Add a menu item with given text to the specified parent menu. */ public static JMenuItem addMenuItem(final JMenu parentMenu, final String menuItemText, final String menuItemToolTip, final Runnable menuActionRunnable) { return addMenuItem(parentMenu, new JMenuItem(menuItemText), menuItemToolTip, menuActionRunnable); } public static JMenuItem addMenuItem(final JMenu parentMenu, final String menuItemText, final String menuItemToolTip, final Runnable menuActionRunnable, final String iconFileName) { final JMenuItem menuItem = addMenuItem(parentMenu, menuItemText, menuItemToolTip, menuActionRunnable); setIcon(menuItem, iconFileName); return menuItem; } /* * Add a menu item that can be checked or unchecked to the specified * parent menu. */ public static JCheckBoxMenuItem addCheckBoxMenuItem(final JMenu parentMenu, final String menuItemText, final String menuItemToolTip, final Runnable menuActionRunnable, final boolean initState) { final JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) addMenuItem(parentMenu, new JCheckBoxMenuItem(menuItemText), menuItemToolTip, menuActionRunnable); menuItem.setSelected(initState); return menuItem; } ////////////// END MENU ITEM UTILITY METHODS //////////////// /* Add a component to the parent panel, set positions of the edges of * component relative to panel. If edges are positive, then they are * positioned relative to north and west edges of parent container. If edges * are negative, then they are positioned relative to south and east * edges of parent container. * Requires that parent container uses SpringLayout. */ public static void addWithEdges(Container parentContainer, JComponent component, int west, int north, int east, int south) { parentContainer.add(component); SpringLayout topLayout = (SpringLayout) parentContainer.getLayout(); topLayout.putConstraint(SpringLayout.EAST, component, east, (east > 0) ? SpringLayout.WEST : SpringLayout.EAST, parentContainer); topLayout.putConstraint(SpringLayout.WEST, component, west, (west >= 0) ? SpringLayout.WEST : SpringLayout.EAST, parentContainer); topLayout.putConstraint(SpringLayout.SOUTH, component, south, (south > 0) ? SpringLayout.NORTH : SpringLayout.SOUTH, parentContainer); topLayout.putConstraint(SpringLayout.NORTH, component, north, (north >= 0) ? SpringLayout.NORTH : SpringLayout.SOUTH, parentContainer); } /* Add a component to the parent panel, set positions of the edges of * component relative to panel. If edges are positive, then they are * positioned relative to north and west edges of parent container. If edges * are negative, then they are positioned relative to south and east * edges of parent container. * Requires that parent container uses SpringLayout. */ public static AbstractButton createButton(final boolean isToggleButton, final String name, final String text, final String toolTipText, final Runnable buttonActionRunnable, final String iconFileName, final Container parentPanel, int west, int north, int east, int south) { AbstractButton button = isToggleButton ? new JToggleButton() : new JButton(); button.setFont(new Font("Arial", Font.PLAIN, 10)); button.setMargin(new Insets(0, 0, 0, 0)); button.setName(name); if (text != null) { button.setText(text); } if (iconFileName != null) { button.setIconTextGap(4); setIcon(button, iconFileName); } if (toolTipText != null) { button.setToolTipText(toolTipText); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { buttonActionRunnable.run(); } }); GUIUtils.addWithEdges(parentPanel, button, west, north, east, south); return button; } public interface StringValidator { public void validate(String string); } // If the user attempts to edit a text field, but doesn't enter a valid input, // as specifed by the StringValidator, then a dialog pops up that reminds // user what kind of input is needed. If the user presses OK, then verifier // returns false. If user presses CANCEL, then verifier reverts the // value and returns true. public static InputVerifier textFieldInputVerifier(final JTextField field, final StringValidator validator) { return new InputVerifier() { private String lastGoodValue = field.getText(); public boolean verify(JComponent input) { String proposedValue = ((JTextField) input).getText(); validator.validate(proposedValue); return true; } @Override public boolean shouldYieldFocus(JComponent input) { try { boolean isValid = super.shouldYieldFocus(input); lastGoodValue = field.getText(); return isValid; } catch (Exception e) { int response = JOptionPane.showConfirmDialog( null, e.getMessage(), "Invalid input", JOptionPane.OK_CANCEL_OPTION); if (response == JOptionPane.OK_OPTION) { return false; } else if (response == JOptionPane.CANCEL_OPTION) { field.setText(lastGoodValue); return true; } } return true; } }; } public static void enforceValidTextField(final JTextField field, final StringValidator validator) { field.setInputVerifier(textFieldInputVerifier(field, validator)); } public static DefaultCellEditor validatingDefaultCellEditor(final StringValidator validator) { final String lastValue[] = {""}; final JTextField field = new JTextField(); field.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) {} public void removeUpdate(DocumentEvent e) {} public void changedUpdate(DocumentEvent e) { lastValue[0] = field.getText(); } }); final InputVerifier verifier = textFieldInputVerifier(field, validator); DefaultCellEditor editor = new DefaultCellEditor(field) { @Override public boolean stopCellEditing() { return verifier.shouldYieldFocus(field) && super.stopCellEditing(); } }; return editor; } public static StringValidator integerStringValidator(final int minValue, final int maxValue) { return new StringValidator() { public void validate(String string) { try { int value = Integer.parseInt(string.trim()); if ((value < minValue) || (value > maxValue)) { throw new RuntimeException("Value should be between " + minValue + " and " + maxValue); } } catch (NumberFormatException e) { throw new RuntimeException("Please enter an integer."); } } }; } public static StringValidator floatStringValidator(final double minValue, final double maxValue) { return new StringValidator() { public void validate(String string) { try { double value = Double.parseDouble(string); if ((value < minValue) || (value > maxValue)) { throw new RuntimeException("Value should be between " + minValue + " and " + maxValue); } } catch (NumberFormatException e) { throw new RuntimeException("Please enter a number."); } } }; } public static void enforceIntegerTextField(final JTextField field, final int minValue, final int maxValue) { enforceValidTextField(field, integerStringValidator(minValue, maxValue)); } public static void enforceFloatFieldText(final JTextField field, final double minValue, final double maxValue) { enforceValidTextField(field, floatStringValidator(minValue, maxValue)); } public static void enforceIntegerTextColumn(final JTable table, int columnInt, int minValue, int maxValue) { table.getColumnModel().getColumn(columnInt) .setCellEditor(validatingDefaultCellEditor(integerStringValidator(minValue, maxValue))); } public static String getStringValue(JComponent component) { if (component instanceof JTextComponent) { return ((JTextComponent) component).getText(); } if (component instanceof JComboBox) { return ((JComboBox) component).getSelectedItem().toString(); } if (component instanceof JList) { return ((JList) component).getSelectedValue().toString(); } return null; } public static void setValue(JComponent component, String value) { if (component instanceof JTextComponent) { ((JTextComponent) component).setText(value); } if (component instanceof JComboBox) { ((JComboBox) component).setSelectedItem(value); } if (component instanceof JList) { ((JList) component).setSelectedValue(value, true); } } public static void setValue(JComponent component, Object value) { String valueText = value.toString(); if (component instanceof JTextComponent) { ((JTextComponent) component).setText(valueText); } if (component instanceof JComboBox) { ((JComboBox) component).setSelectedItem(valueText); } if (component instanceof JList) { ((JList) component).setSelectedValue(valueText, true); } } public static int getIntValue(JTextField component) { return Integer.parseInt(component.getText()); } private static void enableOnTableEvent(final JTable table, final JComponent component) { table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (component.getParent().isEnabled()) { if (table.getSelectedRowCount() > 0) { component.setEnabled(true); } else { component.setEnabled(false); } } } } }); } public static void makeIntoMoveRowUpButton(final JTable table, JButton button) { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int rowIndex = table.getSelectedRow(); if (rowIndex > 0) { ((DefaultTableModel) table.getModel()).moveRow(rowIndex, rowIndex, rowIndex - 1); table.setRowSelectionInterval(rowIndex - 1, rowIndex - 1); } } }); enableOnTableEvent(table, button); } public static void makeIntoMoveRowDownButton(final JTable table, JButton button) { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int rowIndex = table.getSelectedRow(); if (rowIndex < table.getRowCount() - 1) { ((DefaultTableModel) table.getModel()).moveRow(rowIndex, rowIndex, rowIndex + 1); table.setRowSelectionInterval(rowIndex + 1, rowIndex + 1); } } }); enableOnTableEvent(table, button); } public static void makeIntoDeleteRowButton(final JTable table, JButton button) { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int rowIndex = table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.removeRow(rowIndex); if (rowIndex < table.getRowCount()) { table.setRowSelectionInterval(rowIndex, rowIndex); } } }); enableOnTableEvent(table, button); } public static void makeIntoCloneRowButton(final JTable table, JButton button) { button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int rowIndex = table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) table.getModel(); Vector rowData = (Vector) model.getDataVector().elementAt(rowIndex); model.insertRow(rowIndex + 1, new Vector(rowData)); table.setRowSelectionInterval(rowIndex + 1, rowIndex + 1); } }); enableOnTableEvent(table, button); } public static void startEditingAtCell(JTable table, int row, int column) { table.editCellAt(row, column); table.getEditorComponent().requestFocusInWindow(); } public static void tabKeyTraversesTable(final JTable table) { table.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { // Check if the TAB key was pressed. if (event.getKeyCode() == 9) { int row = table.getEditingRow(); int column = table.getEditingColumn(); // Don't proceed if we aren't already editing. if (row < 0 || column < 0) return; if (column == (table.getColumnCount() - 1)) { column = 0; row = row + 1 % table.getRowCount(); } else { ++column; } startEditingAtCell(table, row, column); } } }); } }
package jodd.bean.loader; import jodd.bean.BeanUtil; import jodd.bean.BeanUtilBean; /** * Base {@link BeanLoader}. */ public abstract class BaseBeanLoader implements BeanLoader { private BeanUtilBean beanUtilBean = BeanUtil.getDefaultBeanUtilBean(); protected boolean ignoreNulls; public BeanUtilBean getBeanUtilBean() { return beanUtilBean; } public void setBeanUtilBean(BeanUtilBean beanUtilBean) { this.beanUtilBean = beanUtilBean; } /** * Sets the target bean property with value. */ protected void setProperty(Object targetBean, String name, Object value) { if (ignoreNulls) { if (value == null) { return; } } beanUtilBean.setPropertyForcedSilent(targetBean, name, value); } }
package org.waterforpeople.mapping.app.web; import java.io.BufferedInputStream; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipInputStream; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.servlet.http.HttpServletRequest; import net.sf.jsr107cache.Cache; import net.sf.jsr107cache.CacheFactory; import net.sf.jsr107cache.CacheManager; import org.waterforpeople.mapping.analytics.dao.SurveyInstanceSummaryDao; import org.waterforpeople.mapping.analytics.dao.SurveyQuestionSummaryDao; import org.waterforpeople.mapping.analytics.domain.SurveyQuestionSummary; import org.waterforpeople.mapping.app.web.dto.DataProcessorRequest; import org.waterforpeople.mapping.dao.AccessPointDao; import org.waterforpeople.mapping.dao.DeviceFilesDao; import org.waterforpeople.mapping.dao.QuestionAnswerStoreDao; import org.waterforpeople.mapping.dao.SurveyInstanceDAO; import org.waterforpeople.mapping.dataexport.SurveyReplicationImporter; import org.waterforpeople.mapping.domain.AccessPoint; import org.waterforpeople.mapping.domain.GeoCoordinates; import org.waterforpeople.mapping.domain.QuestionAnswerStore; import org.waterforpeople.mapping.domain.SurveyInstance; import com.gallatinsystems.common.Constants; import com.gallatinsystems.device.domain.DeviceFiles; import com.gallatinsystems.framework.rest.AbstractRestApiServlet; import com.gallatinsystems.framework.rest.RestRequest; import com.gallatinsystems.framework.rest.RestResponse; import com.gallatinsystems.framework.servlet.PersistenceFilter; import com.gallatinsystems.gis.location.GeoLocationService; import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl; import com.gallatinsystems.gis.location.GeoPlace; import com.gallatinsystems.gis.map.MapUtils; import com.gallatinsystems.messaging.dao.MessageDao; import com.gallatinsystems.messaging.domain.Message; import com.gallatinsystems.operations.dao.ProcessingStatusDao; import com.gallatinsystems.operations.domain.ProcessingStatus; import com.gallatinsystems.survey.dao.QuestionDao; import com.gallatinsystems.survey.dao.QuestionGroupDao; import com.gallatinsystems.survey.dao.QuestionOptionDao; import com.gallatinsystems.survey.dao.SurveyDAO; import com.gallatinsystems.survey.dao.SurveyUtils; import com.gallatinsystems.survey.dao.TranslationDao; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; import com.gallatinsystems.survey.domain.QuestionOption; import com.gallatinsystems.survey.domain.Survey; import com.gallatinsystems.survey.domain.Translation; import com.gallatinsystems.surveyal.dao.SurveyedLocaleDao; import com.gallatinsystems.surveyal.domain.SurveyedLocale; import com.google.appengine.api.backends.BackendServiceFactory; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.stdimpl.GCacheFactory; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; /** * Restful servlet to do bulk data update operations * * @author Christopher Fagiani * */ public class DataProcessorRestServlet extends AbstractRestApiServlet { private static final Logger log = Logger .getLogger("DataProcessorRestServlet"); private static final long serialVersionUID = -7902002525342262821L; private static final String REBUILD_Q_SUM_STATUS_KEY = "rebuildQuestionSummary"; private static final Integer QAS_PAGE_SIZE = 300; private static final Integer LOCALE_PAGE_SIZE = 500; private static final Integer T_PAGE_SIZE = 300; private static final String QAS_TO_REMOVE = "QAStoRemove"; @Override protected RestRequest convertRequest() throws Exception { HttpServletRequest req = getRequest(); RestRequest restRequest = new DataProcessorRequest(); restRequest.populateFromHttpRequest(req); return restRequest; } @Override protected RestResponse handleRequest(RestRequest req) throws Exception { DataProcessorRequest dpReq = (DataProcessorRequest) req; if (DataProcessorRequest.PROJECT_FLAG_UPDATE_ACTION .equalsIgnoreCase(dpReq.getAction())) { updateAccessPointProjectFlag(dpReq.getCountry(), dpReq.getCursor()); } else if (DataProcessorRequest.REBUILD_QUESTION_SUMMARY_ACTION .equalsIgnoreCase(dpReq.getAction())) { rebuildQuestionSummary(dpReq.getSurveyId()); } else if (DataProcessorRequest.COPY_SURVEY.equalsIgnoreCase(dpReq .getAction())) { copySurvey(dpReq.getSurveyId(), Long.valueOf(dpReq.getSource())); } else if (DataProcessorRequest.IMPORT_REMOTE_SURVEY_ACTION .equalsIgnoreCase(dpReq.getAction())) { SurveyReplicationImporter sri = new SurveyReplicationImporter(); sri.executeImport(dpReq.getSource(), dpReq.getSurveyId(), dpReq.getApiKey()); } else if (DataProcessorRequest.RESCORE_AP_ACTION .equalsIgnoreCase(dpReq.getAction())) { rescoreAp(dpReq.getCountry()); } else if (DataProcessorRequest.FIX_NULL_SUBMITTER_ACTION .equalsIgnoreCase(dpReq.getAction())) { fixNullSubmitter(); } else if (DataProcessorRequest.FIX_DUPLICATE_OTHER_TEXT_ACTION .equalsIgnoreCase(dpReq.getAction())) { fixDuplicateOtherText(); } else if (DataProcessorRequest.TRIM_OPTIONS.equalsIgnoreCase(dpReq .getAction())) { trimOptions(); } else if (DataProcessorRequest.FIX_OPTIONS2VALUES_ACTION .equalsIgnoreCase(dpReq.getAction())) { fixOptions2Values(); } else if (DataProcessorRequest.SURVEY_INSTANCE_SUMMARIZER .equalsIgnoreCase(dpReq.getAction())) { surveyInstanceSummarizer(dpReq.getSurveyInstanceId(), dpReq.getQasId(), dpReq.getDelta()); } else if (DataProcessorRequest.ADD_SURVEY_INSTANCE_TO_LOCALES_ACTION .equalsIgnoreCase(dpReq.getAction())) { addSurveyInstanceToLocales(dpReq.getCursor()); } else if (DataProcessorRequest.DELETE_DUPLICATE_QAS .equalsIgnoreCase(dpReq.getAction())) { deleteDuplicatedQAS(dpReq.getOffset()); } else if (DataProcessorRequest.CHANGE_LOCALE_TYPE_ACTION .equalsIgnoreCase(dpReq.getAction())) { changeLocaleType(dpReq.getSurveyId()); } else if (DataProcessorRequest.ADD_TRANSLATION_FIELDS .equalsIgnoreCase(dpReq.getAction())) { addTranslationFields(dpReq.getCursor()); } else if (DataProcessorRequest.RECOMPUTE_LOCALE_CLUSTERS .equalsIgnoreCase(dpReq.getAction())) { recomputeLocaleClusters(dpReq.getCursor()); } else if (DataProcessorRequest.ADD_CREATION_SURVEY_ID_TO_LOCALE .equalsIgnoreCase(dpReq.getAction())) { addCreationSurveyIdToLocale(dpReq.getCursor()); } return new RestResponse(); } @Override protected void writeOkResponse(RestResponse resp) throws Exception { getResponse().setStatus(200); } /** * lists all QuestionOptions and trims trailing/leading spaces. Then does * the same for any dependencies */ private void trimOptions() { QuestionOptionDao optDao = new QuestionOptionDao(); QuestionDao qDao = new QuestionDao(); String cursor = null; do { List<QuestionOption> optList = optDao.list(cursor); if (optList != null && optList.size() > 0) { for (QuestionOption opt : optList) { if (opt.getText() != null) { opt.setText(opt.getText().trim()); } List<Question> qList = qDao.listQuestionsByDependency(opt .getQuestionId()); for (Question q : qList) { if (q.getText() != null) { q.setText(q.getText().trim()); } if (q.getDependentQuestionAnswer() != null) { q.setDependentQuestionAnswer(q .getDependentQuestionAnswer().trim()); } } } if (optList.size() == QuestionOptionDao.DEFAULT_RESULT_COUNT) { cursor = QuestionOptionDao.getCursor(optList); } else { cursor = null; } } else { cursor = null; } } while (cursor != null); } /** * lists all "OTHER" type answers and checks if the last tokens are * duplicates. Fixes if they are. */ private void fixDuplicateOtherText() { QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); int pageSize = 300; String cursor = null; do { List<QuestionAnswerStore> answers = qasDao.listByTypeAndDate( "OTHER", null, null, cursor, pageSize); if (answers != null) { for (QuestionAnswerStore ans : answers) { if (ans.getValue() != null && ans.getValue().contains("|")) { String[] tokens = ans.getValue().split("\\|"); String lastVal = null; boolean droppedVal = false; StringBuilder buf = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { if (!tokens[i].equals(lastVal)) { lastVal = tokens[i]; if (i > 0) { buf.append("|"); } buf.append(lastVal); } else { droppedVal = true; } } if (droppedVal) { // only dirty the object if needed ans.setValue(buf.toString()); } } } if (answers.size() == pageSize) { cursor = QuestionAnswerStoreDao.getCursor(answers); } else { cursor = null; } } } while (cursor != null); } /** * changes the surveyedLocales attached to a survey to a different type * 1 = Point * 2 = Household * 3 = Public Institutions */ private void changeLocaleType(Long surveyId) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); SurveyedLocaleDao slDao = new SurveyedLocaleDao(); SurveyDAO sDao = new SurveyDAO(); String cursor = null; // get the desired type from the survey definition Survey s = sDao.getByKey(surveyId); if (s != null && s.getPointType() != null && s.getPointType().length() > 0){ String localeType = s.getPointType(); do { List<SurveyInstance> siList = siDao.listSurveyInstanceBySurvey(surveyId, QAS_PAGE_SIZE, cursor); List<SurveyedLocale> slList = new ArrayList<SurveyedLocale>(); if (siList != null && siList.size() > 0) { for (SurveyInstance si : siList) { if (si.getSurveyedLocaleId() != null) { SurveyedLocale sl = slDao.getByKey(si.getSurveyedLocaleId()); if (sl != null){ // if the locale type is not set or if it is not equal to the survey setting, // reset the local type if (sl.getLocaleType() == null || !sl.getLocaleType().equals(localeType)) { sl.setLocaleType(localeType); slList.add(sl); } } } } slDao.save(slList); if (siList.size() == QAS_PAGE_SIZE) { cursor = SurveyInstanceDAO.getCursor(siList); } else { cursor = null; } } } while (cursor != null); // recompute all clusters final TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.RECOMPUTE_LOCALE_CLUSTERS); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } } private void fixNullSubmitter() { SurveyInstanceDAO instDao = new SurveyInstanceDAO(); List<SurveyInstance> instances = instDao.listInstanceBySubmitter(null); if (instances != null) { DeviceFilesDao dfDao = new DeviceFilesDao(); for (SurveyInstance inst : instances) { DeviceFiles f = dfDao.findByInstance(inst.getKey().getId()); if (f != null) { try { URL url = new URL(f.getURI()); BufferedInputStream bis = new BufferedInputStream( url.openStream()); ZipInputStream zis = new ZipInputStream(bis); ArrayList<String> lines = TaskServlet .extractDataFromZip(zis); zis.close(); if (lines != null) { for (String line : lines) { String[] parts = line.split("\t"); if (parts.length > 5) { if (parts[5] != null && parts[5].trim().length() > 0) { inst.setSubmitterName(parts[5]); break; } } } } } catch (Exception e) { log("Could not download zip: " + f.getURI()); } } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void deleteDuplicatedQAS(Long offset) { log.log(Level.INFO, "Searching for duplicated QAS entities [Offset: " + offset + "]"); Cache cache = null; Map props = new HashMap(); props.put(GCacheFactory.EXPIRATION_DELTA, 12 * 60 * 60); props.put(MemcacheService.SetPolicy.SET_ALWAYS, true); try { CacheFactory cacheFactory = CacheManager.getInstance() .getCacheFactory(); cache = cacheFactory.createCache(props); } catch (Exception e) { log.log(Level.SEVERE, "Couldn't initialize cache: " + e.getMessage(), e); } if (cache == null) { return; } final PersistenceManager pm = PersistenceFilter.getManager(); final Query q = pm.newQuery(QuestionAnswerStore.class); q.setOrdering("createdDateTime asc"); q.setRange(offset, offset + QAS_PAGE_SIZE); final List<QuestionAnswerStore> results = (List<QuestionAnswerStore>) q .execute(); List<QuestionAnswerStore> toRemove; if (cache.containsKey(QAS_TO_REMOVE)) { toRemove = (List<QuestionAnswerStore>) cache.get(QAS_TO_REMOVE); } else { toRemove = new ArrayList<QuestionAnswerStore>(); } for (QuestionAnswerStore item : results) { final Long questionID = Long.valueOf(item.getQuestionID()); final Long surveyInstanceId = item.getSurveyInstanceId(); final Map<Long, Long> k = new HashMap<Long, Long>(); k.put(surveyInstanceId, questionID); if (cache.containsKey(k)) { toRemove.add(item); } cache.put(k, true); } if (results.size() == QAS_PAGE_SIZE) { cache.put(QAS_TO_REMOVE, toRemove); final TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.DELETE_DUPLICATE_QAS) .param(DataProcessorRequest.OFFSET_PARAM, String.valueOf(offset + QAS_PAGE_SIZE)) .header("Host", BackendServiceFactory.getBackendService() .getBackendAddress("dataprocessor")); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } else { log.log(Level.INFO, "Removing " + toRemove.size() + " duplicated QAS entities"); QuestionAnswerStoreDao dao = new QuestionAnswerStoreDao(); pm.makePersistentAll(toRemove); // some objects are in "transient" state dao.delete(toRemove); } } /** * This recomputes all Locale clusters. Clusters are deleted in the testharnessservlet. * The keys are first removed in the testharnessservlet. * @param offset */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void recomputeLocaleClusters(String cursor) { log.log(Level.INFO, "recomputing locale clusters [cursor: " + cursor + "]"); SurveyedLocaleDao slDao = new SurveyedLocaleDao(); final List<SurveyedLocale> results = slDao.listAll(cursor, LOCALE_PAGE_SIZE); // initialize the memcache Cache cache = null; Map props = new HashMap(); props.put(GCacheFactory.EXPIRATION_DELTA, 12 * 60 * 60); props.put(MemcacheService.SetPolicy.SET_ALWAYS, true); try { CacheFactory cacheFactory = CacheManager.getInstance() .getCacheFactory(); cache = cacheFactory.createCache(props); } catch (Exception e) { log.log(Level.SEVERE, "Couldn't initialize cache: " + e.getMessage(), e); } if (cache == null) { return; } for (SurveyedLocale locale : results) { // adjust Geocell cluster data if (locale.getGeocells() != null && !locale.getGeocells().isEmpty()){ MapUtils.recomputeCluster(cache, locale); } } if (results.size() == LOCALE_PAGE_SIZE) { cursor = SurveyedLocaleDao.getCursor(results); final TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.RECOMPUTE_LOCALE_CLUSTERS) .param(DataProcessorRequest.CURSOR_PARAM, cursor != null ? cursor : ""); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } } /** * this method re-runs scoring on all access points for a country * * @param country */ private void rescoreAp(String country) { AccessPointDao apDao = new AccessPointDao(); String cursor = null; List<AccessPoint> apList = null; do { apList = apDao.listAccessPointByLocation(country, null, null, null, cursor, 200); if (apList != null) { cursor = AccessPointDao.getCursor(apList); for (AccessPoint ap : apList) { apDao.save(ap); } } } while (apList != null && apList.size() == 200); } private void copySurvey(Long surveyId, Long sourceId) { final QuestionGroupDao qgDao = new QuestionGroupDao(); final Map<Long, Long> qMap = new HashMap<Long, Long>(); final List<QuestionGroup> qgList = qgDao.listQuestionGroupBySurvey(sourceId); if (qgList == null) { log.log(Level.INFO, "Nothing to copy from {surveyId: " + sourceId + "} to {surveyId: " + surveyId + "}"); SurveyUtils.resetSurveyState(surveyId); return; } log.log(Level.INFO, "Copying " + qgList.size() + " `QuestionGroup`"); int qgOrder = 1; for (final QuestionGroup sourceQG : qgList) { SurveyUtils.copyQuestionGroup(sourceQG, surveyId, qgOrder++, qMap); } SurveyUtils.resetSurveyState(surveyId); MessageDao mDao = new MessageDao(); Message message = new Message(); message.setObjectId(surveyId); message.setActionAbout("copySurvey"); message.setShortMessage("Copy from Survey " + sourceId + " to Survey " + surveyId + " completed"); mDao.save(message); } /** * rebuilds the SurveyQuestionSummary object for ALL data in the system. * This method should only be run on a Backend instance as it is unlikely to * complete within the task duration limits on other instances. */ private void rebuildQuestionSummary(Long surveyId) { ProcessingStatusDao statusDao = new ProcessingStatusDao(); List<Long> surveyIds = new ArrayList<Long>(); if (surveyId == null) { SurveyDAO surveyDao = new SurveyDAO(); List<Survey> surveys = surveyDao.list(Constants.ALL_RESULTS); if (surveys != null) { for (Survey s : surveys) { surveyIds.add(s.getKey().getId()); } } } else { surveyIds.add(surveyId); } for (Long sid : surveyIds) { ProcessingStatus status = statusDao .getStatusByCode(REBUILD_Q_SUM_STATUS_KEY + (sid != null ? ":" + sid : "")); Map<String, Map<String, Long>> summaryMap = summarizeQuestionAnswerStore( sid, null); if (summaryMap != null) { saveSummaries(summaryMap); } // now update the status so we can know it last ran if (status == null) { status = new ProcessingStatus(); status.setCode(REBUILD_Q_SUM_STATUS_KEY + (sid != null ? ":" + sid : "")); } status.setInError(false); status.setLastEventDate(new Date()); statusDao.save(status); } } /** * iterates over the new summary counts and updates the records in the * datastore. Where appropriate, new records will be created and defunct * records will be removed. * * @param summaryMap */ private void saveSummaries(Map<String, Map<String, Long>> summaryMap) { SurveyQuestionSummaryDao summaryDao = new SurveyQuestionSummaryDao(); for (Entry<String, Map<String, Long>> summaryEntry : summaryMap .entrySet()) { List<SurveyQuestionSummary> summaryList = summaryDao .listByQuestion(summaryEntry.getKey()); // iterate over all the counts and update the summaryList with the // count values. Create any missing elements and remove defunct // entries as we go List<SurveyQuestionSummary> toDeleteList = new ArrayList<SurveyQuestionSummary>( summaryList); List<SurveyQuestionSummary> toCreateList = new ArrayList<SurveyQuestionSummary>(); for (Entry<String, Long> valueEntry : summaryEntry.getValue() .entrySet()) { String val = valueEntry.getKey(); boolean found = false; for (SurveyQuestionSummary sum : summaryList) { if (sum.getResponse() != null && sum.getResponse().equals(val)) { // since it's still valid, remove it from toDeleteList toDeleteList.remove(sum); // update the count. Since we still have the // persistenceContext open, this will automatically be // flushed to the datastore without an explicit call to // save sum.setCount(valueEntry.getValue()); found = true; } } if (!found) { // need to create it SurveyQuestionSummary s = new SurveyQuestionSummary(); s.setCount(valueEntry.getValue()); s.setQuestionId(summaryEntry.getKey()); s.setResponse(val); toCreateList.add(s); } } // delete the unseen entities if (toDeleteList.size() > 0) { summaryDao.delete(toDeleteList); } // save the new items if (toCreateList.size() > 0) { summaryDao.save(toCreateList); } // flush the datastore operation summaryDao.flushBatch(); } } /** * loads all the summarizable QuestionAnswerStore instances from the data * store and accrues counts by value occurrence in a map keyed on the * questionId * * @param sinceDate * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Map<String, Map<String, Long>> summarizeQuestionAnswerStore( Long surveyId, Date sinceDate) { final QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); final QuestionDao questionDao = new QuestionDao(); final List<Question> qList = questionDao.listQuestionByType(surveyId, Question.Type.OPTION); Cache cache = null; Map props = new HashMap(); props.put(GCacheFactory.EXPIRATION_DELTA, 60 * 60 * 2); props.put(MemcacheService.SetPolicy.SET_ALWAYS, true); try { CacheFactory cacheFactory = CacheManager.getInstance() .getCacheFactory(); cache = cacheFactory.createCache(props); } catch (Exception e) { log.log(Level.SEVERE, "Couldn't initialize cache: " + e.getMessage(), e); } String cursor = null; final Map<String, Map<String, Long>> summaryMap = new HashMap<String, Map<String, Long>>(); for (Question q : qList) { List<QuestionAnswerStore> qasList = qasDao.listByQuestion(q.getKey().getId(), cursor, QAS_PAGE_SIZE); if (qasList == null || qasList.size() == 0) { continue; // skip } do { cursor = QuestionAnswerStoreDao.getCursor(qasList); for(QuestionAnswerStore qas : qasList) { if (cache != null) { Map<Long, String> answer = new HashMap<Long, String>(); answer.put(qas.getSurveyInstanceId(), qas.getQuestionID()); if (cache.containsKey(answer)) { log.log(Level.INFO, "Found duplicated QAS {surveyInstanceId: " + qas.getSurveyInstanceId() +" , questionID: " + qas.getQuestionID() +"}"); continue; } cache.put(answer, true); } String val = qas.getValue(); Map<String, Long> countMap = summaryMap.get(qas .getQuestionID()); if (countMap == null) { countMap = new HashMap<String, Long>(); summaryMap.put(qas.getQuestionID(), countMap); } // split up multiple answers String[] answers; if (val != null && val.contains("|")) { answers = val.split("\\|"); } else { answers = new String[] { val }; } // perform count for (int i = 0; i < answers.length; i++) { Long count = countMap.get(answers[i]); if (count == null) { count = 1L; } else { count = count + 1; } countMap.put(answers[i], count); } } qasList = qasDao.listByQuestion(q.getKey().getId(), cursor, QAS_PAGE_SIZE); } while (qasList != null && qasList.size() > 0); cursor = null; } return summaryMap; } /** * iterates over all AccessPoints in a country and applies a static set of * rules to determine the proper value of the WFPProjectFlag * * @param country * @param cursor */ private void updateAccessPointProjectFlag(String country, String cursor) { AccessPointDao apDao = new AccessPointDao(); Integer pageSize = 200; List<AccessPoint> apList = apDao.listAccessPointByLocation(country, null, null, null, cursor, pageSize); if (apList != null) { for (AccessPoint ap : apList) { if ("PE".equalsIgnoreCase(ap.getCountryCode())) { ap.setWaterForPeopleProjectFlag(false); } else if ("RW".equalsIgnoreCase(ap.getCountryCode())) { ap.setWaterForPeopleProjectFlag(false); } else if ("MW".equalsIgnoreCase(ap.getCountryCode())) { if (ap.getCommunityName().trim() .equalsIgnoreCase("Kachere/Makhetha/Nkolokoti")) { ap.setCommunityName("Kachere/Makhetha/Nkolokoti"); if (ap.getWaterForPeopleProjectFlag() == null) { ap.setWaterForPeopleProjectFlag(true); } } else if (ap.getWaterForPeopleProjectFlag() == null) { ap.setWaterForPeopleProjectFlag(false); } } else if ("HN".equalsIgnoreCase(ap.getCountryCode())) { if (ap.getCommunityCode().startsWith("IL")) { ap.setWaterForPeopleProjectFlag(false); } else { ap.setWaterForPeopleProjectFlag(true); } } else if ("IN".equalsIgnoreCase(ap.getCountryCode())) { if (ap.getWaterForPeopleProjectFlag() == null) { ap.setWaterForPeopleProjectFlag(true); } } else if ("GT".equalsIgnoreCase(ap.getCountryCode())) { if (ap.getWaterForPeopleProjectFlag() == null) { ap.setWaterAvailableDayVisitFlag(true); } } else { // handles BO, DO, SV if (ap.getWaterForPeopleProjectFlag() == null) { ap.setWaterForPeopleProjectFlag(false); } } } if (apList.size() == pageSize) { // check for more sendProjectUpdateTask(country, AccessPointDao.getCursor(apList)); } } } /** * Sends a message to a task queue to start or continue the processing of * the AP Project Flag * * @param country * @param cursor */ public static void sendProjectUpdateTask(String country, String cursor) { TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.PROJECT_FLAG_UPDATE_ACTION) .param(DataProcessorRequest.COUNTRY_PARAM, country) .param(DataProcessorRequest.CURSOR_PARAM, cursor != null ? cursor : ""); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } /** * fixes wrong Types in questionAnswerStore objects. When cleaned data is * uploaded using an excel file, the type of the answer is set according to * the type of the question, while the device sets the type according to a * different convention. The action handles QAS_PAGE_SIZE items in one call, and * invokes new tasks as necessary if there are more items. * * @param cursor * @author M.T. Westra */ public static void fixOptions2Values() { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); List<QuestionAnswerStore> qasList = siDao.listQAOptions(null, QAS_PAGE_SIZE, "OPTION", "FREE_TEXT", "NUMBER", "SCAN", "PHOTO"); List<QuestionAnswerStore> qasChangedList = new ArrayList<QuestionAnswerStore>(); log.log(Level.INFO, "Running fixOptions2Values"); if (qasList != null) { for (QuestionAnswerStore qas : qasList) { if (Question.Type.OPTION.toString().equals(qas.getType()) || Question.Type.NUMBER.toString() .equals(qas.getType()) || Question.Type.FREE_TEXT.toString().equals( qas.getType()) || Question.Type.SCAN.toString().equals(qas.getType())) { qas.setType("VALUE"); qasChangedList.add(qas); } else if (Question.Type.PHOTO.toString().equals(qas.getType())) { qas.setType("IMAGE"); qasChangedList.add(qas); } } qasDao.save(qasChangedList); // if there are more, invoke another task if (qasList.size() == QAS_PAGE_SIZE) { log.log(Level.INFO, "invoking another fixOptions task"); Queue queue = QueueFactory.getDefaultQueue(); TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.FIX_OPTIONS2VALUES_ACTION); queue.add(options); } } } private void addSurveyInstanceToLocales(String cursor) { log.log(Level.INFO, "adding surveyInstance ids to locales. Cursor at " + cursor); List<SurveyedLocale> slList = null; SurveyedLocaleDao slDao = new SurveyedLocaleDao(); SurveyInstanceDAO siDao = new SurveyInstanceDAO(); slList = slDao.list(cursor); String newCursor = SurveyedLocaleDao.getCursor(slList); Integer num = slList.size(); if (slList != null && slList.size() > 0) { for (SurveyedLocale sl : slList) { // populate surveyIdContrib List<SurveyInstance> siList = siDao.listInstancesByLocale(sl .getKey().getId(), null, null, null); if (siList != null && siList.size() > 0) { List<Long> surveyInstanceContrib = sl.getSurveyInstanceContrib(); if (surveyInstanceContrib == null) { List<Long> newList = new ArrayList<Long>(); for (SurveyInstance si : siList) { newList.add(si.getSurveyId()); } sl.setSurveyInstanceContrib(newList); } else { for (SurveyInstance si : siList) { if (!surveyInstanceContrib.contains(si .getSurveyId())) { surveyInstanceContrib.add(si.getSurveyId()); } } sl.setSurveyInstanceContrib(surveyInstanceContrib); } } slDao.save(sl); } } if (num > 0) { Queue queue = QueueFactory.getDefaultQueue(); queue.add(TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.ADD_SURVEY_INSTANCE_TO_LOCALES_ACTION) .param("cursor", newCursor)); } }; public static void surveyInstanceSummarizer(Long surveyInstanceId, Long qasId, Integer delta) { SurveyInstanceDAO siDao = new SurveyInstanceDAO(); QuestionAnswerStoreDao qasDao = new QuestionAnswerStoreDao(); boolean success = false; if (surveyInstanceId != null) { SurveyInstance si = siDao.getByKey(surveyInstanceId); if (si != null && qasId != null) { QuestionAnswerStore qas = qasDao.getByKey(qasId); if (qas != null) { GeoCoordinates geoC = null; if (qas.getValue() != null && qas.getValue().trim().length() > 0) { geoC = GeoCoordinates.extractGeoCoordinate(qas .getValue()); } if (geoC != null) { GeoLocationService gisService = new GeoLocationServiceGeonamesImpl(); GeoPlace gp = gisService.findDetailedGeoPlace(geoC .getLatitude().toString(), geoC.getLongitude() .toString()); if (gp != null) { SurveyInstanceSummaryDao.incrementCount( gp.getSub1(), gp.getCountryCode(), qas.getCollectionDate(), delta.intValue()); success = true; } } } } } if (!success) { log.log(Level.SEVERE, "Couldnt find geoplace for instance. Instance id: " + surveyInstanceId); } } /** * Adds surveyId and questionGroupId to translations * This only needs to happen once to populate the fields * on old translation values. */ private void addTranslationFields(String cursor) { SurveyDAO sDao = new SurveyDAO(); QuestionGroupDao qgDao = new QuestionGroupDao(); QuestionDao qDao = new QuestionDao(); QuestionOptionDao qoDao = new QuestionOptionDao(); TranslationDao tDao = new TranslationDao(); QuestionGroup qg; Question qu; QuestionOption qo; Long surveyId = null; Long questionGroupId = null; List<Translation> tListSave = new ArrayList<Translation>(); final List<Translation> results = tDao.listTranslations(T_PAGE_SIZE, cursor); for (Translation t : results){ surveyId = null; questionGroupId = null; switch (t.getParentType()){ case SURVEY_NAME: case SURVEY_DESC: Survey s = sDao.getById(t.getParentId()); if (s != null) { surveyId = s.getKey().getId(); } break; case QUESTION_GROUP_DESC: case QUESTION_GROUP_NAME: qg = qgDao.getByKey(t.getParentId()); if (qg != null) { surveyId = qg.getSurveyId(); questionGroupId = qg.getKey().getId(); } break; case QUESTION_NAME: case QUESTION_DESC: case QUESTION_TEXT: case QUESTION_TIP: qu = qDao.getByKey(t.getParentId()); if (qu != null){ surveyId = qu.getSurveyId(); questionGroupId = qu.getQuestionGroupId(); } break; case QUESTION_OPTION: qo = qoDao.getByKey(t.getParentId()); if (qo != null){ Long questionId = qo.getQuestionId(); qu = qDao.getByKey(questionId); if (qu != null){ surveyId = qu.getSurveyId(); questionGroupId = qu.getQuestionGroupId(); } } break; default: break; } t.setSurveyId(surveyId); t.setQuestionGroupId(questionGroupId); tListSave.add(t); } tDao.save(tListSave); if (results.size() == T_PAGE_SIZE) { cursor = TranslationDao.getCursor(results); final TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.ADD_TRANSLATION_FIELDS) .param(DataProcessorRequest.CURSOR_PARAM, cursor != null ? cursor : ""); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } } /** * populates the creationSurveyId field for existing locales * started from testharness with host/webapp/testharness?action=addCreationSurveyIdToLocale * @param cursor */ public static void addCreationSurveyIdToLocale(String cursor){ SurveyedLocaleDao slDao = new SurveyedLocaleDao(); SurveyInstanceDAO siDao = new SurveyInstanceDAO(); List<SurveyedLocale> slList = new ArrayList<SurveyedLocale>(); final List<SurveyedLocale> results = slDao.listAll(cursor, LOCALE_PAGE_SIZE); for (SurveyedLocale sl : results){ // make it idempotent if (sl.getCreationSurveyId() == null && sl.getLastSurveyalInstanceId() != null) { SurveyInstance si = siDao.getByKey(sl.getLastSurveyalInstanceId()); if (si != null) { sl.setCreationSurveyId(si.getSurveyId()); slList.add(sl); } } } slDao.save(slList); if (results.size() == LOCALE_PAGE_SIZE) { cursor = SurveyedLocaleDao.getCursor(results); final TaskOptions options = TaskOptions.Builder .withUrl("/app_worker/dataprocessor") .param(DataProcessorRequest.ACTION_PARAM, DataProcessorRequest.ADD_CREATION_SURVEY_ID_TO_LOCALE) .param(DataProcessorRequest.CURSOR_PARAM, cursor != null ? cursor : ""); Queue queue = QueueFactory.getDefaultQueue(); queue.add(options); } } }
package alma.acs.logging; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import junit.framework.TestCase; import org.omg.CORBA.Any; import org.omg.CORBA.ORB; import org.omg.DsLogAdmin.LogOperations; import si.ijs.maci.Manager; import si.ijs.maci._ManagerStub; import alma.acs.concurrent.DaemonThreadFactory; import alma.acs.logging.config.LogConfig; import alma.acs.logging.level.AcsLogLevelDefinition; import alma.acs.logging.mocks.LogEmptyImpl; /** * Tests remote logging, using mock objects, and therefore does not need a running ACS * which would not even exist in the strict module build order. */ public class RemoteLoggingTest extends TestCase { protected void setUp() throws Exception { System.out.println("\n } /** * Tests the simple case where logging occurs after the call to * {@link ClientLogManager#initRemoteLogging(ORB, Manager, int, boolean)}. */ public void testSimpleRemoteLogging() throws Exception { ClientLogManagerStandalone clm = new ClientLogManagerStandalone(null); // sync call (waits till remote logging is initialized) initRemoteLogging(clm); Logger logger = clm.getLoggerForApplication("testNormalRemoteLogging", true); logger.info("A healthy info log"); logger.severe("And a severe log that actually is not severe"); clm.shutdown(true); } /** * Tests the situation in which the ClientLogManager is shut down before it has finished the * asynchronous <code>initRemoteLogging</code> call. * This can happen in a <code>ComponentClient</code>-based application that performs a short task. * <p> * It is important to make the stdout printing part of this test, * e.g. by using TAT without output suppression tricks, * because among other things we expect the string * <code>Will abort ClientLogManager#initRemoteLogging because remote logging seems no longer needed.</code> * when initRemoteLogging is interrupted by a shutdown. * <p> * The main test thread that logs some messages and the thread that calls initRemoteLogging * compete for the internal lock {@link ClientLogManager#logQueueLock}, whose functioning is being tested here. * <p> * <b>Unfortunately this cannot be totally deterministic, so we must accept occasional failures * of the kind that the output contains "Remote log: <Info .../>" instead of "Will abort ..." strings, or vice versa.</b> */ public void testConcurrentRemoteInitAndStop() throws InterruptedException { DaemonThreadFactory dtf = new DaemonThreadFactory(getName()); // we try this out for different simulated network delays and shutdown delays int[] networkDelays = {0, 2, 18, 22, 100}; // @TODO chose values that give deterministic results on most test machines. int[] shutdownDelays = {1, 20, 102}; // @TODO chose values that give deterministic results on most test machines. for (int networkDelay : networkDelays) { // shutdown delay is the time in milliseconds between the last log and the call to clientlogmanager#shutdown, // with the additional arrangement that initRemoteLogging was running when the last log was produced. for (int shutdownDelay : shutdownDelays) { System.out.println("\n*** Network delay = " + networkDelay + " and shutdown delay = " + shutdownDelay + " ***"); CountDownLatch syncOnPrepareRemoteLogging = new CountDownLatch(1); final ClientLogManagerStandalone clm = new ClientLogManagerStandalone(syncOnPrepareRemoteLogging); LogConfig logConfig = clm.getLogConfig(); logConfig.setDefaultMinLogLevel(AcsLogLevelDefinition.TRACE); logConfig.setDefaultMinLogLevelLocal(AcsLogLevelDefinition.TRACE); Logger logger = clm.getLoggerForApplication(getName(), true); // log something before we init the remote logging: logger.info("A healthy info log before initRemoteLogging ("+networkDelay+"/"+shutdownDelay+")"); // Thread.sleep(2); // to keep these two logs in order, which makes manual ref file comparison easier. logger.fine("now that was a fine log before initRemoteLogging ("+networkDelay+"/"+shutdownDelay+")"); clm.setDelayMillis(networkDelay); // simulated network delay for initRemoteLogging-getLogService and write_records // call initRemoteLogging from a separate thread Thread initRemoteLoggingThread = dtf.newThread(new Runnable() { public void run() { initRemoteLogging(clm); } }); initRemoteLoggingThread.start(); // wait until this thread is actually running, which we check via notification from the ClientLogManager#prepareRemoteLogging method assertTrue("initRemoteLogging should have called prepareRemoteLogging by now...", syncOnPrepareRemoteLogging.await(10, TimeUnit.SECONDS)); // timeout should never apply, just used to stop the test if it gets messed up. logger.info("Another info log after initRemoteLogging ("+networkDelay+"/"+shutdownDelay+")"); // depending on the values of networkDelay and shutdownDelay, we may be calling shutdown while // our ClientLogManager is still delivering the log messages. Thread.sleep(shutdownDelay); clm.shutdown(true); // wait for the thread that called initRemoteLogging initRemoteLoggingThread.join(10000); // wait a bit more for the mock log dispatcher to print out its xml log record Thread.sleep(1000); } } } ////////////////// Helper methods /////////////////// /** * Calls {@linkplain ClientLogManagerStandalone#initRemoteLogging(ORB, Manager, int, boolean)} * with appropriate dummy parameters. * @param clm The instance to call initRemoteLogging on. * @return true if simulated remote logging was initialized successfully */ private boolean initRemoteLogging(ClientLogManagerStandalone clm) { ORB orb = ORB.init(); // unconfigured ORB will do, just needed to produce Any objects for sending remote logs. Manager managerDummy = new _ManagerStub(); // will only be used for != null check. return clm.initRemoteLogging(orb, managerDummy, 1, true); } /** * Modified {@link ClientLogManager} which skips the manager call and uses a mock Log service. * Remote communication delays are simulated, see {@link #setDelayMillis(long)}. */ private static class ClientLogManagerStandalone extends ClientLogManager { private final CountDownLatch syncOnPrepareRemoteLogging; private volatile long delayMillis = 100; /** * Mock impl of the Log service. All methods are total no-ops, * except for {@link LogOperations#write_records(Any[]) which prints the xml log records * contained in the given Any objects to stdout, and simulates network delay by sleeping * via a call to {@link #delay()}. */ private final LogOperations logServiceMock = new LogEmptyImpl() { public void write_records(Any[] records) { for (Any any : records) { // just print to stdout, to be verified by TAT System.out.println("Remote log: " + any.extract_string()); } delay(); } }; /** * Constructor. * @param syncOnPrepareRemoteLogging * Optional synchronization aid (may be <code>null</code>). * Method {@linkplain #prepareRemoteLogging()} will call <code>countDown()</code> * to allow a test to wait until {@linkplain #initRemoteLogging(ORB, Manager, int, boolean)} is actually running * in cases where it gets started from a separate thread. * Note that the parent constructor will not call <code>countDown()</code> even though it calls <code>prepareRemoteLogging</code>, * because we only set the CountDownLatch after calling the parent ctor. Thus passing a <code>CountDownLatch(1)</code> will work. */ ClientLogManagerStandalone(CountDownLatch syncOnPrepareRemoteLogging) { super(); this.syncOnPrepareRemoteLogging = syncOnPrepareRemoteLogging; } /** * This is called by {@linkplain ClientLogManager#initRemoteLogging(ORB, Manager, int, boolean)} * and simulates the access to the Log service by sleeping via {@linkplain #delay()}. * @see alma.acs.logging.ClientLogManager#getLogService(si.ijs.maci.Manager, int) */ protected LogOperations getLogService(Manager manager, int managerHandle) { delay(); return logServiceMock; } /** * Sets the delay in milliseconds which subsequent calls to {@link #delay()} will sleep for. * Default is 100 ms if this method does not get called. */ void setDelayMillis(long delayMillis) { this.delayMillis = delayMillis; } /** * Sleeps for the time given in {@linkplain #setDelayMillis(long)}. */ void delay() { try { Thread.sleep(delayMillis); } catch (InterruptedException ex) { ex.printStackTrace(System.out); } } /** * Overloaded only to allow clients to sync with execution of {@link #initRemoteLogging(ORB, Manager, int, boolean)}. * @see #ClientLogManagerStandalone(CountDownLatch) */ protected void prepareRemoteLogging() { if (syncOnPrepareRemoteLogging != null) { syncOnPrepareRemoteLogging.countDown(); } super.prepareRemoteLogging(); } } }
package org.dspace.content; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.dspace.browse.Browse; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.core.Context; import org.dspace.core.Constants; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.search.DSIndexer; import org.dspace.storage.rdbms.TableRowIterator; import org.dspace.storage.rdbms.DatabaseManager; /** * Support to install item in the archive * * @author dstuve * @version $Revision$ */ public class InstallItem { public static Item installItem(Context c, InProgressSubmission is) throws SQLException, IOException, AuthorizeException { return installItem(c, is, c.getCurrentUser()); } public static Item installItem(Context c, InProgressSubmission is, EPerson e) throws SQLException, IOException, AuthorizeException { Item item = is.getItem(); // create accession date DCDate now = DCDate.getCurrent(); item.addDC("date", "accessioned", null, now.toString()); item.addDC("date", "available", null, now.toString()); // create issue date if not present DCValue[] currentDateIssued = item.getDC("date", "issued", Item.ANY); if(currentDateIssued.length == 0) { item.addDC("date", "issued", null, now.toString()); } // create handle String handle = HandleManager.createHandle(c, item); String handleref = HandleManager.getCanonicalForm(handle); // Add handle as identifier.uri DC value item.addDC("identifier", "uri", null, handleref); // Add format.mimetype and format.extent DC values Bitstream[] bitstreams = item.getNonInternalBitstreams(); for (int i = 0; i < bitstreams.length; i++) { BitstreamFormat bf = bitstreams[i].getFormat(); item.addDC("format", "extent", null, String.valueOf(bitstreams[i].getSize())); item.addDC("format", "mimetype", null, bf.getMIMEType()); } String provDescription = "Made available in DSpace on " + now + " (GMT). " + getBitstreamProvenanceMessage(item); if (currentDateIssued.length != 0) { DCDate d = new DCDate(currentDateIssued[0].value); provDescription = provDescription + " Previous issue date: " + d.toString(); } // Add provenance description item.addDC("description", "provenance", "en", provDescription); // create collection2item mapping is.getCollection().addItem(item); // create date.available // set in_archive=true item.setArchived(true); // save changes ;-) item.update(); // add item to search and browse indices DSIndexer.indexItem(c, item); // item.update() above adds item to browse indices //Browse.itemChanged(c, item); // remove in-progress submission is.deleteWrapper(); // remove the submit authorization policies // and replace them with the collection's READ // policies // FIXME: this is an inelegant hack, but out of time! List policies = AuthorizeManager.getPoliciesActionFilter(c, is.getCollection(), Constants.READ ); item.replaceAllPolicies(policies); return item; } /** generate provenance-worthy description of the bitstreams * contained in an item */ public static String getBitstreamProvenanceMessage(Item myitem) { // Get non-internal format bitstreams Bitstream[] bitstreams = myitem.getNonInternalBitstreams(); // Create provenance description String mymessage = "No. of bitstreams: " + bitstreams.length + "\n"; // Add sizes and checksums of bitstreams for (int j = 0; j < bitstreams.length; j++) { mymessage = mymessage + bitstreams[j].getName() + ": " + bitstreams[j].getSize() + " bytes, checksum: " + bitstreams[j].getChecksum() + " (" + bitstreams[j].getChecksumAlgorithm() + ")\n"; } return mymessage; } }
package lombok.ast; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public class ListAccessor<T extends Node, P extends Node> { private final List<AbstractNode> list; private final AbstractNode parent; private final Class<T> tClass; private final String listName; private final P returnAsParent; private ListAccessor(List<AbstractNode> list, AbstractNode parent, Class<T> tClass, String listName, P returnAsParent) { this.list = list; this.parent = parent; this.tClass = tClass; this.listName = listName; this.returnAsParent = returnAsParent; } static <T extends Node, P extends AbstractNode> ListAccessor<T, P> of(List<AbstractNode> list, P parent, Class<T> tClass, String listName) { return new ListAccessor<T, P>(list, parent, tClass, listName, parent); } <Q extends Node> ListAccessor<T, Q> wrap(Q returnThisAsParent) { return new ListAccessor<T, Q>(list, parent, tClass, listName, returnThisAsParent); } public P up() { return returnAsParent; } public void clear() { list.clear(); } public P migrateAllFrom(ListAccessor<? extends T, ?> otherList) { for (Node n : otherList.list) { if (!tClass.isInstance(n)) throw new AstException(otherList.parent, String.format("List %s contains node that aren't of type %s", otherList.listName, tClass)); } return migrateAllFromRaw(otherList); } public P migrateAllFromRaw(ListAccessor<? extends Node, ?> otherList) { Iterator<AbstractNode> it = otherList.list.iterator(); while (it.hasNext()) { AbstractNode n = it.next(); otherList.parent.disown(n); it.remove(); this.addToEndRaw(n); } return returnAsParent; } public P addToStart(T... node) { return addToStartRaw(node); } public P addToStartRaw(Node... node) { for (Node n : node) { AbstractNode child = (AbstractNode)n; if (child != null) { parent.adopt(child); list.add(0, child); } } return returnAsParent; } public P addToEnd(T... node) { return addToEndRaw(node); } public P addToEndRaw(Node... node) { for (Node n : node) { AbstractNode child = (AbstractNode)n; if (node != null) { parent.adopt(child); list.add(child); } } return returnAsParent; } public P addBefore(Node ref, T... node) { if (node == null) throw new NullPointerException("node"); return addBeforeRaw(ref, node); } public P addBeforeRaw(Node ref, Node... node) { if (ref == null) throw new NullPointerException("ref"); for (int i = 0; i < list.size(); i++) { if (list.get(i) == ref) { int j = 0; for (Node n : node) { AbstractNode child = (AbstractNode)n; if (child != null) { child.ensureParentless(); parent.adopt(child); list.add(i + j, child); j++; } } return returnAsParent; } } throw new IllegalStateException(listName + " does not contain: " + ref); } public P addAfter(Node ref, T... node) { if (node == null) throw new NullPointerException("node"); return addAfterRaw(ref, node); } public P addAfterRaw(Node ref, Node... node) { if (ref == null) throw new NullPointerException("ref"); for (int i = 0; i < list.size(); i++) { if (list.get(i) == ref) { int j = 0; for (Node n : node) { AbstractNode child = (AbstractNode)n; if (child != null) { child.ensureParentless(); parent.adopt(child); list.add(i + j + 1, child); j++; } } return returnAsParent; } } throw new IllegalStateException(listName + " does not contain: " + ref); } public P replace(Node source, T replacement) { if (replacement == null) throw new NullPointerException("replacement"); return replaceRaw(source, replacement); } public P replaceRaw(Node source, Node replacement) { if (replacement != null) ((AbstractNode)replacement).ensureParentless(); parent.ensureParentage((AbstractNode)source); for (int i = 0; i < list.size(); i++) { if (list.get(i) == source) { parent.disown((AbstractNode)source); try { if (replacement != null) parent.adopt((AbstractNode)replacement); } catch (IllegalStateException e) { parent.adopt((AbstractNode)source); throw e; } if (replacement == null) list.remove(i); //screws up for counter, but we return right after anyway, so it doesn't matter. else list.set(i, (AbstractNode)replacement); return returnAsParent; } } throw new IllegalStateException(listName + " does not contain: " + source); } public P remove(Node source) throws NoSuchElementException { if (source == null) return returnAsParent; parent.ensureParentage((AbstractNode)source); for (int i = 0; i < list.size(); i++) { if (list.get(i) == source) { parent.disown((AbstractNode)source); list.remove(i); return returnAsParent; } } throw new NoSuchElementException(listName + " does not contain: " + source); } public boolean contains(Node source) { if (source == null) return false; if (source.getParent() != parent) return false; for (int i = 0; i < list.size(); i++) { if (list.get(i) == source) return true; } return false; } @SuppressWarnings("unchecked") public Iterable<T> getContents() { List<T> out = new ArrayList<T>((List<T>)list); for (Object o : out) { if (!tClass.isInstance(o)) throw new AstException(parent, String.format( "%s contains an element that isn't of the appropriate type(%s): %s", listName, tClass.getSimpleName(), o.getClass().getSimpleName())); } return out; } public Node rawFirst() { try { return list.get(0); } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } public T first() { Node r = rawFirst(); if (!tClass.isInstance(r)) throw new AstException(parent, String.format( "first element of %w isn't of the appropriate type(%s): %s", listName, tClass.getSimpleName(), r.getClass().getSimpleName())); return tClass.cast(r); } public Node rawLast() { try { return list.get(list.size()-1); } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } public T last() { Node r = rawLast(); if (!tClass.isInstance(r)) throw new AstException(parent, String.format( "last element of %w isn't of the appropriate type(%s): %s", listName, tClass.getSimpleName(), r.getClass().getSimpleName())); return tClass.cast(r); } public boolean isEmpty() { return list.isEmpty(); } public Iterable<Node> getRawContents() { return new ArrayList<Node>(list); } public int size() { return list.size(); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // 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 DAVID J. PEARCE 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 wyil.builders; import static wycc.lang.SyntaxError.internalFailure; import static wycc.lang.SyntaxError.syntaxError; import static wyil.util.ErrorMessages.errorMessage; import java.math.BigInteger; import java.util.*; import wyautl.util.BigRational; import wybs.lang.*; import wyfs.lang.Path; import wyil.lang.*; import wyil.util.ErrorMessages; import wycc.lang.Attribute; import wycc.lang.NameID; import wycc.lang.SyntacticElement; import wycc.util.Pair; import wycs.core.SemanticType; import wycs.core.Value; import wycs.syntax.*; /** * Responsible for converting a given Wyil bytecode into an appropriate * constraint which encodes its semantics. * * @author David J. Pearce * */ public class VcTransformer { private final Builder builder; private final WyalFile wycsFile; private final String filename; private final boolean assume; public VcTransformer(Builder builder, WyalFile wycsFile, String filename, boolean assume) { this.builder = builder; this.filename = filename; this.assume = assume; this.wycsFile = wycsFile; } public String filename() { return filename; } public void end(VcBranch.LoopScope scope, VcBranch branch) { // not sure what really needs to be done here, in fact. } public void exit(VcBranch.LoopScope scope, VcBranch branch) { branch.addAll(scope.constraints); } private static int indexCount = 0; public void end(VcBranch.ForScope scope, VcBranch branch) { // we need to build up a quantified formula here. Expr root = and(scope.constraints,branch.entry()); SyntacticType type = convert(scope.loop.type.element(), branch.entry()); TypePattern var; if (scope.loop.type instanceof Type.EffectiveList) { // FIXME: hack to work around limitations of whiley for // loops. Expr.Variable idx = Expr.Variable("i" + indexCount++); TypePattern tp1 = new TypePattern.Leaf(new SyntacticType.Primitive( SemanticType.Int), idx.name, null, null); TypePattern tp2 = new TypePattern.Leaf(type, "_" + scope.index.name, null, null); var = new TypePattern.Tuple(new TypePattern[] { tp1, tp2 }, null, scope.source, null); } else { var = new TypePattern.Leaf(type, "_" + scope.index.name, scope.source, null); } // Now, we have to rename the index variable in the soon-to-be // quantified expression. This is necessary to prevent conflicts with // same-named registers used later in the method. HashMap<String,Expr> binding = new HashMap<String,Expr>(); binding.put(scope.index.name, Expr.Variable("_" + scope.index.name)); root = root.substitute(binding); branch.add(Expr.ForAll(var, root, branch.entry().attributes())); } public void exit(VcBranch.ForScope scope, VcBranch branch) { Expr root = and(scope.constraints, branch.entry()); SyntacticType type = convert(scope.loop.type.element(), branch.entry()); TypePattern var; if (scope.loop.type instanceof Type.EffectiveList) { // FIXME: hack to work around limitations of whiley for // loops. Expr.Variable idx = Expr.Variable("i" + indexCount++); TypePattern tp1 = new TypePattern.Leaf(new SyntacticType.Primitive( SemanticType.Int), idx.name, null, null); TypePattern tp2 = new TypePattern.Leaf(type, "_" + scope.index.name, null, null); var = new TypePattern.Tuple(new TypePattern[] { tp1, tp2 }, null, scope.source, null); } else { var = new TypePattern.Leaf(type, "_" + scope.index.name, scope.source, null); } // Now, we have to rename the index variable in the soon-to-be // quantified expression. This is necessary to prevent conflicts with // same-named registers used later in the method. HashMap<String,Expr> binding = new HashMap<String,Expr>(); binding.put(scope.index.name, Expr.Variable("_" + scope.index.name)); root = root.substitute(binding); branch.add(Expr.Exists(var, root, branch.entry().attributes())); } public void exit(VcBranch.TryScope scope, VcBranch branch) { } protected void transform(Code.Assert code, VcBranch branch) { Expr test = buildTest(code.op, code.leftOperand, code.rightOperand, code.type, branch); if (!assume) { Expr assumptions = branch.constraints(); Expr implication = Expr.Binary(Expr.Binary.Op.IMPLIES, assumptions, test); // build up list of used variables HashSet<String> uses = new HashSet<String>(); implication.freeVariables(uses); // Now, parameterise the assertion appropriately Expr assertion = buildAssertion(0, implication, uses, branch); wycsFile.add(wycsFile.new Assert(code.msg, assertion, branch .entry().attributes())); } // We can now safely assume the assertion. Note that we must assume it // here, even for the case where it is already proven. This is because // it is necessary to cut out unreaslizable paths which may continue // after this assertion. branch.add(test); } protected Expr buildAssertion(int index, Expr implication, HashSet<String> uses, VcBranch branch) { if (index == branch.nScopes()) { return implication; } else { ArrayList<TypePattern> vars = new ArrayList<TypePattern>(); Expr contents = buildAssertion(index + 1, implication, uses, branch); VcBranch.Scope scope = branch.scope(index); if (scope instanceof VcBranch.EntryScope) { VcBranch.EntryScope es = (VcBranch.EntryScope) scope; ArrayList<Type> parameters = es.declaration.type().params(); for (int i = 0; i != parameters.size(); ++i) { Expr.Variable v = Expr.Variable("r" + i); if (uses.contains(v.name)) { // only include variable if actually used uses.remove(v.name); SyntacticType t = convert(branch.typeOf(v.name),branch.entry()); vars.add(new TypePattern.Leaf(t, v.name, null, null)); } } // Finally, scope any remaining free variables. Such variables // occur from modified operands of loops which are no longer on // the scope stack. for (String v : uses) { SyntacticType t = convert(branch.typeOf(v),branch.entry()); vars.add(new TypePattern.Leaf(t, v, null, null)); } } else if (scope instanceof VcBranch.ForScope) { VcBranch.ForScope ls = (VcBranch.ForScope) scope; SyntacticType type = convert(ls.loop.type.element(), branch.entry()); // first, deal with index expression int[] modifiedOperands = ls.loop.modifiedOperands; if (uses.contains(ls.index.name)) { // only parameterise the index variable if it is actually // used. uses.remove(ls.index.name); Expr idx; if (ls.loop.type instanceof Type.EffectiveList) { // FIXME: hack to work around limitations of whiley for // loops. String i = "i" + indexCount++; vars.add(new TypePattern.Leaf( new SyntacticType.Primitive(SemanticType.Int), i, null, null)); vars.add(new TypePattern.Leaf(type, ls.index.name, null, null)); idx = Expr.Nary(Expr.Nary.Op.TUPLE, new Expr[] { Expr.Variable(i), ls.index }); } else { vars.add(new TypePattern.Leaf(type, ls.index.name, null, null)); idx = ls.index; } // since index is used, we need to imply that it is // contained in the source expression. contents = Expr.Binary(Expr.Binary.Op.IMPLIES, Expr.Binary(Expr.Binary.Op.IN, idx, ls.source), contents); ls.source.freeVariables(uses); // updated uses appropriately } // second, deal with modified operands for (int i = 0; i != modifiedOperands.length; ++i) { int reg = modifiedOperands[i]; Expr.Variable v = Expr.Variable("r" + reg); if (uses.contains(v.name)) { // Only parameterise a modified operand if it is // actually used. uses.remove(v.name); SyntacticType t = convert(branch.typeOf(v.name),branch.entry()); vars.add(new TypePattern.Leaf(t, v.name, null, null)); } } } else if (scope instanceof VcBranch.LoopScope) { VcBranch.LoopScope ls = (VcBranch.LoopScope) scope; // now, deal with modified operands int[] modifiedOperands = ls.loop.modifiedOperands; for (int i = 0; i != modifiedOperands.length; ++i) { int reg = modifiedOperands[i]; Expr.Variable v = Expr.Variable("r" + reg); if (uses.contains(v.name)) { // Only parameterise a modified operand if it is // actually used. uses.remove(v.name); SyntacticType t = convert(branch.typeOf(v.name),branch.entry()); vars.add(new TypePattern.Leaf(t, v.name, null, null)); } } } if (vars.size() == 0) { // we have nothing to parameterise, so ignore it. return contents; } else if(vars.size() == 1){ return Expr.ForAll(vars.get(0),contents); } else { return Expr.ForAll( new TypePattern.Tuple(vars.toArray(new TypePattern[vars .size()]), null, null, null), contents); } } } protected void transform(Code.Assume code, VcBranch branch) { // At this point, what we do is invert the condition being asserted and // check that it is unsatisfiable. Expr test = buildTest(code.op, code.leftOperand, code.rightOperand, code.type, branch); branch.add(test); } protected void transform(Code.Assign code, VcBranch branch) { branch.write(code.target, branch.read(code.operand), code.assignedType()); } protected void transform(Code.BinArithOp code, VcBranch branch) { Expr lhs = branch.read(code.leftOperand); Expr rhs = branch.read(code.rightOperand); Expr.Binary.Op op; switch (code.kind) { case ADD: op = Expr.Binary.Op.ADD; break; case SUB: op = Expr.Binary.Op.SUB; break; case MUL: op = Expr.Binary.Op.MUL; break; case DIV: op = Expr.Binary.Op.DIV; break; case RANGE: op = Expr.Binary.Op.RANGE; break; default: internalFailure("unknown binary operator", filename, branch.entry()); return; } branch.write(code.target, Expr.Binary(op, lhs, rhs, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.BinListOp code, VcBranch branch) { Expr lhs = branch.read(code.leftOperand); Expr rhs = branch.read(code.rightOperand); switch (code.kind) { case APPEND: // do nothing break; case LEFT_APPEND: rhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { rhs }, branch.entry().attributes()); break; case RIGHT_APPEND: lhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { lhs }, branch.entry().attributes()); break; default: internalFailure("unknown binary operator", filename, branch.entry()); return; } branch.write(code.target, Expr.Binary(Expr.Binary.Op.LISTAPPEND,lhs, rhs, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.BinSetOp code, VcBranch branch) { Collection<Attribute> attributes = branch.entry().attributes(); Expr lhs = branch.read(code.leftOperand); Expr rhs = branch.read(code.rightOperand); Expr val; switch (code.kind) { case UNION: val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes); break; case LEFT_UNION: rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch .entry().attributes()); val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes); break; case RIGHT_UNION: lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch .entry().attributes()); val = Expr.Binary(Expr.Binary.Op.SETUNION,lhs, rhs, attributes); break; case INTERSECTION: val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes); break; case LEFT_INTERSECTION: rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch .entry().attributes()); val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes); break; case RIGHT_INTERSECTION: lhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { lhs }, branch .entry().attributes()); val = Expr.Binary(Expr.Binary.Op.SETINTERSECTION,lhs, rhs, attributes); break; case LEFT_DIFFERENCE: rhs = Expr.Nary(Expr.Nary.Op.SET, new Expr[] { rhs }, branch .entry().attributes()); val = Expr.Binary(Expr.Binary.Op.SETDIFFERENCE,lhs, rhs, attributes); break; case DIFFERENCE: val = Expr.Binary(Expr.Binary.Op.SETDIFFERENCE,lhs, rhs, attributes); break; default: internalFailure("unknown binary operator", filename, branch.entry()); return; } branch.write(code.target, val, code.assignedType()); } protected void transform(Code.BinStringOp code, VcBranch branch) { Collection<Attribute> attributes = branch.entry().attributes(); Expr lhs = branch.read(code.leftOperand); Expr rhs = branch.read(code.rightOperand); switch (code.kind) { case APPEND: // do nothing break; case LEFT_APPEND: rhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { rhs }, branch.entry().attributes()); break; case RIGHT_APPEND: lhs = Expr.Nary(Expr.Nary.Op.LIST,new Expr[] { lhs }, branch.entry().attributes()); break; default: internalFailure("unknown binary operator", filename, branch.entry()); return; } branch.write(code.target, Expr.Binary(Expr.Binary.Op.LISTAPPEND,lhs, rhs, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.Convert code, VcBranch branch) { Expr result = branch.read(code.operand); // TODO: actually implement some or all coercions? branch.write(code.target, result, code.assignedType()); } protected void transform(Code.Const code, VcBranch branch) { Value val = convert(code.constant, branch.entry()); branch.write(code.target, Expr.Constant(val, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.Debug code, VcBranch branch) { // do nout } protected void transform(Code.Dereference code, VcBranch branch) { // TODO branch.invalidate(code.target,code.type); } protected void transform(Code.FieldLoad code, VcBranch branch) { Collection<Attribute> attributes = branch.entry().attributes(); // Expr src = branch.read(code.operand); // branch.write(code.target, Exprs.FieldOf(src, code.field, // attributes)); ArrayList<String> fields = new ArrayList<String>(code.type.fields() .keySet()); Collections.sort(fields); Expr src = branch.read(code.operand); Expr index = Expr.Constant(Value.Integer(BigInteger.valueOf(fields.indexOf(code.field)))); Expr result = Expr.IndexOf(src, index, branch.entry().attributes()); branch.write(code.target, result, code.assignedType()); } protected void transform(Code.If code, VcBranch falseBranch, VcBranch trueBranch) { // First, cover true branch Expr.Binary trueTest = buildTest(code.op, code.leftOperand, code.rightOperand, code.type, trueBranch); trueBranch.add(trueTest); falseBranch.add(invert(trueTest)); } protected void transform(Code.IndirectInvoke code, VcBranch branch) { // TODO if(code.target != Code.NULL_REG) { branch.invalidate(code.target,code.type.ret()); } } protected void transform(Code.Invoke code, VcBranch branch) throws Exception { SyntacticElement entry = branch.entry(); Collection<Attribute> attributes = entry.attributes(); int[] code_operands = code.operands; if (code.target != Code.NULL_REG) { // Need to assume the post-condition holds. CodeBlock postcondition = findPostcondition(code.name, code.type, branch.entry()); Expr[] operands = new Expr[code_operands.length]; for (int i = 0; i != code_operands.length; ++i) { operands[i] = branch.read(code_operands[i]); } Expr argument = Expr.Nary(Expr.Nary.Op.TUPLE, operands, attributes); branch.write(code.target, Expr.FunCall(toIdentifier(code.name), new SyntacticType[0], argument, attributes), code.assignedType()); // Here, we must add a WycsFile Function to represent the function being called, and to prototype it. TypePattern from = new TypePattern.Leaf(convert(code.type.params(),entry), null, null, null, attributes); TypePattern to = new TypePattern.Leaf(convert(code.type.ret(),entry), null, null, null, attributes); wycsFile.add(wycsFile.new Function(toIdentifier(code.name), Collections.EMPTY_LIST, from, to, null)); if (postcondition != null) { // operands = Arrays.copyOf(operands, operands.length); Expr[] arguments = new Expr[operands.length + 1]; System.arraycopy(operands, 0, arguments, 1, operands.length); arguments[0] = branch.read(code.target); ArrayList<Type> paramTypes = code.type.params(); Type[] types = new Type[paramTypes.size()+1]; for(int i=0;i!=paramTypes.size();++i) { types[i+1] = paramTypes.get(i); } types[0] = branch.typeOf(code.target); Expr constraint = transformExternalBlock(postcondition, arguments, types, branch); // assume the post condition holds branch.add(constraint); } } } protected void transform(Code.Invert code, VcBranch branch) { // TODO branch.invalidate(code.target,code.type); } protected void transform(Code.IndexOf code, VcBranch branch) { Expr src = branch.read(code.leftOperand); Expr idx = branch.read(code.rightOperand); branch.write(code.target, Expr.IndexOf(src, idx, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.LengthOf code, VcBranch branch) { Expr src = branch.read(code.operand); branch.write(code.target, Expr.Unary(Expr.Unary.Op.LENGTHOF, src, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.Loop code, VcBranch branch) { // FIXME: assume loop invariant? } protected void transform(Code.Move code, VcBranch branch) { branch.write(code.target, branch.read(code.operand), code.assignedType()); } protected void transform(Code.NewMap code, VcBranch branch) { // TODO branch.invalidate(code.target,code.type); } protected void transform(Code.NewList code, VcBranch branch) { int[] code_operands = code.operands; Expr[] vals = new Expr[code_operands.length]; for (int i = 0; i != vals.length; ++i) { vals[i] = branch.read(code_operands[i]); } branch.write(code.target, Expr.Nary(Expr.Nary.Op.LIST, vals, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.NewSet code, VcBranch branch) { int[] code_operands = code.operands; Expr[] vals = new Expr[code_operands.length]; for (int i = 0; i != vals.length; ++i) { vals[i] = branch.read(code_operands[i]); } branch.write(code.target, Expr.Nary(Expr.Nary.Op.SET, vals, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.NewRecord code, VcBranch branch) { int[] code_operands = code.operands; Type.Record type = code.type; ArrayList<String> fields = new ArrayList<String>(type.fields().keySet()); Collections.sort(fields); Expr[] vals = new Expr[fields.size()]; for (int i = 0; i != fields.size(); ++i) { vals[i] = branch.read(code_operands[i]); } branch.write(code.target, new Expr.Nary(Expr.Nary.Op.TUPLE, vals, branch.entry().attributes()), code.assignedType()); } protected void transform(Code.NewObject code, VcBranch branch) { // TODO branch.invalidate(code.target,code.type); } protected void transform(Code.NewTuple code, VcBranch branch) { int[] code_operands = code.operands; Expr[] vals = new Expr[code_operands.length]; for (int i = 0; i != vals.length; ++i) { vals[i] = branch.read(code_operands[i]); } branch.write(code.target, Expr.Nary(Expr.Nary.Op.TUPLE, vals, branch .entry().attributes()), code.assignedType()); } protected void transform(Code.Nop code, VcBranch branch) { // do nout } protected void transform(Code.Return code, VcBranch branch) { // nothing to do } protected void transform(Code.SubString code, VcBranch branch) { Expr src = branch.read(code.operands[0]); Expr start = branch.read(code.operands[1]); Expr end = branch.read(code.operands[2]); Expr result = Expr.Ternary(Expr.Ternary.Op.SUBLIST, src, start, end, branch.entry().attributes()); branch.write(code.target, result, code.assignedType()); } protected void transform(Code.SubList code, VcBranch branch) { Expr src = branch.read(code.operands[0]); Expr start = branch.read(code.operands[1]); Expr end = branch.read(code.operands[2]); Expr result = Expr.Ternary(Expr.Ternary.Op.SUBLIST, src, start, end, branch.entry().attributes()); branch.write(code.target, result, code.assignedType()); } protected void transform(Code.Switch code, VcBranch defaultCase, VcBranch... cases) { for(int i=0;i!=cases.length;++i) { Constant caseValue = code.branches.get(i).first(); VcBranch branch = cases[i]; List<Attribute> attributes = branch.entry().attributes(); Expr src = branch.read(code.operand); Expr constant = Expr.Constant(convert(caseValue, branch.entry()),attributes); branch.add(Expr.Binary(Expr.Binary.Op.EQ, src, constant, attributes)); defaultCase.add(Expr.Binary(Expr.Binary.Op.NEQ, src, constant, attributes)); } } protected void transform(Code.Throw code, VcBranch branch) { // TODO } protected void transform(Code.TupleLoad code, VcBranch branch) { Expr src = branch.read(code.operand); Expr index = Expr .Constant(Value.Integer(BigInteger.valueOf(code.index))); Expr result = Expr.IndexOf(src, index, branch.entry().attributes()); branch.write(code.target, result, code.assignedType()); } protected void transform(Code.TryCatch code, VcBranch branch) { // FIXME: do something here? } protected void transform(Code.UnArithOp code, VcBranch branch) { if (code.kind == Code.UnArithKind.NEG) { Expr operand = branch.read(code.operand); branch.write(code.target, Expr.Unary(Expr.Unary.Op.NEG, operand, branch.entry().attributes()), code.assignedType()); } else { // TODO branch.invalidate(code.target,code.type); } } protected void transform(Code.Update code, VcBranch branch) { Expr result = branch.read(code.operand); Expr source = branch.read(code.target); branch.write(code.target, updateHelper(code.iterator(), source, result, branch), code.assignedType()); } protected Expr updateHelper(Iterator<Code.LVal> iter, Expr source, Expr result, VcBranch branch) { if (!iter.hasNext()) { return result; } else { Collection<Attribute> attributes = branch.entry().attributes(); Code.LVal lv = iter.next(); if (lv instanceof Code.RecordLVal) { Code.RecordLVal rlv = (Code.RecordLVal) lv; // result = updateHelper(iter, // Exprs.FieldOf(source, rlv.field, attributes), result, // branch); // return Exprs.FieldUpdate(source, rlv.field, result, // attributes); // FIXME: following is broken for open records. ArrayList<String> fields = new ArrayList<String>(rlv.rawType() .fields().keySet()); Collections.sort(fields); int index = fields.indexOf(rlv.field); Expr[] operands = new Expr[fields.size()]; for (int i = 0; i != fields.size(); ++i) { Expr _i = Expr .Constant(Value.Integer(BigInteger.valueOf(i))); if (i != index) { operands[i] = Expr.IndexOf(source, _i, attributes); } else { operands[i] = updateHelper(iter, Expr.IndexOf(source, _i, attributes), result, branch); } } return Expr.Nary(Expr.Nary.Op.TUPLE, operands, attributes); } else if (lv instanceof Code.ListLVal) { Code.ListLVal rlv = (Code.ListLVal) lv; Expr index = branch.read(rlv.indexOperand); result = updateHelper(iter, Expr.IndexOf(source, index, attributes), result, branch); return Expr.Ternary(Expr.Ternary.Op.UPDATE, source, index, result, branch.entry().attributes()); } else if (lv instanceof Code.MapLVal) { return source; // TODO } else if (lv instanceof Code.StringLVal) { return source; // TODO } else { return source; // TODO } } } protected CodeBlock findPrecondition(NameID name, Type.FunctionOrMethod fun, SyntacticElement elem) throws Exception { Path.Entry<WyilFile> e = builder.project().get(name.module(), WyilFile.ContentType); if (e == null) { syntaxError( errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module() .toString()), filename, elem); } WyilFile m = e.read(); WyilFile.FunctionOrMethodDeclaration method = m.functionOrMethod(name.name(), fun); for (WyilFile.Case c : method.cases()) { // FIXME: this is a hack for now return c.precondition().get(0); } return null; } protected CodeBlock findPostcondition(NameID name, Type.FunctionOrMethod fun, SyntacticElement elem) throws Exception { Path.Entry<WyilFile> e = builder.project().get(name.module(), WyilFile.ContentType); if (e == null) { syntaxError( errorMessage(ErrorMessages.RESOLUTION_ERROR, name.module() .toString()), filename, elem); } WyilFile m = e.read(); WyilFile.FunctionOrMethodDeclaration method = m.functionOrMethod( name.name(), fun); for (WyilFile.Case c : method.cases()) { // FIXME: this is a hack for now if(c.postcondition().size() > 0) { return c.postcondition().get(0); } } return null; } protected Expr transformExternalBlock(CodeBlock externalBlock, Expr[] operands, Type[] types, VcBranch branch) { // first, generate a constraint representing the post-condition. VcBranch master = new VcBranch(externalBlock); // second, set initial environment for (int i = 0; i != operands.length; ++i) { master.write(i, operands[i], types[i]); } return master.transform(new VcTransformer(builder, wycsFile, filename, true)); } /** * Generate a formula representing a condition from an Code.IfCode or * Code.Assert bytecodes. * * @param op * @param stack * @param elem * @return */ private Expr.Binary buildTest(Code.Comparator cop, int leftOperand, int rightOperand, Type type, VcBranch branch) { Expr lhs = branch.read(leftOperand); Expr rhs = branch.read(rightOperand); Expr.Binary.Op op; switch (cop) { case EQ: op = Expr.Binary.Op.EQ; break; case NEQ: op = Expr.Binary.Op.NEQ; break; case GTEQ: op = Expr.Binary.Op.GTEQ; break; case GT: op = Expr.Binary.Op.GT; break; case LTEQ: op = Expr.Binary.Op.LTEQ; break; case LT: op = Expr.Binary.Op.LT; break; case SUBSET: op = Expr.Binary.Op.SUBSET; break; case SUBSETEQ: op = Expr.Binary.Op.SUBSETEQ; break; case IN: op = Expr.Binary.Op.IN; break; default: internalFailure("unknown comparator (" + cop + ")", filename, branch.entry()); return null; } return Expr.Binary(op, lhs, rhs, branch.entry().attributes()); } /** * Generate the logically inverted expression corresponding to this * comparator. * * @param cop * @param leftOperand * @param rightOperand * @param type * @param branch * @return */ private Expr invert(Expr.Binary test) { Expr.Binary.Op op; switch (test.op) { case EQ: op = Expr.Binary.Op.NEQ; break; case NEQ: op = Expr.Binary.Op.EQ; break; case GTEQ: op = Expr.Binary.Op.LT; break; case GT: op = Expr.Binary.Op.LTEQ; break; case LTEQ: op = Expr.Binary.Op.GT; break; case LT: op = Expr.Binary.Op.GTEQ; break; case SUBSET: op = Expr.Binary.Op.SUPSETEQ; break; case SUBSETEQ: op = Expr.Binary.Op.SUPSET; break; case SUPSET: op = Expr.Binary.Op.SUBSETEQ; break; case SUPSETEQ: op = Expr.Binary.Op.SUBSET; break; case IN: op = Expr.Binary.Op.IN; return Expr.Unary( Expr.Unary.Op.NOT, Expr.Binary(op, test.leftOperand, test.rightOperand, test.attributes()), test.attributes()); default: internalFailure("unknown comparator (" + test.op + ")", filename, test); return null; } return Expr.Binary(op, test.leftOperand, test.rightOperand, test.attributes()); } public Value convert(Constant c, SyntacticElement elem) { if (c instanceof Constant.Null) { // TODO: is this the best translation? return wycs.core.Value.Integer(BigInteger.ZERO); } else if (c instanceof Constant.Bool) { Constant.Bool cb = (Constant.Bool) c; return wycs.core.Value.Bool(cb.value); } else if (c instanceof Constant.Byte) { Constant.Byte cb = (Constant.Byte) c; return wycs.core.Value.Integer(BigInteger.valueOf(cb.value)); } else if (c instanceof Constant.Char) { Constant.Char cb = (Constant.Char) c; return wycs.core.Value.Integer(BigInteger.valueOf(cb.value)); } else if (c instanceof Constant.Integer) { Constant.Integer cb = (Constant.Integer) c; return wycs.core.Value.Integer(cb.value); } else if (c instanceof Constant.Decimal) { Constant.Decimal cb = (Constant.Decimal) c; return wycs.core.Value.Decimal(cb.value); } else if (c instanceof Constant.Strung) { Constant.Strung cb = (Constant.Strung) c; String str = cb.value; ArrayList<Value> pairs = new ArrayList<Value>(); for (int i = 0; i != str.length(); ++i) { ArrayList<Value> pair = new ArrayList<Value>(); pair.add(Value.Integer(BigInteger.valueOf(i))); pair.add(Value.Integer(BigInteger.valueOf(str.charAt(i)))); pairs.add(Value.Tuple(pair)); } return Value.Set(pairs); } else if (c instanceof Constant.List) { Constant.List cb = (Constant.List) c; List<Constant> cb_values = cb.values; ArrayList<Value> pairs = new ArrayList<Value>(); for (int i = 0; i != cb_values.size(); ++i) { ArrayList<Value> pair = new ArrayList<Value>(); pair.add(Value.Integer(BigInteger.valueOf(i))); pair.add(convert(cb_values.get(i), elem)); pairs.add(Value.Tuple(pair)); } return Value.Set(pairs); } else if (c instanceof Constant.Map) { Constant.Map cb = (Constant.Map) c; ArrayList<Value> pairs = new ArrayList<Value>(); for (Map.Entry<Constant, Constant> e : cb.values.entrySet()) { ArrayList<Value> pair = new ArrayList<Value>(); pair.add(convert(e.getKey(), elem)); pair.add(convert(e.getValue(), elem)); pairs.add(Value.Tuple(pair)); } return Value.Set(pairs); } else if (c instanceof Constant.Set) { Constant.Set cb = (Constant.Set) c; ArrayList<Value> values = new ArrayList<Value>(); for (Constant v : cb.values) { values.add(convert(v, elem)); } return wycs.core.Value.Set(values); } else if (c instanceof Constant.Tuple) { Constant.Tuple cb = (Constant.Tuple) c; ArrayList<Value> values = new ArrayList<Value>(); for (Constant v : cb.values) { values.add(convert(v, elem)); } return wycs.core.Value.Tuple(values); } else { internalFailure("unknown constant encountered (" + c + ")", filename, elem); return null; } } private SyntacticType convert(List<Type> types, SyntacticElement elem) { SyntacticType[] ntypes = new SyntacticType[types.size()]; for(int i=0;i!=ntypes.length;++i) { ntypes[i] = convert(types.get(i),elem); } return new SyntacticType.Tuple(ntypes); } private SyntacticType convert(Type t, SyntacticElement elem) { // FIXME: this is fundamentally broken in the case of recursive types. // See Issue #298. if (t instanceof Type.Any) { return new SyntacticType.Primitive(SemanticType.Any); } else if (t instanceof Type.Void) { return new SyntacticType.Primitive(SemanticType.Void); } else if (t instanceof Type.Null) { // See Issue #316 return new SyntacticType.Primitive(SemanticType.Any); } else if (t instanceof Type.Bool) { return new SyntacticType.Primitive(SemanticType.Bool); } else if (t instanceof Type.Char) { return new SyntacticType.Primitive(SemanticType.Int); } else if (t instanceof Type.Byte) { return new SyntacticType.Primitive(SemanticType.Int); } else if (t instanceof Type.Int) { return new SyntacticType.Primitive(SemanticType.Int); } else if (t instanceof Type.Real) { return new SyntacticType.Primitive(SemanticType.Real); } else if (t instanceof Type.Strung) { return new SyntacticType.List(new SyntacticType.Primitive(SemanticType.Int)); } else if (t instanceof Type.Set) { Type.Set st = (Type.Set) t; SyntacticType element = convert(st.element(), elem); return new SyntacticType.Set(element); } else if (t instanceof Type.Map) { Type.Map lt = (Type.Map) t; SyntacticType from = convert(lt.key(), elem); SyntacticType to = convert(lt.value(), elem); // ugly. return new SyntacticType.Map(from,to); } else if (t instanceof Type.List) { Type.List lt = (Type.List) t; SyntacticType element = convert(lt.element(), elem); // ugly. return new SyntacticType.List(element); } else if (t instanceof Type.Tuple) { Type.Tuple tt = (Type.Tuple) t; SyntacticType[] elements = new SyntacticType[tt.size()]; for (int i = 0; i != tt.size(); ++i) { elements[i] = convert(tt.element(i), elem); } return new SyntacticType.Tuple(elements); } else if (t instanceof Type.Record) { Type.Record rt = (Type.Record) t; // return new SyntacticType.Set(new SyntacticType.Tuple( // new SyntacticType[] { // new SyntacticType.Primitive(SemanticType.String), // new SyntacticType.Primitive(SemanticType.Any) })); HashMap<String, Type> fields = rt.fields(); ArrayList<String> names = new ArrayList<String>(fields.keySet()); SyntacticType[] elements = new SyntacticType[names.size()]; Collections.sort(names); for (int i = 0; i != names.size(); ++i) { String field = names.get(i); elements[i] = convert(fields.get(field), elem); } return new SyntacticType.Tuple(elements); } else if (t instanceof Type.Reference) { // FIXME: how to translate this?? return new SyntacticType.Primitive(SemanticType.Any); } else if (t instanceof Type.Union) { Type.Union tu = (Type.Union) t; HashSet<Type> tu_elements = tu.bounds(); SyntacticType[] elements = new SyntacticType[tu_elements.size()]; int i = 0; for (Type te : tu_elements) { elements[i++] = convert(te, elem); } return new SyntacticType.Or(elements); } else if (t instanceof Type.Negation) { Type.Negation nt = (Type.Negation) t; SyntacticType element = convert(nt.element(), elem); return new SyntacticType.Not(element); } else if (t instanceof Type.FunctionOrMethod) { Type.FunctionOrMethod ft = (Type.FunctionOrMethod) t; return new SyntacticType.Primitive(SemanticType.Any); } else { internalFailure("unknown type encountered (" + t.getClass().getName() + ")", filename, elem); return null; } } private Expr and(List<Expr> constraints, CodeBlock.Entry entry) { if (constraints.size() == 0) { return Expr.Constant(Value.Bool(true), entry.attributes()); } else if (constraints.size() == 1) { return constraints.get(0); } else { return Expr.Nary(Expr.Nary.Op.AND, constraints, entry.attributes()); } } /** * Convert a wyil NameID into a string that is suitable to be used as a * function name or variable identifier in WycsFiles. * * @param id * @return */ private String toIdentifier(NameID id) { return id.toString().replace(":","_").replace("/","_"); } }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) public class BinaryTest { private String input; private int expectedOutput; @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"1", 1}, {"10", 2}, {"11", 3}, {"100", 4}, {"1001", 9}, {"11010", 26}, {"10001101000", 1128}, {"2", 0}, {"5", 0}, {"9", 0}, {"134678", 0}, {"abc10", 0}, {"10z", 0}, {"10a10", 0}, {"011", 3} }); } public BinaryTest(String input, int expectedOutput) { this.input = input; this.expectedOutput = expectedOutput; } @Test public void test() { Binary binary = new Binary(input); assertEquals(expectedOutput, binary.getDecimal()); } }
package com.monolith.api; import com.monolith.api.components.Transform; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Represents an object. GameObject serves only as container for functionality. * GameObject itself will not be displayed in final rendered content in any way. * <p/> * Functionality is added to GameObject using components. Components need to be * subclasses of {@link com.monolith.api.Component} class and they can be added * through GameObject's methods from scripts or in xml files defining initial scene layouts. * <p/> * GameObject can also be used to only hold children objects for manipulation. */ public class GameObject { private Application mApplication; private GameObject mParent; /** * Contains all GameObject's children. * <p/> * This list is unmodifiable, use appropriate GameObject instance * methods to remove children. * <p/> * Adding children to this GameObject can be done through passing this * object as parent into child GameObject's constructor or * calling {@link com.monolith.api.GameObject#setParent(GameObject)} * on the child GameObject. */ public final List<GameObject> children; private final List<GameObject> mChildren = new ArrayList<>(); /** * Contains all GameObject's components. * <p/> * This list is unmodifiable, use appropriate GameObject instance * methods to add or remove components. */ public final List<Component> components; private final List<Component> mComponents = new ArrayList<>(); // Mandatory GameObject's components // None of them can be removed so make sure it is checked in removeComponent(Component) method public final Transform transform; /** * Creates new GameObject. * <p/> * This constructor is meant for constructing top level GameObjects. * Creating top level object from scripts is currently not supported. * if you pass null as parent appropriate lifecycle methods will not be * called on this object. */ public GameObject(Application application, GameObject parent) { this.mApplication = application; this.mParent = parent; children = Collections.unmodifiableList(mChildren); components = Collections.unmodifiableList(mComponents); if (parent != null) { parent.mChildren.add(this); } transform = new Transform(); addComponent(transform); } /** * Creates new GameObject. Use this in your scripts. * * @param parent GameObject's parent. Can never be null. */ public GameObject(GameObject parent) { if (parent == null) { throw new IllegalStateException("This constructor cannot be used for objects without parent."); } this.mApplication = parent.mApplication; this.mParent = parent; children = Collections.unmodifiableList(mChildren); components = Collections.unmodifiableList(mComponents); parent.mChildren.add(this); transform = new Transform(); addComponent(transform); } /** * Returns GameObject's parent GameObject. * * @return Parent GameObject of this GameObject. */ public GameObject getParent() { return mParent; } /** * Sets new parent to this GameObject and also removes it from children of * previous parent. * * @param parent New parent GameObject. */ public void setParent(GameObject parent) { if (parent == null) { throw new IllegalStateException("GameObject's parent cannot be set to null."); } if (getParent() == null) { throw new IllegalStateException("Cannot change parent of top level object."); } getParent().mChildren.remove(this); parent.mChildren.add(this); mParent = parent; } /** * Removes childObject from children of this object * if childObject is a child of this GameObject. * <p/> * After removing, childObject is no longer valid GameObject * and cannot be used any further. Also no references to it should be * kept. * * @param childObject Child GameObject to remove. */ public void removeChild(GameObject childObject) { if (mChildren.contains(childObject)) { // Remove all components from this object for (int i = childObject.mComponents.size() - 1; i > 0; --i) { childObject.removeComponentInternal(childObject.mComponents.get(i)); } // Remove all child objects from removed object for (int i = childObject.mChildren.size() - 1; i > 0; --i) { childObject.removeChild(childObject.mChildren.get(i)); } mChildren.remove(childObject); } } /** * Adds new {@link com.monolith.api.Component} to this GameObject. * * @param component {@link com.monolith.api.Component} to add. */ public void addComponent(Component component) { if (!mComponents.contains(component)) { component.setup(mApplication, this); // Beware that game object's mandatory components need to stay at the beginning of the list mComponents.add(component); component.start(); } } /** * Used by engine. Allows removing of mandatory components. */ private void removeComponentInternal(Component component) { if (mComponents.contains(component)) { component.finish(); mComponents.remove(component); } } /** * Removes {@link com.monolith.api.Component} from this GameObject * if it is it's component. * * @param component {@link com.monolith.api.Component} to remove. */ public void removeComponent(Component component) { // Make sure none of the mandatory components is removed if (component == transform) { throw new IllegalStateException("Cannot remove GameObject's mandatory component."); } removeComponentInternal(component); } // TODO bring order to children and components lists so searching for them is in O(log(n)) /** * Returns the specific component of type T attached to this GameObject. * <p/> * In case there is more than one component of type T attached * to this GameObject the first that could be found is returned. * * @param componentClass Class of the requested component. * @param <T> Type of the component to be returned. * @return The instance of T attached to this GameObject as component * or null if no instance of T is attached to this GameObject. */ public <T extends Component> T getComponent(Class<T> componentClass) { for (int i = 0; i < mComponents.size(); ++i) { Component component = mComponents.get(i); if (componentClass.isInstance(component)) { return (T) component; } } return null; } /** * Returns the {@link java.util.List} of all components of type T * attached to this GameObject. * * @param componentsClass Class of the requested components. * @param <T> Type of the components to be returned. * @return List of the instances of T attached to this GameObject as components. */ public <T extends Component> List<T> getComponents(Class<T> componentsClass) { List<T> resultList = new ArrayList<>(); for (int i = 0; i < mComponents.size(); ++i) { Component component = mComponents.get(i); if (componentsClass.isInstance(component)) { resultList.add((T) component); } } return resultList; } }
package com.huettermann.all; import org.junit.Test; import static org.junit.Assert.assertEquals; public class TestMe { @Test public void aComplexComputation() { String a = "a"; String b = "a"; assertEquals(a, b); } @Test public void aTest() { Main main = new Main(); assertEquals( 42, main.getValue() ); } }
package com.sometrik.framework; import java.io.IOException; import java.io.InputStream; import com.sometrik.framework.NativeCommand.Selector; import android.content.res.AssetManager; import android.content.res.ColorStateList; import android.graphics.Bitmap.Config; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.RotateAnimation; import android.widget.Button; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class FWButton extends Button implements NativeCommandHandler { FrameWork frame; BitmapDrawable leftDraw; BitmapDrawable rightDraw; BitmapDrawable bottomDraw; BitmapDrawable topDraw; Animation animation = null; ViewStyleManager normalStyle, activeStyle, currentStyle; public FWButton(FrameWork frameWork) { super(frameWork); this.frame = frameWork; final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(scale, true); this.activeStyle = new ViewStyleManager(scale, false); final FWButton button = this; setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getElementId(), 1, 0); if (animation != null) button.startAnimation(animation); } } }); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { button.currentStyle = button.activeStyle; button.currentStyle.apply(button); } else if (event.getAction() == MotionEvent.ACTION_UP) { button.currentStyle = button.normalStyle; button.currentStyle.apply(button); } return false; } }); } @Override public void addChild(View view) { System.out.println("FWButton couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWButton couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWButton couldn't handle command"); } @Override public int getElementId() { return getId(); } @Override public void setViewEnabled(Boolean enabled) { setEnabled(enabled); } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } if (key.equals("font-size")){ if (value.equals("small")){ this.setTextSize(9); } else if (value.equals("medium")){ this.setTextSize(12); } else if (value.equals("large")){ this.setTextSize(15); } else { setTextSize(Integer.parseInt(value)); } } else if (key.equals("pressed")) { if (value.equals("true") || value.equals("1")) { this.setPressed(true); this.setTextColor(Color.RED); } else { this.setTextColor(Color.BLACK); this.setPressed(false); } } else if (key.equals("icon-left") || key.equals("icon-right") || key.equals("icon-top") || key.equals("icon-bottom")){ AssetManager mgr = frame.getAssets(); try { InputStream stream = mgr.open(value); BitmapDrawable draw = new BitmapDrawable(stream); this.setGravity(Gravity.CENTER); if (key.equals("icon-right")){ rightDraw = draw; } else if (key.equals("icon-top")){ topDraw = draw; } else if (key.equals("icon-bottom")){ bottomDraw = draw; } else if (key.equals("icon-left")){ leftDraw = draw; } this.setCompoundDrawablesWithIntrinsicBounds(leftDraw, topDraw, rightDraw, bottomDraw); } catch (IOException e) { System.out.println("no picture found: " + value); e.printStackTrace(); } } else if (key.equals("white-space")) { boolean single = false; if (value.equals("nowrap")) single = true; setSingleLine(single); } else if (key.equals("animation")) { if (value.equals("rotate")) { RotateAnimation r = new RotateAnimation(-5f, 5f,50,50); r.setDuration(100); r.setRepeatCount(10); r.setRepeatMode(RotateAnimation.REVERSE); animation = r; } } } @Override public void setError(boolean hasError, String errorText) { } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWButton couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("couldn't handle command"); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes, int width, int height, Config config) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } }
package org.openlca.app.db; import org.openlca.app.cloud.index.DiffIndex; import org.openlca.app.cloud.index.DiffType; import org.openlca.cloud.model.data.DatasetDescriptor; public class IndexUpdater { private boolean disabled; private boolean inTransaction; public void beginTransaction() { // no multitransaction support implemented if (inTransaction) throw new IllegalStateException("A transaction is already running"); inTransaction = true; } public void endTransaction() { if (!inTransaction) throw new IllegalStateException("No transaction running"); DiffIndex index = getIndex(); if (index != null) index.commit(); inTransaction = false; } public void disable() { disabled = true; } public void enable() { disabled = false; } public void insert(DatasetDescriptor descriptor) { DiffIndex index = getIndex(); if (index == null) return; insert(descriptor, index); if (inTransaction) return; index.commit(); } private void insert(DatasetDescriptor descriptor, DiffIndex index) { index.add(descriptor); index.update(descriptor, DiffType.NEW); } public void update(DatasetDescriptor descriptor) { DiffIndex index = getIndex(); if (index == null) return; update(descriptor, index); if (inTransaction) return; index.commit(); } private void update(DatasetDescriptor descriptor, DiffIndex index) { DiffType previousType = index.get(descriptor.getRefId()).type; if (previousType != DiffType.NEW) index.update(descriptor, DiffType.CHANGED); } public void delete(DatasetDescriptor descriptor) { DiffIndex index = getIndex(); if (index == null) return; delete(descriptor, index); if (inTransaction) return; index.commit(); } private void delete(DatasetDescriptor descriptor, DiffIndex index) { index.update(descriptor, DiffType.DELETED); } private DiffIndex getIndex() { if (disabled) return null; DiffIndex index = Database.getDiffIndex(); return index; } }
package com.bei.newweather; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.preference.PreferenceManager; import android.text.format.Time; import com.bei.newweather.sync.SunshineSyncAdapter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class Utility { public static String getPreferredLocation(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getString(context.getString(R.string.pref_location_key), context.getString(R.string.pref_location_default)); } public static boolean isMetric(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); return prefs.getString(context.getString(R.string.pref_units_key), context.getString(R.string.pref_units_metric)) .equals(context.getString(R.string.pref_units_metric)); } public static String formatTemperature(Context context, double temperature) { // Data stored in Celsius by default. If user prefers to see in Fahrenheit, convert // the values here. String suffix = "\u00B0"; if (!isMetric(context)) { temperature = (temperature * 1.8) + 32; } // For presentation, assume the user doesn't care about tenths of a degree. return String.format(context.getString(R.string.format_temperature), temperature); } static String formatDate(long dateInMilliseconds) { Date date = new Date(dateInMilliseconds); return DateFormat.getDateInstance().format(date); } // Format used for storing dates in the database. ALso used for converting those strings // back into date objects for comparison/processing. public static final String DATE_FORMAT = "yyyyMMdd"; /** * Helper method to convert the database representation of the date into something to display * to users. As classy and polished a user experience as "20140102" is, we can do better. * * @param context Context to use for resource localization * @param dateInMillis The date in milliseconds * @return a user-friendly representation of the date. */ public static String getFriendlyDayString(Context context, long dateInMillis) { // The day string for forecast uses the following logic: // For today: "Today, June 8" // For tomorrow: "Tomorrow" // For the next 5 days: "Wednesday" (just the day name) // For all days after that: "Mon Jun 8" Time time = new Time(); time.setToNow(); long currentTime = System.currentTimeMillis(); int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff); int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff); // If the date we're building the String for is today's date, the format // is "Today, June 24" if (julianDay == currentJulianDay) { String today = context.getString(R.string.today); int formatId = R.string.format_full_friendly_date; return context.getString( formatId, today, getFormattedMonthDay(context, dateInMillis)); } else if ( julianDay < currentJulianDay + 7 ) { // If the input date is less than a week in the future, just return the day name. return getDayName(context, dateInMillis); } else { // Otherwise, use the form "Mon Jun 3" SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(dateInMillis); } } /** * Given a day, returns just the name to use for that day. * E.g "today", "tomorrow", "wednesday". * * @param context Context to use for resource localization * @param dateInMillis The date in milliseconds * @return */ public static String getDayName(Context context, long dateInMillis) { // If the date is today, return the localized version of "Today" instead of the actual // day name. Time t = new Time(); t.setToNow(); int julianDay = Time.getJulianDay(dateInMillis, t.gmtoff); int currentJulianDay = Time.getJulianDay(System.currentTimeMillis(), t.gmtoff); if (julianDay == currentJulianDay) { return context.getString(R.string.today); } else if ( julianDay == currentJulianDay +1 ) { return context.getString(R.string.tomorrow); } else { Time time = new Time(); time.setToNow(); // Otherwise, the format is just the day of the week (e.g "Wednesday". SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE"); return dayFormat.format(dateInMillis); } } /** * Converts db date format to the format "Month day", e.g "June 24". * @param context Context to use for resource localization * @param dateInMillis The db formatted date string, expected to be of the form specified * in Utility.DATE_FORMAT * @return The day in the form of a string formatted "December 6" */ public static String getFormattedMonthDay(Context context, long dateInMillis ) { Time time = new Time(); time.setToNow(); SimpleDateFormat dbDateFormat = new SimpleDateFormat(Utility.DATE_FORMAT); SimpleDateFormat monthDayFormat = new SimpleDateFormat("MMMM dd"); String monthDayString = monthDayFormat.format(dateInMillis); return monthDayString; } public static String getFormattedWind(Context context, float windSpeed, float degrees) { int windFormat; if (Utility.isMetric(context)) { windFormat = R.string.format_wind_kmh; } else { windFormat = R.string.format_wind_mph; windSpeed = .621371192237334f * windSpeed; } // From wind direction in degrees, determine compass direction as a string (e.g NW) // You know what's fun, writing really long if/else statements with tons of possible // conditions. Seriously, try it! String direction = "Unknown"; if (degrees >= 337.5 || degrees < 22.5) { direction = "N"; } else if (degrees >= 22.5 && degrees < 67.5) { direction = "NE"; } else if (degrees >= 67.5 && degrees < 112.5) { direction = "E"; } else if (degrees >= 112.5 && degrees < 157.5) { direction = "SE"; } else if (degrees >= 157.5 && degrees < 202.5) { direction = "S"; } else if (degrees >= 202.5 && degrees < 247.5) { direction = "SW"; } else if (degrees >= 247.5 && degrees < 292.5) { direction = "W"; } else if (degrees >= 292.5 && degrees < 337.5) { direction = "NW"; } return String.format(context.getString(windFormat), windSpeed, direction); } /** * Helper method to provide the icon resource id according to the weather condition id returned * by the OpenWeatherMap call. * @param weatherId from OpenWeatherMap API response * @return resource id for the corresponding icon. -1 if no relation is found. */ public static int getIconResourceForWeatherCondition(int weatherId) { // Based on weather code data found at: if (weatherId >= 200 && weatherId <= 232) { return R.drawable.ic_storm; } else if (weatherId >= 300 && weatherId <= 321) { return R.drawable.ic_light_rain; } else if (weatherId >= 500 && weatherId <= 504) { return R.drawable.ic_rain; } else if (weatherId == 511) { return R.drawable.ic_snow; } else if (weatherId >= 520 && weatherId <= 531) { return R.drawable.ic_rain; } else if (weatherId >= 600 && weatherId <= 622) { return R.drawable.ic_snow; } else if (weatherId >= 701 && weatherId <= 761) { return R.drawable.ic_fog; } else if (weatherId == 761 || weatherId == 781) { return R.drawable.ic_storm; } else if (weatherId == 800) { return R.drawable.ic_clear; } else if (weatherId == 801) { return R.drawable.ic_light_clouds; } else if (weatherId >= 802 && weatherId <= 804) { return R.drawable.ic_cloudy; } return -1; } /** * Helper method to provide the art urls according to the weather condition id returned * by the OpenWeatherMap call. * * @param context Context to use for retrieving the URL format * @param weatherId from OpenWeatherMap API response * @return url for the corresponding weather artwork. null if no relation is found. */ public static String getArtUrlForWeatherCondition(Context context, int weatherId) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String formatArtUrl = prefs.getString(context.getString(R.string.pref_art_pack_key), context.getString(R.string.pref_art_pack_sunshine)); // Based on weather code data found at: if (weatherId >= 200 && weatherId <= 232) { return String.format(Locale.US, formatArtUrl, "storm"); } else if (weatherId >= 300 && weatherId <= 321) { return String.format(Locale.US, formatArtUrl, "light_rain"); } else if (weatherId >= 500 && weatherId <= 504) { return String.format(Locale.US, formatArtUrl, "rain"); } else if (weatherId == 511) { return String.format(Locale.US, formatArtUrl, "snow"); } else if (weatherId >= 520 && weatherId <= 531) { return String.format(Locale.US, formatArtUrl, "rain"); } else if (weatherId >= 600 && weatherId <= 622) { return String.format(Locale.US, formatArtUrl, "snow"); } else if (weatherId >= 701 && weatherId <= 761) { return String.format(Locale.US, formatArtUrl, "fog"); } else if (weatherId == 761 || weatherId == 781) { return String.format(Locale.US, formatArtUrl, "storm"); } else if (weatherId == 800) { return String.format(Locale.US, formatArtUrl, "clear"); } else if (weatherId == 801) { return String.format(Locale.US, formatArtUrl, "light_clouds"); } else if (weatherId >= 802 && weatherId <= 804) { return String.format(Locale.US, formatArtUrl, "clouds"); } return null; } /** * Helper method to provide the art resource id according to the weather condition id returned * by the OpenWeatherMap call. * @param weatherId from OpenWeatherMap API response * @return resource id for the corresponding icon. -1 if no relation is found. */ public static int getArtResourceForWeatherCondition(int weatherId) { // Based on weather code data found at: if (weatherId >= 200 && weatherId <= 232) { return R.drawable.art_storm; } else if (weatherId >= 300 && weatherId <= 321) { return R.drawable.art_light_rain; } else if (weatherId >= 500 && weatherId <= 504) { return R.drawable.art_rain; } else if (weatherId == 511) { return R.drawable.art_snow; } else if (weatherId >= 520 && weatherId <= 531) { return R.drawable.art_rain; } else if (weatherId >= 600 && weatherId <= 622) { return R.drawable.art_snow; } else if (weatherId >= 701 && weatherId <= 761) { return R.drawable.art_fog; } else if (weatherId == 761 || weatherId == 781) { return R.drawable.art_storm; } else if (weatherId == 800) { return R.drawable.art_clear; } else if (weatherId == 801) { return R.drawable.art_light_clouds; } else if (weatherId >= 802 && weatherId <= 804) { return R.drawable.art_clouds; } return -1; } /** * Helper method to provide the string according to the weather * condition id returned by the OpenWeatherMap call. * @param context Android context * @param weatherId from OpenWeatherMap API response * @return string for the weather condition. null if no relation is found. */ public static String getStringForWeatherCondition(Context context, int weatherId) { // Based on weather code data found at: int stringId; if (weatherId >= 200 && weatherId <= 232) { stringId = R.string.condition_2xx; } else if (weatherId >= 300 && weatherId <= 321) { stringId = R.string.condition_3xx; } else switch(weatherId) { case 500: stringId = R.string.condition_500; break; case 501: stringId = R.string.condition_501; break; case 502: stringId = R.string.condition_502; break; case 503: stringId = R.string.condition_503; break; case 504: stringId = R.string.condition_504; break; case 511: stringId = R.string.condition_511; break; case 520: stringId = R.string.condition_520; break; case 531: stringId = R.string.condition_531; break; case 600: stringId = R.string.condition_600; break; case 601: stringId = R.string.condition_601; break; case 602: stringId = R.string.condition_602; break; case 611: stringId = R.string.condition_611; break; case 612: stringId = R.string.condition_612; break; case 615: stringId = R.string.condition_615; break; case 616: stringId = R.string.condition_616; break; case 620: stringId = R.string.condition_620; break; case 621: stringId = R.string.condition_621; break; case 622: stringId = R.string.condition_622; break; case 701: stringId = R.string.condition_701; break; case 711: stringId = R.string.condition_711; break; case 721: stringId = R.string.condition_721; break; case 731: stringId = R.string.condition_731; break; case 741: stringId = R.string.condition_741; break; case 751: stringId = R.string.condition_751; break; case 761: stringId = R.string.condition_761; break; case 762: stringId = R.string.condition_762; break; case 771: stringId = R.string.condition_771; break; case 781: stringId = R.string.condition_781; break; case 800: stringId = R.string.condition_800; break; case 801: stringId = R.string.condition_801; break; case 802: stringId = R.string.condition_802; break; case 803: stringId = R.string.condition_803; break; case 804: stringId = R.string.condition_804; break; case 900: stringId = R.string.condition_900; break; case 901: stringId = R.string.condition_901; break; case 902: stringId = R.string.condition_902; break; case 903: stringId = R.string.condition_903; break; case 904: stringId = R.string.condition_904; break; case 905: stringId = R.string.condition_905; break; case 906: stringId = R.string.condition_906; break; case 951: stringId = R.string.condition_951; break; case 952: stringId = R.string.condition_952; break; case 953: stringId = R.string.condition_953; break; case 954: stringId = R.string.condition_954; break; case 955: stringId = R.string.condition_955; break; case 956: stringId = R.string.condition_956; break; case 957: stringId = R.string.condition_957; break; case 958: stringId = R.string.condition_958; break; case 959: stringId = R.string.condition_959; break; case 960: stringId = R.string.condition_960; break; case 961: stringId = R.string.condition_961; break; case 962: stringId = R.string.condition_962; break; default: return context.getString(R.string.condition_unknown, weatherId); } return context.getString(stringId); } /** * Returns true if the network is available or about to become available. * * @param c Context used to get the ConnectivityManager * @return true if the network is available */ static public boolean isNetworkAvailable(Context c) { ConnectivityManager cm = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } /** * * @param c Context used to get the SharedPreferences * @return the location status integer type */ @SuppressWarnings("ResourceType") static public @SunshineSyncAdapter.LocationStatus int getLocationStatus(Context c){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c); return sp.getInt(c.getString(R.string.pref_location_status_key), SunshineSyncAdapter.LOCATION_STATUS_UNKNOWN); } /** * Resets the location status. (Sets it to SunshineSyncAdapter.LOCATION_STATUS_UNKNOWN) * @param c Context used to get the SharedPreferences */ static public void resetLocationStatus(Context c){ SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(c); SharedPreferences.Editor spe = sp.edit(); spe.putInt(c.getString(R.string.pref_location_status_key), SunshineSyncAdapter.LOCATION_STATUS_UNKNOWN); spe.apply(); } }
package com.wsfmn.habit; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; import com.wsfmn.habittracker.R; import android.graphics.Bitmap; import android.widget.EditText; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; public class HabitEvent{ /** * Variables For the Habit Event that the user will enter or be created * when a user creates a new Habit Event */ private String title; private Habit habit; private String comment; String id; String date; //Path of the file Where image is stored String mCurrentPhotoPath; //private Bitmap image; //private Date date; //change by wei, change location parts //private Geolocation location; //Need to Add Location /** * Constructor for the Habit Event * @param habit * @param title * @param comment * @param mCurrentPhotoPath * @param date * @throws HabitCommentTooLongException */ public HabitEvent(Habit habit, String title, String comment, String mCurrentPhotoPath, String date) throws HabitCommentTooLongException { this.habit = habit; this.title = title; this.comment =comment; this.mCurrentPhotoPath = mCurrentPhotoPath; this.id = null; this.date = date; } // public HabitEvent(Habit habit, EditText nameHabitEvent, EditText comment, Bitmap image){ // this.habit = habit; // this.image = image; // this.comment = "No Comment"; // this.title = "title"; public String getDate(){ return this.date; } /** * Get the path of the file where image is stored for the habit Event * @return mCurrentPhotoPath: filename of the image */ public String getmCurrentPhotoPath(){ return mCurrentPhotoPath; } /** * Get the Habit the user selects for the HabitEvent * @return Habit */ public Habit getHabitFromEvent(){ return habit; } /** * Get the Habit title for the Habit Event * @return habit Title */ public String getHabitTitle(){ return this.habit.getTitle(); } * /*Changes the Habit for the HabitEvent * @param habit */ public void setHabit(Habit habit){ this.habit = habit; } /** * Get Id for ElasticSearch * @return Id */ public String getId() {return id;} /** * Set Id for ElasticSearch * @param id */ public void setId(String id) { this.id = id; } /*Get the Habit for the HabitEvent*/ public Habit getHabit() { return habit; } /*Get the Title of the Habit Event*/ public String getHabitEventTitle() throws HabitEventNameException{ /*Checks the title length of the HabitEvent*/ if(title.length() > 20 || title.length()<1){ /*Throws Exception if violates the condition*/ throw new HabitEventNameException(); } return title; } /*Change Title of the HabitEvent*/ public String setTitle(String title)throws HabitEventNameException{ /*Checks the length of the title*/ if(title.length() > 20 || title.length()<1){ /*Throws this exception*/ throw new HabitEventNameException(); } return this.title = title; } /*Get the comment for HabitEvent that user created*/ public String getComment() throws HabitEventCommentTooLongException { /*If comment larger than 20 characters return and Error*/ if(comment.length() > 20){ /*Throw HabitEventCommentTooLongException*/ throw new HabitEventCommentTooLongException(); } return comment; } /*Changing the Comment of Habit Event*/ public void setComment(String comment) throws HabitEventCommentTooLongException { /*Checking if comment size does not exceed 20 characters*/ if(comment.length() > 20){ /* Throw HabitEventCommentTooLongException*/ throw new HabitEventCommentTooLongException(); } this.comment = comment; } // public Bitmap getImage(){return image;} // public void setImage(Bitmap bit) { // this.image = bit; // public void setLocation(Geolocation location){ // this.location = location; // public Geolocation getLocation() {return this.location;} // public void location(){this.location = 5;} /*Displays This when the List is called*/ @Override public String toString(){ return title + " " + date; } }
package sauer.thatgameimade; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MyView extends View { private static final int SPRITE_SIZE = 8; private static final String TAG = MyView.class.getSimpleName(); public static final float SCALE = 1f; private final Paint paint; private float touchX; private float touchY; private float touchMajor; private Bitmap cakeBitmap; private AdvancedBitmap spriteBitmap; private Bitmap foursquareBitmap; { paint = new Paint(); paint.setColor(Color.RED); cakeBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cake_half_alt); foursquareBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.foursquare); foursquareBitmap = Bitmap.createScaledBitmap(foursquareBitmap, foursquareBitmap.getWidth() * 50, foursquareBitmap.getHeight() * 50, true); } private int canvasWidth; private int canvasHeight; private int halfway; private int blockSize; private Matrix drawMatrix = new Matrix(); public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onSizeChanged(int weight, int height, int oldWidth, int oldHeight) { canvasWidth = weight; canvasHeight = height; halfway = Math.min(canvasWidth, canvasHeight) / 2; blockSize = halfway / SPRITE_SIZE; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // paint background paint.setColor(Color.rgb(200, 250, 200)); canvas.drawRect(0, 0, canvasWidth, canvasHeight, paint); // paint pretty pattern paint.setColor(Color.rgb(255, 0, 0)); for (int i = 0; i <= halfway; i += halfway / 50) { canvas.drawLine(i, halfway, halfway, halfway - i, paint); canvas.drawLine(i, halfway, halfway, halfway + i, paint); canvas.drawLine(halfway * 2 - i, halfway, halfway, halfway - i, paint); canvas.drawLine(halfway * 2 - i, halfway, halfway, halfway + i, paint); } // paint sprite grid for (int x = 0; x < SPRITE_SIZE; x++) { for (int y = 0; y < SPRITE_SIZE; y++) { int x1 = x * blockSize; int y1 = y * blockSize; int x2 = x1 + blockSize - 3; int y2 = y1 + blockSize - 3; if (touchX >= x1 && touchX <= x2 && touchY >= y1 && touchY <= y2) { paint.setColor(Color.rgb(220, 255, 220)); } else { paint.setColor(Color.rgb(255 * x / SPRITE_SIZE, 255 * y / SPRITE_SIZE, 255 - 255 * x / SPRITE_SIZE * y / SPRITE_SIZE)); } canvas.drawRect(x1, y1, x2, y2, paint); } } // paint test foursquare { drawMatrix.reset(); float ratio = halfway / foursquareBitmap.getWidth(); drawMatrix.postScale(ratio, ratio); drawMatrix.postTranslate(0, halfway); canvas.drawBitmap(foursquareBitmap, drawMatrix, paint); } if (isInEditMode()) { return; } Bitmap bitmap = spriteBitmap.getCurrentBitmap(); // paint bitmaps paint.setColor(Color.rgb(255, 255, 100)); float ratio = SCALE * cakeBitmap.getWidth() / bitmap.getWidth(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { drawMatrix.reset(); drawMatrix.postScale(SCALE, SCALE); drawMatrix.postTranslate(halfway + i * SCALE * cakeBitmap.getWidth(), j * SCALE * cakeBitmap.getHeight()); canvas.drawBitmap(cakeBitmap, drawMatrix, paint); drawMatrix.reset(); drawMatrix.postScale(ratio, ratio); drawMatrix.postTranslate(halfway + i * ratio * bitmap.getWidth(), halfway + j * ratio * bitmap.getHeight()); canvas.drawBitmap(bitmap, drawMatrix, paint); } } // paint sprite when touched if (touchX >= SPRITE_SIZE * blockSize || touchY >= SPRITE_SIZE * blockSize) { drawMatrix.reset(); drawMatrix.postTranslate(-bitmap.getWidth() / 2, -bitmap.getHeight() / 2); drawMatrix.postScale(50, 50); drawMatrix.postTranslate(touchX, touchY); canvas.drawBitmap(bitmap, drawMatrix, paint); } // paint dot when touched if (touchMajor > 0) { paint.setColor(Color.rgb(200, 255, 0)); canvas.drawCircle(touchX, touchY, touchMajor / 2, paint); } } @Override public boolean onTouchEvent(@NonNull MotionEvent event) { float x = event.getX(); float y = event.getY(); float touchMajor = event.getTouchMajor(); placeDot(x, y, touchMajor); return true; } public void placeDot(float x, float y, float touchMajor) { this.touchX = x; this.touchY = y; this.touchMajor = touchMajor; invalidate(); } public void setAdvancedBitmap(AdvancedBitmap spriteBitmap) { this.spriteBitmap = spriteBitmap; } }
package space.aauthor.thyme; import android.app.AlarmManager; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.SystemClock; public class Thymer { private Context context; private int delay = 30 * 60 * 1000; // thirty minutes private AlarmManager alarmManager; private Notification notification; private Intent notificationIntent; Thymer(Context context) { this.context = context; alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); notification = createNotification(); notificationIntent = new Intent(context, NotificationPublisher.class) .putExtra(NotificationPublisher.NOTIFICATION_ID, 1) .putExtra(NotificationPublisher.NOTIFICATION, notification); } public boolean isEnabled(){ PendingIntent notifyUserAfterTime = PendingIntent.getBroadcast( context, 0, notificationIntent, PendingIntent.FLAG_NO_CREATE); return notifyUserAfterTime != null; } public void toggle() { if(isEnabled()){ disable(); } else { enable(); } } public void enable() { PendingIntent notifyUserAfterTime = PendingIntent.getBroadcast( context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); long futureInMillis = SystemClock.elapsedRealtime() + delay; alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, delay, notifyUserAfterTime); } public void disable() { PendingIntent notifyUserAfterTime = PendingIntent.getBroadcast( context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.cancel(notifyUserAfterTime); notifyUserAfterTime.cancel(); } private Notification createNotification() { long[] vibrationPattern = { 0, 100, 100, 100, 100, 100 }; Notification.Builder builder = new Notification.Builder(context); builder.setContentTitle("Thyme"); builder.setContentText("Time has passed."); builder.setSmallIcon(R.drawable.ic_stat_notification); builder.setVibrate(vibrationPattern); return builder.build(); } }
package org.xbill.DNS.utils; import java.io.*; import java.math.BigInteger; /** * An extension of ByteArrayInputStream to support directly reading types * used by DNS routines. * @see DataByteOutputStream * * @author Brian Wellington */ public class DataByteInputStream extends ByteArrayInputStream { /** * Creates a new DataByteInputStream * @param b The byte array to read from */ public DataByteInputStream(byte [] b) { super(b); } /** * Read data from the stream. * @param b The array to read into * @return The number of bytes read */ public int read(byte b[]) throws IOException { return read(b, 0, b.length); } /** * Read a byte from the stream * @return The byte */ public byte readByte() throws IOException { int i = read(); if (i == -1) throw new IOException("no bytes left to read"); return (byte) i; } /** * Read an unsigned byte from the stream * @return The unsigned byte as an int */ public int readUnsignedByte() throws IOException { int i = read(); if (i == -1) throw new IOException("no bytes left to read"); return i; } /** * Read a short from the stream * @return The short */ public short readShort() throws IOException { int c1 = read(); int c2 = read(); if (c1 == -1 || c2 == -1) throw new IOException("no bytes left to read"); return (short)((c1 << 8) + c2); } /** * Read an unsigned short from the stream * @return The unsigned short as an int */ public int readUnsignedShort() throws IOException { int c1 = read(); int c2 = read(); if (c1 == -1 || c2 == -1) throw new IOException("no bytes left to read"); return ((c1 << 8) + c2); } /** * Read an int from the stream * @return The int */ public int readInt() throws IOException { int c1 = read(); int c2 = read(); int c3 = read(); int c4 = read(); if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1) throw new IOException("no bytes left to read"); return ((c1 << 24) + (c2 << 16) + (c3 << 8) + c4); } /** * Read a long from the stream * @return The long */ public long readLong() throws IOException { int c1 = read(); int c2 = read(); int c3 = read(); int c4 = read(); int c5 = read(); int c6 = read(); int c7 = read(); int c8 = read(); if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1 || c5 == -1 || c6 == -1 || c7 == -1 || c8 == -1) throw new IOException("no bytes left to read"); return ((c1 << 56) + (c2 << 48) + (c3 << 40) + (c4 << 32) + (c5 << 24) + (c6 << 16) + (c7 << 8) + c8); } /** * Read a String from the stream, represented as a length byte followed by data * @return The String */ public String readString() throws IOException { int len = read(); if (len == -1) throw new IOException("no bytes left to read"); byte [] b = new byte[len]; read(b); return new String(b); } /** * Read a BigInteger from the stream, encoded as binary data. A 0 byte is * prepended so that the value is always positive. * @param len The number of bytes to read * @return The BigInteger */ public BigInteger readBigInteger(int len) throws IOException { byte [] b = new byte[len + 1]; read(b, 1, len); return new BigInteger(b); } /** * Read and ignore bytes from the stream * @param n The number of bytes to skip */ public void skipBytes(int n) throws IOException { skip(n); } /** * Get the current position in the stream * @return The current position */ public int getPos() { return pos; } }
package cf.commonpoint; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cf.commonpoint.cputility.XMLParser; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * * @author Sanjeet Singh R */ public class CPFilter { private static void redirect(String indicator,HttpServletRequest request,HttpServletResponse response) throws IOException, ParserConfigurationException, SAXException { switch(indicator) { case "https": String serverName=request.getServerName(); String requestURI=request.getRequestURI(); response.sendRedirect("https://"+serverName+requestURI); case "login": String uri="C:\\Security-Framework\\SecurityFramework\\src\\cf\\commonpoint\\config\\cpconfig.xml"; String node="login-page"; String redirectURI=XMLParser.getNodeValue(uri, node); response.sendRedirect(redirectURI); } } }
package E1; import java.util.Scanner; public class App { private static Scanner llagir; public static void main(String[] args) { int nombre1, nombre2, patit, gran; System.out.println ("Escriu 5 numeros"); llagir = new Scanner(System.in); nombre1 = llagir.nextInt(); patit = nombre1; gran = nombre1; for (int i=1; i<10; i++){ nombre2 = llagir.nextInt(); if (patit>nombre2){ patit = nombre2; } if (gran<nombre2) { gran = nombre2; } } System.out.println ("El numero mes patit es: " + patit); System.out.println ("El numero mes gran es: " + gran); } }
package com.domeke.app.model; import java.util.List; import com.domeke.app.tablebind.TableBind; import com.domeke.app.utils.EncryptKit; import com.domeke.app.utils.HtmlTagKit; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Model; import com.jfinal.plugin.activerecord.Record; /** * @author Administrator CREATE TABLE IF NOT EXISTS `domeke`.`user` ( `userid` BIGINT(20) NOT NULL AUTO_INCREMENT, `username` VARCHAR(16) NOT NULL, `nickname` VARCHAR(64) NULL, `password` VARCHAR(32) NOT NULL, `email` VARCHAR(255) NULL, `mobile` VARCHAR(32) NULL, `create_time` TIMESTAMP NULL , `creater` BIGINT(20) NULL, `modifier` BIGINT(20) NULL, `modify_time` TIMESTAMP NULL , PRIMARY KEY (`userid`), UNIQUE INDEX `username_idx` (`username` ASC), UNIQUE INDEX `email` (`email` ASC)); */ @TableBind(tableName = "user", pkName = "userid") public class User extends Model<User> { private static final long serialVersionUID = 1L; public static User dao = new User(); public User login(String username) { String sql = "select password from user where username=? "; return dao.findFirst(sql, username); } public void saveUser() { HtmlTagKit.processHtmlSpecialTag(this, "username", "email", "mobile"); String pasword = EncryptKit.encryptMd5(this.getStr("password")); this.set("password", pasword); this.save(); } public void updateUser() { HtmlTagKit.processHtmlSpecialTag(this, "email", "mobile"); this.update(); } public void updatePassword() { this.update(); } public boolean containColumn(String column, String paras) { String sql = " select 1 from user where " + column + "= ? limit 1 "; User user = dao.findFirst(sql, paras); return user != null; } public User findUserIdByUsername(String username) { String sql = "select userid from user where username = ? "; User user = dao.findFirst(sql, username); return user; } public User findUserByUsername(String username) { String sql = "select userid,username,nickname,email,mobile,activation from user where username = ? "; User user = dao.findFirst(sql, username); return user; } public List<Record> getUserRoleByUsername(String username) { List<Record> recordList = Db.find("select roleid,rolename from role r,user u,user_role ur " + "where u.userid=ur.userid and ur.roleid = r.roleid and u.username = ?", username); return recordList; } public List<Record> getUserPermissionsByUsername(String username) { return null; } public List<User> getUser(){ String sql = "select * from user"; List<User> list = dao.find(sql); return list; } public void updateReset(int userid,String pass){ String sql="update user set password='"+pass+"' where userid='"+userid+"'"; Db.update(sql); } public void updateUserMsg(String userid,String clom,String param){ String sql="update user set "+clom+"='"+param+"' where userid='"+userid+"'"; Db.update(sql); } public User getCloumValue(String cloum,String param){ String sql = "select * from user where "+cloum+" = '"+param+"'"; User user = dao.findFirst(sql); return user; } public void updatePassword(Long userid,String pass){ String sql="update user set password='"+pass+"' where userid='"+userid+"'"; Db.update(sql); } }