lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
lgpl-2.1
06096466c0223f95b76e72ffb93b19934333ecb1
0
cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl,cytoscape/cytoscape-impl
package org.cytoscape.search.internal.index; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Set; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.NetworkTestSupport; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.search.internal.LogSilenceRule; import org.cytoscape.search.internal.search.NetworkSearchTask; import org.cytoscape.search.internal.search.SearchResults; import org.cytoscape.search.internal.search.SearchResults.Status; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.work.TaskMonitor; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; public class QueryTest { @Rule public TestRule logSilenceRule = new LogSilenceRule(); private static final String TEST_ID = "TestID"; private static final String NODE_COMMON = "namespace::COMMON"; private static final String NODE_DEGREE_LAYOUT = "degree.layout"; private static final String NODE_GAL_FILTERED_GAL1R_GEXP = "gal1RGexp"; private static final String NODE_DUMMY_TEXT = "dummyText"; private static final String EDGE_EDGEBETWEENNESS = "EdgeBetweenness"; private CyNetwork network; private SearchManager searchManager; public static CyNetwork createTestNetwork() { NetworkTestSupport networkTestSupport = new NetworkTestSupport(); CyNetwork network = networkTestSupport.getNetwork(); CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); nodeTable.createColumn(TEST_ID, Integer.class, false); // We can't chose the SUID value so use this instead nodeTable.createColumn(NODE_COMMON, String.class, false); nodeTable.createColumn(NODE_DEGREE_LAYOUT, Integer.class, false); nodeTable.createColumn(NODE_GAL_FILTERED_GAL1R_GEXP, Double.class, false); // Use a namespace nodeTable.createColumn(NODE_DUMMY_TEXT, String.class, false); // Use a namespace CyTable edgeTable = network.getTable(CyEdge.class, CyNetwork.DEFAULT_ATTRS); edgeTable.createColumn(TEST_ID, Integer.class, false); // We can't chose the SUID value so use this instead edgeTable.createColumn(EDGE_EDGEBETWEENNESS, Double.class, false); addNode(network, 1, "YIL015W", "BAR1", 2, -0.622, "Far far away, behind the word mountains, far from the countries"); addNode(network, 2, "YJL159W", "HSP150", 2, -0.357, "Vokalia and Consonantia, there live the blind texts. Separated they"); addNode(network, 3, "YKR097W", "PCK1", 2, 1.289, "live in Bookmarksgrove right at the coast of the Semantics, a large"); addNode(network, 4, "YPR119W", "CLB2", 2, -0.234, "language ocean. A small river named Duden flows by their place and"); addNode(network, 5, "YGR108W", "CLB1", 3, -0.25, "supplies it with the necessary regelialia. It is a paradisematic"); addNode(network, 6, "YAL040C", "CLN3", 2, -0.027, "country, in which roasted parts of sentences fly into your mouth."); addNode(network, 7, "YGL008C", "PMA1", 2, -0.352, "Even the all-powerful Pointing has no control about the blind texts it"); addNode(network, 8, "YDR461W", "MFA1", 3, -0.659, "is an almost unorthographic life One day however a small line of"); addNode(network, 9, "YNL145W", "MFA2", 3, -0.764, "blind text by the name of Lorem Ipsum decided to leave for the far"); addNode(network, 10, "YJL157C", "FAR1", 4, -0.158, "World of Grammar. The Big Oxmox advised her not to do so, because"); addNode(network, 11, "YFL026W", "STE2", 3, -0.653, "there were thousands of bad Commas, wild Question Marks and"); addNode(network, 12, "YJL194W", "CDC6", 2, 0.018, "devious Semikoli, but the Little Blind Text didn’t listen. She packed"); addNode(network, 13, "YCR084C", "TUP1", 2, 0.044, "her seven versalia, put her initial into the belt and made herself on"); addNode(network, 14, "YHR084W", "STE12", 4, -0.109, "the way. When she reached the first hills of the Italic Mountains, she"); addNode(network, 15, "YBR112C", "SSN6", 1, 0.108, "had a last view back on the skyline of her hometown"); addNode(network, 16, "YCL067C", null, 6, 0.169, "Bookmarksgrove, the headline of Alphabet Village and the subline of"); addNode(network, 17, "YER111C", "SWI4", 2, 0.195, "her own road, the Line Lane. Pityful a rethoric question ran over her"); addNode(network, 18, "YDR146C", "SWI5", 2, -0.19, "cheek, then she continued her way. On her way she met a copy. The"); addNode(network, 19, "YPR113W", "PIS1", 1, -0.495, "copy warned the Little Blind Text, that where it came from it would"); addNode(network, 20, "YMR043W", "MCM1", 99, -0.183, "have been rewritten a thousand times and everything that was left"); addNode(network, 21, "YBR160W", "CDC28", 3, -0.016, "from its origin would be the word \"and\" and the Little Blind Text"); addEdge(network, 1, "YNL145W", "YHR084W", "pd", 4.83333333); addEdge(network, 2, "YJL157C", "YAL040C", "pp", 115.0); addEdge(network, 3, "YER111C", "YMR043W", "pd", 2361.73260073); addEdge(network, 4, "YBR160W", "YMR043W", "pd", 940.0); addEdge(network, 5, "YBR160W", "YGR108W", "pp", 48.0); addEdge(network, 6, "YDR146C", "YMR043W", "pd", 19179.59362859); addEdge(network, 7, "YPR119W", "YMR043W", "pd", 18360.0); addEdge(network, 8, "YJL194W", "YMR043W", "pd", 988.0); addEdge(network, 9, "YPR113W", "YMR043W", "pd", 496.0); addEdge(network, 10, "YGL008C", "YMR043W", "pd", 988.0); addEdge(network, 11, "YHR084W", "YMR043W", "pp", 485.5); addEdge(network, 12, "YHR084W", "YDR461W", "pd", 4.83333333); addEdge(network, 13, "YHR084W", "YFL026W", "pd", 4.83333333); addEdge(network, 14, "YAL040C", "YMR043W", "pd", 381.0); addEdge(network, 15, "YMR043W", "YIL015W", "pd", 487.0); addEdge(network, 16, "YCR084C", "YBR112C", "pp", 496.0); addEdge(network, 17, "YMR043W", "YJL159W", "pd", 988.0); addEdge(network, 18, "YCR084C", "YCL067C", "pp", 988.0); addEdge(network, 19, "YCL067C", "YIL015W", "pd", 9.0); addEdge(network, 20, "YMR043W", "YKR097W", "pd", 3136.17527473); addEdge(network, 21, "YMR043W", "YGR108W", "pd", 4058.08455433); addEdge(network, 22, "YCL067C", "YMR043W", "pp", 1447.5); addEdge(network, 23, "YCL067C", "YDR461W", "pd", 9.83333333); addEdge(network, 24, "YMR043W", "YDR461W", "pd", 484.33333333); addEdge(network, 25, "YMR043W", "YNL145W", "pd", 484.33333333); addEdge(network, 26, "YCL067C", "YFL026W", "pd", 9.83333333); addEdge(network, 27, "YMR043W", "YJL157C", "pd", 9243.86127206); addEdge(network, 28, "YMR043W", "YFL026W", "pd", 484.33333333); addEdge(network, 29, "YNL145W", "YCL067C", "pd", 9.83333333); // sanity check assertEquals(21, network.getNodeCount()); assertEquals(29, network.getEdgeCount()); return network; } private static Long addNode(CyNetwork network, int testId, String sharedName, String common, int degree, double galexp, String dummyText) { CyNode node = network.addNode(); CyRow row = network.getRow(node); row.set(CyRootNetwork.SHARED_NAME, sharedName); row.set(TEST_ID, testId); row.set(NODE_COMMON, common); row.set(NODE_DEGREE_LAYOUT, degree); row.set(NODE_GAL_FILTERED_GAL1R_GEXP, galexp); row.set(NODE_DUMMY_TEXT, dummyText); return node.getSUID(); } private static Long addEdge(CyNetwork network, int testId, String sourceName, String targetName, String interaction, double edgeBetweenness) { CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); Long sourceSuid = nodeTable.getMatchingKeys(CyRootNetwork.SHARED_NAME, sourceName, Long.class).iterator().next(); Long targetSuid = nodeTable.getMatchingKeys(CyRootNetwork.SHARED_NAME, targetName, Long.class).iterator().next(); CyNode source = network.getNode(sourceSuid); CyNode target = network.getNode(targetSuid); CyEdge edge = network.addEdge(source, target, false); CyRow row = network.getRow(edge); row.set(CyRootNetwork.SHARED_NAME, sourceName + " (" + interaction + ") " + targetName); // TODO this might be automatic row.set(CyRootNetwork.SHARED_INTERACTION, interaction); row.set(TEST_ID, testId); row.set(EDGE_EDGEBETWEENNESS, edgeBetweenness); return edge.getSUID(); } private static Long getSUID(CyTable table, int testID) { return table.getMatchingKeys(TEST_ID, testID, Long.class).iterator().next(); } @Before public void initializeTestNetwork() throws Exception { // Each test network will have a different SUID network = createTestNetwork(); Path baseDir = Files.createTempDirectory("search2_impl_"); baseDir.toFile().deleteOnExit(); var registrar = mock(CyServiceRegistrar.class); searchManager = new SearchManager(registrar, baseDir); var future1 = searchManager.addTable(network.getDefaultNodeTable(), TableType.NODE); var future2 = searchManager.addTable(network.getDefaultEdgeTable(), TableType.EDGE); future1.get(); // wait for network to be indexed future2.get(); } private SearchResults queryIndex(String query) { NetworkSearchTask searchTask = new NetworkSearchTask(searchManager, query, network); var results = searchTask.runQuery(mock(TaskMonitor.class)); assertEquals("Error running search", Status.SUCCESS, results.getStatus()); return results; } private void assertNodeHits(SearchResults results, int ... ids) { assertEquals("wrong number of hits", ids.length, results.getHitCount(network.getDefaultNodeTable())); if(ids.length == 0) return; CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); List<String> nodeHits = results.getResultsFor(network.getDefaultNodeTable()); for(int id : ids) { Long suid = nodeTable.getMatchingKeys(TEST_ID, id, Long.class).iterator().next(); assertTrue("id " + id + " not in query results", nodeHits.contains(String.valueOf(suid))); } } private void assertEdgeHits(SearchResults results, int ... ids) { assertEquals("wrong number of hits", ids.length, results.getHitCount(network.getDefaultEdgeTable())); if(ids.length == 0) return; CyTable edgeTable = network.getTable(CyEdge.class, CyNetwork.DEFAULT_ATTRS); List<String> edgeHits = results.getResultsFor(network.getDefaultEdgeTable()); for(int id : ids) { Long suid = edgeTable.getMatchingKeys(TEST_ID, id, Long.class).iterator().next(); assertTrue("id " + id + " not in query results", edgeHits.contains(String.valueOf(suid))); } } @Test public void testBasicQueries() { SearchResults results; results = queryIndex("BAR1"); assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("bar1"); // Case insensitive assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("YMR043W"); assertNodeHits(results, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex("ymR043W"); // Case insensitive assertNodeHits(results, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex("BAR1 YMR043W"); // two terms assertNodeHits(results, 1, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex(""); assertNodeHits(results); assertEdgeHits(results); results = queryIndex("blah"); assertNodeHits(results); assertEdgeHits(results); } @Test public void testCaseInsensitiveFieldNames() { SearchResults results; results = queryIndex("dummyText:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("dummytext:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("DuMmYtExT:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("edgebetweenness:9"); assertEdgeHits(results, 19); results = queryIndex("EDGEBETWEENNESS:9"); assertEdgeHits(results, 19); } @Test public void testWildcardQueries() { SearchResults results; results = queryIndex("BAR?"); assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("CLB?"); assertNodeHits(results, 4, 5); assertEdgeHits(results); results = queryIndex("C???"); assertNodeHits(results, 4, 5, 6, 12, 19); // but not CDC28 because that has 5 chars assertEdgeHits(results); results = queryIndex("BAR? C???"); assertNodeHits(results, 1, 4, 5, 6, 12, 19); assertEdgeHits(results); results = queryIndex("YC*"); assertNodeHits(results, 13, 16); assertEdgeHits(results, 16, 18, 19, 22, 23, 26, 29); results = queryIndex("YC* BAR? C???"); assertNodeHits(results, 1, 4, 5, 6, 12, 13, 16, 19); assertEdgeHits(results, 16, 18, 19, 22, 23, 26, 29); } @Test public void testUpdateRows() throws Exception { SearchResults results; results = queryIndex("foo bazinga baz"); assertNodeHits(results); var nodeTable = network.getDefaultNodeTable(); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(NODE_COMMON, "foo"); nodeTable.getRow(nodeSuid9).set(NODE_COMMON, "bazinga"); nodeTable.getRow(nodeSuid15).set(NODE_COMMON, "baz"); var keys = Set.of(nodeSuid1, nodeSuid9, nodeSuid15); searchManager.updateRows(nodeTable, keys).get(); results = queryIndex("foo"); assertNodeHits(results, 1); results = queryIndex("bazinga"); assertNodeHits(results, 9); results = queryIndex("baz"); assertNodeHits(results, 15); results = queryIndex("SSN6"); // This was replaced with 'baz', should not have results anymore assertNodeHits(results); results = queryIndex("YMR043W"); // Sanity test, querying a node that wasn't changed should still work assertNodeHits(results, 20); } @Test public void testDeleteRows() throws Exception { var nodeTable = network.getDefaultNodeTable(); assertEquals(21, searchManager.getDocumentCount(nodeTable)); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); CyNode node1 = network.getNode(nodeSuid1); CyNode node9 = network.getNode(nodeSuid9); CyNode node15 = network.getNode(nodeSuid15); network.removeNodes(List.of(node1, node9, node15)); var keys = Set.of(nodeSuid1, nodeSuid9, nodeSuid15); searchManager.updateRows(nodeTable, keys).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); assertEquals(18, searchManager.getDocumentCount(nodeTable)); } @Test public void testAddRows() throws Exception { var nodeTable = network.getDefaultNodeTable(); assertEquals(21, searchManager.getDocumentCount(nodeTable)); Long nodeSuid90 = addNode(network, 90, "QWERTY", "frodo", 99, -0.999, "blah"); Long nodeSuid91 = addNode(network, 91, "ASDFGH", "sam", 99, -0.999, "blah"); Long nodeSuid92 = addNode(network, 92, "ZXCVBN", "gandalf", 99, -0.999, "blah"); var keys = Set.of(nodeSuid90, nodeSuid91, nodeSuid92); searchManager.updateRows(nodeTable, keys).get(); assertEquals(24, searchManager.getDocumentCount(nodeTable)); SearchResults results = queryIndex("QWERTY ASDFGH ZXCVBN"); assertNodeHits(results, 90, 91, 92); } @Test public void testDeleteColumn() throws Exception { var nodeTable = network.getDefaultNodeTable(); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); nodeTable.deleteColumn(NODE_COMMON); searchManager.reindexTable(nodeTable).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); nodeTable.createColumn(NODE_COMMON, String.class, false); nodeTable.getRow(nodeSuid1).set(NODE_COMMON, "frodo"); nodeTable.getRow(nodeSuid9).set(NODE_COMMON, "sam"); nodeTable.getRow(nodeSuid15).set(NODE_COMMON, "gandalf"); searchManager.reindexTable(nodeTable).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); results = queryIndex("frodo sam gandalf"); assertNodeHits(results, 1, 9, 15); } @Test public void testRenameColumn() throws Exception { var nodeTable = network.getDefaultNodeTable(); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); nodeTable.getColumn(NODE_COMMON).setName("ReNamed"); searchManager.reindexTable(nodeTable).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); results = queryIndex("COMMON:BAR1"); assertNodeHits(results); results = queryIndex("renamed:BAR1"); assertNodeHits(results, 1); } @Test public void testStopWords() throws Exception { // Stop words should not be removed, should be able to find 'the' SearchResults results = queryIndex("the"); assertNodeHits(results, 1, 2, 3, 5, 7, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21); } @Test public void testNumericRangeQueries() throws Exception { SearchResults results; results = queryIndex("degree.layout:99"); assertNodeHits(results, 20); results = queryIndex("degree.layout:[3 TO 6]"); assertNodeHits(results, 5, 8, 9, 10, 11, 14, 16, 21); results = queryIndex("degree.layout:[3 TO 6}"); assertNodeHits(results, 5, 8, 9, 10, 11, 14, 21); results = queryIndex(EDGE_EDGEBETWEENNESS+":9"); assertEdgeHits(results, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[300.0 TO 500.0]"); assertEdgeHits(results, 9, 11, 14, 15, 16, 24, 25, 28); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.83333333 TO 9.83333333]"); assertEdgeHits(results, 1, 12, 13, 23, 26, 29, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.8 TO 9.9]"); assertEdgeHits(results, 1, 12, 13, 23, 26, 29, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.83333333 TO 9.83333333}"); assertEdgeHits(results, 1, 12, 13, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":{4.83333333 TO 9.83333333}"); assertEdgeHits(results, 19); // TODO: The MultiFieldQueryParser doesn't support this. // If you want to do a numeric query you must specify the column name. // results = queryIndex("19179.59362859"); // assertEdgeHits(results, 6); } @Test public void testColumnNamespaces() throws Exception { SearchResults results; results = queryIndex("BAR1"); assertNodeHits(results, 1); // Namespace separator must be escaped results = queryIndex("namespace\\:\\:common:BAR1"); assertNodeHits(results, 1); // Can use just the name without the namespace. results = queryIndex("common:BAR1"); assertNodeHits(results, 1); final String COMMON2 = "namespace2::common"; final String NUMERIC = "numeric::mycolumn"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createColumn(COMMON2, String.class, false); nodeTable.createColumn(NUMERIC, Double.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(COMMON2, "sam"); nodeTable.getRow(nodeSuid9).set(COMMON2, "frodo"); nodeTable.getRow(nodeSuid15).set(COMMON2, "gandalf"); nodeTable.getRow(nodeSuid1).set(NUMERIC, 1.0); nodeTable.getRow(nodeSuid9).set(NUMERIC, 2.0); nodeTable.getRow(nodeSuid15).set(NUMERIC, 3.0); searchManager.reindexTable(nodeTable).get(); results = queryIndex("common:BAR1"); assertNodeHits(results, 1); results = queryIndex("common:sam"); assertNodeHits(results, 1); // Should work for numbers results = queryIndex("mycolumn:2.0"); assertNodeHits(results, 9); } @Test public void testNameCollision() throws Exception { var nodeTable = network.getDefaultNodeTable(); final String common2 = "namespace2::Common"; final String common3 = "namespace3::CoMmOn"; final String common4 = "Common"; nodeTable.createColumn(common2, String.class, false); nodeTable.createColumn(common3, Double.class, false); nodeTable.createColumn(common4, String.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(common2, "sam"); nodeTable.getRow(nodeSuid9).set(common2, "frodo"); nodeTable.getRow(nodeSuid15).set(common2, "gandalf"); nodeTable.getRow(nodeSuid1).set(common3, 1.0); nodeTable.getRow(nodeSuid9).set(common3, 2.0); nodeTable.getRow(nodeSuid15).set(common3, 3.0); nodeTable.getRow(nodeSuid1).set(common4, "3.0"); nodeTable.getRow(nodeSuid9).set(common4, "GANDALF"); nodeTable.getRow(nodeSuid15).set(common4, "frodo"); searchManager.reindexTable(nodeTable).get(); SearchResults results; results = queryIndex("common:frodo"); assertNodeHits(results, 9, 15); results = queryIndex("Common:frodo"); assertNodeHits(results, 9, 15); results = queryIndex("common:gandalf"); assertNodeHits(results, 9, 15); results = queryIndex("common:frodo common:PMA1"); assertNodeHits(results, 9, 15, 7); results = queryIndex("common:1.0"); assertNodeHits(results, 1); results = queryIndex("common:2.0"); assertNodeHits(results, 9); results = queryIndex("common:3.0"); assertNodeHits(results, 1, 15); results = queryIndex("common:3"); assertNodeHits(results, 15); } @Test public void testListColumns() throws Exception { final String INT_LIST = "nodeIntList"; final String STR_LIST = "nodeStrList"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createListColumn(INT_LIST, Integer.class, false); nodeTable.createListColumn(STR_LIST, String.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1) .set(INT_LIST, List.of(100, 101, 102)); nodeTable.getRow(nodeSuid9 ).set(INT_LIST, List.of(102, 103, 104)); nodeTable.getRow(nodeSuid15).set(INT_LIST, List.of(100)); nodeTable.getRow(nodeSuid1) .set(STR_LIST, List.of("sam", "gandalf", "frodo")); nodeTable.getRow(nodeSuid9) .set(STR_LIST, List.of("gandalf", "legolas")); nodeTable.getRow(nodeSuid15).set(STR_LIST, List.of("legolas", "boromir")); searchManager.reindexTable(nodeTable).get(); SearchResults results; results = queryIndex("gandalf"); assertNodeHits(results, 1, 9); results = queryIndex("nodestrlist:gandalf"); assertNodeHits(results, 1, 9); results = queryIndex("gandalf legolas"); assertNodeHits(results, 1, 9, 15); results = queryIndex("nodeIntList:102"); assertNodeHits(results, 1, 9); results = queryIndex("nodeIntList:[100 TO 102]"); assertNodeHits(results, 1, 9, 15); results = queryIndex("nodeIntList:{100 TO 102]"); assertNodeHits(results, 1, 9); } @Test public void testBooleanColumns() throws Exception { final String BOOL = "boolCol"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createColumn(BOOL, Boolean.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1) .set(BOOL, true); nodeTable.getRow(nodeSuid9) .set(BOOL, false); nodeTable.getRow(nodeSuid15).set(BOOL, true); searchManager.reindexTable(nodeTable).get(); SearchResults results; // Booleans are indexed as strings with value "true" or "false" results = queryIndex("true"); assertNodeHits(results, 1, 15); results = queryIndex("boolCol:true"); assertNodeHits(results, 1, 15); results = queryIndex("false"); assertNodeHits(results, 9); results = queryIndex("name:true"); assertNodeHits(results); } @Test public void testBooleanOperators() throws Exception { SearchResults results; results = queryIndex("far"); assertNodeHits(results, 1, 9); results = queryIndex("from"); assertNodeHits(results, 1, 19, 21); results = queryIndex("far from"); assertNodeHits(results, 1, 9, 19, 21); results = queryIndex("far OR from"); assertNodeHits(results, 1, 9, 19, 21); results = queryIndex("\"far from\""); assertNodeHits(results, 1); results = queryIndex("far AND from"); assertNodeHits(results, 1); results = queryIndex("\"blind text by\""); assertNodeHits(results, 9); } }
search2-impl/src/test/java/org/cytoscape/search/internal/index/QueryTest.java
package org.cytoscape.search.internal.index; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Set; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.NetworkTestSupport; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.search.internal.LogSilenceRule; import org.cytoscape.search.internal.search.NetworkSearchTask; import org.cytoscape.search.internal.search.SearchResults; import org.cytoscape.search.internal.search.SearchResults.Status; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.work.TaskMonitor; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; public class QueryTest { @Rule public TestRule logSilenceRule = new LogSilenceRule(); private static final String TEST_ID = "TestID"; private static final String NODE_COMMON = "namespace::COMMON"; private static final String NODE_DEGREE_LAYOUT = "degree.layout"; private static final String NODE_GAL_FILTERED_GAL1R_GEXP = "gal1RGexp"; private static final String NODE_DUMMY_TEXT = "dummyText"; private static final String EDGE_EDGEBETWEENNESS = "EdgeBetweenness"; private CyNetwork network; private SearchManager searchManager; public static CyNetwork createTestNetwork() { NetworkTestSupport networkTestSupport = new NetworkTestSupport(); CyNetwork network = networkTestSupport.getNetwork(); CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); nodeTable.createColumn(TEST_ID, Integer.class, false); // We can't chose the SUID value so use this instead nodeTable.createColumn(NODE_COMMON, String.class, false); nodeTable.createColumn(NODE_DEGREE_LAYOUT, Integer.class, false); nodeTable.createColumn(NODE_GAL_FILTERED_GAL1R_GEXP, Double.class, false); // Use a namespace nodeTable.createColumn(NODE_DUMMY_TEXT, String.class, false); // Use a namespace CyTable edgeTable = network.getTable(CyEdge.class, CyNetwork.DEFAULT_ATTRS); edgeTable.createColumn(TEST_ID, Integer.class, false); // We can't chose the SUID value so use this instead edgeTable.createColumn(EDGE_EDGEBETWEENNESS, Double.class, false); addNode(network, 1, "YIL015W", "BAR1", 2, -0.622, "Far far away, behind the word mountains, far from the countries"); addNode(network, 2, "YJL159W", "HSP150", 2, -0.357, "Vokalia and Consonantia, there live the blind texts. Separated they"); addNode(network, 3, "YKR097W", "PCK1", 2, 1.289, "live in Bookmarksgrove right at the coast of the Semantics, a large"); addNode(network, 4, "YPR119W", "CLB2", 2, -0.234, "language ocean. A small river named Duden flows by their place and"); addNode(network, 5, "YGR108W", "CLB1", 3, -0.25, "supplies it with the necessary regelialia. It is a paradisematic"); addNode(network, 6, "YAL040C", "CLN3", 2, -0.027, "country, in which roasted parts of sentences fly into your mouth."); addNode(network, 7, "YGL008C", "PMA1", 2, -0.352, "Even the all-powerful Pointing has no control about the blind texts it"); addNode(network, 8, "YDR461W", "MFA1", 3, -0.659, "is an almost unorthographic life One day however a small line of"); addNode(network, 9, "YNL145W", "MFA2", 3, -0.764, "blind text by the name of Lorem Ipsum decided to leave for the far"); addNode(network, 10, "YJL157C", "FAR1", 4, -0.158, "World of Grammar. The Big Oxmox advised her not to do so, because"); addNode(network, 11, "YFL026W", "STE2", 3, -0.653, "there were thousands of bad Commas, wild Question Marks and"); addNode(network, 12, "YJL194W", "CDC6", 2, 0.018, "devious Semikoli, but the Little Blind Text didn’t listen. She packed"); addNode(network, 13, "YCR084C", "TUP1", 2, 0.044, "her seven versalia, put her initial into the belt and made herself on"); addNode(network, 14, "YHR084W", "STE12", 4, -0.109, "the way. When she reached the first hills of the Italic Mountains, she"); addNode(network, 15, "YBR112C", "SSN6", 1, 0.108, "had a last view back on the skyline of her hometown"); addNode(network, 16, "YCL067C", null, 6, 0.169, "Bookmarksgrove, the headline of Alphabet Village and the subline of"); addNode(network, 17, "YER111C", "SWI4", 2, 0.195, "her own road, the Line Lane. Pityful a rethoric question ran over her"); addNode(network, 18, "YDR146C", "SWI5", 2, -0.19, "cheek, then she continued her way. On her way she met a copy. The"); addNode(network, 19, "YPR113W", "PIS1", 1, -0.495, "copy warned the Little Blind Text, that where it came from it would"); addNode(network, 20, "YMR043W", "MCM1", 99, -0.183, "have been rewritten a thousand times and everything that was left"); addNode(network, 21, "YBR160W", "CDC28", 3, -0.016, "from its origin would be the word \"and\" and the Little Blind Text"); addEdge(network, 1, "YNL145W", "YHR084W", "pd", 4.83333333); addEdge(network, 2, "YJL157C", "YAL040C", "pp", 115.0); addEdge(network, 3, "YER111C", "YMR043W", "pd", 2361.73260073); addEdge(network, 4, "YBR160W", "YMR043W", "pd", 940.0); addEdge(network, 5, "YBR160W", "YGR108W", "pp", 48.0); addEdge(network, 6, "YDR146C", "YMR043W", "pd", 19179.59362859); addEdge(network, 7, "YPR119W", "YMR043W", "pd", 18360.0); addEdge(network, 8, "YJL194W", "YMR043W", "pd", 988.0); addEdge(network, 9, "YPR113W", "YMR043W", "pd", 496.0); addEdge(network, 10, "YGL008C", "YMR043W", "pd", 988.0); addEdge(network, 11, "YHR084W", "YMR043W", "pp", 485.5); addEdge(network, 12, "YHR084W", "YDR461W", "pd", 4.83333333); addEdge(network, 13, "YHR084W", "YFL026W", "pd", 4.83333333); addEdge(network, 14, "YAL040C", "YMR043W", "pd", 381.0); addEdge(network, 15, "YMR043W", "YIL015W", "pd", 487.0); addEdge(network, 16, "YCR084C", "YBR112C", "pp", 496.0); addEdge(network, 17, "YMR043W", "YJL159W", "pd", 988.0); addEdge(network, 18, "YCR084C", "YCL067C", "pp", 988.0); addEdge(network, 19, "YCL067C", "YIL015W", "pd", 9.0); addEdge(network, 20, "YMR043W", "YKR097W", "pd", 3136.17527473); addEdge(network, 21, "YMR043W", "YGR108W", "pd", 4058.08455433); addEdge(network, 22, "YCL067C", "YMR043W", "pp", 1447.5); addEdge(network, 23, "YCL067C", "YDR461W", "pd", 9.83333333); addEdge(network, 24, "YMR043W", "YDR461W", "pd", 484.33333333); addEdge(network, 25, "YMR043W", "YNL145W", "pd", 484.33333333); addEdge(network, 26, "YCL067C", "YFL026W", "pd", 9.83333333); addEdge(network, 27, "YMR043W", "YJL157C", "pd", 9243.86127206); addEdge(network, 28, "YMR043W", "YFL026W", "pd", 484.33333333); addEdge(network, 29, "YNL145W", "YCL067C", "pd", 9.83333333); // sanity check assertEquals(21, network.getNodeCount()); assertEquals(29, network.getEdgeCount()); return network; } private static Long addNode(CyNetwork network, int testId, String sharedName, String common, int degree, double galexp, String dummyText) { CyNode node = network.addNode(); CyRow row = network.getRow(node); row.set(CyRootNetwork.SHARED_NAME, sharedName); row.set(TEST_ID, testId); row.set(NODE_COMMON, common); row.set(NODE_DEGREE_LAYOUT, degree); row.set(NODE_GAL_FILTERED_GAL1R_GEXP, galexp); row.set(NODE_DUMMY_TEXT, dummyText); return node.getSUID(); } private static Long addEdge(CyNetwork network, int testId, String sourceName, String targetName, String interaction, double edgeBetweenness) { CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); Long sourceSuid = nodeTable.getMatchingKeys(CyRootNetwork.SHARED_NAME, sourceName, Long.class).iterator().next(); Long targetSuid = nodeTable.getMatchingKeys(CyRootNetwork.SHARED_NAME, targetName, Long.class).iterator().next(); CyNode source = network.getNode(sourceSuid); CyNode target = network.getNode(targetSuid); CyEdge edge = network.addEdge(source, target, false); CyRow row = network.getRow(edge); row.set(CyRootNetwork.SHARED_NAME, sourceName + " (" + interaction + ") " + targetName); // TODO this might be automatic row.set(CyRootNetwork.SHARED_INTERACTION, interaction); row.set(TEST_ID, testId); row.set(EDGE_EDGEBETWEENNESS, edgeBetweenness); return edge.getSUID(); } private static Long getSUID(CyTable table, int testID) { return table.getMatchingKeys(TEST_ID, testID, Long.class).iterator().next(); } @Before public void initializeTestNetwork() throws Exception { // Each test network will have a different SUID network = createTestNetwork(); Path baseDir = Files.createTempDirectory("search2_impl_"); baseDir.toFile().deleteOnExit(); var registrar = mock(CyServiceRegistrar.class); searchManager = new SearchManager(registrar, baseDir); var future1 = searchManager.addTable(network.getDefaultNodeTable(), TableType.NODE); var future2 = searchManager.addTable(network.getDefaultEdgeTable(), TableType.EDGE); future1.get(); // wait for network to be indexed future2.get(); } private SearchResults queryIndex(String query) { NetworkSearchTask searchTask = new NetworkSearchTask(searchManager, query, network); var results = searchTask.runQuery(mock(TaskMonitor.class)); assertEquals("Error running search", Status.SUCCESS, results.getStatus()); return results; } private void assertNodeHits(SearchResults results, int ... ids) { assertEquals("wrong number of hits", ids.length, results.getHitCount(network.getDefaultNodeTable())); if(ids.length == 0) return; CyTable nodeTable = network.getTable(CyNode.class, CyNetwork.DEFAULT_ATTRS); List<String> nodeHits = results.getResultsFor(network.getDefaultNodeTable()); for(int id : ids) { Long suid = nodeTable.getMatchingKeys(TEST_ID, id, Long.class).iterator().next(); assertTrue("id " + id + " not in query results", nodeHits.contains(String.valueOf(suid))); } } private void assertEdgeHits(SearchResults results, int ... ids) { assertEquals("wrong number of hits", ids.length, results.getHitCount(network.getDefaultEdgeTable())); if(ids.length == 0) return; CyTable edgeTable = network.getTable(CyEdge.class, CyNetwork.DEFAULT_ATTRS); List<String> edgeHits = results.getResultsFor(network.getDefaultEdgeTable()); for(int id : ids) { Long suid = edgeTable.getMatchingKeys(TEST_ID, id, Long.class).iterator().next(); assertTrue("id " + id + " not in query results", edgeHits.contains(String.valueOf(suid))); } } @Test public void testBasicQueries() { SearchResults results; results = queryIndex("BAR1"); assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("bar1"); // Case insensitive assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("YMR043W"); assertNodeHits(results, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex("ymR043W"); // Case insensitive assertNodeHits(results, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex("BAR1 YMR043W"); // two terms assertNodeHits(results, 1, 20); assertEdgeHits(results, 3, 4, 6, 7, 8, 9, 10, 11, 14, 15, 17, 20, 21, 22, 24, 25, 27, 28); results = queryIndex(""); assertNodeHits(results); assertEdgeHits(results); results = queryIndex("blah"); assertNodeHits(results); assertEdgeHits(results); } @Test public void testCaseInsensitiveFieldNames() { SearchResults results; results = queryIndex("dummyText:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("dummytext:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("DuMmYtExT:blind"); assertNodeHits(results, 2, 7, 9, 12, 19, 21); results = queryIndex("edgebetweenness:9"); assertEdgeHits(results, 19); results = queryIndex("EDGEBETWEENNESS:9"); assertEdgeHits(results, 19); } @Test public void testWildcardQueries() { SearchResults results; results = queryIndex("BAR?"); assertNodeHits(results, 1); assertEdgeHits(results); results = queryIndex("CLB?"); assertNodeHits(results, 4, 5); assertEdgeHits(results); results = queryIndex("C???"); assertNodeHits(results, 4, 5, 6, 12, 19); // but not CDC28 because that has 5 chars assertEdgeHits(results); results = queryIndex("BAR? C???"); assertNodeHits(results, 1, 4, 5, 6, 12, 19); assertEdgeHits(results); results = queryIndex("YC*"); assertNodeHits(results, 13, 16); assertEdgeHits(results, 16, 18, 19, 22, 23, 26, 29); results = queryIndex("YC* BAR? C???"); assertNodeHits(results, 1, 4, 5, 6, 12, 13, 16, 19); assertEdgeHits(results, 16, 18, 19, 22, 23, 26, 29); } @Test public void testUpdateRows() throws Exception { SearchResults results; results = queryIndex("foo bazinga baz"); assertNodeHits(results); var nodeTable = network.getDefaultNodeTable(); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(NODE_COMMON, "foo"); nodeTable.getRow(nodeSuid9).set(NODE_COMMON, "bazinga"); nodeTable.getRow(nodeSuid15).set(NODE_COMMON, "baz"); var keys = Set.of(nodeSuid1, nodeSuid9, nodeSuid15); searchManager.updateRows(nodeTable, keys).get(); results = queryIndex("foo"); assertNodeHits(results, 1); results = queryIndex("bazinga"); assertNodeHits(results, 9); results = queryIndex("baz"); assertNodeHits(results, 15); results = queryIndex("SSN6"); // This was replaced with 'baz', should not have results anymore assertNodeHits(results); results = queryIndex("YMR043W"); // Sanity test, querying a node that wasn't changed should still work assertNodeHits(results, 20); } @Test public void testDeleteRows() throws Exception { var nodeTable = network.getDefaultNodeTable(); assertEquals(21, searchManager.getDocumentCount(nodeTable)); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); CyNode node1 = network.getNode(nodeSuid1); CyNode node9 = network.getNode(nodeSuid9); CyNode node15 = network.getNode(nodeSuid15); network.removeNodes(List.of(node1, node9, node15)); var keys = Set.of(nodeSuid1, nodeSuid9, nodeSuid15); searchManager.updateRows(nodeTable, keys).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); assertEquals(18, searchManager.getDocumentCount(nodeTable)); } @Test public void testAddRows() throws Exception { var nodeTable = network.getDefaultNodeTable(); assertEquals(21, searchManager.getDocumentCount(nodeTable)); Long nodeSuid90 = addNode(network, 90, "QWERTY", "frodo", 99, -0.999, "blah"); Long nodeSuid91 = addNode(network, 91, "ASDFGH", "sam", 99, -0.999, "blah"); Long nodeSuid92 = addNode(network, 92, "ZXCVBN", "gandalf", 99, -0.999, "blah"); var keys = Set.of(nodeSuid90, nodeSuid91, nodeSuid92); searchManager.updateRows(nodeTable, keys).get(); assertEquals(24, searchManager.getDocumentCount(nodeTable)); SearchResults results = queryIndex("QWERTY ASDFGH ZXCVBN"); assertNodeHits(results, 90, 91, 92); } @Test public void testDeleteColumn() throws Exception { var nodeTable = network.getDefaultNodeTable(); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); nodeTable.deleteColumn(NODE_COMMON); searchManager.reindexTable(nodeTable).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); nodeTable.createColumn(NODE_COMMON, String.class, false); nodeTable.getRow(nodeSuid1).set(NODE_COMMON, "frodo"); nodeTable.getRow(nodeSuid9).set(NODE_COMMON, "sam"); nodeTable.getRow(nodeSuid15).set(NODE_COMMON, "gandalf"); searchManager.reindexTable(nodeTable); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results); results = queryIndex("frodo sam gandalf"); assertNodeHits(results, 1, 9, 15); } @Test public void testRenameColumn() throws Exception { var nodeTable = network.getDefaultNodeTable(); SearchResults results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); nodeTable.getColumn(NODE_COMMON).setName("ReNamed"); searchManager.reindexTable(nodeTable).get(); results = queryIndex("BAR1 MFA2 SSN6"); assertNodeHits(results, 1, 9, 15); results = queryIndex("COMMON:BAR1"); assertNodeHits(results); results = queryIndex("renamed:BAR1"); assertNodeHits(results, 1); } @Test public void testStopWords() throws Exception { // Stop words should not be removed, should be able to find 'the' SearchResults results = queryIndex("the"); assertNodeHits(results, 1, 2, 3, 5, 7, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21); } @Test public void testNumericRangeQueries() throws Exception { SearchResults results; results = queryIndex("degree.layout:99"); assertNodeHits(results, 20); results = queryIndex("degree.layout:[3 TO 6]"); assertNodeHits(results, 5, 8, 9, 10, 11, 14, 16, 21); results = queryIndex("degree.layout:[3 TO 6}"); assertNodeHits(results, 5, 8, 9, 10, 11, 14, 21); results = queryIndex(EDGE_EDGEBETWEENNESS+":9"); assertEdgeHits(results, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[300.0 TO 500.0]"); assertEdgeHits(results, 9, 11, 14, 15, 16, 24, 25, 28); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.83333333 TO 9.83333333]"); assertEdgeHits(results, 1, 12, 13, 23, 26, 29, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.8 TO 9.9]"); assertEdgeHits(results, 1, 12, 13, 23, 26, 29, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":[4.83333333 TO 9.83333333}"); assertEdgeHits(results, 1, 12, 13, 19); results = queryIndex(EDGE_EDGEBETWEENNESS+":{4.83333333 TO 9.83333333}"); assertEdgeHits(results, 19); // TODO: The MultiFieldQueryParser doesn't support this. // If you want to do a numeric query you must specify the column name. // results = queryIndex("19179.59362859"); // assertEdgeHits(results, 6); } @Test public void testColumnNamespaces() throws Exception { SearchResults results; results = queryIndex("BAR1"); assertNodeHits(results, 1); // Namespace separator must be escaped results = queryIndex("namespace\\:\\:common:BAR1"); assertNodeHits(results, 1); // Can use just the name without the namespace. results = queryIndex("common:BAR1"); assertNodeHits(results, 1); final String COMMON2 = "namespace2::common"; final String NUMERIC = "numeric::mycolumn"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createColumn(COMMON2, String.class, false); nodeTable.createColumn(NUMERIC, Double.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(COMMON2, "sam"); nodeTable.getRow(nodeSuid9).set(COMMON2, "frodo"); nodeTable.getRow(nodeSuid15).set(COMMON2, "gandalf"); nodeTable.getRow(nodeSuid1).set(NUMERIC, 1.0); nodeTable.getRow(nodeSuid9).set(NUMERIC, 2.0); nodeTable.getRow(nodeSuid15).set(NUMERIC, 3.0); searchManager.reindexTable(nodeTable).get(); results = queryIndex("common:BAR1"); assertNodeHits(results, 1); results = queryIndex("common:sam"); assertNodeHits(results, 1); // Should work for numbers results = queryIndex("mycolumn:2.0"); assertNodeHits(results, 9); } @Test public void testNameCollision() throws Exception { var nodeTable = network.getDefaultNodeTable(); final String common2 = "namespace2::Common"; final String common3 = "namespace3::CoMmOn"; final String common4 = "Common"; nodeTable.createColumn(common2, String.class, false); nodeTable.createColumn(common3, Double.class, false); nodeTable.createColumn(common4, String.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1).set(common2, "sam"); nodeTable.getRow(nodeSuid9).set(common2, "frodo"); nodeTable.getRow(nodeSuid15).set(common2, "gandalf"); nodeTable.getRow(nodeSuid1).set(common3, 1.0); nodeTable.getRow(nodeSuid9).set(common3, 2.0); nodeTable.getRow(nodeSuid15).set(common3, 3.0); nodeTable.getRow(nodeSuid1).set(common4, "3.0"); nodeTable.getRow(nodeSuid9).set(common4, "GANDALF"); nodeTable.getRow(nodeSuid15).set(common4, "frodo"); searchManager.reindexTable(nodeTable).get(); SearchResults results; results = queryIndex("common:frodo"); assertNodeHits(results, 9, 15); results = queryIndex("Common:frodo"); assertNodeHits(results, 9, 15); results = queryIndex("common:gandalf"); assertNodeHits(results, 9, 15); results = queryIndex("common:frodo common:PMA1"); assertNodeHits(results, 9, 15, 7); results = queryIndex("common:1.0"); assertNodeHits(results, 1); results = queryIndex("common:2.0"); assertNodeHits(results, 9); results = queryIndex("common:3.0"); assertNodeHits(results, 1, 15); results = queryIndex("common:3"); assertNodeHits(results, 15); } @Test public void testListColumns() throws Exception { final String INT_LIST = "nodeIntList"; final String STR_LIST = "nodeStrList"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createListColumn(INT_LIST, Integer.class, false); nodeTable.createListColumn(STR_LIST, String.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1) .set(INT_LIST, List.of(100, 101, 102)); nodeTable.getRow(nodeSuid9 ).set(INT_LIST, List.of(102, 103, 104)); nodeTable.getRow(nodeSuid15).set(INT_LIST, List.of(100)); nodeTable.getRow(nodeSuid1) .set(STR_LIST, List.of("sam", "gandalf", "frodo")); nodeTable.getRow(nodeSuid9) .set(STR_LIST, List.of("gandalf", "legolas")); nodeTable.getRow(nodeSuid15).set(STR_LIST, List.of("legolas", "boromir")); searchManager.reindexTable(nodeTable).get(); SearchResults results; results = queryIndex("gandalf"); assertNodeHits(results, 1, 9); results = queryIndex("nodestrlist:gandalf"); assertNodeHits(results, 1, 9); results = queryIndex("gandalf legolas"); assertNodeHits(results, 1, 9, 15); results = queryIndex("nodeIntList:102"); assertNodeHits(results, 1, 9); results = queryIndex("nodeIntList:[100 TO 102]"); assertNodeHits(results, 1, 9, 15); results = queryIndex("nodeIntList:{100 TO 102]"); assertNodeHits(results, 1, 9); } @Test public void testBooleanColumns() throws Exception { final String BOOL = "boolCol"; var nodeTable = network.getDefaultNodeTable(); nodeTable.createColumn(BOOL, Boolean.class, false); Long nodeSuid1 = getSUID(nodeTable, 1); Long nodeSuid9 = getSUID(nodeTable, 9); Long nodeSuid15 = getSUID(nodeTable, 15); nodeTable.getRow(nodeSuid1) .set(BOOL, true); nodeTable.getRow(nodeSuid9) .set(BOOL, false); nodeTable.getRow(nodeSuid15).set(BOOL, true); searchManager.reindexTable(nodeTable).get(); SearchResults results; // Booleans are indexed as strings with value "true" or "false" results = queryIndex("true"); assertNodeHits(results, 1, 15); results = queryIndex("boolCol:true"); assertNodeHits(results, 1, 15); results = queryIndex("false"); assertNodeHits(results, 9); results = queryIndex("name:true"); assertNodeHits(results); } @Test public void testBooleanOperators() throws Exception { SearchResults results; results = queryIndex("far"); assertNodeHits(results, 1, 9); results = queryIndex("from"); assertNodeHits(results, 1, 19, 21); results = queryIndex("far from"); assertNodeHits(results, 1, 9, 19, 21); results = queryIndex("far OR from"); assertNodeHits(results, 1, 9, 19, 21); results = queryIndex("\"far from\""); assertNodeHits(results, 1); results = queryIndex("far AND from"); assertNodeHits(results, 1); results = queryIndex("\"blind text by\""); assertNodeHits(results, 9); } }
# WARNING: head commit changed in the meantime Fix to search2 test suite.
search2-impl/src/test/java/org/cytoscape/search/internal/index/QueryTest.java
# WARNING: head commit changed in the meantime
<ide><path>earch2-impl/src/test/java/org/cytoscape/search/internal/index/QueryTest.java <ide> nodeTable.getRow(nodeSuid9).set(NODE_COMMON, "sam"); <ide> nodeTable.getRow(nodeSuid15).set(NODE_COMMON, "gandalf"); <ide> <del> searchManager.reindexTable(nodeTable); <add> searchManager.reindexTable(nodeTable).get(); <ide> <ide> results = queryIndex("BAR1 MFA2 SSN6"); <ide> assertNodeHits(results);
Java
mit
0f33bf2bbe37b771e69f67106756c1f12ee06056
0
spkaplan/chess
package main.java; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; /** * Created by brandon on 3/29/2016 at 4:44 PM as part of the chess project. */ public class TextController { private static final Set<Character> validColumns = new HashSet<Character>(Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')); private Model model; private TextView view; private static Map<Character, Integer> charToIntMap; public TextController() { buildCharToIntMap(); } public void setModel(Model model) { this.model = model; } void buildCharToIntMap() { charToIntMap = new HashMap<>(); charToIntMap.put('a', 0); charToIntMap.put('b', 1); charToIntMap.put('c', 2); charToIntMap.put('d', 3); charToIntMap.put('e', 4); charToIntMap.put('f', 5); charToIntMap.put('g', 6); charToIntMap.put('h', 7); } /** * Processes the input of the user and tells model how to react/update. Also * queues the model to refresh the view. * * @param input User input. */ void processInput(String input) { if (input.length() == 0) { String message = "Command must contain one or more characters"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } input = input.toLowerCase(); String[] inputArray = input.split("\\s+"); /*Make sure command is not just whitespace*/ if (inputArray.length == 0) { String message = "Command must contain one or more non-whitespace characters"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } switch (inputArray[0]) { case "move": move(inputArray); break; case "validmoves": validmoves(inputArray); break; case "castle": castle(inputArray); break; case "quit": case "exit": if (exit(inputArray)) break; case "refresh": this.view.refresh(); break; case "help": this.view.help(); break; default: String message = "Unrecognized Command: " + input; model.setExceptionThrown(new IllegalArgumentException(message)); break; } } /** * Checks to be sure that "exit" was the only thing passed as input and then * ends the program * * @param inputArray * @return */ private boolean exit(String[] inputArray) { if (inputArray.length != 1) { String message = "The quit/exit commands do not take any arguments."; model.setExceptionThrown(new IllegalArgumentException(message)); return true; } System.exit(0); return false; } /** * Validate input for castle, load the Position objects, and pass the * request on to model * * @param inputArray an array of two positions, one being a rook, and the * other being a king */ private void castle(String[] inputArray) { String arg1, arg2; if (inputArray.length != 3) { String message = "The castle command requires two grid positions (e.g. castle a1 a2)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; arg2 = inputArray[2]; if (!validColumns.contains(arg1.charAt(0))) { String message = "Invalid column label: " + String.valueOf(arg1.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); return; } if (!validColumns.contains(arg2.charAt(0))) { String message = "Invalid column label: " + String.valueOf(arg2.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); return; } try { Position position1 = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); Position position2 = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); model.castle(position1, position2); this.model.incrementTurnCount(); this.model.switchWhosTurn(); } catch (InvalidPositionException e) { model.setExceptionThrown(e); } } /** * Request list of valid moves from the model and return them to the view * * @param inputArray an array containing the single position string passed * by the user */ private void validmoves(String[] inputArray) { String arg1; if (inputArray.length != 2) { String message = "The validmoves command requires one grid position (e.g. validmoves a1)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; try { Position position = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); model.getValidNewPositions(position); } catch (InvalidPositionException e) { model.setExceptionThrown(e); } } /** * Validates string input, loads into position objects, and moves pieces * * @param inputArray the two strings input by the user (old pos, new pos) */ private void move(String[] inputArray) { String arg1; String arg2; boolean valid = true; if (inputArray.length != 3) { String message = "The move command requires two grid positions separated by a space (e.g. move a1 a2)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; arg2 = inputArray[2]; if (!validColumns.contains(arg1.charAt(0))) { String message = "Invalid column label: " + String.valueOf(arg1.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); return; } if (!validColumns.contains(arg2.charAt(0))) { String message = "Invalid column label: " + String.valueOf(arg2.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); return; } try { Position curPos = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); Position newPos = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); model.movePiece(curPos, newPos); this.model.incrementTurnCount(); this.model.switchWhosTurn(); } catch (InvalidPositionException | IllegalArgumentException e) { model.setExceptionThrown(e); } } public void setView(TextView view) { this.view = view; } /** * Loop indefinitely, awaiting commands from the user. */ public void run() { Scanner reader = new Scanner(System.in); /*Cause the view to be displayed immediately*/ this.model.notifyObservers(); while (true) { if (this.model.isCheckmate()) { this.model.setIsCheckmate(true); this.model.notifyObservers(); System.exit(0); } else if (this.model.isCheck()) { this.model.setIsCheck(true); this.model.notifyObservers(); } System.out.print(">>"); String input = reader.nextLine(); processInput(input); this.model.notifyObservers(); } } }
src/main/java/TextController.java
package main.java; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Created by brandon on 3/29/2016 at 4:44 PM as part of the chess project. */ public class TextController { private Model model; private TextView view; private String validCoords = "abcdefh"; private enum validCommands { move, validmoves, help, exit, quit, castle, refresh } Map<Character, Integer> charToIntMap; public TextController() { buildCharToIntMap(); } public void setModel(Model model) { this.model = model; } void buildCharToIntMap() { charToIntMap = new HashMap<>(); charToIntMap.put('a', 0); charToIntMap.put('b', 1); charToIntMap.put('c', 2); charToIntMap.put('d', 3); charToIntMap.put('e', 4); charToIntMap.put('f', 5); charToIntMap.put('g', 6); charToIntMap.put('h', 7); } /** * Processes the input of the user and tells model how to react/update. Also * queues the model to refresh the view. * * @param input User input. */ void processInput(String input) { input = input.toLowerCase(); String[] inputArray = input.split("\\s+"); String arg1, arg2; switch (inputArray[0]) { case "move": move(inputArray); break; case "validmoves": validmoves(inputArray); break; case "castle": castle(inputArray); break; case "quit": case "exit": if (exit(inputArray)) break; case "refresh": this.view.refresh(); break; case "help": this.view.help(); break; default: String message = "Unrecognized Command: " + input; model.setExceptionThrown(new IllegalArgumentException(message)); break; } } /** * Checks to be sure that "exit" was the only thing passed as input and then ends the program * @param inputArray * @return */ private boolean exit(String[] inputArray) { if (inputArray.length != 1) { String message = "The quit/exit commands do not take any arguments."; model.setExceptionThrown(new IllegalArgumentException(message)); return true; } System.exit(0); return false; } /** * Validate input for castle, load the Position objects, and pass the request on to model * @param inputArray an array of two positions, one being a rook, and the other being a king */ private void castle(String[] inputArray) { String arg1, arg2; boolean valid = true; if (inputArray.length != 3) { String message = "The castle command requires two grid positions (e.g. castle a1 a2)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; arg2 = inputArray[2]; if(!validCoords.contains(String.valueOf(arg1.charAt(0)))) { String message = "invalid coordinate: " + String.valueOf(arg1.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); valid = false; } if(!validCoords.contains(String.valueOf(arg2.charAt(0)))) { String message = "invalid coordinate: " + String.valueOf(arg2.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); valid = false; } if(valid) { try { if(charToIntMap.get(arg1.charAt(0)) != null && charToIntMap.get(arg2.charAt(0)) != null) { Position position1 = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); Position position2 = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); model.castle(position1, position2); this.model.incrementTurnCount(); this.model.switchWhosTurn(); } } catch (InvalidPositionException e) { model.setExceptionThrown(e); } } } /** * Request list of valid moves from the model and return them to the view * @param inputArray an array containing the single position string passed by the user */ private void validmoves(String[] inputArray) { String arg1; if (inputArray.length != 2) { String message = "The validmoves command requires one grid position (e.g. validmoves a1)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; try { Position position = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); model.getValidNewPositions(position); } catch (InvalidPositionException e) { model.setExceptionThrown(e); } } /** * Validates string input, loads into position objects, and moves pieces * @param inputArray the two strings input by the user (old pos, new pos) */ private void move(String[] inputArray) { String arg1; String arg2; boolean valid = true; if (inputArray.length != 3) { String message = "The move command requires two grid positions separated by a space (e.g. move a1 a2)"; model.setExceptionThrown(new IllegalArgumentException(message)); return; } arg1 = inputArray[1]; arg2 = inputArray[2]; if(!validCoords.contains(String.valueOf(arg1.charAt(0)))) { String message = "invalid coordinate: " + String.valueOf(arg1.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); valid = false; } if(!validCoords.contains(String.valueOf(arg2.charAt(0)))) { String message = "invalid coordinate: " + String.valueOf(arg2.charAt(0)); model.setExceptionThrown(new IllegalArgumentException(message)); valid = false; } if(valid) { try { Position curPos = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); Position newPos = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); model.movePiece(curPos, newPos); this.model.incrementTurnCount(); this.model.switchWhosTurn(); } catch (InvalidPositionException | IllegalArgumentException e) { model.setExceptionThrown(e); } } } public void setView(TextView view) { this.view = view; } /** * Loop indefinitely, awaiting commands from the user. */ public void run() { Scanner reader = new Scanner(System.in); /*Cause the view to be displayed immediately*/ this.model.notifyObservers(); while (true) { if (this.model.isCheckmate()) { this.model.setIsCheckmate(true); this.model.notifyObservers(); System.exit(0); } else if (this.model.isCheck()) { this.model.setIsCheck(true); this.model.notifyObservers(); } System.out.print(">>"); String input = reader.nextLine(); processInput(input); this.model.notifyObservers(); } } }
Cleaning up the code for parsing user input.
src/main/java/TextController.java
Cleaning up the code for parsing user input.
<ide><path>rc/main/java/TextController.java <ide> package main.java; <ide> <add>import java.util.Arrays; <ide> import java.util.HashMap; <add>import java.util.HashSet; <ide> import java.util.Map; <ide> import java.util.Scanner; <add>import java.util.Set; <ide> <ide> /** <ide> * Created by brandon on 3/29/2016 at 4:44 PM as part of the chess project. <ide> <ide> public class TextController <ide> { <add> private static final Set<Character> validColumns = new HashSet<Character>(Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')); <ide> private Model model; <ide> private TextView view; <del> <del> private String validCoords = "abcdefh"; <del> <del> private enum validCommands { <del> move, validmoves, help, exit, quit, castle, refresh <del> } <del> <del> Map<Character, Integer> charToIntMap; <add> private static Map<Character, Integer> charToIntMap; <ide> <ide> public TextController() <ide> { <ide> */ <ide> void processInput(String input) <ide> { <add> if (input.length() == 0) <add> { <add> String message = "Command must contain one or more characters"; <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <ide> input = input.toLowerCase(); <ide> String[] inputArray = input.split("\\s+"); <del> String arg1, arg2; <add> <add> /*Make sure command is not just whitespace*/ <add> if (inputArray.length == 0) <add> { <add> String message = "Command must contain one or more non-whitespace characters"; <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <add> <ide> switch (inputArray[0]) <ide> { <ide> case "move": <ide> <ide> case "quit": <ide> case "exit": <del> if (exit(inputArray)) break; <add> if (exit(inputArray)) <add> break; <ide> <ide> case "refresh": <ide> this.view.refresh(); <ide> } <ide> <ide> /** <del> * Checks to be sure that "exit" was the only thing passed as input and then ends the program <add> * Checks to be sure that "exit" was the only thing passed as input and then <add> * ends the program <add> * <ide> * @param inputArray <ide> * @return <ide> */ <del> private boolean exit(String[] inputArray) { <add> private boolean exit(String[] inputArray) <add> { <ide> if (inputArray.length != 1) <ide> { <ide> String message = "The quit/exit commands do not take any arguments."; <ide> } <ide> <ide> /** <del> * Validate input for castle, load the Position objects, and pass the request on to model <del> * @param inputArray an array of two positions, one being a rook, and the other being a king <del> */ <del> private void castle(String[] inputArray) { <add> * Validate input for castle, load the Position objects, and pass the <add> * request on to model <add> * <add> * @param inputArray an array of two positions, one being a rook, and the <add> * other being a king <add> */ <add> private void castle(String[] inputArray) <add> { <ide> String arg1, arg2; <del> boolean valid = true; <ide> if (inputArray.length != 3) <ide> { <ide> String message = "The castle command requires two grid positions (e.g. castle a1 a2)"; <ide> } <ide> arg1 = inputArray[1]; <ide> arg2 = inputArray[2]; <del> if(!validCoords.contains(String.valueOf(arg1.charAt(0)))) { <del> String message = "invalid coordinate: " + String.valueOf(arg1.charAt(0)); <del> model.setExceptionThrown(new IllegalArgumentException(message)); <del> valid = false; <del> } <del> if(!validCoords.contains(String.valueOf(arg2.charAt(0)))) { <del> String message = "invalid coordinate: " + String.valueOf(arg2.charAt(0)); <del> model.setExceptionThrown(new IllegalArgumentException(message)); <del> valid = false; <del> } <del> if(valid) { <del> try <del> { <del> if(charToIntMap.get(arg1.charAt(0)) != null && charToIntMap.get(arg2.charAt(0)) != null) { <del> Position position1 = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); <del> Position position2 = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); <del> model.castle(position1, position2); <del> <del> this.model.incrementTurnCount(); <del> this.model.switchWhosTurn(); <del> } <del> } catch (InvalidPositionException e) <del> { <del> model.setExceptionThrown(e); <del> } <add> if (!validColumns.contains(arg1.charAt(0))) <add> { <add> String message = "Invalid column label: " + String.valueOf(arg1.charAt(0)); <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <add> if (!validColumns.contains(arg2.charAt(0))) <add> { <add> String message = "Invalid column label: " + String.valueOf(arg2.charAt(0)); <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <add> <add> try <add> { <add> Position position1 = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); <add> Position position2 = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); <add> model.castle(position1, position2); <add> <add> this.model.incrementTurnCount(); <add> this.model.switchWhosTurn(); <add> } catch (InvalidPositionException e) <add> { <add> model.setExceptionThrown(e); <ide> } <ide> } <ide> <ide> /** <ide> * Request list of valid moves from the model and return them to the view <del> * @param inputArray an array containing the single position string passed by the user <del> */ <del> private void validmoves(String[] inputArray) { <add> * <add> * @param inputArray an array containing the single position string passed <add> * by the user <add> */ <add> private void validmoves(String[] inputArray) <add> { <ide> String arg1; <ide> if (inputArray.length != 2) <ide> { <ide> <ide> /** <ide> * Validates string input, loads into position objects, and moves pieces <add> * <ide> * @param inputArray the two strings input by the user (old pos, new pos) <ide> */ <del> private void move(String[] inputArray) { <add> private void move(String[] inputArray) <add> { <ide> String arg1; <ide> String arg2; <ide> boolean valid = true; <ide> } <ide> arg1 = inputArray[1]; <ide> arg2 = inputArray[2]; <del> if(!validCoords.contains(String.valueOf(arg1.charAt(0)))) { <del> String message = "invalid coordinate: " + String.valueOf(arg1.charAt(0)); <del> model.setExceptionThrown(new IllegalArgumentException(message)); <del> valid = false; <del> } <del> if(!validCoords.contains(String.valueOf(arg2.charAt(0)))) { <del> String message = "invalid coordinate: " + String.valueOf(arg2.charAt(0)); <del> model.setExceptionThrown(new IllegalArgumentException(message)); <del> valid = false; <del> } <del> if(valid) { <del> try <del> { <del> Position curPos = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); <del> Position newPos = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); <del> model.movePiece(curPos, newPos); <del> <del> this.model.incrementTurnCount(); <del> this.model.switchWhosTurn(); <del> } catch (InvalidPositionException | IllegalArgumentException e) <del> { <del> model.setExceptionThrown(e); <del> } <del> } <del> } <del> <del> public void setView(TextView view) { <add> if (!validColumns.contains(arg1.charAt(0))) <add> { <add> String message = "Invalid column label: " + String.valueOf(arg1.charAt(0)); <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <add> if (!validColumns.contains(arg2.charAt(0))) <add> { <add> String message = "Invalid column label: " + String.valueOf(arg2.charAt(0)); <add> model.setExceptionThrown(new IllegalArgumentException(message)); <add> return; <add> } <add> try <add> { <add> Position curPos = new Position(8 - Character.getNumericValue(arg1.charAt(1)), charToIntMap.get(arg1.charAt(0))); <add> Position newPos = new Position(8 - Character.getNumericValue(arg2.charAt(1)), charToIntMap.get(arg2.charAt(0))); <add> model.movePiece(curPos, newPos); <add> <add> this.model.incrementTurnCount(); <add> this.model.switchWhosTurn(); <add> } catch (InvalidPositionException | IllegalArgumentException e) <add> { <add> model.setExceptionThrown(e); <add> } <add> } <add> <add> public void setView(TextView view) <add> { <ide> this.view = view; <ide> } <ide>
JavaScript
apache-2.0
9548bdcf69cdb978b747c358c6b368ad6700f464
0
TotallyInformation/node-red-contrib-uibuilder,TotallyInformation/node-red-contrib-uibuilder
/* eslint-disable class-methods-use-this, sonarjs/no-duplicate-string, max-params */ /** Manage Socket.IO on behalf of uibuilder * Singleton. only 1 instance of this class will ever exist. So it can be used in other modules within Node-RED. * * Copyright (c) 2017-2022 Julian Knight (Totally Information) * https://it.knightnet.org.uk, https://github.com/TotallyInformation/node-red-contrib-uibuilder * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict' /** --- Type Defs --- * @typedef {import('../../typedefs.js').runtimeRED} runtimeRED * @typedef {import('../../typedefs.js').MsgAuth} MsgAuth * @typedef {import('../../typedefs.js').uibNode} uibNode * @typedef {import('../../typedefs.js').uibConfig} uibConfig * @typedef {import('Express')} Express */ const path = require('path') const socketio = require('socket.io') const tilib = require('./tilib') // General purpose library (by Totally Information) const uiblib = require('./uiblib') // Utility library for uibuilder const security = require('./security') // uibuilder security module const tiEventManager = require('@totallyinformation/ti-common-event-handler') class UibSockets { // TODO: Replace _XXX with #XXX once node.js v14 is the minimum supported version /** Flag to indicate whether setup() has been run * @type {boolean} * @protected */ //_isConfigured = false /** Called when class is instantiated */ constructor() { // setup() has not yet been run this._isConfigured = false //#region ---- References to core Node-RED & uibuilder objects ---- // /** @type {runtimeRED} */ this.RED = undefined /** @type {uibConfig} Reference link to uibuilder.js global configuration object */ this.uib = undefined /** Reference to uibuilder's global log functions */ this.log = undefined /** Reference to ExpressJS server instance being used by uibuilder * Used to enable the Socket.IO client code to be served to the front-end */ this.server = undefined //#endregion ---- References to core Node-RED & uibuilder objects ---- // //#region ---- Common variables ---- // /** URI path for accessing the socket.io client from FE code. Based on the uib node instance URL. * @constant {string} uib_socketPath */ this.uib_socketPath = undefined /** An instance of Socket.IO Server */ this.io = undefined /** Collection of Socket.IO namespaces * Each namespace correstponds to a uibuilder node instance and must have a unique namespace name that matches the unique URL parameter for the node. * The namespace is stored in the this.ioNamespaces object against a property name matching the URL so that it can be referenced later. * Because this is a Singleton object, any reference to this module can access all of the namespaces (by url). * The namespace has some uib extensions that track the originating node id (searchable in Node-RED), the number of connected clients * and the number of messages recieved. * @type {!Object.<string, socketio.Namespace>} */ this.ioNamespaces = {} //#endregion ---- ---- // } // --- End of constructor() --- // /** Assign uibuilder and Node-RED core vars to Class static vars. * This makes them available wherever this MODULE is require'd. * Because JS passess objects by REFERENCE, updates to the original * variables means that these are updated as well. * @param {uibConfig} uib reference to uibuilder 'global' configuration object * @param {Express} server reference to ExpressJS server being used by uibuilder */ setup( uib, server ) { // Prevent setup from being called more than once if ( this._isConfigured === true ) { uib.RED.log.warn('[uibuilder:web:setup] Setup has already been called, it cannot be called again.') return } if ( ! uib || ! server ) { throw new Error(`[uibuilder:socket.js:setup] Called without required parameters. uib=${uib}, server=${server}`) } /** @type {runtimeRED} reference to Core Node-RED runtime object */ this.RED = uib.RED this.uib = uib this.log = uib.RED.log this.server = server // TODO: Replace _XXX with #XXX once node.js v14 is the minimum supported version this._socketIoSetup() this._isConfigured = true } // --- End of setup() --- // /** Holder for Socket.IO - we want this to survive redeployments of each node instance * so that existing clients can be reconnected. * Start Socket.IO - make sure the right version of SIO is used so keeping this separate from other * modules that might also use it (path). This is only needed ONCE for ALL uib.instances of this node. * Must only be run once and so is made an ECMA2018 private class method * @private */ _socketIoSetup() { // Reference static vars const uib = this.uib const RED = this.RED const log = this.log const server = this.server const uib_socketPath = this.uib_socketPath = tilib.urlJoin(uib.nodeRoot, uib.moduleName, 'vendor', 'socket.io') log.trace(`[uibuilder:socket:socketIoSetup] Socket.IO initialisation - Socket Path=${uib_socketPath}` ) // Socket.Io server options, see https://socket.io/docs/v4/server-options/ let ioOptions = { 'path': uib_socketPath, // Socket.Io 3+ CORS is disabled by default, also options have changed. // for CORS need to handle preflight request explicitly 'cause there's an // Allow-Headers:X-ClientId in there. see https://socket.io/docs/v4/handling-cors/ // handlePreflightRequest: (req, res) => { // res.writeHead(204, { // 'Access-Control-Allow-Origin': req.headers['origin'], // eslint-disable-line dot-notation // 'Access-Control-Allow-Methods': 'GET,POST', // 'Access-Control-Allow-Headers': 'X-ClientId', // 'Access-Control-Allow-Credentials': true, // }) // res.end() // }, } // Merge in overrides from settings.js if given. if ( RED.settings.uibuilder && RED.settings.uibuilder.sioOptions ) { ioOptions = Object.assign( {}, RED.settings.uibuilder.sioOptions, ioOptions ) } // @ts-ignore ts(2769) this.io = new socketio.Server(server, ioOptions) // listen === attach } // --- End of socketIoSetup() --- // /** Allow the isConfigured flag to be read (not written) externally * @returns {boolean} True if this class as been configured */ get isConfigured() { return this._isConfigured } //? Consider adding isConfigered checks on each method? /** Output a msg to the front-end. * @param {object} msg The message to output, include msg._socketId to send to a single client * @param {string} url THe uibuilder id * @param {string} channel Which channel to send to (see uib.ioChannels) */ sendToFe( msg, url, channel ) { const uib = this.uib const log = this.log const ioNs = this.ioNamespaces[url] let socketId = msg._socketId || undefined if ( channel === uib.ioChannels.control ) msg.from = 'server' //console.log('> > > > ', msg) // pass the complete msg object to the uibuilder client // TODO: This should have some safety validation on it! Also need to add security processing if (socketId !== undefined) { // Send to specific client // TODO ...If socketId not validated as having a current session, don't send log.trace(`[uibuilder:socket.js:sendToFe:${url}] msg sent on to client ${socketId}. Channel: ${channel}. ${JSON.stringify(msg)}`) ioNs.to(socketId).emit(channel, msg) } else { // Broadcast //? - is there any way to prevent sending to clients not logged in? log.trace(`[uibuilder:socket.js:sendToFe:${url}] msg sent on to ALL clients. Channel: ${channel}. ${JSON.stringify(msg)}`) //console.log('> > > > ', channel, ioNs.name, msg) ioNs.emit(channel, msg) } } // ---- End of sendToFe ---- // /** Output a normal msg to the front-end. WARNING: Cannot use uibuilder security on this because! Currently only used to send a reload msg to FE. * To add security, would need reference to node. When called from a uib api, the node isn't available. * @param {object} msg The message to output * @param {object} url The uibuilder instance url - will be unique. Used to lookup the correct Socket.IO namespace for sending. * @param {string=} socketId Optional. If included, only send to specific client id (mostly expecting this to be on msg._socketID so not often required) */ send(msg, url, socketId) { // eslint-disable-line class-methods-use-this const uib = this.uib const ioNs = this.ioNamespaces[url] if (socketId) msg._socketId = socketId // TODO: This should have some safety validation on it! if (msg._socketId) { // TODO If socketId not validated as having a current session, don't send this.log.trace(`[uibuilder:socket:send:${url}] msg sent on to client ${msg._socketId}. Channel: ${uib.ioChannels.server}. ${JSON.stringify(msg)}`) ioNs.to(msg._socketId).emit(uib.ioChannels.server, msg) } else { this.log.trace(`[uibuilder:socket:send:${url}] msg sent on to ALL clients. Channel: ${uib.ioChannels.server}. ${JSON.stringify(msg)}`) ioNs.emit(uib.ioChannels.server, msg) } } /** Get client details for JWT security check * @param {socketio.Socket} socket Reference to client socket connection * @returns {object} Extracted key information */ getClientDetails(socket) { // tilib.mylog('>>>>> ========================= <<<<<') // tilib.mylog('>>>>> remote address:', socket.request.connection.remoteAddress) // client ip address. May be IPv4 or v6 // tilib.mylog('>>>>> handshake secure:', socket.handshake.secure) // true if https/wss // // tilib.mylog('>>>>>', socket.handshake.time) // tilib.mylog('>>>>> handshake issued:', (new Date(socket.handshake.issued)).toISOString()) // when the client connected to the server // // tilib.mylog('>>>>>', socket.handshake.url) // tilib.mylog('>>>>> x-clientid:', socket.request.headers['x-clientid']) // = 'uibuilderfe' // tilib.mylog('>>>>> referer:', socket.request.headers.referer) // = uibuilder url // tilib.mylog('>>>>> ========================= <<<<<') return { /** Client remote IP address (v4 or v6) */ remoteAddress: socket.request.connection.remoteAddress, /** True if https/wss */ secure: socket.handshake.secure, /** When the client connected to the server */ connectedTimestamp: (new Date(socket.handshake.issued)).toISOString(), /** 'x-clientid' from headers. uibuilderfe sets this to 'uibuilderfe' */ clientId: socket.request.headers['x-clientid'], /** THe referring webpage, should be the full URL of the uibuilder page */ referer: socket.request.headers.referer, //url: socket.handshake.url } } /** Get a uib node instance namespace * @param {string} url The uibuilder node instance's url (identifier) * @returns {socketio.Namespace} Return a reference to the namespace of the specified uib instance for convenience in core code */ getNs(url) { return this.ioNamespaces[url] } /** Send a msg either directly out of the node instance OR via return event name * @param {object} msg Message object received from a client * @param {uibNode} node Reference to the uibuilder node instance */ sendIt(msg, node) { if ( msg._uib && msg._uib.originator ) { //const eventName = `node-red-contrib-uibuilder/return/${msg._uib.originator}` tiEventManager.emit(`node-red-contrib-uibuilder/return/${msg._uib.originator}`, msg) } else { node.send(msg) } } /** Socket listener fn for msgs from clients * @param {object} msg Message object received from a client * @param {socketio.Socket} socket Reference to the socket for this node * @param {uibNode} node Reference to the uibuilder node instance */ listenFromClient(msg, socket, node) { const log = this.log node.rcvMsgCount++ log.trace(`[uibuilder:socket:${node.url}] Data received from client, ID: ${socket.id}, Msg: ${JSON.stringify(msg)}`) // Make sure the incoming msg is a correctly formed Node-RED msg switch ( typeof msg ) { case 'string': case 'number': case 'boolean': msg = { 'topic': node.topic, 'payload': msg} } // If the sender hasn't added msg._socketId, add the Socket.id now if ( ! Object.prototype.hasOwnProperty.call(msg, '_socketId') ) msg._socketId = socket.id // If security is active... if (node.useSecurity === true) { /** Check for valid auth and session - JWT is removed if not authorised * @type {MsgAuth} */ msg._auth = security.authCheck2( msg, node, this.getClientDetails(socket) ) //msg._auth = security.authCheck(msg, node, socket.id) //msg._auth = uiblib.authCheck(msg, ioNs, node, socket.id, log, uib) //console.log('[UIBUILDER:addNs:on-client-msg] _auth: ', msg._auth) // Only send the msg onward if the user is validated or if unauth traffic permitted if ( node.allowUnauth === true || msg._auth.jwt !== undefined ) { this.sendIt(msg, node) tilib.mylog(`[uibuilder:socket.js:addNs:connection:on:client] Msg received from ${node.url} client but they are not authorised. But unauth traffic allowed.`) } else log.info(`[uibuilder:socket.js:addNs:connection:on:client] Msg received from ${node.url} client but they are not authorised. Ignoring.`) } else { // Send out the message for downstream flows // TODO: This should probably have safety validations! this.sendIt(msg, node) } } // ---- End of listenFromClient ---- // /** Add a new Socket.IO NAMESPACE * Each namespace correstponds to a uibuilder node instance and must have a unique namespace name that matches the unique URL parameter for the node. * The namespace is stored in the this.ioNamespaces object against a property name matching the URL so that it can be referenced later. * Because this is a Singleton object, any reference to this module can access all of the namespaces (by url). * The namespace has some uib extensions that track the originating node id (searchable in Node-RED), the number of connected clients * and the number of messages received. * @param {uibNode} node Reference to the uibuilder node instance */ addNS(node) { const log = this.log const uib = this.uib const ioNs = this.ioNamespaces[node.url] = this.io.of(node.url) // Add some additional metadata to NS const url = ioNs.url = node.url ioNs.nodeId = node.id // allows us to track back to the actual node in Node-RED ioNs.useSecurity = node.useSecurity // Is security on for this node instance? ioNs.rcvMsgCount = 0 ioNs.log = log // Make Node-RED's log available to middleware via custom ns property /** Check for <uibRoot>/.config/sioMiddleware.js, use it if present. * Applies ONCE on a new client connection. * Had to move to addNS since MW no longer globally loadable since sio v3 */ let sioMwPath = path.join(uib.configFolder, 'sioMiddleware.js') try { const sioMiddleware = require(sioMwPath) if ( typeof sioMiddleware === 'function' ) { ioNs.use(sioMiddleware) log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware loaded successfully for NS.`) } else { log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware failed to execute for NS - check that uibRoot/.config/sioMiddleware.js has a valid exported fn.`) } } catch (e) { log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware failed to load for NS. Reason: ${e.message}`) } const that = this ioNs.on('connection', function(socket) { //#region ----- Event Handlers ----- // // NOTE: as of sio v4, disconnect seems to be fired AFTER a connect when a client reconnects socket.on('disconnect', function(reason) { node.ioClientsCount = ioNs.sockets.size log.trace( `[uibuilder:socket:${url}:disconnect] Client disconnected, clientCount: ${ioNs.sockets.size}, Reason: ${reason}, ID: ${socket.id}, IP Addr: ${socket.handshake.address}, for node ${node.id}` ) node.statusDisplay.text = 'connected ' + ioNs.sockets.size uiblib.setNodeStatus( node ) // Let the control output port know a client has disconnected const ctrlMsg = { 'uibuilderCtrl': 'client disconnect', 'reason': reason, 'topic': node.topic || undefined, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference ctrlMsg.ip = socket.handshake.address node.send([null,ctrlMsg]) }) // --- End of on-connection::on-disconnect() --- // // Listen for msgs from clients only on specific input channels: socket.on(uib.ioChannels.client, function(msg) { that.listenFromClient(msg, socket, node ) }) // --- End of on-connection::on-incoming-client-msg() --- // socket.on(uib.ioChannels.control, function(msg) { node.rcvMsgCount++ log.trace(`[uibuilder:socket:${url}] Control Msg from client, ID: ${socket.id}, Msg: ${JSON.stringify(msg)}`) // Make sure the incoming msg is a correctly formed Node-RED msg switch ( typeof msg ) { case 'string': case 'number': case 'boolean': msg = { 'uibuilderCtrl': msg } } // If the sender hasn't added Socket.id, add it now if ( ! Object.prototype.hasOwnProperty.call(msg, '_socketId') ) msg._socketId = socket.id // @since 2017-11-05 v0.4.9 If the sender hasn't added msg.from, add it now if ( ! Object.prototype.hasOwnProperty.call(msg, 'from') ) msg.from = 'client' if ( ! msg.topic ) msg.topic = node.topic /** If an auth/logon/logoff msg, we need to process it directly (don't send on the msg in this case) */ if ( msg.uibuilderCtrl === 'logon') { //uiblib.logon(msg, ioNs, node, socket, log, uib) security.logon(msg, ioNs, node, socket) } else if ( msg.uibuilderCtrl === 'logoff') { //uiblib.logoff(msg, ioNs, node, socket, log, uib) security.logoff(msg, ioNs, node, socket.id) } else if ( msg.uibuilderCtrl === 'auth') { // 'auth' is sent by client after server sends 'client connect' or 'request for logon' if security is on /** * == Server receives 'auth' control message. Checks auth * 1. If auth is dummy * 1. => Send 'request for logon' to client * 1. ++ client must prompt user for logon * 2. <= Client must send 'auth' control message to server * 3. GOTO 1.0 * * 2. Otherwise * 1. == Server validates msg._auth (*1). Only succeeds if client was already auth and send a valid _auth with JWT (due to node redeploy since nr restart invalidates all JWT's). * 1. => Server returns either an 'auth succeded' or 'auth failed' message to client. * 2. If auth failed * 1. => Send 'request for logon' to client * 2. ++ client must prompt user for logon * 3. <= Client must send 'auth' control message to server * 4. GOTO 1.0 */ msg._auth = security.authCheck2(msg, node, that.getClientDetails(socket)) //! temp node.send([null,msg]) // Report success & send token to client & to port #2 //if ( msg._auth.userValidated === true ) { const ctrlMsg = { 'uibuilderCtrl': msg._auth.userValidated ? 'authorised' : 'not authorised', 'topic': msg.topic || node.topic || undefined, '_auth': msg._auth, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference node.send(null,msg) //} } else if (node.useSecurity === true) { // If security is active... /** Check for valid auth and session * @type {MsgAuth} */ msg._auth = security.authCheck2( msg, node, that.getClientDetails(socket) ) //msg._auth = security.authCheck(msg, node, socket.id) //msg._auth = uiblib.authCheck(msg, ioNs, node, socket.id, log, uib) // Only send the msg onward if the user is validated or if unauth traffic permitted or if the msg is the initial ready for content handshake. if ( node.allowUnauth === true || msg._auth.jwt !== undefined || msg.uibuilderCtrl === 'ready for content' ) { node.send([null,msg]) tilib.mylog(`[uibuilder:socket.js:addNs:connection:on:control] '${msg.uibuilderCtrl}' msg received from ${node.url} client but they are not authorised. But unauth traffic allowed.`) } else log.info(`[uibuilder:socket.js:addNs:connection:on:control] '${msg.uibuilderCtrl}' msg received from ${node.url} client but they are not authorised. Ignoring.`) } else { // Send out the message on port #2 for downstream flows node.send([null,msg]) } }) // --- End of on-connection::on-incoming-control-msg() --- // socket.on('error', function(err) { log.error(`[uibuilder:socket:addNs:${url}] ERROR received, ID: ${socket.id}, Reason: ${err.message}`) // Let the control output port know there has been an error const ctrlMsg = { 'uibuilderCtrl': 'socket error', 'error': err.message, 'topic': node.topic || undefined, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference node.send(null,msg) }) // --- End of on-connection::on-error() --- // //#endregion ----- Event Handlers ----- // node.ioClientsCount = ioNs.sockets.size log.trace( `[uibuilder:socket:addNS:${url}:connect] Client connected. ClientCount: ${ioNs.sockets.size}, Socket ID: ${socket.id}, IP Addr: ${socket.handshake.address}, for node ${node.id}` ) // Try to load the sioUse middleware function - sioUse applies to all incoming msgs try { const sioUseMw = require( path.join(uib.configFolder, uib.sioUseMwName) ) if ( typeof sioUseMw === 'function' ) { socket.use(sioUseMw) log.trace(`[uibuilder:socket:onConnect:${url}] sioUse Middleware loaded successfully for NS ${url}.`) } else { log.trace(`[uibuilder:socket:onConnect:${url}] sioUse Middleware failed to execute for NS ${url} - check that uibRoot/.config/sioUse.js has a valid exported fn.`) } } catch(e) { log.trace(`[uibuilder:socket:addNS:${url}] sioUse Failed to load Use middleware. Reason: ${e.message}`) } node.statusDisplay.text = `connected ${ioNs.sockets.size}` uiblib.setNodeStatus( node ) // Initial client connect message const msg = { 'uibuilderCtrl': 'client connect', 'serverTimestamp': (new Date()), 'topic': node.topic || undefined, 'security': node.useSecurity, // Let the client know whether to use security or not 'version': uib.version, // Let the front-end know what v of uib is in use '_socketId': socket.id, } // Let the clients (and output #2) know we are connecting that.sendToFe(msg, node.url, uib.ioChannels.control) // Copy to port#2 for reference msg.ip = socket.handshake.address node.send([null,msg]) }) // --- End of on-connection() --- // } // --- End of addNS() --- // /** Remove the current clients and namespace for this node. * Called from uiblib.processClose. * @param {uibNode} node Reference to the uibuilder node instance */ removeNS(node) { const ioNs = this.ioNamespaces[node.url] // Disconnect all connected sockets for this Namespace (Socket.io v4+) ioNs.disconnectSockets(true) ioNs.removeAllListeners() // Remove all Listeners for the event emitter // No longer works from socket.io v3+ //delete this.io.nsps[`/${node.url}`] // Remove from the server namespaces } // --- End of removeNS() --- // } // ==== End of UibSockets Class Definition ==== // /** Singleton model. Only 1 instance of UibSockets should ever exist. * Use as: `const sockets = require('./libs/socket.js')` * Wrap in try/catch to force out better error logging if there is a problem * Downside of this approach is that you cannot directly pass in parameters. Use the startup(...) method instead. */ try { // Wrap in a try in case any errors creep into the class let uibsockets = new UibSockets() module.exports = uibsockets } catch (e) { console.error(`[uibuilder:socket.js] Unable to create class instance. Error: ${e.message}`) } // EOF
nodes/libs/socket.js
/* eslint-disable class-methods-use-this, sonarjs/no-duplicate-string, max-params */ /** Manage Socket.IO on behalf of uibuilder * Singleton. only 1 instance of this class will ever exist. So it can be used in other modules within Node-RED. * * Copyright (c) 2017-2022 Julian Knight (Totally Information) * https://it.knightnet.org.uk, https://github.com/TotallyInformation/node-red-contrib-uibuilder * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict' /** --- Type Defs --- * @typedef {import('../../typedefs.js').runtimeRED} runtimeRED * @typedef {import('../../typedefs.js').MsgAuth} MsgAuth * @typedef {import('../../typedefs.js').uibNode} uibNode * @typedef {import('../../typedefs.js').uibConfig} uibConfig * @typedef {import('Express')} Express */ const path = require('path') const socketio = require('socket.io') const tilib = require('./tilib') // General purpose library (by Totally Information) const uiblib = require('./uiblib') // Utility library for uibuilder const security = require('./security') // uibuilder security module const tiEventManager = require('@totallyinformation/ti-common-event-handler') class UibSockets { // TODO: Replace _XXX with #XXX once node.js v14 is the minimum supported version /** Flag to indicate whether setup() has been run * @type {boolean} * @protected */ //_isConfigured = false /** Called when class is instantiated */ constructor() { // setup() has not yet been run this._isConfigured = false //#region ---- References to core Node-RED & uibuilder objects ---- // /** @type {runtimeRED} */ this.RED = undefined /** @type {uibConfig} Reference link to uibuilder.js global configuration object */ this.uib = undefined /** Reference to uibuilder's global log functions */ this.log = undefined /** Reference to ExpressJS server instance being used by uibuilder * Used to enable the Socket.IO client code to be served to the front-end */ this.server = undefined //#endregion ---- References to core Node-RED & uibuilder objects ---- // //#region ---- Common variables ---- // /** URI path for accessing the socket.io client from FE code. Based on the uib node instance URL. * @constant {string} uib_socketPath */ this.uib_socketPath = undefined /** An instance of Socket.IO Server */ this.io = undefined /** Collection of Socket.IO namespaces * Each namespace correstponds to a uibuilder node instance and must have a unique namespace name that matches the unique URL parameter for the node. * The namespace is stored in the this.ioNamespaces object against a property name matching the URL so that it can be referenced later. * Because this is a Singleton object, any reference to this module can access all of the namespaces (by url). * The namespace has some uib extensions that track the originating node id (searchable in Node-RED), the number of connected clients * and the number of messages recieved. * @type {!Object.<string, socketio.Namespace>} */ this.ioNamespaces = {} //#endregion ---- ---- // } // --- End of constructor() --- // /** Assign uibuilder and Node-RED core vars to Class static vars. * This makes them available wherever this MODULE is require'd. * Because JS passess objects by REFERENCE, updates to the original * variables means that these are updated as well. * @param {uibConfig} uib reference to uibuilder 'global' configuration object * @param {Express} server reference to ExpressJS server being used by uibuilder */ setup( uib, server ) { // Prevent setup from being called more than once if ( this._isConfigured === true ) { uib.RED.log.warn('[uibuilder:web:setup] Setup has already been called, it cannot be called again.') return } if ( ! uib || ! server ) { throw new Error(`[uibuilder:socket.js:setup] Called without required parameters. uib=${uib}, server=${server}`) } /** @type {runtimeRED} reference to Core Node-RED runtime object */ this.RED = uib.RED this.uib = uib this.log = uib.RED.log this.server = server // TODO: Replace _XXX with #XXX once node.js v14 is the minimum supported version this._socketIoSetup() this._isConfigured = true } // --- End of setup() --- // /** Holder for Socket.IO - we want this to survive redeployments of each node instance * so that existing clients can be reconnected. * Start Socket.IO - make sure the right version of SIO is used so keeping this separate from other * modules that might also use it (path). This is only needed ONCE for ALL uib.instances of this node. * Must only be run once and so is made an ECMA2018 private class method * @private */ _socketIoSetup() { // Reference static vars const uib = this.uib const RED = this.RED const log = this.log const server = this.server const uib_socketPath = this.uib_socketPath = tilib.urlJoin(uib.nodeRoot, uib.moduleName, 'vendor', 'socket.io') log.trace(`[uibuilder:socket:socketIoSetup] Socket.IO initialisation - Socket Path=${uib_socketPath}` ) // Socket.Io server options, see https://socket.io/docs/v4/server-options/ let ioOptions = { 'path': uib_socketPath, // Socket.Io 3+ CORS is disabled by default, also options have changed. // for CORS need to handle preflight request explicitly 'cause there's an // Allow-Headers:X-ClientId in there. see https://socket.io/docs/v4/handling-cors/ // handlePreflightRequest: (req, res) => { // res.writeHead(204, { // 'Access-Control-Allow-Origin': req.headers['origin'], // eslint-disable-line dot-notation // 'Access-Control-Allow-Methods': 'GET,POST', // 'Access-Control-Allow-Headers': 'X-ClientId', // 'Access-Control-Allow-Credentials': true, // }) // res.end() // }, } // Merge in overrides from settings.js if given. if ( RED.settings.uibuilder && RED.settings.uibuilder.sioOptions ) { ioOptions = Object.assign( {}, RED.settings.uibuilder.sioOptions, ioOptions ) } // @ts-ignore ts(2769) this.io = new socketio.Server(server, ioOptions) // listen === attach } // --- End of socketIoSetup() --- // /** Allow the isConfigured flag to be read (not written) externally * @returns {boolean} True if this class as been configured */ get isConfigured() { return this._isConfigured } //? Consider adding isConfigered checks on each method? /** Output a msg to the front-end. * @param {object} msg The message to output, include msg._socketId to send to a single client * @param {string} url THe uibuilder id * @param {string} channel Which channel to send to (see uib.ioChannels) */ sendToFe( msg, url, channel ) { const uib = this.uib const log = this.log const ioNs = this.ioNamespaces[url] let socketId = msg._socketId || undefined if ( channel === uib.ioChannels.control ) msg.from = 'server' //console.log('> > > > ', msg) // pass the complete msg object to the uibuilder client // TODO: This should have some safety validation on it! Also need to add security processing if (socketId !== undefined) { // Send to specific client // TODO ...If socketId not validated as having a current session, don't send log.trace(`[uibuilder:socket.js:sendToFe:${url}] msg sent on to client ${socketId}. Channel: ${channel}. ${JSON.stringify(msg)}`) ioNs.to(socketId).emit(channel, msg) } else { // Broadcast //? - is there any way to prevent sending to clients not logged in? log.trace(`[uibuilder:socket.js:sendToFe:${url}] msg sent on to ALL clients. Channel: ${channel}. ${JSON.stringify(msg)}`) //console.log('> > > > ', channel, ioNs.name, msg) ioNs.emit(channel, msg) } } // ---- End of sendToFe ---- // /** Output a normal msg to the front-end. WARNING: Cannot use uibuilder security on this because! Currently only used to send a reload msg to FE. * To add security, would need reference to node. When called from a uib api, the node isn't available. * @param {object} msg The message to output * @param {object} url The uibuilder instance url - will be unique. Used to lookup the correct Socket.IO namespace for sending. * @param {string=} socketId Optional. If included, only send to specific client id (mostly expecting this to be on msg._socketID so not often required) */ send(msg, url, socketId) { // eslint-disable-line class-methods-use-this const uib = this.uib const ioNs = this.ioNamespaces[url] if (socketId) msg._socketId = socketId // TODO: This should have some safety validation on it! if (msg._socketId) { // TODO If socketId not validated as having a current session, don't send this.log.trace(`[uibuilder:socket:send:${url}] msg sent on to client ${msg._socketId}. Channel: ${uib.ioChannels.server}. ${JSON.stringify(msg)}`) ioNs.to(msg._socketId).emit(uib.ioChannels.server, msg) } else { this.log.trace(`[uibuilder:socket:send:${url}] msg sent on to ALL clients. Channel: ${uib.ioChannels.server}. ${JSON.stringify(msg)}`) ioNs.emit(uib.ioChannels.server, msg) } } /** Get client details for JWT security check * @param {socketio.Socket} socket Reference to client socket connection * @returns {object} Extracted key information */ getClientDetails(socket) { // tilib.mylog('>>>>> ========================= <<<<<') // tilib.mylog('>>>>> remote address:', socket.request.connection.remoteAddress) // client ip address. May be IPv4 or v6 // tilib.mylog('>>>>> handshake secure:', socket.handshake.secure) // true if https/wss // // tilib.mylog('>>>>>', socket.handshake.time) // tilib.mylog('>>>>> handshake issued:', (new Date(socket.handshake.issued)).toISOString()) // when the client connected to the server // // tilib.mylog('>>>>>', socket.handshake.url) // tilib.mylog('>>>>> x-clientid:', socket.request.headers['x-clientid']) // = 'uibuilderfe' // tilib.mylog('>>>>> referer:', socket.request.headers.referer) // = uibuilder url // tilib.mylog('>>>>> ========================= <<<<<') return { /** Client remote IP address (v4 or v6) */ remoteAddress: socket.request.connection.remoteAddress, /** True if https/wss */ secure: socket.handshake.secure, /** When the client connected to the server */ connectedTimestamp: (new Date(socket.handshake.issued)).toISOString(), /** 'x-clientid' from headers. uibuilderfe sets this to 'uibuilderfe' */ clientId: socket.request.headers['x-clientid'], /** THe referring webpage, should be the full URL of the uibuilder page */ referer: socket.request.headers.referer, //url: socket.handshake.url } } /** Get a uib node instance namespace * @param {string} url The uibuilder node instance's url (identifier) * @returns {socketio.Namespace} Return a reference to the namespace of the specified uib instance for convenience in core code */ getNs(url) { return this.ioNamespaces[url] } /** Send a msg either directly out of the node instance OR via return event name * @param {object} msg Message object received from a client * @param {uibNode} node Reference to the uibuilder node instance */ sendIt(msg, node) { if ( msg._uib && msg._uib.originator ) { //const eventName = `node-red-contrib-uibuilder/return/${msg._uib.originator}` tiEventManager.emit(`node-red-contrib-uibuilder/return/${msg._uib.originator}`, msg) } else { node.send(msg) } } /** Socket listener fn for msgs from clients * @param {object} msg Message object received from a client * @param {socketio.Socket} socket Reference to the socket for this node * @param {uibNode} node Reference to the uibuilder node instance */ listenFromClient(msg, socket, node) { const log = this.log node.rcvMsgCount++ log.trace(`[uibuilder:socket:${node.url}] Data received from client, ID: ${socket.id}, Msg: ${JSON.stringify(msg)}`) // Make sure the incoming msg is a correctly formed Node-RED msg switch ( typeof msg ) { case 'string': case 'number': case 'boolean': msg = { 'topic': node.topic, 'payload': msg} } // If the sender hasn't added msg._socketId, add the Socket.id now if ( ! Object.prototype.hasOwnProperty.call(msg, '_socketId') ) msg._socketId = socket.id // If security is active... if (node.useSecurity === true) { /** Check for valid auth and session - JWT is removed if not authorised * @type {MsgAuth} */ msg._auth = security.authCheck2( msg, node, this.getClientDetails(socket) ) //msg._auth = security.authCheck(msg, node, socket.id) //msg._auth = uiblib.authCheck(msg, ioNs, node, socket.id, log, uib) //console.log('[UIBUILDER:addNs:on-client-msg] _auth: ', msg._auth) // Only send the msg onward if the user is validated or if unauth traffic permitted if ( node.allowUnauth === true || msg._auth.jwt !== undefined ) { this.sendIt(msg, node) tilib.mylog(`[uibuilder:socket.js:addNs:connection:on:client] Msg received from ${node.url} client but they are not authorised. But unauth traffic allowed.`) } else log.info(`[uibuilder:socket.js:addNs:connection:on:client] Msg received from ${node.url} client but they are not authorised. Ignoring.`) } else { // Send out the message for downstream flows // TODO: This should probably have safety validations! this.sendIt(msg, node) } } // ---- End of listenFromClient ---- // /** Add a new Socket.IO NAMESPACE * Each namespace correstponds to a uibuilder node instance and must have a unique namespace name that matches the unique URL parameter for the node. * The namespace is stored in the this.ioNamespaces object against a property name matching the URL so that it can be referenced later. * Because this is a Singleton object, any reference to this module can access all of the namespaces (by url). * The namespace has some uib extensions that track the originating node id (searchable in Node-RED), the number of connected clients * and the number of messages received. * @param {uibNode} node Reference to the uibuilder node instance */ addNS(node) { const log = this.log const uib = this.uib const ioNs = this.ioNamespaces[node.url] = this.io.of(node.url) // Add some additional metadata to NS const url = ioNs.url = node.url ioNs.nodeId = node.id // allows us to track back to the actual node in Node-RED ioNs.useSecurity = node.useSecurity // Is security on for this node instance? ioNs.rcvMsgCount = 0 ioNs.log = log // Make Node-RED's log available to middleware via custom ns property /** Check for <uibRoot>/.config/sioMiddleware.js, use it if present. * Applies ONCE on a new client connection. * Had to move to addNS since MW no longer globally loadable since sio v3 */ let sioMwPath = path.join(uib.configFolder, 'sioMiddleware.js') try { const sioMiddleware = require(sioMwPath) if ( typeof sioMiddleware === 'function' ) { ioNs.use(sioMiddleware) log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware loaded successfully for NS.`) } else { log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware failed to execute for NS - check that uibRoot/.config/sioMiddleware.js has a valid exported fn.`) } } catch (e) { log.trace(`[uibuilder:socket:addNs:${url}] Socket.IO Middleware failed to load for NS. Reason: ${e.message}`) } const that = this ioNs.on('connection', function(socket) { //#region ----- Event Handlers ----- // // NOTE: as of sio v4, disconnect seems to be fired AFTER a connect when a client reconnects socket.on('disconnect', function(reason) { node.ioClientsCount = ioNs.sockets.size log.trace( `[uibuilder:socket:${url}:disconnect] Client disconnected, clientCount: ${ioNs.sockets.size}, Reason: ${reason}, ID: ${socket.id}, IP Addr: ${socket.handshake.address}, for node ${node.id}` ) node.statusDisplay.text = 'connected ' + ioNs.sockets.size uiblib.setNodeStatus( node ) // Let the control output port know a client has disconnected const ctrlMsg = { 'uibuilderCtrl': 'client disconnect', 'reason': reason, 'topic': node.topic || undefined, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference ctrlMsg.ip = socket.handshake.address node.send([null,ctrlMsg]) }) // --- End of on-connection::on-disconnect() --- // // Listen for msgs from clients only on specific input channels: socket.on(uib.ioChannels.client, function(msg) { that.listenFromClient(msg, socket, node ) }) // --- End of on-connection::on-incoming-client-msg() --- // socket.on(uib.ioChannels.control, function(msg) { node.rcvMsgCount++ log.trace(`[uibuilder:socket:${url}] Control Msg from client, ID: ${socket.id}, Msg: ${JSON.stringify(msg)}`) // Make sure the incoming msg is a correctly formed Node-RED msg switch ( typeof msg ) { case 'string': case 'number': case 'boolean': msg = { 'uibuilderCtrl': msg } } // If the sender hasn't added Socket.id, add it now if ( ! Object.prototype.hasOwnProperty.call(msg, '_socketId') ) msg._socketId = socket.id // @since 2017-11-05 v0.4.9 If the sender hasn't added msg.from, add it now if ( ! Object.prototype.hasOwnProperty.call(msg, 'from') ) msg.from = 'client' if ( ! msg.topic ) msg.topic = node.topic /** If an auth/logon/logoff msg, we need to process it directly (don't send on the msg in this case) */ if ( msg.uibuilderCtrl === 'logon') { //uiblib.logon(msg, ioNs, node, socket, log, uib) security.logon(msg, ioNs, node, socket) } else if ( msg.uibuilderCtrl === 'logoff') { //uiblib.logoff(msg, ioNs, node, socket, log, uib) security.logoff(msg, ioNs, node, socket.id) } else if ( msg.uibuilderCtrl === 'auth') { // 'auth' is sent by client after server sends 'client connect' or 'request for logon' if security is on /** * == Server receives 'auth' control message. Checks auth * 1. If auth is dummy * 1. => Send 'request for logon' to client * 1. ++ client must prompt user for logon * 2. <= Client must send 'auth' control message to server * 3. GOTO 1.0 * * 2. Otherwise * 1. == Server validates msg._auth (*1). Only succeeds if client was already auth and send a valid _auth with JWT (due to node redeploy since nr restart invalidates all JWT's). * 1. => Server returns either an 'auth succeded' or 'auth failed' message to client. * 2. If auth failed * 1. => Send 'request for logon' to client * 2. ++ client must prompt user for logon * 3. <= Client must send 'auth' control message to server * 4. GOTO 1.0 */ msg._auth = security.authCheck2(msg, node, that.getClientDetails(socket)) //! temp node.send([null,msg]) // Report success & send token to client & to port #2 //if ( msg._auth.userValidated === true ) { const ctrlMsg = { 'uibuilderCtrl': msg._auth.userValidated ? 'authorised' : 'not authorised', 'topic': msg.topic || node.topic || undefined, '_auth': msg._auth, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference node.send(null,msg) //} } else if (node.useSecurity === true) { // If security is active... /** Check for valid auth and session * @type {MsgAuth} */ msg._auth = security.authCheck2( msg, node, that.getClientDetails(socket) ) //msg._auth = security.authCheck(msg, node, socket.id) //msg._auth = uiblib.authCheck(msg, ioNs, node, socket.id, log, uib) // Only send the msg onward if the user is validated or if unauth traffic permitted or if the msg is the initial ready for content handshake. if ( node.allowUnauth === true || msg._auth.jwt !== undefined || msg.uibuilderCtrl === 'ready for content' ) { node.send([null,msg]) tilib.mylog(`[uibuilder:socket.js:addNs:connection:on:control] '${msg.uibuilderCtrl}' msg received from ${node.url} client but they are not authorised. But unauth traffic allowed.`) } else log.info(`[uibuilder:socket.js:addNs:connection:on:control] '${msg.uibuilderCtrl}' msg received from ${node.url} client but they are not authorised. Ignoring.`) } else { // Send out the message on port #2 for downstream flows node.send([null,msg]) } }) // --- End of on-connection::on-incoming-control-msg() --- // socket.on('error', function(err) { log.error(`[uibuilder:socket:addNs:${url}] ERROR received, ID: ${socket.id}, Reason: ${err.message}`) // Let the control output port know there has been an error const ctrlMsg = { 'uibuilderCtrl': 'socket error', 'error': err.message, 'topic': node.topic || undefined, '_socketId': socket.id, } that.sendToFe(ctrlMsg, node.url, uib.ioChannels.control) // Copy to port#2 for reference node.send(null,msg) }) // --- End of on-connection::on-error() --- // //#endregion ----- Event Handlers ----- // node.ioClientsCount = ioNs.sockets.size console.log('>> cookies >>', socket.handshake) log.trace( `[uibuilder:socket:addNS:${url}:connect] Client connected. ClientCount: ${ioNs.sockets.size}, Socket ID: ${socket.id}, IP Addr: ${socket.handshake.address}, for node ${node.id}` ) // Try to load the sioUse middleware function - sioUse applies to all incoming msgs try { const sioUseMw = require( path.join(uib.configFolder, uib.sioUseMwName) ) if ( typeof sioUseMw === 'function' ) { socket.use(sioUseMw) log.trace(`[uibuilder:socket:onConnect:${url}] sioUse Middleware loaded successfully for NS ${url}.`) } else { log.trace(`[uibuilder:socket:onConnect:${url}] sioUse Middleware failed to execute for NS ${url} - check that uibRoot/.config/sioUse.js has a valid exported fn.`) } } catch(e) { log.trace(`[uibuilder:socket:addNS:${url}] sioUse Failed to load Use middleware. Reason: ${e.message}`) } node.statusDisplay.text = 'connected ' + ioNs.sockets.size uiblib.setNodeStatus( node ) // Initial client connect message const msg = { 'uibuilderCtrl': 'client connect', 'serverTimestamp': (new Date()), 'topic': node.topic || undefined, 'security': node.useSecurity, // Let the client know whether to use security or not 'version': uib.version, // Let the front-end know what v of uib is in use '_socketId': socket.id, } // Let the clients (and output #2) know we are connecting that.sendToFe(msg, node.url, uib.ioChannels.control) //ioNs.emit( uib.ioChannels.control, { 'uibuilderCtrl': 'server connected', 'debug': node.debugFE } ) // Copy to port#2 for reference msg.ip = socket.handshake.address node.send([null,msg]) }) // --- End of on-connection() --- // } // --- End of addNS() --- // /** Remove the current clients and namespace for this node. * Called from uiblib.processClose. * @param {uibNode} node Reference to the uibuilder node instance */ removeNS(node) { const ioNs = this.ioNamespaces[node.url] // Disconnect all connected sockets for this Namespace (Socket.io v4+) ioNs.disconnectSockets(true) ioNs.removeAllListeners() // Remove all Listeners for the event emitter // No longer works from socket.io v3+ //delete this.io.nsps[`/${node.url}`] // Remove from the server namespaces } // --- End of removeNS() --- // } // ==== End of UibSockets Class Definition ==== // /** Singleton model. Only 1 instance of UibSockets should ever exist. * Use as: `const sockets = require('./libs/socket.js')` * Wrap in try/catch to force out better error logging if there is a problem * Downside of this approach is that you cannot directly pass in parameters. Use the startup(...) method instead. */ try { // Wrap in a try in case any errors creep into the class let uibsockets = new UibSockets() module.exports = uibsockets } catch (e) { console.error(`[uibuilder:socket.js] Unable to create class instance. Error: ${e.message}`) } // EOF
Tidy code
nodes/libs/socket.js
Tidy code
<ide><path>odes/libs/socket.js <ide> <ide> node.ioClientsCount = ioNs.sockets.size <ide> <del> console.log('>> cookies >>', socket.handshake) <del> <ide> log.trace( <ide> `[uibuilder:socket:addNS:${url}:connect] Client connected. ClientCount: ${ioNs.sockets.size}, Socket ID: ${socket.id}, IP Addr: ${socket.handshake.address}, for node ${node.id}` <ide> ) <ide> log.trace(`[uibuilder:socket:addNS:${url}] sioUse Failed to load Use middleware. Reason: ${e.message}`) <ide> } <ide> <del> node.statusDisplay.text = 'connected ' + ioNs.sockets.size <add> node.statusDisplay.text = `connected ${ioNs.sockets.size}` <ide> uiblib.setNodeStatus( node ) <ide> <ide> // Initial client connect message <ide> <ide> // Let the clients (and output #2) know we are connecting <ide> that.sendToFe(msg, node.url, uib.ioChannels.control) <del> //ioNs.emit( uib.ioChannels.control, { 'uibuilderCtrl': 'server connected', 'debug': node.debugFE } ) <ide> <ide> // Copy to port#2 for reference <ide> msg.ip = socket.handshake.address
Java
apache-2.0
772b41e335664a9904f7c8a81aafe064b9746f70
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.move.moveFilesOrDirectories; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.RefactoringSettings; import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler; import com.intellij.refactoring.move.MoveCallback; import com.intellij.refactoring.move.MoveHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; public class MoveFilesOrDirectoriesUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil"); private MoveFilesOrDirectoriesUtil() { } /** * Moves the specified directory to the specified parent directory. Does not process non-code usages! * * @param dir the directory to move. * @param newParentDir the directory to move {@code dir} into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void doMoveDirectory(final PsiDirectory aDirectory, final PsiDirectory destDirectory) throws IncorrectOperationException { PsiManager manager = aDirectory.getManager(); // do actual move checkMove(aDirectory, destDirectory); try { aDirectory.getVirtualFile().move(manager, destDirectory.getVirtualFile()); } catch (IOException e) { throw new IncorrectOperationException(e); } DumbService.getInstance(manager.getProject()).completeJustSubmittedTasks(); } /** * Moves the specified file to the specified directory. Does not process non-code usages! file may be invalidated, need to be refreshed before use, like {@code newDirectory.findFile(file.getName())} * * @param file the file to move. * @param newDirectory the directory to move the file into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void doMoveFile(@NotNull PsiFile file, @NotNull PsiDirectory newDirectory) throws IncorrectOperationException { // the class is already there, this is true when multiple classes are defined in the same file if (!newDirectory.equals(file.getContainingDirectory())) { // do actual move checkMove(file, newDirectory); VirtualFile vFile = file.getVirtualFile(); if (vFile == null) { throw new IncorrectOperationException("Non-physical file: " + file + " (" + file.getClass() + ")"); } try { vFile.move(file.getManager(), newDirectory.getVirtualFile()); } catch (IOException e) { throw new IncorrectOperationException(e); } } } /** * @param elements should contain PsiDirectories or PsiFiles only */ public static void doMove(final Project project, final PsiElement[] elements, final PsiElement[] targetElement, final MoveCallback moveCallback) { doMove(project, elements, targetElement, moveCallback, null); } /** * @param elements should contain PsiDirectories or PsiFiles only if adjustElements == null */ public static void doMove(final Project project, final PsiElement[] elements, final PsiElement[] targetElement, final MoveCallback moveCallback, final Function<PsiElement[], PsiElement[]> adjustElements) { if (adjustElements == null) { for (PsiElement element : elements) { if (!(element instanceof PsiFile) && !(element instanceof PsiDirectory)) { throw new IllegalArgumentException("unexpected element type: " + element); } } } final PsiDirectory targetDirectory = resolveToDirectory(project, targetElement[0]); if (targetElement[0] != null && targetDirectory == null) return; final PsiElement[] newElements = adjustElements != null ? adjustElements.fun(elements) : elements; final PsiDirectory initialTargetDirectory = getInitialTargetDirectory(targetDirectory, elements); final MoveFilesOrDirectoriesDialog.Callback doRun = new MoveFilesOrDirectoriesDialog.Callback() { @Override public void run(final MoveFilesOrDirectoriesDialog moveDialog) { CommandProcessor.getInstance().executeCommand(project, () -> { final PsiDirectory targetDirectory1 = moveDialog != null ? moveDialog.getTargetDirectory() : initialTargetDirectory; if (targetDirectory1 == null) { LOG.error("It is null! The target directory, it is null!"); return; } Collection<PsiElement> toCheck = ContainerUtil.newArrayList((PsiElement)targetDirectory1); for (PsiElement e : newElements) { toCheck.add(e instanceof PsiFileSystemItem && e.getParent() != null ? e.getParent() : e); } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, toCheck, false)) { return; } targetElement[0] = targetDirectory1; try { final int[] choice = elements.length > 1 || elements[0] instanceof PsiDirectory ? new int[]{-1} : null; final List<PsiElement> els = new ArrayList<>(); for (final PsiElement psiElement : newElements) { if (psiElement instanceof PsiFile) { final PsiFile file = (PsiFile)psiElement; if (CopyFilesOrDirectoriesHandler.checkFileExist(targetDirectory1, choice, file, file.getName(), "Move")) continue; } checkMove(psiElement, targetDirectory1); els.add(psiElement); } final Runnable callback = () -> { if (moveDialog != null) moveDialog.close(DialogWrapper.CANCEL_EXIT_CODE); }; if (els.isEmpty()) { callback.run(); return; } new MoveFilesOrDirectoriesProcessor(project, els.toArray(PsiElement.EMPTY_ARRAY), targetDirectory1, RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE, false, false, moveCallback, callback).run(); } catch (IncorrectOperationException e) { CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), "refactoring.moveFile", project); } }, MoveHandler.REFACTORING_NAME, null); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { doRun.run(null); } else { final MoveFilesOrDirectoriesDialog moveDialog = new MoveFilesOrDirectoriesDialog(project, doRun); moveDialog.setData(newElements, initialTargetDirectory, "refactoring.moveFile"); moveDialog.show(); } } @Nullable public static PsiDirectory resolveToDirectory(final Project project, final PsiElement element) { if (!(element instanceof PsiDirectoryContainer)) { return (PsiDirectory)element; } PsiDirectory[] directories = ((PsiDirectoryContainer)element).getDirectories(); switch (directories.length) { case 0: return null; case 1: return directories[0]; default: return DirectoryChooserUtil.chooseDirectory(directories, directories[0], project, new HashMap<>()); } } @Nullable private static PsiDirectory getCommonDirectory(PsiElement[] movedElements) { PsiDirectory commonDirectory = null; for (PsiElement movedElement : movedElements) { final PsiDirectory containingDirectory; if (movedElement instanceof PsiDirectory) { containingDirectory = ((PsiDirectory)movedElement).getParentDirectory(); } else { final PsiFile containingFile = movedElement.getContainingFile(); containingDirectory = containingFile == null ? null : containingFile.getContainingDirectory(); } if (containingDirectory != null) { if (commonDirectory == null) { commonDirectory = containingDirectory; } else { if (commonDirectory != containingDirectory) { return null; } } } } return commonDirectory; } @Nullable public static PsiDirectory getInitialTargetDirectory(PsiDirectory initialTargetElement, final PsiElement[] movedElements) { PsiDirectory initialTargetDirectory = initialTargetElement; if (initialTargetDirectory == null) { if (movedElements != null) { final PsiDirectory commonDirectory = getCommonDirectory(movedElements); if (commonDirectory != null) { initialTargetDirectory = commonDirectory; } else { initialTargetDirectory = getContainerDirectory(movedElements[0]); } } } return initialTargetDirectory; } @Nullable private static PsiDirectory getContainerDirectory(final PsiElement psiElement) { if (psiElement instanceof PsiDirectory) { return (PsiDirectory)psiElement; } else if (psiElement != null) { PsiFile containingFile = psiElement.getContainingFile(); if (containingFile != null) { return containingFile.getContainingDirectory(); } } return null; } /** * Checks if it is possible to move the specified PSI element under the specified container, * and throws an exception if the move is not possible. Does not actually modify anything. * * @param element the element to check the move possibility. * @param newContainer the target container element to move into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void checkMove(@NotNull PsiElement element, @NotNull PsiElement newContainer) throws IncorrectOperationException { if (element instanceof PsiDirectoryContainer) { PsiDirectory[] dirs = ((PsiDirectoryContainer)element).getDirectories(); if (dirs.length == 0) { throw new IncorrectOperationException(); } else if (dirs.length > 1) { throw new IncorrectOperationException( "Moving of packages represented by more than one physical directory is not supported."); } checkMove(dirs[0], newContainer); return; } //element.checkDelete(); //move != delete + add newContainer.checkAdd(element); checkIfMoveIntoSelf(element, newContainer); } public static void checkIfMoveIntoSelf(PsiElement element, PsiElement newContainer) throws IncorrectOperationException { PsiElement container = newContainer; while (container != null) { if (container == element) { if (element instanceof PsiDirectory) { if (element == newContainer) { throw new IncorrectOperationException("Cannot place directory into itself."); } else { throw new IncorrectOperationException("Cannot place directory into its subdirectory."); } } else { throw new IncorrectOperationException(); } } container = container.getParent(); } } }
platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.refactoring.move.moveFilesOrDirectories; import com.intellij.ide.util.DirectoryChooserUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.RefactoringSettings; import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler; import com.intellij.refactoring.move.MoveCallback; import com.intellij.refactoring.move.MoveHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.util.Function; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; public class MoveFilesOrDirectoriesUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil"); private MoveFilesOrDirectoriesUtil() { } /** * Moves the specified directory to the specified parent directory. Does not process non-code usages! * * @param dir the directory to move. * @param newParentDir the directory to move {@code dir} into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void doMoveDirectory(final PsiDirectory aDirectory, final PsiDirectory destDirectory) throws IncorrectOperationException { PsiManager manager = aDirectory.getManager(); // do actual move checkMove(aDirectory, destDirectory); try { aDirectory.getVirtualFile().move(manager, destDirectory.getVirtualFile()); } catch (IOException e) { throw new IncorrectOperationException(e); } DumbService.getInstance(manager.getProject()).completeJustSubmittedTasks(); } /** * Moves the specified file to the specified directory. Does not process non-code usages! file may be invalidated, need to be refreshed before use, like {@code newDirectory.findFile(file.getName())} * * @param file the file to move. * @param newDirectory the directory to move the file into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void doMoveFile(@NotNull PsiFile file, @NotNull PsiDirectory newDirectory) throws IncorrectOperationException { // the class is already there, this is true when multiple classes are defined in the same file if (!newDirectory.equals(file.getContainingDirectory())) { // do actual move checkMove(file, newDirectory); VirtualFile vFile = file.getVirtualFile(); if (vFile == null) { throw new IncorrectOperationException("Non-physical file: " + file + " (" + file.getClass() + ")"); } try { vFile.move(file.getManager(), newDirectory.getVirtualFile()); } catch (IOException e) { throw new IncorrectOperationException(e); } } } /** * @param elements should contain PsiDirectories or PsiFiles only */ public static void doMove(final Project project, final PsiElement[] elements, final PsiElement[] targetElement, final MoveCallback moveCallback) { doMove(project, elements, targetElement, moveCallback, null); } /** * @param elements should contain PsiDirectories or PsiFiles only if adjustElements == null */ public static void doMove(final Project project, final PsiElement[] elements, final PsiElement[] targetElement, final MoveCallback moveCallback, final Function<PsiElement[], PsiElement[]> adjustElements) { if (adjustElements == null) { for (PsiElement element : elements) { if (!(element instanceof PsiFile) && !(element instanceof PsiDirectory)) { throw new IllegalArgumentException("unexpected element type: " + element); } } } final PsiDirectory targetDirectory = resolveToDirectory(project, targetElement[0]); if (targetElement[0] != null && targetDirectory == null) return; final PsiElement[] newElements = adjustElements != null ? adjustElements.fun(elements) : elements; final PsiDirectory initialTargetDirectory = getInitialTargetDirectory(targetDirectory, elements); final MoveFilesOrDirectoriesDialog.Callback doRun = new MoveFilesOrDirectoriesDialog.Callback() { @Override public void run(final MoveFilesOrDirectoriesDialog moveDialog) { CommandProcessor.getInstance().executeCommand(project, () -> { final PsiDirectory targetDirectory1 = moveDialog != null ? moveDialog.getTargetDirectory() : initialTargetDirectory; if (targetDirectory1 == null) { LOG.error("It is null! The target directory, it is null!"); return; } Collection<PsiElement> toCheck = ContainerUtil.newArrayList((PsiElement)targetDirectory1); for (PsiElement e : newElements) { toCheck.add(e instanceof PsiFileSystemItem && e.getParent() != null ? e.getParent() : e); } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, toCheck, false)) { return; } targetElement[0] = targetDirectory1; try { final int[] choice = elements.length > 1 || elements[0] instanceof PsiDirectory ? new int[]{-1} : null; final List<PsiElement> els = new ArrayList<>(); for (final PsiElement psiElement : newElements) { if (psiElement instanceof PsiFile) { final PsiFile file = (PsiFile)psiElement; if (CopyFilesOrDirectoriesHandler.checkFileExist(targetDirectory1, choice, file, file.getName(), "Move")) continue; } checkMove(psiElement, targetDirectory1); els.add(psiElement); } final Runnable callback = () -> { if (moveDialog != null) moveDialog.close(DialogWrapper.CANCEL_EXIT_CODE); }; if (els.isEmpty()) { callback.run(); return; } new MoveFilesOrDirectoriesProcessor(project, els.toArray(PsiElement.EMPTY_ARRAY), targetDirectory1, RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE, false, false, moveCallback, callback).run(); } catch (IncorrectOperationException e) { CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"), e.getMessage(), "refactoring.moveFile", project); } }, MoveHandler.REFACTORING_NAME, null); } }; if (ApplicationManager.getApplication().isUnitTestMode()) { doRun.run(null); } else { final MoveFilesOrDirectoriesDialog moveDialog = new MoveFilesOrDirectoriesDialog(project, doRun); moveDialog.setData(newElements, initialTargetDirectory, "refactoring.moveFile"); moveDialog.show(); } } @Nullable public static PsiDirectory resolveToDirectory(final Project project, final PsiElement element) { if (!(element instanceof PsiDirectoryContainer)) { return (PsiDirectory)element; } PsiDirectory[] directories = ((PsiDirectoryContainer)element).getDirectories(); switch (directories.length) { case 0: return null; case 1: return directories[0]; default: return DirectoryChooserUtil.chooseDirectory(directories, directories[0], project, new HashMap<>()); } } @Nullable private static PsiDirectory getCommonDirectory(PsiElement[] movedElements) { PsiDirectory commonDirectory = null; for (PsiElement movedElement : movedElements) { final PsiDirectory containingDirectory; if (movedElement instanceof PsiDirectory) { containingDirectory = ((PsiDirectory)movedElement).getParentDirectory(); } else { final PsiFile containingFile = movedElement.getContainingFile(); containingDirectory = containingFile == null ? null : containingFile.getContainingDirectory(); } if (containingDirectory != null) { if (commonDirectory == null) { commonDirectory = containingDirectory; } else { if (commonDirectory != containingDirectory) { return null; } } } } return commonDirectory; } @Nullable public static PsiDirectory getInitialTargetDirectory(PsiDirectory initialTargetElement, final PsiElement[] movedElements) { PsiDirectory initialTargetDirectory = initialTargetElement; if (initialTargetDirectory == null) { if (movedElements != null) { final PsiDirectory commonDirectory = getCommonDirectory(movedElements); if (commonDirectory != null) { initialTargetDirectory = commonDirectory; } else { initialTargetDirectory = getContainerDirectory(movedElements[0]); } } } return initialTargetDirectory; } @Nullable private static PsiDirectory getContainerDirectory(final PsiElement psiElement) { if (psiElement instanceof PsiDirectory) { return (PsiDirectory)psiElement; } else if (psiElement != null) { return psiElement.getContainingFile().getContainingDirectory(); } else { return null; } } /** * Checks if it is possible to move the specified PSI element under the specified container, * and throws an exception if the move is not possible. Does not actually modify anything. * * @param element the element to check the move possibility. * @param newContainer the target container element to move into. * @throws IncorrectOperationException if the modification is not supported or not possible for some reason. */ public static void checkMove(@NotNull PsiElement element, @NotNull PsiElement newContainer) throws IncorrectOperationException { if (element instanceof PsiDirectoryContainer) { PsiDirectory[] dirs = ((PsiDirectoryContainer)element).getDirectories(); if (dirs.length == 0) { throw new IncorrectOperationException(); } else if (dirs.length > 1) { throw new IncorrectOperationException( "Moving of packages represented by more than one physical directory is not supported."); } checkMove(dirs[0], newContainer); return; } //element.checkDelete(); //move != delete + add newContainer.checkAdd(element); checkIfMoveIntoSelf(element, newContainer); } public static void checkIfMoveIntoSelf(PsiElement element, PsiElement newContainer) throws IncorrectOperationException { PsiElement container = newContainer; while (container != null) { if (container == element) { if (element instanceof PsiDirectory) { if (element == newContainer) { throw new IncorrectOperationException("Cannot place directory into itself."); } else { throw new IncorrectOperationException("Cannot place directory into its subdirectory."); } } else { throw new IncorrectOperationException(); } } container = container.getParent(); } } }
EA-117885 - NPE: MoveFilesOrDirectoriesUtil.getContainerDirectory
platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java
EA-117885 - NPE: MoveFilesOrDirectoriesUtil.getContainerDirectory
<ide><path>latform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesUtil.java <ide> return (PsiDirectory)psiElement; <ide> } <ide> else if (psiElement != null) { <del> return psiElement.getContainingFile().getContainingDirectory(); <del> } <del> else { <del> return null; <del> } <add> PsiFile containingFile = psiElement.getContainingFile(); <add> if (containingFile != null) { <add> return containingFile.getContainingDirectory(); <add> } <add> } <add> <add> return null; <ide> } <ide> <ide> /**
JavaScript
mit
2c2d76c8fe652adc23f2af9c5cccf89b3338f4be
0
jmjuanes/siimple,siimple/siimple,jmjuanes/siimple,siimple/siimple
//Import dependencies var autoprefixer = require('gulp-autoprefixer'); var fs = require('fs'); var gulp = require('gulp'); var concat = require('gulp-concat'); var cleanCSS = require('gulp-clean-css'); var rename = require('gulp-rename'); var header = require('gulp-header'); var sass = require('gulp-sass'); var del = require('del'); //Import the package var pkg = require('./package.json'); //Banner structure var banner = [] banner.push('/**'); banner.push(' * <%= pkg.name %> - <%= pkg.description %>'); banner.push(' * @version v<%= pkg.version %>'); banner.push(' * @link <%= pkg.homepage %>'); banner.push(' * @license <%= pkg.license %>'); banner.push('**/'); banner.push(' '); banner.push(' '); //Join the banner banner = banner.join('\n'); //Clean the dist folder gulp.task('clean', function() { //Clean the dist folder return del.sync([ './dist/**' ]); }); //Build the SCSS files gulp.task('build:scss', function() { //Select all the SCSS files gulp.src('scss/**/*.scss') //Build the scss files .pipe(sass().on('error', sass.logError)) //Autoprefix .pipe(autoprefixer({ browsers: ['last 3 versions', 'IE 9'], cascade: false })) //Add the header .pipe(header(banner, { pkg : pkg } )) //Save on the dist folder .pipe(gulp.dest('./dist/')); }); //Minimize the css gulp.task('minimize', function() { //Set the source file gulp.src('dist/*.css') //Clean the css .pipe(cleanCSS({ compatibility: '*', processImportFrom: ['!fonts.googleapis.com'] })) //Rename the file .pipe(rename({ extname: '.min.css' })) //Add the header .pipe(header(banner, { pkg : pkg } )) //Save on the dist folder .pipe(gulp.dest('dist/')); }); //Build task gulp.task('build', [ 'build:scss' ]); //Execute the tasks gulp.task('default', [ 'clean', 'build' ]);
gulpfile.js
//Import dependencies var autoprefixer = require('gulp-autoprefixer'); var fs = require('fs'); var gulp = require('gulp'); var concat = require('gulp-concat'); var cleanCSS = require('gulp-clean-css'); var rename = require('gulp-rename'); var header = require('gulp-header'); var sass = require('gulp-sass'); var del = require('del'); //Import the package var pkg = require('./package.json'); //Banner structure var banner = [] banner.push('/**'); banner.push(' * <%= pkg.name %> - <%= pkg.description %>'); banner.push(' * @version v<%= pkg.version %>'); banner.push(' * @link <%= pkg.homepage %>'); banner.push(' * @license <%= pkg.license %>'); banner.push('**/'); banner.push(' '); banner.push(' '); //Join the banner banner = banner.join('\n'); //Clean the dist folder gulp.task('clean', function() { //Clean the dist folder return del.sync([ './dist/**' ]); }); //Build the SCSS files gulp.task('build', function() { //Select all the SCSS files gulp.src('src/**/*.scss') //Build the scss files .pipe(sass().on('error', sass.logError)) //Autoprefix .pipe(autoprefixer({ browsers: ['last 3 versions', 'IE 9'], cascade: false })) //Add the header .pipe(header(banner, { pkg : pkg } )) //Save on the dist folder .pipe(gulp.dest('./dist/')); }); //Minimize the css gulp.task('minimize', function() { //Set the source file gulp.src('dist/*.css') //Clean the css .pipe(cleanCSS({ compatibility: '*', processImportFrom: ['!fonts.googleapis.com'] })) //Rename the file .pipe(rename({ extname: '.min.css' })) //Add the header .pipe(header(banner, { pkg : pkg } )) //Save on the dist folder .pipe(gulp.dest('dist/')); }); //Execute the tasks gulp.task('default', [ 'clean', 'build' ]);
gulpfile.js: updated sscss files folder
gulpfile.js
gulpfile.js: updated sscss files folder
<ide><path>ulpfile.js <ide> }); <ide> <ide> //Build the SCSS files <del>gulp.task('build', function() <add>gulp.task('build:scss', function() <ide> { <ide> //Select all the SCSS files <del> gulp.src('src/**/*.scss') <add> gulp.src('scss/**/*.scss') <ide> <ide> //Build the scss files <ide> .pipe(sass().on('error', sass.logError)) <ide> .pipe(gulp.dest('dist/')); <ide> }); <ide> <add>//Build task <add>gulp.task('build', [ 'build:scss' ]); <add> <ide> //Execute the tasks <ide> gulp.task('default', [ 'clean', 'build' ]);
Java
agpl-3.0
78e13fd92f528976216e82bc256ff33db945f455
0
cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack,cinquin/mutinack
/** * Mutinack mutation detection program. * Copyright (C) 2014-2016 Olivier Cinquin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.org.cinquin.mutinack; import static uk.org.cinquin.mutinack.misc_util.Util.nonNullify; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.edu.stanford.nlp.util.HasInterval; import contrib.edu.stanford.nlp.util.Interval; import contrib.net.sf.samtools.Cigar; import contrib.net.sf.samtools.CigarElement; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMFileReader; import contrib.net.sf.samtools.SAMFileReader.QueryInterval; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SAMRecordIterator; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.nf.fr.eraasoft.pool.PoolException; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectByteHashMap; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.exceptions.ParseRTException; /** * Hashcode and equality based on read name + first or second of pair. * @author olivier * */ public final class ExtendedSAMRecord implements HasInterval<Integer> { static final Logger logger = LoggerFactory.getLogger(ExtendedSAMRecord.class); public boolean discarded = false; private final @Nullable Map<String, ExtendedSAMRecord> extSAMCache; public final @NonNull SAMRecord record; private final @NonNull String name; private @Nullable ExtendedSAMRecord mate; private boolean triedRetrievingMateFromFile = false; private final @NonNull String mateName; private final int hashCode; public @Nullable DuplexRead duplexRead; private byte @Nullable[] mateVariableBarcode; public final byte @NonNull[] variableBarcode; public final byte @Nullable[] constantBarcode; public final @NonNull SequenceLocation location; final int medianPhred; final float averagePhred; private final Cigar cigar; /** * Length of read ignoring trailing Ns. */ public final int effectiveLength; int nReferenceDisagreements = 0; public static final byte PHRED_NO_ENTRY = -1; public final @NonNull TObjectByteHashMap<SequenceLocation> basePhredScores = new TObjectByteHashMap<>(150, 0.5f, PHRED_NO_ENTRY); private int nClipped = -1; private Boolean formsWrongPair; public boolean processed = false; public boolean duplexAlreadyVisitedForStats = false; public final int xLoc, yLoc; public final String runAndTile; public boolean opticalDuplicate = false; public boolean hasOpticalDuplicates = false; public boolean visitedForOptDups = false; public int tempIndex0 = -1, tempIndex1 = -1; private final @NonNull MutinackGroup groupSettings; private final @NonNull Mutinack analyzer; public static @NonNull String getReadFullName(SAMRecord rec, boolean getMate) { return (rec.getReadName() + "--" + ((getMate ^ rec.getFirstOfPairFlag())? "1" : "2") + "--" + (getMate ? rec.getMateAlignmentStart() : rec.getAlignmentStart())) + (!getMate && rec.getSupplementaryAlignmentFlag() ? "--suppl" : "")/*.intern()*/; } public @NonNull String getFullName() { return name; } @Override public final int hashCode() { return hashCode; } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } return name.equals(((ExtendedSAMRecord) obj).name); } private void computeNClipped() { final int readLength = record.getReadLength(); final int adapterClipped = readLength - effectiveLength; int nClippedLeft = (!getReadNegativeStrandFlag() ? /* positive strand */ getAlignmentStart() - getUnclippedStart() : /* negative strand */ /* Note: getMateAlignmentEnd will return Integer.MAX_INT if mate not loaded*/ (getAlignmentStart() <= getMateAlignmentStart() ? /* adapter run through, causes clipping we should ignore */ 0 : getAlignmentStart() - getUnclippedStart() - adapterClipped)); nClippedLeft = Math.max(0, nClippedLeft); int nClippedRight = getReadNegativeStrandFlag() ? /* negative strand */ getUnclippedEnd() - getAlignmentEnd() : /* positive strand */ (getAlignmentEnd() >= getMateAlignmentEnd() ? /* adapter run through, causes clipping we should ignore */ 0 : getUnclippedEnd() - getAlignmentEnd() - adapterClipped); nClippedRight = Math.max(0, nClippedRight); nClipped = nClippedLeft + nClippedRight; } public int getnClipped() { if (nClipped == -1) { computeNClipped(); } return nClipped; } public void resetnClipped() { nClipped = -1; } @SuppressWarnings("static-access") public ExtendedSAMRecord(@NonNull SAMRecord rec, @NonNull String fullName, @NonNull List<@NonNull AnalysisStats> stats, @NonNull Mutinack analyzer, @NonNull SequenceLocation location, @Nullable Map<String, ExtendedSAMRecord> extSAMCache) { this.groupSettings = Objects.requireNonNull(analyzer.groupSettings); this.analyzer = Objects.requireNonNull(analyzer); this.extSAMCache = extSAMCache; this.name = Objects.requireNonNull(fullName); this.record = Objects.requireNonNull(rec); this.cigar = rec.getCigar(); this.location = location; hashCode = fullName.hashCode(); mateName = getReadFullName(rec, true); final int readLength = rec.getReadLength(); //Find effective end of read, i.e. first position that is not an 'N' (the trimming //step run prior to mutation detection might shorten reads that ran into the //adapter because the insert was shorter than read length, by transforming all //bases that should be ignored to an N) @SuppressWarnings("hiding") int effectiveLength = readLength; final byte[] read = record.getReadBases(); final byte[] baseQualities = record.getBaseQualities(); if (getReadNegativeStrandFlag()) { int i = 0; while (read[i] == 'N' && i < readLength - 1) { i++; } effectiveLength = readLength - i; } else { while (read[effectiveLength - 1] == 'N' && effectiveLength > 0) { effectiveLength--; } } Assert.isFalse(effectiveLength < 0); this.effectiveLength = effectiveLength; int sumBaseQualities0 = 0; int nConsidered0 = 0; TIntList qualities = new TIntArrayList(effectiveLength); int n = Math.min(effectiveLength, readLength / 2); for (int index1 = 0; index1 < n; index1++) { nConsidered0++; final byte b = baseQualities[index1]; sumBaseQualities0 += b; stats.forEach(s -> s.nProcessedBases.add(location, 1)); stats.forEach(s -> s.phredSumProcessedbases.add(b)); qualities.add(b); } int avQuality = sumBaseQualities0 / nConsidered0; stats.forEach(s-> s.averageReadPhredQuality0.insert(avQuality)); int sumBaseQualities1 = 0; int nConsidered1 = 0; for (int index1 = readLength / 2; index1 < effectiveLength; index1++) { nConsidered1++; final byte b = baseQualities[index1]; sumBaseQualities1 += b; stats.forEach(s -> s.nProcessedBases.add(location, 1)); stats.forEach(s -> s.phredSumProcessedbases.add(b)); qualities.add(b); } if (nConsidered1 > 0) { int avQuality1 = sumBaseQualities1 / nConsidered1; stats.forEach(s -> s.averageReadPhredQuality1.insert(avQuality1)); } qualities.sort(); medianPhred = qualities.get(qualities.size() / 2); averagePhred = (sumBaseQualities0 + sumBaseQualities1) / ((float) (nConsidered0 + nConsidered1)); stats.forEach(s -> s.medianReadPhredQuality.insert(medianPhred)); Assert.isTrue(rec.getUnclippedEnd() - 1 >= getAlignmentEnd(), (Supplier<Object>) () -> "" + (rec.getUnclippedEnd() - 1), (Supplier<Object>) this::toString, "Unclipped end is %s for read %s"); Assert.isTrue(rec.getAlignmentStart() - 1 >= getUnclippedStart()); final @NonNull String fullBarcodeString; String bcAttr = (String) record.getAttribute("BC"); if (groupSettings.getVariableBarcodeEnd() > 0) { if (bcAttr == null) { final int firstIndex = name.indexOf("BC:Z:"); if (firstIndex == -1) { throw new ParseRTException("Missing first barcode for read " + name + ' ' + record.toString()); } final int index; if (record.getFirstOfPairFlag()) { index = firstIndex; } else { index = name.indexOf("BC:Z:", firstIndex + 1); if (index == -1) { throw new ParseRTException("Missing second barcode for read " + name + ' ' + record.toString()); } } fullBarcodeString = nonNullify(name.substring(index + 5, name.indexOf('_', index))); } else { fullBarcodeString = bcAttr; } variableBarcode = Util.getInternedVB(fullBarcodeString.substring( groupSettings.getVariableBarcodeStart(), groupSettings.getVariableBarcodeEnd() + 1).getBytes()); constantBarcode = Util.getInternedCB(fullBarcodeString.substring( groupSettings.getConstantBarcodeStart(), groupSettings.getConstantBarcodeEnd() + 1).getBytes()); } else { variableBarcode = EMPTY_BARCODE; constantBarcode = DUMMY_BARCODE;//EMPTY_BARCODE } String readName = record.getReadName(); int endFirstChunk = nthIndexOf(readName, ':', 5); //Interning below required for equality checks performed in optical duplicate detection runAndTile = record.getReadName().substring(0, endFirstChunk).intern(); byte[] readNameBytes = readName.getBytes(); xLoc = parseInt(readNameBytes, endFirstChunk + 1); int endXLoc = readName.indexOf(':', endFirstChunk + 1); yLoc = parseInt(readNameBytes, endXLoc + 1); //interval = Interval.toInterval(rec.getAlignmentStart(), rec.getAlignmentEnd()); } private static boolean LENIENT_COORDINATE_PARSING = true; private static int parseInt(final byte[] b, final int fromIndex) { final int end = b.length - 1; int i = fromIndex; int result = 0; while (i <= end) { if (b[i] == ':') { return result; } byte character = b[i]; if (character < 48 || character > 57) { if (LENIENT_COORDINATE_PARSING) { return result; } throw new ParseRTException("Character " + character + " is not a digit when parsing " + new String(b) + " from " + fromIndex); } result = 10 * result + b[i] - 48; i++; } return result; } private static int nthIndexOf(final String s, final char c, final int n) { int i = -1; int found = 0; while (found < n) { i = s.indexOf(c, i + 1); found++; } return i; } private static final byte @NonNull[] EMPTY_BARCODE = new byte [0]; private static final byte @NonNull[] DUMMY_BARCODE = {'N', 'N', 'N'}; public ExtendedSAMRecord(@NonNull SAMRecord rec, @NonNull Mutinack analyzer, @NonNull SequenceLocation location, @NonNull Map<String, ExtendedSAMRecord> extSAMCache) { this(rec, getReadFullName(rec, false), analyzer.stats, analyzer, location, extSAMCache); } public byte @NonNull[] getMateVariableBarcode() { if (mateVariableBarcode == null || mateVariableBarcode == groupSettings.getNs()) { checkMate(); if (mate == null) { mateVariableBarcode = groupSettings.getNs(); } else { mateVariableBarcode = nonNullify(mate).variableBarcode; } } return Objects.requireNonNull(mateVariableBarcode); } @Override public String toString() { return (discarded ? "DISCARDED" : "" ) + name + ": " + "startNoBC: " + getAlignmentStart() + "; endNoBC: " + getAlignmentEnd() + "; alignmentStart: " + (getReadNegativeStrandFlag() ? "-" : "+") + getAlignmentStart() + "; alignmentEnd: " + getAlignmentEnd() + "; cigar: " + record.getCigarString() + "; length: " + record.getReadLength() + "; effectiveLength: " + effectiveLength + "; nClipped: " + (nClipped == -1 ? "Uncomputed" : getnClipped()) + "; insertSize: " + getInsertSize() + "; bases: " + new String(record.getReadBases()); } @Override public Interval<Integer> getInterval() { throw new RuntimeException("Unimplemented"); //return interval; } public int referencePositionToReadPosition(int refPosition) { if (refPosition <= getAlignmentStart()) { return refPosition - getUnclippedStart(); } List<CigarElement> cElmnts = getCigar().getCigarElements(); final int nElmnts = cElmnts.size(); int ceIndex = 0; int nReadBasesProcessed = getAlignmentStart() - getUnclippedStart(); final int nBasesToAlign = refPosition - getAlignmentStart(); int nBasesAligned = 0; while (ceIndex < nElmnts && nBasesAligned < nBasesToAlign) { final CigarElement c = cElmnts.get(ceIndex); final int blockLength = c.getLength(); switch(c.getOperator()) { case M: int nTakenBases = Math.min(blockLength, nBasesToAlign - nBasesAligned); nBasesAligned += nTakenBases; nReadBasesProcessed += nTakenBases; break; case I: nReadBasesProcessed += blockLength; break; case D: case N: nBasesAligned += blockLength; break; default://Nothing to do } //Ignoring clipping at end of read ceIndex++; } if (nBasesAligned == nBasesToAlign) { return nReadBasesProcessed; } else { return nReadBasesProcessed + (nBasesToAlign - nBasesAligned); } } public Cigar getCigar() { return cigar; } private int intronAdjustment(final int readPosition, boolean reverse) { if (!groupSettings.isRnaSeq()) { return 0; } SettableInteger nReadBases = new SettableInteger(0); SettableInteger intronBases = new SettableInteger(0); MutableList<CigarElement> cigarElements = Lists.mutable.withAll(getCigar().getCigarElements()); if (reverse) { cigarElements.reverseThis(); } cigarElements.detect(e -> { CigarOperator operator = e.getOperator(); int truncatedLength = operator.consumesReadBases() ? Math.min(e.getLength(), readPosition - nReadBases.get()) : e.getLength(); if (operator.consumesReadBases()) { nReadBases.addAndGet(truncatedLength); } if (operator == CigarOperator.N) { intronBases.addAndGet(e.getLength()); } if (nReadBases.get() == readPosition) { return true; } return false; }); Assert.isTrue(nReadBases.get() == readPosition); return intronBases.get(); } public static final int NO_MATE_POSITION = Integer.MAX_VALUE - 1000; public int tooCloseToBarcode(int readPosition, int ignoreFirstNBases) { final boolean readOnNegativeStrand = getReadNegativeStrandFlag(); final int distance0; if (readOnNegativeStrand) { distance0 = readPosition - ((record.getReadLength() - 1) - ignoreFirstNBases); } else { distance0 = ignoreFirstNBases - readPosition; } //Now check if position is too close to other adapter barcode ligation site, //or on the wrong side of it final int refPositionOfMateLigationSite = getRefPositionOfMateLigationSite(); final int distance1; if (!formsWrongPair() && refPositionOfMateLigationSite != NO_MATE_POSITION) { final int readPositionOfLigSiteA = referencePositionToReadPosition(refPositionOfMateLigationSite - 1) + 1; final int readPositionOfLigSiteB = referencePositionToReadPosition(refPositionOfMateLigationSite + 1) - 1; if (getReadNegativeStrandFlag()) { distance1 = Math.max(readPositionOfLigSiteA, readPositionOfLigSiteB) + ignoreFirstNBases - readPosition; } else { distance1 = readPosition - (Math.min(readPositionOfLigSiteA, readPositionOfLigSiteB ) - ignoreFirstNBases); } } else { //Mate info not available, or pair is "wrong" pair //Just go by effectiveLength to infer presence of adapter, although //it should not happen in practice that reads form a wrong pair //when there is adapter read-through final int readLength = record.getReadLength(); final int adapterClipped = readLength - effectiveLength; if (readOnNegativeStrand) { distance1 = (adapterClipped == 0) ? Integer.MIN_VALUE : ignoreFirstNBases + adapterClipped - readPosition; } else { distance1 = (adapterClipped == 0) ? Integer.MIN_VALUE : readPosition - (effectiveLength - ignoreFirstNBases - 1); } } return Math.max(distance0, distance1); } public int getRefPositionOfMateLigationSite() { return getReadNegativeStrandFlag() ? getMateUnclippedStart() : getMateUnclippedEnd(); } public int getRefAlignmentStart() { int referenceStart = getAlignmentStart(); Assert.isFalse(referenceStart < 0); return referenceStart; } public int getRefAlignmentEnd() { int referenceEnd = getAlignmentEnd(); Assert.isFalse(referenceEnd < 0, () -> "Negative alignment end in read " + this); return referenceEnd; } public int getMateRefAlignmentStart() { checkMate(); return mate == null ? NO_MATE_POSITION : nonNullify(mate).getRefAlignmentStart(); } public int getMateRefAlignmentEnd() { checkMate(); return mate == null ? NO_MATE_POSITION : nonNullify(mate).getRefAlignmentEnd(); } public int getInsertSize() { return record.getInferredInsertSize(); } public ExtendedSAMRecord getMate() { checkMate(); return mate; } //Adapted from SamPairUtil public PairOrientation getPairOrientation() { final boolean readIsOnReverseStrand = record.getReadNegativeStrandFlag(); if (record.getReadUnmappedFlag() || !record.getReadPairedFlag() || record.getMateUnmappedFlag()) { throw new IllegalArgumentException("Invalid SAMRecord: " + record.getReadName() + ". This method only works for SAMRecords " + "that are paired reads with both reads aligned."); } if (readIsOnReverseStrand == record.getMateNegativeStrandFlag()) { return PairOrientation.TANDEM; } final int positiveStrandFivePrimePos = readIsOnReverseStrand ? getMateOffsetUnclippedStart() : getOffsetUnclippedStart(); final int negativeStrandFivePrimePos = readIsOnReverseStrand ? getOffsetUnclippedEnd() : getMateOffsetUnclippedEnd(); return positiveStrandFivePrimePos < negativeStrandFivePrimePos ? PairOrientation.FR : PairOrientation.RF; } public boolean formsWrongPair() { if (formsWrongPair == null) { formsWrongPair = record.getReadPairedFlag() && ( record.getReadUnmappedFlag() || record.getMateUnmappedFlag() || getPairOrientation() == PairOrientation.TANDEM || getPairOrientation() == PairOrientation.RF ); } return formsWrongPair; } public boolean getReadNegativeStrandFlag() { return record.getReadNegativeStrandFlag(); } public boolean getReadPositiveStrand() { return !record.getReadNegativeStrandFlag(); } private void checkMate() { if (mate == null) { if (extSAMCache != null) mate = extSAMCache.get(mateName); if (mate == null && !triedRetrievingMateFromFile && !record.getMateUnmappedFlag()) { mate = getRead(analyzer, record.getReadName(), !record.getFirstOfPairFlag(), new SequenceLocation(record.getMateReferenceName(), groupSettings.indexContigNameReverseMap, record.getMateAlignmentStart() - 1, false) , -1, 1); triedRetrievingMateFromFile = true; } } } /** Indexing starts at 0 */ public int getAlignmentStart() { return record.getAlignmentStart() - 1; } /** Indexing starts at 0 */ public int getUnclippedStart() { return record.getUnclippedStart() - 1; } /** Indexing starts at 0 */ public int getMateAlignmentStart() { return record.getMateAlignmentStart() - 1; } /** Indexing starts at 0 */ public int getAlignmentEnd() { return record.getAlignmentEnd() - 1; } /** Indexing starts at 0 * * @return */ public int getMateAlignmentEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getAlignmentEnd(); } public int getMateUnclippedEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getUnclippedEnd(); } public int getOffsetUnclippedEnd() { return record.getUnclippedEnd() - 1 - intronAdjustment(16, true); } public int getOffsetUnclippedStart() { return record.getUnclippedStart() - 1 + intronAdjustment(16, false); } public int getMateOffsetUnclippedEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getOffsetUnclippedEnd(); } public int getMateOffsetUnclippedStart() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getOffsetUnclippedStart(); } public int getUnclippedEnd() { return record.getUnclippedEnd() - 1; } public int getMateUnclippedStart() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getUnclippedStart(); } public int getMappingQuality() { return record.getMappingQuality(); } public boolean overlapsWith(SequenceLocation otherLocation) { if (getRefAlignmentStart() > otherLocation.position || getRefAlignmentEnd() < otherLocation.position || otherLocation.contigIndex != getReferenceIndex()) { return false; } return true; } boolean duplexLeft() { return formsWrongPair() ? getAlignmentStart() <= getMateAlignmentStart() : getReadPositiveStrand(); } public @NonNull SequenceLocation getLocation() { return location; } /** * Not necessarily the same as that of SAMRecord * @return */ public int getReferenceIndex() { return location.contigIndex; } public @NonNull String getReferenceName() { return location.getContigName(); } public int getxLoc() { return xLoc; } public int getyLoc() { return yLoc; } public String getRunAndTile() { return runAndTile; } public boolean isOpticalDuplicate() { return opticalDuplicate; } public float getAveragePhred() { return averagePhred; } public List<ExtendedAlignmentBlock> getAlignmentBlocks() { return ExtendedAlignmentBlock.getAlignmentBlocks(getCigar(), record.getAlignmentStart(), "read cigar"); } public static @Nullable ExtendedSAMRecord getRead(Mutinack analyzer, String name, boolean firstOfPair, SequenceLocation location, int avoidAlignmentStart0Based, int windowHalfWidth) { SAMFileReader bamReader; try { bamReader = analyzer.readerPool.getObj(); } catch (PoolException e) { throw new RuntimeException(e); } try { final QueryInterval[] bamContig = { bamReader.makeQueryInterval(location.contigName, location.position - windowHalfWidth, location.position + windowHalfWidth)}; try (SAMRecordIterator it = bamReader.queryOverlapping(bamContig)) { while (it.hasNext()) { SAMRecord record = it.next(); if (record.getReadName().equals(name) && record.getFirstOfPairFlag() == firstOfPair && record.getAlignmentStart() - 1 != avoidAlignmentStart0Based) { return SubAnalyzer.getExtendedNoCaching(record, new SequenceLocation(location.contigName, analyzer.groupSettings.indexContigNameReverseMap, record.getAlignmentStart() - 1, false), analyzer); } } return null; } } finally { analyzer.readerPool.returnObj(bamReader); } } }
src/uk/org/cinquin/mutinack/ExtendedSAMRecord.java
/** * Mutinack mutation detection program. * Copyright (C) 2014-2016 Olivier Cinquin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.org.cinquin.mutinack; import static uk.org.cinquin.mutinack.misc_util.Util.nonNullify; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Supplier; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import contrib.edu.stanford.nlp.util.HasInterval; import contrib.edu.stanford.nlp.util.Interval; import contrib.net.sf.samtools.Cigar; import contrib.net.sf.samtools.CigarElement; import contrib.net.sf.samtools.CigarOperator; import contrib.net.sf.samtools.SAMFileReader; import contrib.net.sf.samtools.SAMFileReader.QueryInterval; import contrib.net.sf.samtools.SAMRecord; import contrib.net.sf.samtools.SAMRecordIterator; import contrib.net.sf.samtools.SamPairUtil.PairOrientation; import contrib.nf.fr.eraasoft.pool.PoolException; import contrib.uk.org.lidalia.slf4jext.Logger; import contrib.uk.org.lidalia.slf4jext.LoggerFactory; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TObjectByteHashMap; import uk.org.cinquin.mutinack.candidate_sequences.ExtendedAlignmentBlock; import uk.org.cinquin.mutinack.misc_util.Assert; import uk.org.cinquin.mutinack.misc_util.SettableInteger; import uk.org.cinquin.mutinack.misc_util.Util; import uk.org.cinquin.mutinack.misc_util.exceptions.ParseRTException; /** * Hashcode and equality based on read name + first or second of pair. * @author olivier * */ public final class ExtendedSAMRecord implements HasInterval<Integer> { static final Logger logger = LoggerFactory.getLogger(ExtendedSAMRecord.class); public boolean discarded = false; private final @Nullable Map<String, ExtendedSAMRecord> extSAMCache; public final @NonNull SAMRecord record; private final @NonNull String name; private @Nullable ExtendedSAMRecord mate; private boolean triedRetrievingMateFromFile = false; private final @NonNull String mateName; private final int hashCode; public @Nullable DuplexRead duplexRead; private byte @Nullable[] mateVariableBarcode; public final byte @NonNull[] variableBarcode; public final byte @Nullable[] constantBarcode; public final @NonNull SequenceLocation location; final int medianPhred; final float averagePhred; private final Cigar cigar; /** * Length of read ignoring trailing Ns. */ public final int effectiveLength; int nReferenceDisagreements = 0; public static final byte PHRED_NO_ENTRY = -1; public final @NonNull TObjectByteHashMap<SequenceLocation> basePhredScores = new TObjectByteHashMap<>(150, 0.5f, PHRED_NO_ENTRY); private int nClipped = -1; private Boolean formsWrongPair; public boolean processed = false; public boolean duplexAlreadyVisitedForStats = false; public final int xLoc, yLoc; public final String runAndTile; public boolean opticalDuplicate = false; public boolean hasOpticalDuplicates = false; public boolean visitedForOptDups = false; public int tempIndex0 = -1, tempIndex1 = -1; private final @NonNull MutinackGroup groupSettings; private final @NonNull Mutinack analyzer; public static @NonNull String getReadFullName(SAMRecord rec, boolean getMate) { return (rec.getReadName() + "--" + ((getMate ^ rec.getFirstOfPairFlag())? "1" : "2") + "--" + (getMate ? rec.getMateAlignmentStart() : rec.getAlignmentStart())) + (!getMate && rec.getSupplementaryAlignmentFlag() ? "--suppl" : "")/*.intern()*/; } public @NonNull String getFullName() { return name; } @Override public final int hashCode() { return hashCode; } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } return name.equals(((ExtendedSAMRecord) obj).name); } private void computeNClipped() { final int readLength = record.getReadLength(); final int adapterClipped = readLength - effectiveLength; int nClippedLeft = (!getReadNegativeStrandFlag() ? /* positive strand */ getAlignmentStart() - getUnclippedStart() : /* negative strand */ /* Note: getMateAlignmentEnd will return Integer.MAX_INT if mate not loaded*/ (getAlignmentStart() <= getMateAlignmentStart() ? /* adapter run through, causes clipping we should ignore */ 0 : getAlignmentStart() - getUnclippedStart() - adapterClipped)); nClippedLeft = Math.max(0, nClippedLeft); int nClippedRight = getReadNegativeStrandFlag() ? /* negative strand */ getUnclippedEnd() - getAlignmentEnd() : /* positive strand */ (getAlignmentEnd() >= getMateAlignmentEnd() ? /* adapter run through, causes clipping we should ignore */ 0 : getUnclippedEnd() - getAlignmentEnd() - adapterClipped); nClippedRight = Math.max(0, nClippedRight); nClipped = nClippedLeft + nClippedRight; } public int getnClipped() { if (nClipped == -1) { computeNClipped(); } return nClipped; } public void resetnClipped() { nClipped = -1; } @SuppressWarnings("static-access") public ExtendedSAMRecord(@NonNull SAMRecord rec, @NonNull String fullName, @NonNull List<@NonNull AnalysisStats> stats, @NonNull Mutinack analyzer, @NonNull SequenceLocation location, @Nullable Map<String, ExtendedSAMRecord> extSAMCache) { this.groupSettings = Objects.requireNonNull(analyzer.groupSettings); this.analyzer = Objects.requireNonNull(analyzer); this.extSAMCache = extSAMCache; this.name = Objects.requireNonNull(fullName); this.record = Objects.requireNonNull(rec); this.cigar = rec.getCigar(); this.location = location; hashCode = fullName.hashCode(); mateName = getReadFullName(rec, true); final int readLength = rec.getReadLength(); //Find effective end of read, i.e. first position that is not an 'N' (the trimming //step run prior to mutation detection might shorten reads that ran into the //adapter because the insert was shorter than read length, by transforming all //bases that should be ignored to an N) @SuppressWarnings("hiding") int effectiveLength = readLength; final byte[] read = record.getReadBases(); final byte[] baseQualities = record.getBaseQualities(); if (getReadNegativeStrandFlag()) { int i = 0; while (read[i] == 'N' && i < readLength - 1) { i++; } effectiveLength = readLength - i; } else { while (read[effectiveLength - 1] == 'N' && effectiveLength > 0) { effectiveLength--; } } Assert.isFalse(effectiveLength < 0); this.effectiveLength = effectiveLength; int sumBaseQualities0 = 0; int nConsidered0 = 0; TIntList qualities = new TIntArrayList(effectiveLength); int n = Math.min(effectiveLength, readLength / 2); for (int index1 = 0; index1 < n; index1++) { nConsidered0++; final byte b = baseQualities[index1]; sumBaseQualities0 += b; stats.forEach(s -> s.nProcessedBases.add(location, 1)); stats.forEach(s -> s.phredSumProcessedbases.add(b)); qualities.add(b); } int avQuality = sumBaseQualities0 / nConsidered0; stats.forEach(s-> s.averageReadPhredQuality0.insert(avQuality)); int sumBaseQualities1 = 0; int nConsidered1 = 0; for (int index1 = readLength / 2; index1 < effectiveLength; index1++) { nConsidered1++; final byte b = baseQualities[index1]; sumBaseQualities1 += b; stats.forEach(s -> s.nProcessedBases.add(location, 1)); stats.forEach(s -> s.phredSumProcessedbases.add(b)); qualities.add(b); } if (nConsidered1 > 0) { int avQuality1 = sumBaseQualities1 / nConsidered1; stats.forEach(s -> s.averageReadPhredQuality1.insert(avQuality1)); } qualities.sort(); medianPhred = qualities.get(qualities.size() / 2); averagePhred = (sumBaseQualities0 + sumBaseQualities1) / ((float) (nConsidered0 + nConsidered1)); stats.forEach(s -> s.medianReadPhredQuality.insert(medianPhred)); Assert.isTrue(rec.getUnclippedEnd() - 1 >= getAlignmentEnd(), (Supplier<Object>) () -> "" + (rec.getUnclippedEnd() - 1), (Supplier<Object>) this::toString, "Unclipped end is %s for read %s"); Assert.isTrue(rec.getAlignmentStart() - 1 >= getUnclippedStart()); final @NonNull String fullBarcodeString; String bcAttr = (String) record.getAttribute("BC"); if (groupSettings.getVariableBarcodeEnd() > 0) { if (bcAttr == null) { final int firstIndex = name.indexOf("BC:Z:"); if (firstIndex == -1) { throw new ParseRTException("Missing first barcode for read " + name + ' ' + record.toString()); } final int index; if (record.getFirstOfPairFlag()) { index = firstIndex; } else { index = name.indexOf("BC:Z:", firstIndex + 1); if (index == -1) { throw new ParseRTException("Missing second barcode for read " + name + ' ' + record.toString()); } } fullBarcodeString = nonNullify(name.substring(index + 5, name.indexOf('_', index))); } else { fullBarcodeString = bcAttr; } variableBarcode = Util.getInternedVB(fullBarcodeString.substring( groupSettings.getVariableBarcodeStart(), groupSettings.getVariableBarcodeEnd() + 1).getBytes()); constantBarcode = Util.getInternedCB(fullBarcodeString.substring( groupSettings.getConstantBarcodeStart(), groupSettings.getConstantBarcodeEnd() + 1).getBytes()); } else { variableBarcode = EMPTY_BARCODE; constantBarcode = DUMMY_BARCODE;//EMPTY_BARCODE } String readName = record.getReadName(); int endFirstChunk = nthIndexOf(readName, ':', 5); //Interning below required for equality checks performed in optical duplicate detection runAndTile = record.getReadName().substring(0, endFirstChunk).intern(); byte[] readNameBytes = readName.getBytes(); xLoc = parseInt(readNameBytes, endFirstChunk + 1); int endXLoc = readName.indexOf(':', endFirstChunk + 1); yLoc = parseInt(readNameBytes, endXLoc + 1); //interval = Interval.toInterval(rec.getAlignmentStart(), rec.getAlignmentEnd()); } private static boolean LENIENT_COORDINATE_PARSING = true; private static int parseInt(final byte[] b, final int fromIndex) { final int end = b.length - 1; int i = fromIndex; int result = 0; while (i <= end) { if (b[i] == ':') { return result; } byte character = b[i]; if (character < 48 || character > 57) { if (LENIENT_COORDINATE_PARSING) { return result; } throw new ParseRTException("Character " + character + " is not a digit when parsing " + new String(b) + " from " + fromIndex); } result = 10 * result + b[i] - 48; i++; } return result; } private static int nthIndexOf(final String s, final char c, final int n) { int i = -1; int found = 0; while (found < n) { i = s.indexOf(c, i + 1); found++; } return i; } private static final byte @NonNull[] EMPTY_BARCODE = new byte [0]; private static final byte @NonNull[] DUMMY_BARCODE = {'N', 'N', 'N'}; public ExtendedSAMRecord(@NonNull SAMRecord rec, @NonNull Mutinack analyzer, @NonNull SequenceLocation location, @NonNull Map<String, ExtendedSAMRecord> extSAMCache) { this(rec, getReadFullName(rec, false), analyzer.stats, analyzer, location, extSAMCache); } public byte @NonNull[] getMateVariableBarcode() { if (mateVariableBarcode == null || mateVariableBarcode == groupSettings.getNs()) { checkMate(); if (mate == null) { mateVariableBarcode = groupSettings.getNs(); } else { mateVariableBarcode = nonNullify(mate).variableBarcode; } } return Objects.requireNonNull(mateVariableBarcode); } @Override public String toString() { return (discarded ? "DISCARDED" : "" ) + name + ": " + "startNoBC: " + getAlignmentStart() + "; endNoBC: " + getAlignmentEnd() + "; alignmentStart: " + (getReadNegativeStrandFlag() ? "-" : "+") + getAlignmentStart() + "; alignmentEnd: " + getAlignmentEnd() + "; cigar: " + record.getCigarString() + "; length: " + record.getReadLength() + "; effectiveLength: " + effectiveLength + "; nClipped: " + (nClipped == -1 ? "Uncomputed" : getnClipped()) + "; insertSize: " + getInsertSize() + "; bases: " + new String(record.getReadBases()); } @Override public Interval<Integer> getInterval() { throw new RuntimeException("Unimplemented"); //return interval; } public int referencePositionToReadPosition(int refPosition) { if (refPosition <= getAlignmentStart()) { return refPosition - getUnclippedStart(); } List<CigarElement> cElmnts = getCigar().getCigarElements(); final int nElmnts = cElmnts.size(); int ceIndex = 0; int nReadBasesProcessed = getAlignmentStart() - getUnclippedStart(); final int nBasesToAlign = refPosition - getAlignmentStart(); int nBasesAligned = 0; while (ceIndex < nElmnts && nBasesAligned < nBasesToAlign) { final CigarElement c = cElmnts.get(ceIndex); final int blockLength = c.getLength(); switch(c.getOperator()) { case M: int nTakenBases = Math.min(blockLength, nBasesToAlign - nBasesAligned); nBasesAligned += nTakenBases; nReadBasesProcessed += nTakenBases; break; case I: nReadBasesProcessed += blockLength; break; case D: case N: nBasesAligned += blockLength; break; default://Nothing to do } //Ignoring clipping at end of read ceIndex++; } if (nBasesAligned == nBasesToAlign) { return nReadBasesProcessed; } else { return nReadBasesProcessed + (nBasesToAlign - nBasesAligned); } } public Cigar getCigar() { return cigar; } private int intronAdjustment(final int readPosition, boolean reverse) { if (!groupSettings.isRnaSeq()) { return 0; } SettableInteger nReadBases = new SettableInteger(0); SettableInteger intronBases = new SettableInteger(0); MutableList<CigarElement> cigarElements = Lists.mutable.withAll(getCigar().getCigarElements()); if (reverse) { cigarElements.reverseThis(); } cigarElements.detect(e -> { CigarOperator operator = e.getOperator(); int truncatedLength = operator.consumesReadBases() ? Math.min(e.getLength(), readPosition - nReadBases.get()) : e.getLength(); if (operator.consumesReadBases()) { nReadBases.addAndGet(truncatedLength); } if (operator == CigarOperator.N) { intronBases.addAndGet(e.getLength()); } if (nReadBases.get() == readPosition) { return true; } return false; }); Assert.isTrue(nReadBases.get() == readPosition); return intronBases.get(); } public static final int NO_MATE_POSITION = Integer.MAX_VALUE - 1000; public int tooCloseToBarcode(int readPosition, int ignoreFirstNBases) { final boolean readOnNegativeStrand = getReadNegativeStrandFlag(); final int distance0; if (readOnNegativeStrand) { distance0 = readPosition - ((record.getReadLength() - 1) - ignoreFirstNBases); } else { distance0 = ignoreFirstNBases - readPosition; } //Now check if position is too close to other adapter barcode ligation site, //or on the wrong side of it final int refPositionOfMateLigationSite = getRefPositionOfMateLigationSite(); final int distance1; if (!formsWrongPair() && refPositionOfMateLigationSite != NO_MATE_POSITION) { final int readPositionOfLigSiteA = referencePositionToReadPosition(refPositionOfMateLigationSite - 1) + 1; final int readPositionOfLigSiteB = referencePositionToReadPosition(refPositionOfMateLigationSite + 1) - 1; if (getReadNegativeStrandFlag()) { distance1 = Math.max(readPositionOfLigSiteA, readPositionOfLigSiteB) + ignoreFirstNBases - readPosition; } else { distance1 = readPosition - (Math.min(readPositionOfLigSiteA, readPositionOfLigSiteB ) - ignoreFirstNBases); } } else { //Mate info not available, or pair is "wrong" pair //Just go by effectiveLength to infer presence of adapter, although //it should not happen in practice that reads form a wrong pair //when there is adapter read-through final int readLength = record.getReadLength(); final int adapterClipped = readLength - effectiveLength; if (readOnNegativeStrand) { distance1 = (adapterClipped == 0) ? Integer.MIN_VALUE : ignoreFirstNBases + adapterClipped - readPosition; } else { distance1 = (adapterClipped == 0) ? Integer.MIN_VALUE : readPosition - (effectiveLength - ignoreFirstNBases - 1); } } return Math.max(distance0, distance1); } public int getRefPositionOfMateLigationSite() { return getReadNegativeStrandFlag() ? getMateUnclippedStart() : getMateUnclippedEnd(); } public int getRefAlignmentStart() { int referenceStart = getAlignmentStart(); Assert.isFalse(referenceStart < 0); return referenceStart; } public int getRefAlignmentEnd() { int referenceEnd = getAlignmentEnd(); Assert.isFalse(referenceEnd < 0, () -> "Negative alignment end in read " + this); return referenceEnd; } public int getMateRefAlignmentStart() { checkMate(); return mate == null ? NO_MATE_POSITION : nonNullify(mate).getRefAlignmentStart(); } public int getMateRefAlignmentEnd() { checkMate(); return mate == null ? NO_MATE_POSITION : nonNullify(mate).getRefAlignmentEnd(); } public int getInsertSize() { return record.getInferredInsertSize(); } public ExtendedSAMRecord getMate() { checkMate(); return mate; } //Adapted from SamPairUtil public PairOrientation getPairOrientation() { final boolean readIsOnReverseStrand = record.getReadNegativeStrandFlag(); if (record.getReadUnmappedFlag() || !record.getReadPairedFlag() || record.getMateUnmappedFlag()) { throw new IllegalArgumentException("Invalid SAMRecord: " + record.getReadName() + ". This method only works for SAMRecords " + "that are paired reads with both reads aligned."); } if (readIsOnReverseStrand == record.getMateNegativeStrandFlag()) { return PairOrientation.TANDEM; } final int positiveStrandFivePrimePos = readIsOnReverseStrand ? getMateOffsetUnclippedStart() : getOffsetUnclippedStart(); final int negativeStrandFivePrimePos = readIsOnReverseStrand ? getOffsetUnclippedEnd() : getMateOffsetUnclippedEnd(); return positiveStrandFivePrimePos < negativeStrandFivePrimePos ? PairOrientation.FR : PairOrientation.RF; } public boolean formsWrongPair() { if (formsWrongPair == null) { formsWrongPair = record.getReadPairedFlag() && ( record.getReadUnmappedFlag() || record.getMateUnmappedFlag() || getPairOrientation() == PairOrientation.TANDEM || getPairOrientation() == PairOrientation.RF ); } return formsWrongPair; } public boolean getReadNegativeStrandFlag() { return record.getReadNegativeStrandFlag(); } public boolean getReadPositiveStrand() { return !record.getReadNegativeStrandFlag(); } private void checkMate() { if (mate == null) { if (extSAMCache != null) mate = extSAMCache.get(mateName); if (mate == null && !triedRetrievingMateFromFile && !record.getMateUnmappedFlag()) { mate = getRead(analyzer, record.getReadName(), !record.getFirstOfPairFlag(), new SequenceLocation(record.getMateReferenceName(), groupSettings.indexContigNameReverseMap, record.getMateAlignmentStart() - 1, false) , -1, 1); triedRetrievingMateFromFile = true; } } } /** Indexing starts at 0 */ public int getAlignmentStart() { return record.getAlignmentStart() - 1; } /** Indexing starts at 0 */ public int getUnclippedStart() { return record.getUnclippedStart() - 1; } /** Indexing starts at 0 */ public int getMateAlignmentStart() { return record.getMateAlignmentStart() - 1; } /** Indexing starts at 0 */ public int getAlignmentEnd() { return record.getAlignmentEnd() - 1; } /** Indexing starts at 0 * * @return */ public int getMateAlignmentEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getAlignmentEnd(); } public int getMateUnclippedEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getUnclippedEnd(); } public int getOffsetUnclippedEnd() { return record.getUnclippedEnd() - 1 - intronAdjustment(16, true); } public int getOffsetUnclippedStart() { return record.getUnclippedStart() - 1 + intronAdjustment(16, false); } public int getMateOffsetUnclippedEnd() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getOffsetUnclippedEnd(); } public int getMateOffsetUnclippedStart() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getOffsetUnclippedStart(); } public int getUnclippedEnd() { return record.getUnclippedEnd() - 1; } public int getMateUnclippedStart() { checkMate(); if (mate == null) { return NO_MATE_POSITION; } return nonNullify(mate).getUnclippedStart(); } public int getMappingQuality() { return record.getMappingQuality(); } public boolean overlapsWith(SequenceLocation otherLocation) { if (getRefAlignmentStart() > otherLocation.position || getRefAlignmentEnd() < otherLocation.position || otherLocation.contigIndex != getReferenceIndex()) { return false; } return true; } boolean duplexLeft() { return formsWrongPair() ? getAlignmentStart() <= getMateAlignmentStart() : getReadPositiveStrand(); } public @NonNull SequenceLocation getLocation() { return location; } /** * Not necessarily the same as that of SAMRecord * @return */ public int getReferenceIndex() { return location.contigIndex; } public @NonNull String getReferenceName() { return location.getContigName(); } public int getxLoc() { return xLoc; } public int getyLoc() { return yLoc; } public String getRunAndTile() { return runAndTile; } public boolean isOpticalDuplicate() { return opticalDuplicate; } public float getAveragePhred() { return averagePhred; } public List<ExtendedAlignmentBlock> getAlignmentBlocks() { return ExtendedAlignmentBlock.getAlignmentBlocks(getCigar(), record.getAlignmentStart(), "read cigar"); } public static @Nullable ExtendedSAMRecord getRead(Mutinack analyzer, String name, boolean firstOfPair, SequenceLocation location, int avoidAlignmentStart0Based, int windowHalfWidth) { SAMFileReader bamReader; try { bamReader = analyzer.readerPool.getObj(); } catch (PoolException e) { throw new RuntimeException(e); } try { final QueryInterval[] bamContig = { bamReader.makeQueryInterval(location.contigName, location.position - windowHalfWidth, location.position + windowHalfWidth)}; try (SAMRecordIterator it = bamReader.queryOverlapping(bamContig)) { while (it.hasNext()) { SAMRecord record = it.next(); if (record.getReadName().equals(name) && record.getFirstOfPairFlag() == firstOfPair && record.getAlignmentStart() - 1 != avoidAlignmentStart0Based) { return SubAnalyzer.getExtendedNoCaching(record, new SequenceLocation(location.contigName, analyzer.groupSettings.indexContigNameReverseMap, record.getAlignmentStart() - 1, false), analyzer); } } return null; } } finally { analyzer.readerPool.returnObj(bamReader); } } }
Allow null in ExtendedSAMRecord::equals.
src/uk/org/cinquin/mutinack/ExtendedSAMRecord.java
Allow null in ExtendedSAMRecord::equals.
<ide><path>rc/uk/org/cinquin/mutinack/ExtendedSAMRecord.java <ide> if (this == obj) { <ide> return true; <ide> } <add> if (obj == null) { <add> return false; <add> } <ide> return name.equals(((ExtendedSAMRecord) obj).name); <ide> } <ide>
Java
mit
7c67edbf949d54cf8483647697adfa3f32fa7c50
0
CMPUT301F17T08/habit_rabbit
package ca.ualberta.cmput301f17t08.habitrabbit; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; public class FeedActivity extends AppCompatActivity { public RecyclerView feedRecyclerView; public ArrayList<HabitEvent> feedList; public ArrayList<String> followerList; private historyAdapter cAdapt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.feed); feedRecyclerView = (RecyclerView) findViewById(R.id.feed_recycle); feedRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); //get the current user's feed list feedList = LoginManager.getInstance().getCurrentUser().getHistory(); //get the followers followerList = LoginManager.getInstance().getCurrentUser().getFollowers(); //testing code followerList.add("Yuxuan"); String username; ArrayList<HabitEvent> followerFeedList; // get the followers feed, and append them to the feedList for(int each = 0; each < followerList.size(); each++){ username = followerList.get(each); followerFeedList = new User(username).getHistory(); for (int index = 0; index<followerFeedList.size();index++){ feedList.add(followerFeedList.get(index)); } } // set up the adapter cAdapt = new historyAdapter(LoginManager.getInstance().getCurrentUser().getUsername(), feedList); feedRecyclerView.setAdapter(cAdapt); } public void showMenu(View v){ Intent intent = new Intent(this, MenuActivity.class); startActivity(intent); } }
app/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/FeedActivity.java
package ca.ualberta.cmput301f17t08.habitrabbit; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import java.util.ArrayList; public class FeedActivity extends AppCompatActivity { public RecyclerView feedRecyclerView; public ArrayList<HabitEvent> feedList; public ArrayList<String> followerList; private historyAdapter cAdapt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.feed); feedRecyclerView = (RecyclerView) findViewById(R.id.feed_recycle); feedRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); //get the current user's feed list feedList = LoginManager.getInstance().getCurrentUser().getHistory(); //get the followers followerList = LoginManager.getInstance().getCurrentUser().getFollowers(); String username; ArrayList<HabitEvent> followerFeedList; // get the followers feed, and append them to the feedList for(int each = 0; each < followerList.size(); each++){ username = followerList.get(each); followerFeedList = new User(username).getHistory(); for (int index = 0; index<followerFeedList.size();index++){ feedList.add(followerFeedList.get(index)); } } // set up the adapter cAdapt = new historyAdapter(LoginManager.getInstance().getCurrentUser().getUsername(), feedList); feedRecyclerView.setAdapter(cAdapt); } public void showMenu(View v){ Intent intent = new Intent(this, MenuActivity.class); startActivity(intent); } }
testing can be done once the adding the follower is completed
app/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/FeedActivity.java
testing can be done once the adding the follower is completed
<ide><path>pp/src/main/java/ca/ualberta/cmput301f17t08/habitrabbit/FeedActivity.java <ide> //get the followers <ide> followerList = LoginManager.getInstance().getCurrentUser().getFollowers(); <ide> <add> //testing code <add> followerList.add("Yuxuan"); <add> <add> <ide> String username; <ide> ArrayList<HabitEvent> followerFeedList; <ide> <ide> } <ide> <ide> <add> <add> <add> <add> <ide> // set up the adapter <ide> cAdapt = new historyAdapter(LoginManager.getInstance().getCurrentUser().getUsername(), feedList); <ide> feedRecyclerView.setAdapter(cAdapt);
Java
epl-1.0
8a402719cbad3f6b6ef254813dcb2d17e04a76dd
0
tobiasb/CodeFinder,tobiasb/CodeFinder,tobiasb/CodeFinder
package org.eclipse.recommenders.internal.codesearch.rcp.views; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_OVERLAY_ICONS; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_PARAMETERS; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_POST_QUALIFIED; import static org.eclipse.recommenders.utils.Checks.cast; import java.util.Iterator; import java.util.Set; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.SharedASTProvider; import org.eclipse.jface.text.ITextPresentationListener; import org.eclipse.jface.text.TextPresentation; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.recommenders.codesearch.rcp.index.searcher.SearchResult; import org.eclipse.recommenders.internal.codesearch.rcp.Activator; import org.eclipse.recommenders.utils.annotations.Experimental; import org.eclipse.recommenders.utils.rcp.RCPUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.ViewPart; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.ui.editor.model.XtextDocument; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import com.google.common.base.Optional; @SuppressWarnings("restriction") public class SearchQueryView extends ViewPart implements ISearchView { public static final String ID = SearchQueryView.class.getName(); protected Button triggerSearchButton; protected Text searchQueryText; protected TableViewer searchResultTable; private Combo exampleCombo; private int selectedLanguageIndex = 0; private AbstractEmbeddedEditorWrapper currentEditor = null; public SearchQueryView() { super(); } @Override public void init(final IViewSite site) throws PartInitException { super.init(site); } @Override public void createPartControl(final Composite parent) { parent.setLayout(new GridLayout(2, true)); final Composite compositeForEditor = createCompositeForEditor(parent); createSearchResultsViewer(parent); createTriggerSearchButton(parent); createSearchExampleCombobox(parent); // Default editor currentEditor = new LuceneQueryEditorWrapper(); currentEditor.createQueryEditor(compositeForEditor, exampleCombo, this); createLanguageSelectionComboBox(parent, compositeForEditor); parent.pack(); } private Composite createCompositeForEditor(final Composite parent) { final Composite compositeForEditor = new Composite(parent, SWT.NONE); final GridLayout layout = new GridLayout(1, true); layout.marginWidth = 0; layout.marginHeight = 0; compositeForEditor.setLayout(layout); final GridData gridData = new GridData(GridData.FILL_BOTH); compositeForEditor.setLayoutData(gridData); return compositeForEditor; } private void createSearchExampleCombobox(final Composite parent) { exampleCombo = new Combo(parent, SWT.READ_ONLY); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 1; exampleCombo.setLayoutData(gridData); exampleCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { if (exampleCombo.getSelectionIndex() > 0) { currentEditor.setSearchQuery(exampleCombo.getItems()[exampleCombo.getSelectionIndex()]); exampleCombo.select(0); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createLanguageSelectionComboBox(final Composite parent, final Composite createEmbeddedEditorInComposite) { final Combo combo = new Combo(parent, SWT.READ_ONLY); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 1; combo.setItems(new String[] { LuceneQueryEditorWrapper.getName(), QL1EditorWrapper.getName() }); combo.setLayoutData(gridData); combo.select(selectedLanguageIndex); combo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { selectedLanguageIndex = combo.getSelectionIndex(); if (selectedLanguageIndex == 0) { currentEditor = new LuceneQueryEditorWrapper(); currentEditor .createQueryEditor(createEmbeddedEditorInComposite, exampleCombo, SearchQueryView.this); } else if (selectedLanguageIndex == 1) { currentEditor = new QL1EditorWrapper(); currentEditor .createQueryEditor(createEmbeddedEditorInComposite, exampleCombo, SearchQueryView.this); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createTriggerSearchButton(final Composite parent) { triggerSearchButton = new Button(parent, SWT.PUSH); triggerSearchButton.setText("Search"); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; triggerSearchButton.setLayoutData(gridData); triggerSearchButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { try { doSearch(); } catch (final Exception e1) { Activator.logError(e1); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createSearchResultsViewer(final Composite parent) { searchResultTable = new TableViewer(parent, SWT.VIRTUAL); searchResultTable.setContentProvider(new LazyContentProvider()); searchResultTable.setLabelProvider(new JavaElementLabelProvider(SHOW_OVERLAY_ICONS | SHOW_POST_QUALIFIED | SHOW_PARAMETERS)); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); gridData.horizontalSpan = 1; searchResultTable.getControl().setLayoutData(gridData); searchResultTable.addDoubleClickListener(new IDoubleClickListener() { @Override @Experimental public void doubleClick(final DoubleClickEvent event) { final Optional<IJavaElement> first = RCPUtils.first(event.getSelection()); if (first.isPresent()) { try { final JavaEditor editor = cast(JavaUI.openInEditor(first.get())); final SourceViewer s = (SourceViewer) editor.getViewer(); final XtextDocument document = currentEditor.getDocument(); final IUnitOfWork<Set<String>, XtextResource> searchTermExtractor = currentEditor .getSearchTermExtractor(); if (searchTermExtractor != null) { final Set<String> searchTerms = document.readOnly(searchTermExtractor); s.addTextPresentationListener(new ITextPresentationListener() { @Override public void applyTextPresentation(final TextPresentation textPresentation) { final ITypeRoot cu = (ITypeRoot) EditorUtility.getActiveEditorJavaInput(); final Color foreground = JavaUI.getColorManager().getColor(new RGB(255, 0, 0)); // final Color white = // JavaUI.getColorManager().getColor(new // RGB(255, 255, 255)); final Color background = JavaUI.getColorManager().getColor(new RGB(255, 255, 128)); final Color heuristic = JavaUI.getColorManager().getColor(new RGB(220, 245, 139)); SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_YES, null).accept( new ASTVisitor() { @Override public boolean visit(final SimpleName node) { final String word = node.getIdentifier().toLowerCase(); for (final String searchterm : searchTerms) { final Color gray = Display.getDefault().getSystemColor( SWT.COLOR_GRAY); if (word.equals(searchterm)) { setHighlightStyleForNode(textPresentation, foreground, background, node); } else if (word.contains(searchterm)) { setHighlightStyleForNode(textPresentation, heuristic, gray, node); } } return true; } private void setHighlightStyleForNode( final TextPresentation textPresentation, final Color foreground, final Color background, final ASTNode node) { final int start = node.getStartPosition(); final int length = node.getLength(); calculateRanges(textPresentation, start, length, foreground, background); } @SuppressWarnings("unchecked") private void calculateRanges(final TextPresentation textPresentation, final int start, final int length, final Color foreground, final Color background) { final Iterator<StyleRange> srIterator = textPresentation .getAllStyleRangeIterator(); while (srIterator.hasNext()) { final StyleRange current = srIterator.next(); if (current.start > start && current.start + current.length > start + length && current.start < start + length) { textPresentation.mergeStyleRange(new StyleRange( current.start, start + length - current.start, foreground, background)); } else if (current.start >= start && current.start + current.length <= start + length) { current.background = background; current.foreground = foreground; } else if (current.start < start && current.start + current.length > start + length) { textPresentation.mergeStyleRange(new StyleRange(start, length, foreground, background)); } else if (current.start < start && current.length + current.start < start + length && current.start + current.length > start) { textPresentation.mergeStyleRange(new StyleRange(start, start + length - current.start + current.length, foreground, background)); } } }; }); } }); s.invalidateTextPresentation(); } } catch (final PartInitException e) { Activator.logError(e); } catch (final JavaModelException e) { Activator.logError(e); } } } }); } public void setSearching() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // searchQueryText.setEnabled(false); searchResultTable.setItemCount(0); triggerSearchButton.setEnabled(false); } }); } public void setResult(final SearchResult result) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { searchResultTable.setInput(result); searchResultTable.setItemCount(result.scoreDocs().length); triggerSearchButton.setEnabled(true); } }); } @Override public void setFocus() { // searchQueryText.setFocus(); } @Override public void doSearch() throws Exception { final WorkspaceJob job = new WorkspaceJob("Searching...") { @Override public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException { setSearching(); try { if (currentEditor != null) { setResult(currentEditor.search()); } } catch (final Exception e) { Activator.logError(e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; job.schedule(); } @Override public void setSearchEnabled(final boolean value) { triggerSearchButton.setEnabled(value); } }
plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/SearchQueryView.java
package org.eclipse.recommenders.internal.codesearch.rcp.views; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_OVERLAY_ICONS; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_PARAMETERS; import static org.eclipse.jdt.ui.JavaElementLabelProvider.SHOW_POST_QUALIFIED; import static org.eclipse.recommenders.utils.Checks.cast; import java.util.Iterator; import java.util.Set; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.SharedASTProvider; import org.eclipse.jface.text.ITextPresentationListener; import org.eclipse.jface.text.TextPresentation; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.recommenders.codesearch.rcp.index.searcher.SearchResult; import org.eclipse.recommenders.internal.codesearch.rcp.Activator; import org.eclipse.recommenders.utils.annotations.Experimental; import org.eclipse.recommenders.utils.rcp.RCPUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.ViewPart; import org.eclipse.xtext.resource.XtextResource; import org.eclipse.xtext.ui.editor.model.XtextDocument; import org.eclipse.xtext.util.concurrent.IUnitOfWork; import com.google.common.base.Optional; @SuppressWarnings("restriction") public class SearchQueryView extends ViewPart implements ISearchView { public static final String ID = SearchQueryView.class.getName(); protected Button triggerSearchButton; protected Text searchQueryText; protected TableViewer searchResultTable; private Combo exampleCombo; private int selectedLanguageIndex = 0; private AbstractEmbeddedEditorWrapper currentEditor = null; public SearchQueryView() { super(); } @Override public void init(final IViewSite site) throws PartInitException { super.init(site); } @Override public void createPartControl(final Composite parent) { parent.setLayout(new GridLayout(2, true)); final Composite compositeForEditor = createCompositeForEditor(parent); createSearchResultsViewer(parent); createTriggerSearchButton(parent); createSearchExampleCombobox(parent); // Default editor currentEditor = new LuceneQueryEditorWrapper(); currentEditor.createQueryEditor(compositeForEditor, exampleCombo, this); createLanguageSelectionComboBox(parent, compositeForEditor); parent.pack(); } private Composite createCompositeForEditor(final Composite parent) { final Composite compositeForEditor = new Composite(parent, SWT.NONE); final GridLayout layout = new GridLayout(1, true); layout.marginWidth = 0; layout.marginHeight = 0; compositeForEditor.setLayout(layout); final GridData gridData = new GridData(GridData.FILL_BOTH); compositeForEditor.setLayoutData(gridData); return compositeForEditor; } private void createSearchExampleCombobox(final Composite parent) { exampleCombo = new Combo(parent, SWT.READ_ONLY); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 1; exampleCombo.setLayoutData(gridData); exampleCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { if (exampleCombo.getSelectionIndex() > 0) { currentEditor.setSearchQuery(exampleCombo.getItems()[exampleCombo.getSelectionIndex()]); exampleCombo.select(0); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createLanguageSelectionComboBox(final Composite parent, final Composite createEmbeddedEditorInComposite) { final Combo combo = new Combo(parent, SWT.READ_ONLY); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = 1; combo.setItems(new String[] { LuceneQueryEditorWrapper.getName(), QL1EditorWrapper.getName() }); combo.setLayoutData(gridData); combo.select(selectedLanguageIndex); combo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { selectedLanguageIndex = combo.getSelectionIndex(); if (selectedLanguageIndex == 0) { currentEditor = new LuceneQueryEditorWrapper(); currentEditor .createQueryEditor(createEmbeddedEditorInComposite, exampleCombo, SearchQueryView.this); } else if (selectedLanguageIndex == 1) { currentEditor = new QL1EditorWrapper(); currentEditor .createQueryEditor(createEmbeddedEditorInComposite, exampleCombo, SearchQueryView.this); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createTriggerSearchButton(final Composite parent) { triggerSearchButton = new Button(parent, SWT.PUSH); triggerSearchButton.setText("Search"); final GridData gridData = new GridData(); gridData.horizontalSpan = 2; triggerSearchButton.setLayoutData(gridData); triggerSearchButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { try { doSearch(); } catch (final Exception e1) { Activator.logError(e1); } } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }); } private void createSearchResultsViewer(final Composite parent) { searchResultTable = new TableViewer(parent, SWT.VIRTUAL); searchResultTable.setContentProvider(new LazyContentProvider()); searchResultTable.setLabelProvider(new JavaElementLabelProvider(SHOW_OVERLAY_ICONS | SHOW_POST_QUALIFIED | SHOW_PARAMETERS)); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); gridData.horizontalSpan = 1; searchResultTable.getControl().setLayoutData(gridData); searchResultTable.addDoubleClickListener(new IDoubleClickListener() { @Override @Experimental public void doubleClick(final DoubleClickEvent event) { final Optional<IJavaElement> first = RCPUtils.first(event.getSelection()); if (first.isPresent()) { try { final JavaEditor editor = cast(JavaUI.openInEditor(first.get())); final SourceViewer s = (SourceViewer) editor.getViewer(); final XtextDocument document = currentEditor.getDocument(); final IUnitOfWork<Set<String>, XtextResource> searchTermExtractor = currentEditor .getSearchTermExtractor(); if (searchTermExtractor != null) { final Set<String> searchTerms = document.readOnly(searchTermExtractor); s.addTextPresentationListener(new ITextPresentationListener() { @Override public void applyTextPresentation(final TextPresentation textPresentation) { final ITypeRoot cu = (ITypeRoot) EditorUtility.getActiveEditorJavaInput(); final Color foreground = JavaUI.getColorManager().getColor(new RGB(255, 0, 0)); // final Color white = // JavaUI.getColorManager().getColor(new // RGB(255, 255, 255)); final Color background = JavaUI.getColorManager().getColor(new RGB(255, 255, 128)); final Color heuristic = JavaUI.getColorManager().getColor(new RGB(220, 245, 139)); SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_YES, null).accept( new ASTVisitor() { @Override public boolean visit(final SimpleName node) { final String word = node.getIdentifier().toLowerCase(); for (final String searchterm : searchTerms) { final Color gray = Display.getDefault().getSystemColor( SWT.COLOR_GRAY); if (word.equals(searchterm)) { setHighlightStyleForNode(textPresentation, foreground, background, node); } else if (word.contains(searchterm)) { setHighlightStyleForNode(textPresentation, heuristic, gray, node); } } return true; } private void setHighlightStyleForNode( final TextPresentation textPresentation, final Color foreground, final Color background, final ASTNode node) { final int start = node.getStartPosition(); final int length = node.getLength(); calculateRanges(textPresentation, start, length, foreground, background); } @SuppressWarnings("unchecked") private void calculateRanges(final TextPresentation textPresentation, final int start, final int length, final Color foreground, final Color background) { final Iterator<StyleRange> srIterator = textPresentation .getAllStyleRangeIterator(); while (srIterator.hasNext()) { final StyleRange current = srIterator.next(); if (current.start > start && current.start + current.length > start + length && current.start < start + length) { textPresentation.mergeStyleRange(new StyleRange( current.start, start + length - current.start, foreground, background)); } else if (current.start >= start && current.start + current.length <= start + length) { current.background = background; current.foreground = foreground; } else if (current.start < start && current.start + current.length > start + length) { textPresentation.mergeStyleRange(new StyleRange(start, length, foreground, background)); } else if (current.start < start && current.length + current.start < start + length && current.start + current.length > start) { textPresentation.mergeStyleRange(new StyleRange(start, start + length - current.start + current.length, foreground, background)); } } }; }); } }); s.invalidateTextPresentation(); } } catch (final PartInitException e) { Activator.logError(e); } catch (final JavaModelException e) { Activator.logError(e); } } } }); } public void setSearching() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { // searchQueryText.setEnabled(false); searchResultTable.setItemCount(0); triggerSearchButton.setEnabled(false); } }); } public void setResult(final SearchResult result) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { searchResultTable.setInput(result); searchResultTable.setItemCount(result.scoreDocs().length); } }); } @Override public void setFocus() { // searchQueryText.setFocus(); } @Override public void doSearch() throws Exception { final WorkspaceJob job = new WorkspaceJob("Searching...") { @Override public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException { setSearching(); try { if (currentEditor != null) { setResult(currentEditor.search()); } } catch (final Exception e) { Activator.logError(e); return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; job.schedule(); } @Override public void setSearchEnabled(final boolean value) { triggerSearchButton.setEnabled(value); } }
[ui] search button wasn't enabled after query finished...
plugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/SearchQueryView.java
[ui] search button wasn't enabled after query finished...
<ide><path>lugins/org.eclipselabs.recommenders.codesearch.rcp/src/org/eclipse/recommenders/internal/codesearch/rcp/views/SearchQueryView.java <ide> public void run() { <ide> searchResultTable.setInput(result); <ide> searchResultTable.setItemCount(result.scoreDocs().length); <add> triggerSearchButton.setEnabled(true); <ide> } <ide> }); <ide>
Java
mit
f8a1160a05e587d5306e269132b1ed9a41f531cd
0
mockito/mockito,bric3/mockito,bric3/mockito,bric3/mockito,mockito/mockito,terebesirobert/mockito,mockito/mockito,ze-pequeno/mockito,ze-pequeno/mockito
package org.mockitousage.debugging; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.internal.debugging.InvocationsPrinter; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; public class InvocationsPrinterTest extends TestBase { @Mock IMethods mock; @Test public void no_invocations() { Assert.assertEquals("No interactions and stubbings found for mock: mock", new InvocationsPrinter().printInvocations(mock)); } @Test public void prints_invocations() { mock.simpleMethod(100); triggerInteraction(); assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(100);\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n")) .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_stubbings() { triggerStubbing(); assertThat(filterLineNo("[Mockito] Unused stubbings of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n")) .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_invocations_and_stubbings() { triggerStubbing(); mock.simpleMethod("a"); triggerInteraction(); assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n")) .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_invocations_and_unused_stubbings() { triggerStubbing(); mock.simpleMethod("b"); triggerInteraction(); assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(\"b\");\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" + "[Mockito] Unused stubbings of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n")) .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); } private void triggerInteraction() { mock.otherMethod(); } private void triggerStubbing() { when(mock.simpleMethod("a")).thenReturn("x"); } }
src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java
package org.mockitousage.debugging; import org.junit.Assert; import org.junit.Test; import org.mockito.Mock; import org.mockito.internal.debugging.InvocationsPrinter; import org.mockitousage.IMethods; import org.mockitoutil.TestBase; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; public class InvocationsPrinterTest extends TestBase { @Mock IMethods mock; @Test public void no_invocations() { Assert.assertEquals("No interactions and stubbings found for mock: mock", new InvocationsPrinter().printInvocations(mock)); } @Test public void prints_invocations() { mock.simpleMethod(100); triggerInteraction(); assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(100);\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n"), filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_stubbings() { triggerStubbing(); assertEquals(filterLineNo("[Mockito] Unused stubbings of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n"), filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_invocations_and_stubbings() { triggerStubbing(); mock.simpleMethod("a"); triggerInteraction(); assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n"), filterLineNo(new InvocationsPrinter().printInvocations(mock))); } @Test public void prints_invocations_and_unused_stubbings() { triggerStubbing(); mock.simpleMethod("b"); triggerInteraction(); assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + " 1. mock.simpleMethod(\"b\");\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" + " 2. mock.otherMethod();\n" + " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" + "[Mockito] Unused stubbings of: mock\n" + " 1. mock.simpleMethod(\"a\");\n" + " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n"), filterLineNo(new InvocationsPrinter().printInvocations(mock))); } private void triggerInteraction() { mock.otherMethod(); } private void triggerStubbing() { when(mock.simpleMethod("a")).thenReturn("x"); } }
Used AssertJ Updated to use AssertJ following really good feedback from Brice.
src/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java
Used AssertJ
<ide><path>rc/test/java/org/mockitousage/debugging/InvocationsPrinterTest.java <ide> package org.mockitousage.debugging; <ide> <add>import org.assertj.core.api.Assertions; <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> import org.mockito.Mock; <ide> import org.mockitousage.IMethods; <ide> import org.mockitoutil.TestBase; <ide> <add>import static org.assertj.core.api.Assertions.assertThat; <ide> import static org.junit.Assert.assertEquals; <ide> import static org.mockito.Mockito.when; <ide> <ide> mock.simpleMethod(100); <ide> triggerInteraction(); <ide> <del> assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + <add> assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + <ide> " 1. mock.simpleMethod(100);\n" + <ide> " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations(InvocationsPrinterTest.java:0)\n" + <ide> " 2. mock.otherMethod();\n" + <del> " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n"), <del> filterLineNo(new InvocationsPrinter().printInvocations(mock))); <add> " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:0)\n")) <add> .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); <ide> } <ide> <ide> @Test public void prints_stubbings() { <ide> triggerStubbing(); <ide> <del> assertEquals(filterLineNo("[Mockito] Unused stubbings of: mock\n" + <add> assertThat(filterLineNo("[Mockito] Unused stubbings of: mock\n" + <ide> " 1. mock.simpleMethod(\"a\");\n" + <del> " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n"), <del> filterLineNo(new InvocationsPrinter().printInvocations(mock))); <add> " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:70)\n")) <add> .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); <ide> } <ide> <ide> @Test public void prints_invocations_and_stubbings() { <ide> mock.simpleMethod("a"); <ide> triggerInteraction(); <ide> <del> assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + <add> assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + <ide> " 1. mock.simpleMethod(\"a\");\n" + <ide> " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_stubbings(InvocationsPrinterTest.java:49)\n" + <ide> " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:73)\n" + <ide> " 2. mock.otherMethod();\n" + <del> " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n"), <del> filterLineNo(new InvocationsPrinter().printInvocations(mock))); <add> " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n")) <add> .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); <ide> } <ide> <ide> @Test public void prints_invocations_and_unused_stubbings() { <ide> mock.simpleMethod("b"); <ide> triggerInteraction(); <ide> <del> assertEquals(filterLineNo("[Mockito] Interactions of: mock\n" + <add> assertThat(filterLineNo("[Mockito] Interactions of: mock\n" + <ide> " 1. mock.simpleMethod(\"b\");\n" + <ide> " -> at org.mockitousage.debugging.InvocationsPrinterTest.prints_invocations_and_unused_stubbings(InvocationsPrinterTest.java:55)\n" + <ide> " 2. mock.otherMethod();\n" + <ide> " -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerInteraction(InvocationsPrinterTest.java:34)\n" + <ide> "[Mockito] Unused stubbings of: mock\n" + <ide> " 1. mock.simpleMethod(\"a\");\n" + <del> " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n"), <del> filterLineNo(new InvocationsPrinter().printInvocations(mock))); <add> " - stubbed -> at org.mockitousage.debugging.InvocationsPrinterTest.triggerStubbing(InvocationsPrinterTest.java:62)\n")) <add> .isEqualTo(filterLineNo(new InvocationsPrinter().printInvocations(mock))); <ide> } <ide> <ide> private void triggerInteraction() {
Java
apache-2.0
43710b10b3262d44e063743db73f7693d97a446e
0
scalecube/scalecube,scalecube/scalecube,servicefabric/servicefabric
package io.scalecube.services.benchmarks.gateway.codec; import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.metrics.BenchmarkMeter; import io.scalecube.benchmarks.metrics.BenchmarkTimer; import io.scalecube.benchmarks.metrics.BenchmarkTimer.Context; import io.scalecube.services.gateway.ReferenceCountUtil; import io.scalecube.services.gateway.ws.GatewayMessage; import io.scalecube.services.gateway.ws.GatewayMessageCodec; import java.util.Optional; import java.util.concurrent.TimeUnit; public class GwMessageDecoderBenchmark { /** * Main runner. * * @param args program arguments */ public static void main(String[] args) { BenchmarkSettings settings = BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build(); new GwMessageCodecBenchmarkState(settings) .runForSync( state -> { GatewayMessageCodec codec = state.codec(); BenchmarkTimer timer = state.timer("timer"); BenchmarkMeter meter = state.meter("meter"); return i -> { Context timerContext = timer.time(); GatewayMessage message = codec.decode(state.byteBufExample().retain()); Optional.ofNullable(message.data()) // .ifPresent(ReferenceCountUtil::safestRelease); timerContext.stop(); meter.mark(); return message; }; }); } }
services-benchmarks/src/main/java/io/scalecube/services/benchmarks/gateway/codec/GwMessageDecoderBenchmark.java
package io.scalecube.services.benchmarks.gateway.codec; import io.netty.buffer.ByteBuf; import io.scalecube.benchmarks.BenchmarkSettings; import io.scalecube.benchmarks.metrics.BenchmarkMeter; import io.scalecube.benchmarks.metrics.BenchmarkTimer; import io.scalecube.benchmarks.metrics.BenchmarkTimer.Context; import io.scalecube.services.gateway.ReferenceCountUtil; import io.scalecube.services.gateway.ws.GatewayMessage; import io.scalecube.services.gateway.ws.GatewayMessageCodec; import java.util.Optional; import java.util.concurrent.TimeUnit; public class GwMessageDecoderBenchmark { /** * Main runner. * * @param args program arguments */ public static void main(String[] args) { BenchmarkSettings settings = BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build(); new GwMessageCodecBenchmarkState(settings) .runForSync( state -> { GatewayMessageCodec codec = state.codec(); ByteBuf bb = state.byteBufExample(); BenchmarkTimer timer = state.timer("timer"); BenchmarkMeter meter = state.meter("meter"); return i -> { Context timerContext = timer.time(); GatewayMessage message = codec.decode(bb.retain()); Optional.ofNullable(message.data()) // .ifPresent(ReferenceCountUtil::safestRelease); timerContext.stop(); meter.mark(); return message; }; }); } }
Fixed issues/423 with failing GwMessageDecoderBenchmark.java
services-benchmarks/src/main/java/io/scalecube/services/benchmarks/gateway/codec/GwMessageDecoderBenchmark.java
Fixed issues/423 with failing GwMessageDecoderBenchmark.java
<ide><path>ervices-benchmarks/src/main/java/io/scalecube/services/benchmarks/gateway/codec/GwMessageDecoderBenchmark.java <ide> package io.scalecube.services.benchmarks.gateway.codec; <ide> <del>import io.netty.buffer.ByteBuf; <ide> import io.scalecube.benchmarks.BenchmarkSettings; <ide> import io.scalecube.benchmarks.metrics.BenchmarkMeter; <ide> import io.scalecube.benchmarks.metrics.BenchmarkTimer; <ide> .runForSync( <ide> state -> { <ide> GatewayMessageCodec codec = state.codec(); <del> ByteBuf bb = state.byteBufExample(); <ide> BenchmarkTimer timer = state.timer("timer"); <ide> BenchmarkMeter meter = state.meter("meter"); <ide> <ide> return i -> { <ide> Context timerContext = timer.time(); <del> GatewayMessage message = codec.decode(bb.retain()); <add> GatewayMessage message = codec.decode(state.byteBufExample().retain()); <ide> Optional.ofNullable(message.data()) // <ide> .ifPresent(ReferenceCountUtil::safestRelease); <ide> timerContext.stop();
Java
unlicense
5ccb33362b5365c3ceebc69c346bd6d55af0c234
0
rafmeeusen/java-examples
package net.meeusen.crypto; import java.util.Arrays; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.modes.CCMBlockCipher; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import net.meeusen.util.ByteString; /** * Wrappers around BC AES-CCM, with easy API to validate NIST test vectors for AES-CCM. * * */ public class AesCcmTest { public byte[] getCalculatedOutput() { return calculatedOutput; } public byte[] getPayLoad() { return payLoad; } public byte[] getCipherText() { return cipherText; } private CCMBlockCipher ccmCipher; private KeyParameter keyParameter; private int TlenBytes; private byte[] key; private byte[] nonce; private byte[] Adata; private byte[] payLoad; private byte[] cipherText; private TestType type; // following can be either payload or ciphertext depending on test type. private byte[] calculatedOutput; public String toString() { return this.type.toString() + " Tlen:" + TlenBytes + " KeyLen:" + key.length + " Nlen: " + nonce.length + " Alen: " + Adata.length + " Plen:" + payLoad.length; } /** * Constructor with (hex) String arguments * @throws Exception * */ public AesCcmTest(TestType type, int argTlenBytes, String Key, String Nonce, String argAdata, String argPayload, String argCipherText) throws Exception { this(type, argTlenBytes, new ByteString(Key).getBytes(), new ByteString(Nonce).getBytes(), new ByteString(argAdata).getBytes(), new ByteString(argPayload).getBytes(), new ByteString(argCipherText).getBytes()); } /** * Constructor with byte[] arguments * @throws Exception * */ public AesCcmTest(TestType argTestType, int argTlenBytes, byte[] Key, byte[] Nonce, byte[] argAdata, byte[] argPayload, byte[] argCipherText) throws Exception { switch ( argTestType ) { case ENCRYPT: // need payload to encrypt something if ( argPayload == null ) throw new Exception ("Cannot encrypt without payload."); break; case DECRYPT: // need CT to decrypt something if ( argCipherText == null ) throw new Exception ("Cannot decrypt without ciphertext."); break; default: throw new Exception("not allowed"); } this.type = argTestType; this.ccmCipher = new CCMBlockCipher(new AESEngine()); this.keyParameter = new KeyParameter(Key); this.TlenBytes = argTlenBytes; this.key = Key.clone(); this.nonce = Nonce.clone(); // some of these are optional: if ( argAdata != null ) this.Adata = argAdata.clone(); if ( argPayload != null ) this.payLoad = argPayload.clone(); if ( argCipherText != null ) this.cipherText = argCipherText.clone(); } /** * encrypt or decrypt depending on test type. * store result in instance variable calculatedOutput * result is NOT interpreted, not compared to any expected output... * @throws Exception * */ public void doCalculate() throws Exception{ boolean isEncryption; byte[] testInput=null; //byte[] testOutput=null; switch ( this.type ) { case ENCRYPT: isEncryption = true; testInput = this.payLoad; break; case DECRYPT: isEncryption = false; testInput = this.cipherText; break; default: throw new Exception("not allowed"); } /** Java docs: * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/crypto/modes/CCMBlockCipher.html * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/crypto/params/AEADParameters.html */ // init int TlenBits = this.TlenBytes * 8; ccmCipher.init(isEncryption, new AEADParameters(this.keyParameter, TlenBits, this.nonce, this.Adata)); // process int inputOffset = 0; int outputOffset = 0; int expectedOutputSize = this.ccmCipher.getOutputSize(testInput.length); this.calculatedOutput = new byte[expectedOutputSize]; int nrProcessBytes = this.ccmCipher.processPacket(testInput, inputOffset, testInput.length, this.calculatedOutput, outputOffset); if ( nrProcessBytes != expectedOutputSize ) { throw new Exception("unexpected internal error or misunderstanding..."); } // strange, when I do another doFinal, there is data coming out, not // expected, and not sure what this data means... // byte[] finalOutput = new byte[ccmCipher.getOutputSize(0)]; // int nrOutputBytes =ccmCipher.doFinal(finalOutput, 0); // if ( nrOutputBytes != finalOutput.length) { // throw new Error("this should not happen."); // } } /** * calculate AND compare with expected output * */ public boolean checkTestVector() throws Exception { this.doCalculate(); byte[] expectedOutput=null; switch ( this.type ) { case ENCRYPT: expectedOutput = this.cipherText; break; case DECRYPT: expectedOutput = this.payLoad; break; default: throw new Exception("not allowed"); } return Arrays.equals(this.calculatedOutput, expectedOutput); } /** * Check some CCM test vectors NIST. * */ public static void main(String[] args) throws Exception { /** * * http://csrc.nist.gov/groups/STM/cavp/block-cipher-modes.html#test- * vectors explained in : * http://csrc.nist.gov/groups/STM/cavp/documents/mac/CCMVS.pdf (ccmvs = * ccm validation system) * * summary of test vector types: DVPT : Decryption-Verification Process * Test VADT : variable associated data test VNT : variable nonce test * VPT : variable playload test VTT : variable tag test */ AesCcmTest someNistAesCcmTestVectors[] = new AesCcmTest[] { // from VPT256.rsp NIST file: /* 0 */ new AesCcmTest(TestType.ENCRYPT, 16, "7da6ef35ad594a09cb74daf27e50a6b30d6b4160cf0de41ee32bbf2a208b911d", "98a32d7fe606583e2906420297", "217d130408a738e6a833931e69f8696960c817407301560bbe5fbd92361488b4", "b0053d1f490809794250d856062d0aaa92", "a6341ee3d60eb34a8a8bc2806d50dd57a3f628ee49a8c2005c7d07d354bf80994d"), /* 1 */ new AesCcmTest(TestType.ENCRYPT, 16, "c6c14c655e52c8a4c7e8d54e974d698e1f21ee3ba717a0adfa6136d02668c476", "291e91b19de518cd7806de44f6", "b4f8326944a45d95f91887c2a6ac36b60eea5edef84c1c358146a666b6878335", "", "ca482c674b599046cc7d7ee0d00eec1e"), /* 2 */ new AesCcmTest(TestType.ENCRYPT, 16, "cc49d4a397887cb57bc92c8a8c26a7aac205c653ef4011c1f48390ad35f5df14", "6df8c5c28d1728975a0b766cd7", "080f82469505118842e5fa70df5323de175a37609904ee5e76288f94ca84b3c5", "1a", "a5f24e87a11a95374d4c190945bf08ef2f"), /* 3 */ new AesCcmTest(TestType.ENCRYPT, 16, "62b82637e567ad27c3066d533ed76e314522ac5c53851a8c958ce6c64b82ffd0", "5bc2896d8b81999546f88232ab", "fffb40b0d18cb23018aac109bf62d849adca42629d8a9ad1299b83fe274f9a63", "87294078", "2bc22735ab21dfdcfe95bd83592fb6b4168d9a23"), // from VNT256.rsp: /* 4 */ new AesCcmTest(TestType.ENCRYPT, 16, "553521a765ab0c3fd203654e9916330e189bdf951feee9b44b10da208fee7acf", "aaa23f101647d8", "a355d4c611812e5f9258d7188b3df8851477094ffc2af2cf0c8670db903fbbe0", "644eb34b9a126e437b5e015eea141ca1a88020f2d5d6cc2c", "27ed90668174ebf8241a3c74b35e1246b6617e4123578f153bdb67062a13ef4e986f5bb3d0bb4307"), /* 5 */ new AesCcmTest(TestType.ENCRYPT, 16, "4a75ff2f66dae2935403cce27e829ad8be98185c73f8bc61d3ce950a83007e11", "ef284d1ddf35d1d23de6a2f84b", "0b90b3a087b9a4d3267bc57c470695ef7cf658353f2f680ee00ccc32c2ba0bdc", "bf35ddbad5e059169468ae8537f00ec790cc038b9ed0a5d7", "b702ad593b4169fd7011f0288e4e62620543095186b32c122389523b5ccc33c6b41b139108a99442"), // from VADT128.rsp: /* 6 */ new AesCcmTest(TestType.ENCRYPT, 16, "d24a3d3dde8c84830280cb87abad0bb3", "f1100035bb24a8d26004e0e24b", "", "7c86135ed9c2a515aaae0e9a208133897269220f30870006", "1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab1123301219c70599b7c373ad4b3ad67b"), /* 7 */ new AesCcmTest(TestType.ENCRYPT, 16, "5a33980e71e7d67fd6cf171454dc96e5", "33ae68ebb8010c6b3da6b9cb29", "eca622a37570df619e10ebb18bebadb2f2b49c4d2b2ff715873bb672e30fc0ff", "a34dfa24847c365291ce1b54bcf8d9a75d861e5133cc3a74", "7a60fa7ee8859e283cce378fb6b95522ab8b70efcdb0265f7c4b4fa597666b86dd1353e400f28864"), // from VTT192.rsp: /* 8 */ new AesCcmTest(TestType.ENCRYPT, 4, "11fd45743d946e6d37341fec49947e8c70482494a8f07fcc", "c6aeebcb146cfafaae66f78aab", "7dc8c52144a7cb65b3e5a846e8fd7eae37bf6996c299b56e49144ebf43a1770f", "ee7e6075ba52846de5d6254959a18affc4faf59c8ef63489", "137d9da59baf5cbfd46620c5f298fc766de10ac68e774edf1f2c5bad"), /* 9 */ new AesCcmTest(TestType.ENCRYPT, 14, "d2d4482ea8e98c1cf309671895a16610152ce283434bca38", "6ee177d48f59bd37045ec03731", "d4cd69b26ea43596278b8caec441fedcf0d729d4e0c27ed1332f48871c96e958", "e4abe343f98a2df09413c3defb85b56a6d34dba305dcce46", "7e8f27726c042d73aa6ebf43217395202e0af071eacf53790065601bb59972c35b580852e684"), // from DVPT256.rsp: /* 10 */ new AesCcmTest(TestType.DECRYPT, 4, "af063639e66c284083c5cf72b70d8bc277f5978e80d9322d99f2fdc718cda569", "a544218dadd3c1", "", "d3d5424e20fbec43ae495353ed830271515ab104f8860c98", "64a1341679972dc5869fcf69b19d5c5ea50aa0b5e985f5b722aa8d59"), /* 11 */ new AesCcmTest(TestType.DECRYPT, 4, "a4bc10b1a62c96d459fbaf3a5aa3face7313bb9e1253e696f96a7a8e36801088", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "", "866d4227"), /* 12 */ new AesCcmTest(TestType.DECRYPT, 16, "314a202f836f9f257e22d8c11757832ae5131d357a72df88f3eff0ffcee0da4e", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "e8de970f6ee8e80ede933581b5bcf4d837e2b72baa8b00c3", "8d34cdca37ce77be68f65baf3382e31efa693e63f914a781367f30f2eaad8c063ca50795acd90203"), }; System.out.println("Running " + someNistAesCcmTestVectors.length + " NIST test vectors."); int testCounter = 0; for (AesCcmTest t : someNistAesCcmTestVectors) { System.out.print(testCounter + ":" + t + ": "); boolean hasPassed = t.checkTestVector(); if (!hasPassed) { System.out.println("ERROR."); } else { System.out.println("OK."); } testCounter++; } System.out.println("DONE running NIST test vectors."); } public enum TestType { ENCRYPT, DECRYPT; public String toString() { switch (this) { case ENCRYPT: return "ENCRYPT"; case DECRYPT: return "DECRYPT"; default: throw new IllegalArgumentException(); } } } }
cryptography/src/net/meeusen/crypto/AesCcmTest.java
package net.meeusen.crypto; import java.util.Arrays; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.modes.CCMBlockCipher; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import net.meeusen.util.ByteString; public class AesCcmTest { private CCMBlockCipher ccmCipher; private KeyParameter keyParameter; private int TlenBytes; // nr bytes! private byte[] key; private byte[] nonce; private byte[] Adata; private byte[] Payload; private byte[] ExpectedCT; private TestType type; public String toString() { return this.type.toString() + " Tlen:" + TlenBytes + " KeyLen:" + key.length + " Nlen: " + nonce.length + " Alen: " + Adata.length + " Plen:" + Payload.length; } public AesCcmTest(TestType type, int Tlen, String Key, String Nonce, String Adata, String Payload, String ExpectedCT) throws IllegalStateException, InvalidCipherTextException { this(type, Tlen, new ByteString(Key).getBytes(), new ByteString(Nonce).getBytes(), new ByteString(Adata).getBytes(), new ByteString(Payload).getBytes(), new ByteString(ExpectedCT).getBytes()); } public AesCcmTest(TestType testType, int Tlen, byte[] Key, byte[] Nonce, byte[] Adata, byte[] Payload, byte[] ExpectedCT) throws IllegalStateException, InvalidCipherTextException { this.type = testType; this.ccmCipher = new CCMBlockCipher(new AESEngine()); this.keyParameter = new KeyParameter(Key); this.TlenBytes = Tlen; this.key = Key.clone(); this.nonce = Nonce.clone(); this.Adata = Adata.clone(); this.Payload = Payload.clone(); this.ExpectedCT = ExpectedCT.clone(); } /** * use BC to check (NIST) test vector. Java doc: * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/ * crypto/params/AEADParameters.html * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/ * crypto/modes/CCMBlockCipher.html */ public boolean checkTestVector() throws IllegalStateException, InvalidCipherTextException { boolean isEncryption; byte[] testInput; byte[] ourOutput; byte[] expectedOutput; if (this.type == TestType.ENCRYPT) { isEncryption = true; testInput = this.Payload; // stream cipher: CT len = PT len (plus tag) ourOutput = new byte[this.Payload.length + this.TlenBytes]; expectedOutput = this.ExpectedCT; } else { isEncryption = false; testInput = this.ExpectedCT; ourOutput = new byte[this.ExpectedCT.length - this.TlenBytes]; expectedOutput = this.Payload; } int TlenBits = this.TlenBytes * 8; ccmCipher.init(isEncryption, new AEADParameters(this.keyParameter, TlenBits, this.nonce, this.Adata)); int inputOffset = 0; int outputOffset = 0; int nrProcessBytes = this.ccmCipher.processPacket(testInput, inputOffset, testInput.length, ourOutput, outputOffset); if (nrProcessBytes != ourOutput.length) { System.out.println( "mmmm, our processPacket didn't give number of expected bytes. Maybe doFinal is needed after all..."); } // strange, when I do another doFinal, there is data coming out, not // expected, and not sure what this data means... // byte[] finalOutput = new byte[ccmCipher.getOutputSize(0)]; // int nrOutputBytes =ccmCipher.doFinal(finalOutput, 0); // if ( nrOutputBytes != finalOutput.length) { // throw new Error("this should not happen."); // } return Arrays.equals(ourOutput, expectedOutput); } public static void main(String[] args) throws IllegalStateException, InvalidCipherTextException { /** * CCM test vectors NIST: * http://csrc.nist.gov/groups/STM/cavp/block-cipher-modes.html#test- * vectors explained in : * http://csrc.nist.gov/groups/STM/cavp/documents/mac/CCMVS.pdf (ccmvs = * ccm validation system) * * summary of test vector types: DVPT : Decryption-Verification Process * Test VADT : variable associated data test VNT : variable nonce test * VPT : variable playload test VTT : variable tag test */ AesCcmTest someNistAesCcmTestVectors[] = new AesCcmTest[] { // from VPT256.rsp NIST file: /* 0 */ new AesCcmTest(TestType.ENCRYPT, 16, "7da6ef35ad594a09cb74daf27e50a6b30d6b4160cf0de41ee32bbf2a208b911d", "98a32d7fe606583e2906420297", "217d130408a738e6a833931e69f8696960c817407301560bbe5fbd92361488b4", "b0053d1f490809794250d856062d0aaa92", "a6341ee3d60eb34a8a8bc2806d50dd57a3f628ee49a8c2005c7d07d354bf80994d"), /* 1 */ new AesCcmTest(TestType.ENCRYPT, 16, "c6c14c655e52c8a4c7e8d54e974d698e1f21ee3ba717a0adfa6136d02668c476", "291e91b19de518cd7806de44f6", "b4f8326944a45d95f91887c2a6ac36b60eea5edef84c1c358146a666b6878335", "", "ca482c674b599046cc7d7ee0d00eec1e"), /* 2 */ new AesCcmTest(TestType.ENCRYPT, 16, "cc49d4a397887cb57bc92c8a8c26a7aac205c653ef4011c1f48390ad35f5df14", "6df8c5c28d1728975a0b766cd7", "080f82469505118842e5fa70df5323de175a37609904ee5e76288f94ca84b3c5", "1a", "a5f24e87a11a95374d4c190945bf08ef2f"), /* 3 */ new AesCcmTest(TestType.ENCRYPT, 16, "62b82637e567ad27c3066d533ed76e314522ac5c53851a8c958ce6c64b82ffd0", "5bc2896d8b81999546f88232ab", "fffb40b0d18cb23018aac109bf62d849adca42629d8a9ad1299b83fe274f9a63", "87294078", "2bc22735ab21dfdcfe95bd83592fb6b4168d9a23"), // from VNT256.rsp: /* 4 */ new AesCcmTest(TestType.ENCRYPT, 16, "553521a765ab0c3fd203654e9916330e189bdf951feee9b44b10da208fee7acf", "aaa23f101647d8", "a355d4c611812e5f9258d7188b3df8851477094ffc2af2cf0c8670db903fbbe0", "644eb34b9a126e437b5e015eea141ca1a88020f2d5d6cc2c", "27ed90668174ebf8241a3c74b35e1246b6617e4123578f153bdb67062a13ef4e986f5bb3d0bb4307"), /* 5 */ new AesCcmTest(TestType.ENCRYPT, 16, "4a75ff2f66dae2935403cce27e829ad8be98185c73f8bc61d3ce950a83007e11", "ef284d1ddf35d1d23de6a2f84b", "0b90b3a087b9a4d3267bc57c470695ef7cf658353f2f680ee00ccc32c2ba0bdc", "bf35ddbad5e059169468ae8537f00ec790cc038b9ed0a5d7", "b702ad593b4169fd7011f0288e4e62620543095186b32c122389523b5ccc33c6b41b139108a99442"), // from VADT128.rsp: /* 6 */ new AesCcmTest(TestType.ENCRYPT, 16, "d24a3d3dde8c84830280cb87abad0bb3", "f1100035bb24a8d26004e0e24b", "", "7c86135ed9c2a515aaae0e9a208133897269220f30870006", "1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab1123301219c70599b7c373ad4b3ad67b"), /* 7 */ new AesCcmTest(TestType.ENCRYPT, 16, "5a33980e71e7d67fd6cf171454dc96e5", "33ae68ebb8010c6b3da6b9cb29", "eca622a37570df619e10ebb18bebadb2f2b49c4d2b2ff715873bb672e30fc0ff", "a34dfa24847c365291ce1b54bcf8d9a75d861e5133cc3a74", "7a60fa7ee8859e283cce378fb6b95522ab8b70efcdb0265f7c4b4fa597666b86dd1353e400f28864"), // from VTT192.rsp: /* 8 */ new AesCcmTest(TestType.ENCRYPT, 4, "11fd45743d946e6d37341fec49947e8c70482494a8f07fcc", "c6aeebcb146cfafaae66f78aab", "7dc8c52144a7cb65b3e5a846e8fd7eae37bf6996c299b56e49144ebf43a1770f", "ee7e6075ba52846de5d6254959a18affc4faf59c8ef63489", "137d9da59baf5cbfd46620c5f298fc766de10ac68e774edf1f2c5bad"), /* 9 */ new AesCcmTest(TestType.ENCRYPT, 14, "d2d4482ea8e98c1cf309671895a16610152ce283434bca38", "6ee177d48f59bd37045ec03731", "d4cd69b26ea43596278b8caec441fedcf0d729d4e0c27ed1332f48871c96e958", "e4abe343f98a2df09413c3defb85b56a6d34dba305dcce46", "7e8f27726c042d73aa6ebf43217395202e0af071eacf53790065601bb59972c35b580852e684"), // from DVPT256.rsp: /* 10 */ new AesCcmTest(TestType.DECRYPT, 4, "af063639e66c284083c5cf72b70d8bc277f5978e80d9322d99f2fdc718cda569", "a544218dadd3c1", "", "d3d5424e20fbec43ae495353ed830271515ab104f8860c98", "64a1341679972dc5869fcf69b19d5c5ea50aa0b5e985f5b722aa8d59"), /* 11 */ new AesCcmTest(TestType.DECRYPT, 4, "a4bc10b1a62c96d459fbaf3a5aa3face7313bb9e1253e696f96a7a8e36801088", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "", "866d4227"), /* 12 */ new AesCcmTest(TestType.DECRYPT, 16, "314a202f836f9f257e22d8c11757832ae5131d357a72df88f3eff0ffcee0da4e", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "e8de970f6ee8e80ede933581b5bcf4d837e2b72baa8b00c3", "8d34cdca37ce77be68f65baf3382e31efa693e63f914a781367f30f2eaad8c063ca50795acd90203"), }; System.out.println("Running " + someNistAesCcmTestVectors.length + " NIST test vectors."); int testCounter = 0; for (AesCcmTest t : someNistAesCcmTestVectors) { System.out.print(testCounter + ":" + t + ": "); boolean hasPassed = t.checkTestVector(); if (!hasPassed) { System.out.println("ERROR."); } else { System.out.println("OK."); } testCounter++; } System.out.println("DONE running NIST test vectors."); } private enum TestType { ENCRYPT, DECRYPT; public String toString() { switch (this) { case ENCRYPT: return "ENCRYPT"; case DECRYPT: return "DECRYPT"; default: throw new IllegalArgumentException(); } } } }
Made class suiteable to call from other classes: - added some getters - split calculation from checking test vectors with known output - made some inner enums public
cryptography/src/net/meeusen/crypto/AesCcmTest.java
Made class suiteable to call from other classes: - added some getters - split calculation from checking test vectors with known output - made some inner enums public
<ide><path>ryptography/src/net/meeusen/crypto/AesCcmTest.java <ide> <ide> import java.util.Arrays; <ide> <del>import org.bouncycastle.crypto.InvalidCipherTextException; <ide> import org.bouncycastle.crypto.engines.AESEngine; <ide> import org.bouncycastle.crypto.modes.CCMBlockCipher; <ide> import org.bouncycastle.crypto.params.AEADParameters; <ide> <ide> import net.meeusen.util.ByteString; <ide> <add> <add>/** <add> * Wrappers around BC AES-CCM, with easy API to validate NIST test vectors for AES-CCM. * <add> * */ <ide> public class AesCcmTest { <add> <add> public byte[] getCalculatedOutput() { <add> return calculatedOutput; <add> } <add> <add> public byte[] getPayLoad() { <add> return payLoad; <add> } <add> <add> public byte[] getCipherText() { <add> return cipherText; <add> } <ide> <ide> private CCMBlockCipher ccmCipher; <ide> private KeyParameter keyParameter; <del> private int TlenBytes; // nr bytes! <add> private int TlenBytes; <ide> private byte[] key; <ide> private byte[] nonce; <ide> private byte[] Adata; <del> private byte[] Payload; <del> private byte[] ExpectedCT; <add> private byte[] payLoad; <add> private byte[] cipherText; <ide> private TestType type; <add> <add> // following can be either payload or ciphertext depending on test type. <add> private byte[] calculatedOutput; <ide> <ide> public String toString() { <ide> return this.type.toString() + " Tlen:" + TlenBytes + " KeyLen:" + key.length + " Nlen: " + nonce.length <del> + " Alen: " + Adata.length + " Plen:" + Payload.length; <del> } <del> <del> public AesCcmTest(TestType type, int Tlen, String Key, String Nonce, String Adata, String Payload, <del> String ExpectedCT) throws IllegalStateException, InvalidCipherTextException { <del> this(type, Tlen, new ByteString(Key).getBytes(), new ByteString(Nonce).getBytes(), <del> new ByteString(Adata).getBytes(), new ByteString(Payload).getBytes(), <del> new ByteString(ExpectedCT).getBytes()); <del> } <del> <del> public AesCcmTest(TestType testType, int Tlen, byte[] Key, byte[] Nonce, byte[] Adata, byte[] Payload, <del> byte[] ExpectedCT) throws IllegalStateException, InvalidCipherTextException { <del> this.type = testType; <add> + " Alen: " + Adata.length + " Plen:" + payLoad.length; <add> } <add> <add> /** <add> * Constructor with (hex) String arguments <add> * @throws Exception <add> * */ <add> public AesCcmTest(TestType type, int argTlenBytes, String Key, String Nonce, String argAdata, String argPayload, <add> String argCipherText) throws Exception { <add> this(type, argTlenBytes, new ByteString(Key).getBytes(), new ByteString(Nonce).getBytes(), <add> new ByteString(argAdata).getBytes(), new ByteString(argPayload).getBytes(), <add> new ByteString(argCipherText).getBytes()); <add> } <add> <add> /** <add> * Constructor with byte[] arguments <add> * @throws Exception <add> * */ <add> public AesCcmTest(TestType argTestType, int argTlenBytes, byte[] Key, byte[] Nonce, byte[] argAdata, byte[] argPayload, <add> byte[] argCipherText) throws Exception { <add> <add> switch ( argTestType ) { <add> case ENCRYPT: <add> // need payload to encrypt something <add> if ( argPayload == null ) throw new Exception ("Cannot encrypt without payload."); <add> break; <add> case DECRYPT: <add> // need CT to decrypt something <add> if ( argCipherText == null ) throw new Exception ("Cannot decrypt without ciphertext."); <add> break; <add> default: <add> throw new Exception("not allowed"); <add> } <add> <add> this.type = argTestType; <ide> this.ccmCipher = new CCMBlockCipher(new AESEngine()); <ide> this.keyParameter = new KeyParameter(Key); <del> this.TlenBytes = Tlen; <add> this.TlenBytes = argTlenBytes; <ide> this.key = Key.clone(); <ide> this.nonce = Nonce.clone(); <del> this.Adata = Adata.clone(); <del> this.Payload = Payload.clone(); <del> this.ExpectedCT = ExpectedCT.clone(); <del> } <del> <del> /** <del> * use BC to check (NIST) test vector. Java doc: <del> * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/ <del> * crypto/params/AEADParameters.html <del> * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/ <del> * crypto/modes/CCMBlockCipher.html <del> */ <del> public boolean checkTestVector() throws IllegalStateException, InvalidCipherTextException { <del> <add> <add> // some of these are optional: <add> if ( argAdata != null ) this.Adata = argAdata.clone(); <add> if ( argPayload != null ) this.payLoad = argPayload.clone(); <add> if ( argCipherText != null ) this.cipherText = argCipherText.clone(); <add> } <add> <add> /** <add> * encrypt or decrypt depending on test type. <add> * store result in instance variable calculatedOutput <add> * result is NOT interpreted, not compared to any expected output... <add> * @throws Exception <add> * */ <add> public void doCalculate() throws Exception{ <ide> boolean isEncryption; <del> byte[] testInput; <del> byte[] ourOutput; <del> byte[] expectedOutput; <del> <del> if (this.type == TestType.ENCRYPT) { <add> byte[] testInput=null; <add> //byte[] testOutput=null; <add> <add> switch ( this.type ) { <add> case ENCRYPT: <ide> isEncryption = true; <del> testInput = this.Payload; <del> // stream cipher: CT len = PT len (plus tag) <del> ourOutput = new byte[this.Payload.length + this.TlenBytes]; <del> expectedOutput = this.ExpectedCT; <del> <del> } else { <add> testInput = this.payLoad; <add> break; <add> case DECRYPT: <ide> isEncryption = false; <del> testInput = this.ExpectedCT; <del> ourOutput = new byte[this.ExpectedCT.length - this.TlenBytes]; <del> expectedOutput = this.Payload; <del> } <del> <add> testInput = this.cipherText; <add> break; <add> default: <add> throw new Exception("not allowed"); <add> } <add> <add> /** Java docs: <add> * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/crypto/modes/CCMBlockCipher.html <add> * http://javadox.com/org.bouncycastle/bcprov-jdk15on/1.51/org/bouncycastle/crypto/params/AEADParameters.html <add> */ <add> <add> // init <ide> int TlenBits = this.TlenBytes * 8; <ide> ccmCipher.init(isEncryption, new AEADParameters(this.keyParameter, TlenBits, this.nonce, this.Adata)); <ide> <add> // process <ide> int inputOffset = 0; <ide> int outputOffset = 0; <del> int nrProcessBytes = this.ccmCipher.processPacket(testInput, inputOffset, testInput.length, ourOutput, <add> int expectedOutputSize = this.ccmCipher.getOutputSize(testInput.length); <add> this.calculatedOutput = new byte[expectedOutputSize]; <add> int nrProcessBytes = this.ccmCipher.processPacket(testInput, inputOffset, testInput.length, this.calculatedOutput, <ide> outputOffset); <ide> <del> if (nrProcessBytes != ourOutput.length) { <del> System.out.println( <del> "mmmm, our processPacket didn't give number of expected bytes. Maybe doFinal is needed after all..."); <del> } <add> if ( nrProcessBytes != expectedOutputSize ) { <add> throw new Exception("unexpected internal error or misunderstanding..."); <add> } <add> <ide> // strange, when I do another doFinal, there is data coming out, not <ide> // expected, and not sure what this data means... <ide> // byte[] finalOutput = new byte[ccmCipher.getOutputSize(0)]; <ide> // if ( nrOutputBytes != finalOutput.length) { <ide> // throw new Error("this should not happen."); <ide> // } <del> <del> return Arrays.equals(ourOutput, expectedOutput); <del> } <del> <del> public static void main(String[] args) throws IllegalStateException, InvalidCipherTextException { <add> } <add> <add> /** <add> * calculate AND compare with expected output <add> * */ <add> public boolean checkTestVector() throws Exception { <add> <add> this.doCalculate(); <add> <add> byte[] expectedOutput=null; <add> switch ( this.type ) { <add> case ENCRYPT: <add> expectedOutput = this.cipherText; <add> break; <add> case DECRYPT: <add> expectedOutput = this.payLoad; <add> break; <add> default: <add> throw new Exception("not allowed"); <add> } <add> <add> return Arrays.equals(this.calculatedOutput, expectedOutput); <add> } <add> <add> /** <add> * Check some CCM test vectors NIST. <add> * */ <add> public static void main(String[] args) throws Exception { <ide> /** <del> * CCM test vectors NIST: <add> * <ide> * http://csrc.nist.gov/groups/STM/cavp/block-cipher-modes.html#test- <ide> * vectors explained in : <ide> * http://csrc.nist.gov/groups/STM/cavp/documents/mac/CCMVS.pdf (ccmvs = <ide> "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", <ide> "e8de970f6ee8e80ede933581b5bcf4d837e2b72baa8b00c3", <ide> "8d34cdca37ce77be68f65baf3382e31efa693e63f914a781367f30f2eaad8c063ca50795acd90203"), <del> <ide> }; <ide> <ide> System.out.println("Running " + someNistAesCcmTestVectors.length + " NIST test vectors."); <ide> testCounter++; <ide> } <ide> System.out.println("DONE running NIST test vectors."); <del> } <del> <del> private enum TestType { <add> <add> <add> } <add> <add> public enum TestType { <ide> ENCRYPT, DECRYPT; <ide> public String toString() { <ide> switch (this) {
Java
apache-2.0
a9d7e142a7faeff851e0b7bca98a7101fcc7663d
0
kantega/kembe
package kembe; import fj.F; import fj.Ord; import kembe.sim.rand.Rand; import org.joda.time.*; import java.util.Random; public class Time { public static final Ord<Instant> instantOrd = Ord.longOrd.comap( new F<Instant, Long>() { @Override public Long f(Instant instant) { return instant.getMillis(); } } ); public static F<Interval, Duration> toDuration = new F<Interval, Duration>() { @Override public Duration f(Interval interval) { return interval.toDuration(); } }; public static F<Duration, Long> toDurationMillis = new F<Duration, Long>() { @Override public Long f(Duration duration) { return duration.getMillis(); } }; public static Instant quantumIncrement(Instant instant) { return instant.plus( 1 ); } public static Instant now() { return new Instant( System.currentTimeMillis() ); } public static Instant plus(ReadableInstant instant, ReadablePeriod period) { return instant.toInstant().plus( period.toPeriod().toStandardDuration() ); } public static IntervalBuilder from(ReadableInstant instant) { return new IntervalBuilder( instant ); } public static DurationBuilder durationOf(ReadableInstant start){ return new DurationBuilder(start); } public static Rand<Duration> randomDuration(final Duration min, final Duration max) { final long diff = Math.abs( max.getMillis() - min.getMillis() ); if (diff > Integer.MAX_VALUE) return new Rand<Duration>() { @Override public Duration next(Random t) { int r = t.nextInt( (int) diff / 60 / 1000 ); return min.plus( r * 60 * 1000 ); } }; else return new Rand<Duration>() { @Override public Duration next(Random t) { int r = t.nextInt( (int) diff ); return min.plus( r ); } }; } public static DateTime midnightBefore(ReadableInstant instant) { return instant.toInstant().toDateTime().toDateMidnight().toDateTime(); } public static DateTime nextMidnightAfter(ReadableInstant instant) { return instant.toInstant().toDateTime().toDateMidnight().toDateTime().plusDays( 1 ); } public static DateTime next(LocalTime time, Instant instant) { DateTime dt = instant.toDateTime().withFields( time ); return dt.isAfter( instant ) ? dt : dt.plusDays( 1 ); } public static LocalTime timeOfDay(int hours, int seconds) { return new LocalTime( hours, seconds ).withMillisOfSecond( 0 ); } public static class IntervalBuilder { final ReadableInstant start; public IntervalBuilder(ReadableInstant start) { this.start = start; } public Interval until(ReadableInstant end) { return new Interval( start, end ); } public Interval lasting(ReadableDuration duration) { return duration.toDuration().toIntervalFrom( start ); } public Interval lasting(ReadablePeriod period) { return new Interval( start, start.toInstant().toDateTime().plus( period ) ); } } public static class DurationBuilder{ final ReadableInstant start; public DurationBuilder(ReadableInstant start) { this.start = start; } public Duration until(ReadableInstant end){ long s = Math.min( start.getMillis(),end.getMillis() ); long e = Math.max( start.getMillis(),end.getMillis() ); if(s == e) return Duration.ZERO; else return Duration.millis( e-s); } } }
src/main/java/kembe/Time.java
package kembe; import fj.F; import fj.Ord; import kembe.sim.rand.Rand; import org.joda.time.*; import java.util.Random; public class Time { public static final Ord<Instant> instantOrd = Ord.longOrd.comap( new F<Instant, Long>() { @Override public Long f(Instant instant) { return instant.getMillis(); } } ); public static F<Interval, Duration> toDuration = new F<Interval, Duration>() { @Override public Duration f(Interval interval) { return interval.toDuration(); } }; public static F<Duration, Long> toDurationMillis = new F<Duration, Long>() { @Override public Long f(Duration duration) { return duration.getMillis(); } }; public static Instant quantumIncrement(Instant instant) { return instant.plus( 1 ); } public static Instant now() { return new Instant( System.currentTimeMillis() ); } public static Instant plus(ReadableInstant instant, ReadablePeriod period) { return instant.toInstant().plus( period.toPeriod().toStandardDuration() ); } public static IntervalBuilder from(ReadableInstant instant) { return new IntervalBuilder( instant ); } public static DurationBuilder durationOf(ReadableInstant start){ return new DurationBuilder(start); } public static Rand<Duration> randomDuration(final Duration min, final Duration max) { final long diff = Math.abs( max.getMillis() - min.getMillis() ); if (diff > Integer.MAX_VALUE) return new Rand<Duration>() { @Override public Duration next(Random t) { int r = t.nextInt( (int) diff / 60 / 1000 ); return min.plus( r * 60 * 1000 ); } }; else return new Rand<Duration>() { @Override public Duration next(Random t) { int r = t.nextInt( (int) diff ); return min.plus( r ); } }; } public static DateTime midnightBefore(ReadableInstant instant) { return instant.toInstant().toDateTime().toDateMidnight().toDateTime(); } public static DateTime nextMidnightAfter(ReadableInstant instant) { return instant.toInstant().toDateTime().toDateMidnight().toDateTime().plusDays( 1 ); } public static DateTime next(LocalTime time, Instant instant) { DateTime dt = instant.toDateTime().withFields( time ); return dt.isAfter( instant ) ? dt : dt.plusDays( 1 ); } public static LocalTime timeOfDay(int hours, int seconds) { return new LocalTime( hours, seconds ); } public static class IntervalBuilder { final ReadableInstant start; public IntervalBuilder(ReadableInstant start) { this.start = start; } public Interval until(ReadableInstant end) { return new Interval( start, end ); } public Interval lasting(ReadableDuration duration) { return duration.toDuration().toIntervalFrom( start ); } public Interval lasting(ReadablePeriod period) { return new Interval( start, start.toInstant().toDateTime().plus( period ) ); } } public static class DurationBuilder{ final ReadableInstant start; public DurationBuilder(ReadableInstant start) { this.start = start; } public Duration until(ReadableInstant end){ long s = Math.min( start.getMillis(),end.getMillis() ); long e = Math.max( start.getMillis(),end.getMillis() ); if(s == e) return Duration.ZERO; else return Duration.millis( e-s); } } }
Setting 0 millis in local time
src/main/java/kembe/Time.java
Setting 0 millis in local time
<ide><path>rc/main/java/kembe/Time.java <ide> } <ide> <ide> public static LocalTime timeOfDay(int hours, int seconds) { <del> return new LocalTime( hours, seconds ); <add> return new LocalTime( hours, seconds ).withMillisOfSecond( 0 ); <ide> } <ide> <ide> public static class IntervalBuilder {
JavaScript
mit
f717c35f68554e82fe2d58453f048b5ea98da21e
0
hangilc/myclinic-db
index-orig.js
var mysql = require("mysql"); function Pool(config){ this.pool = mysql.createPool(config); } Pool.prototype.getConnection = function(cb){ this.pool.getConnection(function(err, conn){ if( err ){ throw err; } cb(conn); }); }; Pool.prototype.withConnection = function(cb){ this.pool.getConnection(function(err, conn){ if( err ){ throw err; } try { cb(conn); } finally { conn.release(); } }) } Pool.prototype.dispose = function(){ this.pool.end(function(err){ if( err ){ throw err; } }); } exports.Pool = Pool; function query(conn, sql, args){ if( args == null ) args = []; return new Promise(function(resolve, reject){ conn.query(sql, args, function(err, results){ if( err ){ reject(err); return; } resolve(results); }) }) } exports.query = query; function find(conn, sql, args){ if( args == null ) args = []; return new Promise(function(resolve, reject){ conn.query(sql, args, function(err, results){ var len; if( err ){ reject(err); return; } len = results.length; if( len === 0 ){ resolve(null); } else if( len === 1 ){ resolve(results[0]); } else { reject("multiple rows found for get"); } }) }) } exports.find = find; function get(conn, sql, args){ return find(conn, sql, args) .then(function(result){ if( result === null ){ throw new Error("cannot find row"); } return result; }) } exports.get = get; function getValue(conn, sql, args){ return get(conn, sql, args) .then(function(row){ for(var name in row){ return row[name]; } }); } exports.getValue = getValue; function insert(conn, sql, args){ if( args == null ) args = []; return new Promise(function(resolve, reject){ conn.query(sql, args, function(err, result){ if( err ){ reject(err); return; } resolve(result.insertId); }) }) } exports.insert = insert; function exec(conn, sql, args){ if( args == null ) args = []; return new Promise(function(resolve, reject){ conn.query(sql, args, function(err, result){ if( err ){ reject(err); return; } resolve(result.affectedRows); }) }) } exports.exec = exec; function withTransaction(conn, fn){ return new Promise(function(resolve, reject){ conn.beginTransaction(function(err){ if( err ){ reject(err); return; } console.log("start transaction"); fn().then(function(value){ conn.commit(function(err){ if( err ){ reject(err); return; } console.log("commit"); resolve(value); }); }, function(err){ conn.rollback(function(){ console.log("rollback"); reject(err); }) }); }); }); } exports.withTransaction = withTransaction; function recentVisits(conn){ return query(conn, "select p.patient_id, p.last_name, p.first_name, p.last_name_yomi, p.first_name_yomi, " + " v.visit_id " + " from visit v, patient p where v.patient_id = p.patient_id order by visit_id desc limit 30"); } exports.recentVisits = recentVisits; function getPatient(conn, patient_id){ return get(conn, "select * from patient where patient_id = ?", [patient_id]); } exports.getPatient = getPatient; function calcVisits(conn, patient_id){ return getValue(conn, "select count(*) from visit where patient_id = ?", [patient_id]); } exports.calcVisits = calcVisits; function extendVisitWithTexts(conn, visit){ return query(conn, "select * from visit_text where visit_id = ? order by text_id", [visit.visit_id]) .then(function(texts){ visit.texts = texts; }); } function extendVisitWithShahokokuho(conn, visit){ if( visit.shahokokuho_id == 0 ){ visit.shahokokuho = null; return Promise.resolve(null); } else { return get(conn, "select * from hoken_shahokokuho where shahokokuho_id = ?", [visit.shahokokuho_id]) .then(function(hoken){ visit.shahokokuho = hoken; }); } } function extendVisitWithKoukikourei(conn, visit){ if( visit.koukikourei_id == 0 ){ visit.koukikourei = null; return Promise.resolve(null); } else { return get(conn, "select * from hoken_koukikourei where koukikourei_id = ?", [visit.koukikourei_id]) .then(function(hoken){ visit.koukikourei = hoken; }); } } function extendVisitWithRoujin(conn, visit){ if( visit.roujin_id == 0 ){ visit.roujin = null; return Promise.resolve(null); } else { return get(conn, "select * from hoken_roujin where roujin_id = ?", [visit.roujin_id]) .then(function(hoken){ visit.roujin = hoken; }); } } function extendVisitWithKouhiIter(conn, visit, kouhi_id){ if( kouhi_id == 0 ){ return Promise.resolve(visit); } return get(conn, "select * from kouhi where kouhi_id = ?", [kouhi_id]).then(function(kouhi){ visit.kouhi_list.push(kouhi); return visit; }) } function extendVisitWithKouhi(conn, visit){ visit.kouhi_list = []; return extendVisitWithKouhiIter(conn, visit, visit.kouhi_1_id).then(function(){ return extendVisitWithKouhiIter(conn, visit, visit.kouhi_2_id) }).then(function(){ return extendVisitWithKouhiIter(conn, visit, visit.kouhi_3_id) }); } function extendVisitWithHoken(conn, visit){ return extendVisitWithShahokokuho(conn, visit) .then(function(){ return extendVisitWithKoukikourei(conn, visit); }) .then(function(){ return extendVisitWithRoujin(conn, visit); }) .then(function(){ return extendVisitWithKouhi(conn, visit); }) } function extendVisitWithDrugs(conn, visit){ var sql; sql = "select d.*, m.* from visit_drug d, iyakuhin_master_arch m " + " where d.visit_id = ? " + " and m.iyakuhincode = d.d_iyakuhincode " + " and m.valid_from <= date(?) " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + " order by drug_id"; return query(conn, sql, [visit.visit_id, visit.v_datetime, visit.v_datetime]) .then(function(drugs){ visit.drugs = drugs; }); } function extendVisitWithShinryou(conn, visit){ var sql; sql = "select s.*, m.* from visit_shinryou s, shinryoukoui_master_arch m " + " where s.visit_id = ? " + " and m.shinryoucode = s.shinryoucode " + " and m.valid_from <= date(?) " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + " order by s.shinryoucode"; return query(conn, sql, [visit.visit_id, visit.v_datetime, visit.v_datetime]) .then(function(shinryouList){ visit.shinryou_list = shinryouList; return visit; }); } function extendConductWithGazouLabel(conn, conduct){ return find(conn, "select * from visit_gazou_label where visit_conduct_id = ?", [conduct.id]) .then(function(gazou){ conduct.gazou_label = gazou ? gazou.label : ""; return conduct; }); } function extendConductWithShinryou(conn, conduct, at){ var sql; sql = "select s.*, m.* from visit_conduct_shinryou s, shinryoukoui_master_arch m " + " where s.visit_conduct_id = ? " + " and m.shinryoucode = s.shinryoucode " + " and m.valid_from <= date(?) " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + " order by id"; return query(conn, sql, [conduct.id, at, at]) .then(function(list){ conduct.shinryou_list = list; }); } function extendConductWithDrugs(conn, conduct, at){ var sql; sql = "select d.*, m.* from visit_conduct_drug d, iyakuhin_master_arch m " + " where d.visit_conduct_id = ? " + " and m.iyakuhincode = d.iyakuhincode " + " and m.valid_from <= date(?) " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + " order by id"; return query(conn, sql, [conduct.id, at, at]) .then(function(list){ conduct.drugs = list; }); } function extendConductWithKizai(conn, conduct, at){ var sql; sql = "select k.*, m.* from visit_conduct_kizai k, tokuteikizai_master_arch m " + " where k.visit_conduct_id = ? " + " and m.kizaicode = k.kizaicode " + " and m.valid_from <= date(?) " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + " order by id"; return query(conn, sql, [conduct.id, at, at]) .then(function(list){ conduct.kizai_list = list; return conduct; }); } function extendConduct(conn, conduct, visit){ var at = visit.v_datetime; return extendConductWithGazouLabel(conn, conduct) .then(function(){ return extendConductWithShinryou(conn, conduct, at); }) .then(function(){ return extendConductWithDrugs(conn, conduct, at); }) .then(function(){ return extendConductWithKizai(conn, conduct, at); }) } function extendVisitWithConducts(conn, visit){ var sql; sql = "select * from visit_conduct where visit_id = ? order by id"; return query(conn, sql, [visit.visit_id]).then(function(conducts){ visit.conducts = conducts; return Promise.all(conducts.map(function(conduct){ return extendConduct(conn, conduct, visit); })); }) } function extendVisitWithCharge(conn, visit){ return find(conn, "select * from visit_charge where visit_id = ?", [visit.visit_id]) .then(function(charge){ visit.charge = charge; }) } function extendVisit(conn, visit){ return extendVisitWithTexts(conn, visit) .then(function(){ return extendVisitWithHoken(conn, visit); }) .then(function(){ return extendVisitWithDrugs(conn, visit); }) .then(function(){ return extendVisitWithShinryou(conn, visit); }) .then(function(){ return extendVisitWithConducts(conn, visit); }) .then(function(){ return extendVisitWithCharge(conn, visit); }) .then(function(){ return visit; }) } function listFullVisits(conn, patient_id, offset, n){ return query(conn, "select * from visit where patient_id = ? order by visit_id desc limit ?,?", [patient_id, offset, n]).then(function(visits){ return Promise.all(visits.map(function(visit){ return extendVisit(conn, visit); })) }); } exports.listFullVisits = listFullVisits; function getVisit(conn, visit_id){ return get(conn, "select * from visit where visit_id = ?", [visit_id]); } exports.getVisit = getVisit; function getFullVisit(conn, visit_id){ var visit; return getVisit(conn, visit_id) .then(function(visit_){ visit = visit_; return extendVisit(conn, visit); }) .then(function(){ return visit; }) } exports.getFullVisit = getFullVisit; function extendDiseaseWithMaster(conn, disease){ var sql; sql = "select a.*, m.* from disease_adj a, shuushokugo_master m " + " where a.disease_id = ? and a.shuushokugocode = m.shuushokugocode " + " order by disease_adj_id"; return query(conn, sql, [disease.disease_id]).then(function(list){ disease.adj_list = list; return disease; }); } function listCurrentDiseasesWithMaster(conn, patientId){ var sql; sql = "select d.*, m.* from disease d, shoubyoumei_master_arch m " + " where d.patient_id = ? and d.end_reason = 'N' " + " and d.shoubyoumeicode = m.shoubyoumeicode " + " and m.valid_from <= d.start_date " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= d.start_date) " + " order by disease_id"; return query(conn, sql, [patientId]); } function listCurrentFullDiseases(conn, patientId){ return listCurrentDiseasesWithMaster(conn, patientId) .then(function(diseases){ return Promise.all(diseases.map(extendDiseaseWithMaster.bind(null, conn))) }); } exports.listCurrentFullDiseases = listCurrentFullDiseases; function listAllDiseasesWithMaster(conn, patientId){ var sql; sql = "select d.*, m.* from disease d, shoubyoumei_master_arch m " + " where d.patient_id = ? " + " and d.shoubyoumeicode = m.shoubyoumeicode " + " and m.valid_from <= d.start_date " + " and (m.valid_upto = '0000-00-00' or m.valid_upto >= d.start_date) " + " order by disease_id"; return query(conn, sql, [patientId]); } function listAllFullDiseases(conn, patientId){ return listAllDiseasesWithMaster(conn, patientId) .then(function(diseases){ return Promise.all(diseases.map(extendDiseaseWithMaster.bind(null, conn))) }); } exports.listAllFullDiseases = listAllFullDiseases; function listAvailableShahokokuho(conn, patientId, at){ var sql; sql = "select * from hoken_shahokokuho where patient_id = ? " + " and valid_from <= date(?) " + " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + " order by shahokokuho_id "; return query(conn, sql, [patientId, at, at]); } function listAllShahokokuho(conn, patientId){ var sql = "select * from hoken_shahokokuho where patient_id = ? order by shahokokuho_id"; return query(conn, sql, [patientId]); } function listAvailableKoukikourei(conn, patientId, at){ var sql; sql = "select * from hoken_koukikourei where patient_id = ? " + " and valid_from <= date(?) " + " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + " order by koukikourei_id "; return query(conn, sql, [patientId, at, at]); } function listAllKoukikourei(conn, patientId){ var sql = "select * from hoken_koukikourei where patient_id = ? order by koukikourei_id"; return query(conn, sql, [patientId]); } function listAllRoujin(conn, patientId){ var sql = "select * from hoken_roujin where patient_id = ? order by roujin_id"; return query(conn, sql, [patientId]); } function listAvailableKouhi(conn, patientId, at){ var sql; sql = "select * from kouhi where patient_id = ? " + " and valid_from <= date(?) " + " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + " order by kouhi_id "; return query(conn, sql, [patientId, at, at]); } function listAllKouhi(conn, patientId){ var sql = "select * from kouhi where patient_id = ? order by kouhi_id"; return query(conn, sql, [patientId]); } function listAvailableHoken(conn, patientId, at){ var obj = {}; return listAvailableShahokokuho(conn, patientId, at) .then(function(list){ obj.shahokokuho_list = list; return listAvailableKoukikourei(conn, patientId, at); }) .then(function(list){ obj.koukikourei_list = list; return listAvailableKouhi(conn, patientId, at); }) .then(function(list){ obj.kouhi_list = list; return obj; }); } exports.listAvailableHoken = listAvailableHoken; function listAllHoken(conn, patientId){ var obj = {}; return listAllShahokokuho(conn, patientId) .then(function(list){ obj.shahokokuho_list = list; return listAllKoukikourei(conn, patientId); }) .then(function(list){ obj.koukikourei_list = list; return listAllRoujin(conn, patientId); }) .then(function(list){ obj.roujin_list = list; return listAllKouhi(conn, patientId); }) .then(function(list){ obj.kouhi_list = list; return obj; }); } exports.listAllHoken = listAllHoken; function enterText(conn, visitId, content){ var sql; sql = "insert into visit_text set visit_id = ?, content = ?"; return insert(conn, sql, [visitId, content]); } exports.enterText = enterText; function getText(conn, textId){ var sql; sql = "select * from visit_text where text_id = ?"; return get(conn, sql, [textId]); } exports.getText = getText; function updateText(conn, textId, content){ var sql; sql = "update visit_text set content = ? where text_id = ?"; return exec(conn, sql, [content, textId]) .then(function(affected){ if( affected !== 1 ){ throw new Error("update text failed"); } return true; }) } exports.updateText = updateText; function deleteText(conn, textId){ var sql; sql = "delete from visit_text where text_id = ?"; return exec(conn, sql, [textId]) .then(function(affected){ if( affected !== 1 ){ throw new Error("delete text failed"); } return true; }) } exports.deleteText = deleteText; function updateVisitHoken(conn, visitId, shahokokuhoId, koukikoureiId, kouhi1Id, kouhi2Id, kouhi3Id){ var sql; sql = "update visit set shahokokuho_id = ?, koukikourei_id = ?, kouhi_1_id = ?, " + " kouhi_2_id = ?, kouhi_3_id = ? where visit_id = ?"; return exec(conn, sql, [shahokokuhoId, koukikoureiId, kouhi1Id, kouhi2Id, kouhi3Id, visitId]) .then(function(affected){ if( affected !== 1 ){ throw new Error("update visit hoken failed"); } return true; }) } exports.updateVisitHoken = updateVisitHoken;
cleanup
index-orig.js
cleanup
<ide><path>ndex-orig.js <del>var mysql = require("mysql"); <del> <del>function Pool(config){ <del> this.pool = mysql.createPool(config); <del>} <del> <del>Pool.prototype.getConnection = function(cb){ <del> this.pool.getConnection(function(err, conn){ <del> if( err ){ <del> throw err; <del> } <del> cb(conn); <del> }); <del>}; <del> <del>Pool.prototype.withConnection = function(cb){ <del> this.pool.getConnection(function(err, conn){ <del> if( err ){ <del> throw err; <del> } <del> try { <del> cb(conn); <del> } <del> finally { <del> conn.release(); <del> } <del> }) <del>} <del> <del>Pool.prototype.dispose = function(){ <del> this.pool.end(function(err){ <del> if( err ){ <del> throw err; <del> } <del> }); <del>} <del> <del>exports.Pool = Pool; <del> <del>function query(conn, sql, args){ <del> if( args == null ) args = []; <del> return new Promise(function(resolve, reject){ <del> conn.query(sql, args, function(err, results){ <del> if( err ){ <del> reject(err); <del> return; <del> } <del> resolve(results); <del> }) <del> }) <del>} <del>exports.query = query; <del> <del>function find(conn, sql, args){ <del> if( args == null ) args = []; <del> return new Promise(function(resolve, reject){ <del> conn.query(sql, args, function(err, results){ <del> var len; <del> if( err ){ <del> reject(err); <del> return; <del> } <del> len = results.length; <del> if( len === 0 ){ <del> resolve(null); <del> } else if( len === 1 ){ <del> resolve(results[0]); <del> } else { <del> reject("multiple rows found for get"); <del> } <del> }) <del> }) <del>} <del>exports.find = find; <del> <del>function get(conn, sql, args){ <del> return find(conn, sql, args) <del> .then(function(result){ <del> if( result === null ){ <del> throw new Error("cannot find row"); <del> } <del> return result; <del> }) <del>} <del>exports.get = get; <del> <del>function getValue(conn, sql, args){ <del> return get(conn, sql, args) <del> .then(function(row){ <del> for(var name in row){ <del> return row[name]; <del> } <del> }); <del>} <del>exports.getValue = getValue; <del> <del>function insert(conn, sql, args){ <del> if( args == null ) args = []; <del> return new Promise(function(resolve, reject){ <del> conn.query(sql, args, function(err, result){ <del> if( err ){ <del> reject(err); <del> return; <del> } <del> resolve(result.insertId); <del> }) <del> }) <del>} <del>exports.insert = insert; <del> <del>function exec(conn, sql, args){ <del> if( args == null ) args = []; <del> return new Promise(function(resolve, reject){ <del> conn.query(sql, args, function(err, result){ <del> if( err ){ <del> reject(err); <del> return; <del> } <del> resolve(result.affectedRows); <del> }) <del> }) <del>} <del>exports.exec = exec; <del> <del>function withTransaction(conn, fn){ <del> return new Promise(function(resolve, reject){ <del> conn.beginTransaction(function(err){ <del> if( err ){ <del> reject(err); <del> return; <del> } <del> console.log("start transaction"); <del> fn().then(function(value){ <del> conn.commit(function(err){ <del> if( err ){ <del> reject(err); <del> return; <del> } <del> console.log("commit"); <del> resolve(value); <del> }); <del> }, function(err){ <del> conn.rollback(function(){ <del> console.log("rollback"); <del> reject(err); <del> }) <del> }); <del> }); <del> }); <del>} <del>exports.withTransaction = withTransaction; <del> <del>function recentVisits(conn){ <del> return query(conn, "select p.patient_id, p.last_name, p.first_name, p.last_name_yomi, p.first_name_yomi, " + <del> " v.visit_id " + <del> " from visit v, patient p where v.patient_id = p.patient_id order by visit_id desc limit 30"); <del>} <del>exports.recentVisits = recentVisits; <del> <del>function getPatient(conn, patient_id){ <del> return get(conn, "select * from patient where patient_id = ?", [patient_id]); <del>} <del>exports.getPatient = getPatient; <del> <del>function calcVisits(conn, patient_id){ <del> return getValue(conn, "select count(*) from visit where patient_id = ?", [patient_id]); <del>} <del>exports.calcVisits = calcVisits; <del> <del>function extendVisitWithTexts(conn, visit){ <del> return query(conn, "select * from visit_text where visit_id = ? order by text_id", [visit.visit_id]) <del> .then(function(texts){ <del> visit.texts = texts; <del> }); <del>} <del> <del>function extendVisitWithShahokokuho(conn, visit){ <del> if( visit.shahokokuho_id == 0 ){ <del> visit.shahokokuho = null; <del> return Promise.resolve(null); <del> } else { <del> return get(conn, "select * from hoken_shahokokuho where shahokokuho_id = ?", [visit.shahokokuho_id]) <del> .then(function(hoken){ <del> visit.shahokokuho = hoken; <del> }); <del> } <del>} <del> <del>function extendVisitWithKoukikourei(conn, visit){ <del> if( visit.koukikourei_id == 0 ){ <del> visit.koukikourei = null; <del> return Promise.resolve(null); <del> } else { <del> return get(conn, "select * from hoken_koukikourei where koukikourei_id = ?", [visit.koukikourei_id]) <del> .then(function(hoken){ <del> visit.koukikourei = hoken; <del> }); <del> } <del>} <del> <del>function extendVisitWithRoujin(conn, visit){ <del> if( visit.roujin_id == 0 ){ <del> visit.roujin = null; <del> return Promise.resolve(null); <del> } else { <del> return get(conn, "select * from hoken_roujin where roujin_id = ?", [visit.roujin_id]) <del> .then(function(hoken){ <del> visit.roujin = hoken; <del> }); <del> } <del>} <del> <del>function extendVisitWithKouhiIter(conn, visit, kouhi_id){ <del> if( kouhi_id == 0 ){ <del> return Promise.resolve(visit); <del> } <del> return get(conn, "select * from kouhi where kouhi_id = ?", [kouhi_id]).then(function(kouhi){ <del> visit.kouhi_list.push(kouhi); <del> return visit; <del> }) <del>} <del> <del>function extendVisitWithKouhi(conn, visit){ <del> visit.kouhi_list = []; <del> return extendVisitWithKouhiIter(conn, visit, visit.kouhi_1_id).then(function(){ <del> return extendVisitWithKouhiIter(conn, visit, visit.kouhi_2_id) <del> }).then(function(){ <del> return extendVisitWithKouhiIter(conn, visit, visit.kouhi_3_id) <del> }); <del>} <del> <del>function extendVisitWithHoken(conn, visit){ <del> return extendVisitWithShahokokuho(conn, visit) <del> .then(function(){ <del> return extendVisitWithKoukikourei(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithRoujin(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithKouhi(conn, visit); <del> }) <del>} <del> <del>function extendVisitWithDrugs(conn, visit){ <del> var sql; <del> sql = "select d.*, m.* from visit_drug d, iyakuhin_master_arch m " + <del> " where d.visit_id = ? " + <del> " and m.iyakuhincode = d.d_iyakuhincode " + <del> " and m.valid_from <= date(?) " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + <del> " order by drug_id"; <del> return query(conn, sql, [visit.visit_id, visit.v_datetime, visit.v_datetime]) <del> .then(function(drugs){ <del> visit.drugs = drugs; <del> }); <del>} <del> <del>function extendVisitWithShinryou(conn, visit){ <del> var sql; <del> sql = "select s.*, m.* from visit_shinryou s, shinryoukoui_master_arch m " + <del> " where s.visit_id = ? " + <del> " and m.shinryoucode = s.shinryoucode " + <del> " and m.valid_from <= date(?) " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + <del> " order by s.shinryoucode"; <del> return query(conn, sql, [visit.visit_id, visit.v_datetime, visit.v_datetime]) <del> .then(function(shinryouList){ <del> visit.shinryou_list = shinryouList; <del> return visit; <del> }); <del>} <del> <del>function extendConductWithGazouLabel(conn, conduct){ <del> return find(conn, "select * from visit_gazou_label where visit_conduct_id = ?", [conduct.id]) <del> .then(function(gazou){ <del> conduct.gazou_label = gazou ? gazou.label : ""; <del> return conduct; <del> }); <del>} <del> <del>function extendConductWithShinryou(conn, conduct, at){ <del> var sql; <del> sql = "select s.*, m.* from visit_conduct_shinryou s, shinryoukoui_master_arch m " + <del> " where s.visit_conduct_id = ? " + <del> " and m.shinryoucode = s.shinryoucode " + <del> " and m.valid_from <= date(?) " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + <del> " order by id"; <del> return query(conn, sql, [conduct.id, at, at]) <del> .then(function(list){ <del> conduct.shinryou_list = list; <del> }); <del>} <del> <del>function extendConductWithDrugs(conn, conduct, at){ <del> var sql; <del> sql = "select d.*, m.* from visit_conduct_drug d, iyakuhin_master_arch m " + <del> " where d.visit_conduct_id = ? " + <del> " and m.iyakuhincode = d.iyakuhincode " + <del> " and m.valid_from <= date(?) " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + <del> " order by id"; <del> return query(conn, sql, [conduct.id, at, at]) <del> .then(function(list){ <del> conduct.drugs = list; <del> }); <del>} <del> <del>function extendConductWithKizai(conn, conduct, at){ <del> var sql; <del> sql = "select k.*, m.* from visit_conduct_kizai k, tokuteikizai_master_arch m " + <del> " where k.visit_conduct_id = ? " + <del> " and m.kizaicode = k.kizaicode " + <del> " and m.valid_from <= date(?) " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= date(?)) " + <del> " order by id"; <del> return query(conn, sql, [conduct.id, at, at]) <del> .then(function(list){ <del> conduct.kizai_list = list; <del> return conduct; <del> }); <del>} <del> <del>function extendConduct(conn, conduct, visit){ <del> var at = visit.v_datetime; <del> return extendConductWithGazouLabel(conn, conduct) <del> .then(function(){ <del> return extendConductWithShinryou(conn, conduct, at); <del> }) <del> .then(function(){ <del> return extendConductWithDrugs(conn, conduct, at); <del> }) <del> .then(function(){ <del> return extendConductWithKizai(conn, conduct, at); <del> }) <del>} <del> <del>function extendVisitWithConducts(conn, visit){ <del> var sql; <del> sql = "select * from visit_conduct where visit_id = ? order by id"; <del> return query(conn, sql, [visit.visit_id]).then(function(conducts){ <del> visit.conducts = conducts; <del> return Promise.all(conducts.map(function(conduct){ <del> return extendConduct(conn, conduct, visit); <del> })); <del> }) <del>} <del> <del>function extendVisitWithCharge(conn, visit){ <del> return find(conn, "select * from visit_charge where visit_id = ?", [visit.visit_id]) <del> .then(function(charge){ <del> visit.charge = charge; <del> }) <del>} <del> <del>function extendVisit(conn, visit){ <del> return extendVisitWithTexts(conn, visit) <del> .then(function(){ <del> return extendVisitWithHoken(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithDrugs(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithShinryou(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithConducts(conn, visit); <del> }) <del> .then(function(){ <del> return extendVisitWithCharge(conn, visit); <del> }) <del> .then(function(){ <del> return visit; <del> }) <del>} <del> <del>function listFullVisits(conn, patient_id, offset, n){ <del> return query(conn, "select * from visit where patient_id = ? order by visit_id desc limit ?,?", <del> [patient_id, offset, n]).then(function(visits){ <del> return Promise.all(visits.map(function(visit){ return extendVisit(conn, visit); })) <del> }); <del>} <del>exports.listFullVisits = listFullVisits; <del> <del>function getVisit(conn, visit_id){ <del> return get(conn, "select * from visit where visit_id = ?", [visit_id]); <del>} <del>exports.getVisit = getVisit; <del> <del>function getFullVisit(conn, visit_id){ <del> var visit; <del> return getVisit(conn, visit_id) <del> .then(function(visit_){ <del> visit = visit_; <del> return extendVisit(conn, visit); <del> }) <del> .then(function(){ <del> return visit; <del> }) <del>} <del>exports.getFullVisit = getFullVisit; <del> <del>function extendDiseaseWithMaster(conn, disease){ <del> var sql; <del> sql = "select a.*, m.* from disease_adj a, shuushokugo_master m " + <del> " where a.disease_id = ? and a.shuushokugocode = m.shuushokugocode " + <del> " order by disease_adj_id"; <del> return query(conn, sql, [disease.disease_id]).then(function(list){ <del> disease.adj_list = list; <del> return disease; <del> }); <del>} <del> <del>function listCurrentDiseasesWithMaster(conn, patientId){ <del> var sql; <del> sql = "select d.*, m.* from disease d, shoubyoumei_master_arch m " + <del> " where d.patient_id = ? and d.end_reason = 'N' " + <del> " and d.shoubyoumeicode = m.shoubyoumeicode " + <del> " and m.valid_from <= d.start_date " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= d.start_date) " + <del> " order by disease_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listCurrentFullDiseases(conn, patientId){ <del> return listCurrentDiseasesWithMaster(conn, patientId) <del> .then(function(diseases){ <del> return Promise.all(diseases.map(extendDiseaseWithMaster.bind(null, conn))) <del> }); <del>} <del>exports.listCurrentFullDiseases = listCurrentFullDiseases; <del> <del>function listAllDiseasesWithMaster(conn, patientId){ <del> var sql; <del> sql = "select d.*, m.* from disease d, shoubyoumei_master_arch m " + <del> " where d.patient_id = ? " + <del> " and d.shoubyoumeicode = m.shoubyoumeicode " + <del> " and m.valid_from <= d.start_date " + <del> " and (m.valid_upto = '0000-00-00' or m.valid_upto >= d.start_date) " + <del> " order by disease_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listAllFullDiseases(conn, patientId){ <del> return listAllDiseasesWithMaster(conn, patientId) <del> .then(function(diseases){ <del> return Promise.all(diseases.map(extendDiseaseWithMaster.bind(null, conn))) <del> }); <del>} <del>exports.listAllFullDiseases = listAllFullDiseases; <del> <del>function listAvailableShahokokuho(conn, patientId, at){ <del> var sql; <del> sql = "select * from hoken_shahokokuho where patient_id = ? " + <del> " and valid_from <= date(?) " + <del> " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + <del> " order by shahokokuho_id "; <del> return query(conn, sql, [patientId, at, at]); <del>} <del> <del>function listAllShahokokuho(conn, patientId){ <del> var sql = "select * from hoken_shahokokuho where patient_id = ? order by shahokokuho_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listAvailableKoukikourei(conn, patientId, at){ <del> var sql; <del> sql = "select * from hoken_koukikourei where patient_id = ? " + <del> " and valid_from <= date(?) " + <del> " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + <del> " order by koukikourei_id "; <del> return query(conn, sql, [patientId, at, at]); <del>} <del> <del>function listAllKoukikourei(conn, patientId){ <del> var sql = "select * from hoken_koukikourei where patient_id = ? order by koukikourei_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listAllRoujin(conn, patientId){ <del> var sql = "select * from hoken_roujin where patient_id = ? order by roujin_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listAvailableKouhi(conn, patientId, at){ <del> var sql; <del> sql = "select * from kouhi where patient_id = ? " + <del> " and valid_from <= date(?) " + <del> " and (valid_upto = '0000-00-00' or valid_upto >= date(?)) " + <del> " order by kouhi_id "; <del> return query(conn, sql, [patientId, at, at]); <del>} <del> <del>function listAllKouhi(conn, patientId){ <del> var sql = "select * from kouhi where patient_id = ? order by kouhi_id"; <del> return query(conn, sql, [patientId]); <del>} <del> <del>function listAvailableHoken(conn, patientId, at){ <del> var obj = {}; <del> return listAvailableShahokokuho(conn, patientId, at) <del> .then(function(list){ <del> obj.shahokokuho_list = list; <del> return listAvailableKoukikourei(conn, patientId, at); <del> }) <del> .then(function(list){ <del> obj.koukikourei_list = list; <del> return listAvailableKouhi(conn, patientId, at); <del> }) <del> .then(function(list){ <del> obj.kouhi_list = list; <del> return obj; <del> }); <del>} <del>exports.listAvailableHoken = listAvailableHoken; <del> <del>function listAllHoken(conn, patientId){ <del> var obj = {}; <del> return listAllShahokokuho(conn, patientId) <del> .then(function(list){ <del> obj.shahokokuho_list = list; <del> return listAllKoukikourei(conn, patientId); <del> }) <del> .then(function(list){ <del> obj.koukikourei_list = list; <del> return listAllRoujin(conn, patientId); <del> }) <del> .then(function(list){ <del> obj.roujin_list = list; <del> return listAllKouhi(conn, patientId); <del> }) <del> .then(function(list){ <del> obj.kouhi_list = list; <del> return obj; <del> }); <del>} <del>exports.listAllHoken = listAllHoken; <del> <del>function enterText(conn, visitId, content){ <del> var sql; <del> sql = "insert into visit_text set visit_id = ?, content = ?"; <del> return insert(conn, sql, [visitId, content]); <del>} <del>exports.enterText = enterText; <del> <del>function getText(conn, textId){ <del> var sql; <del> sql = "select * from visit_text where text_id = ?"; <del> return get(conn, sql, [textId]); <del>} <del>exports.getText = getText; <del> <del>function updateText(conn, textId, content){ <del> var sql; <del> sql = "update visit_text set content = ? where text_id = ?"; <del> return exec(conn, sql, [content, textId]) <del> .then(function(affected){ <del> if( affected !== 1 ){ <del> throw new Error("update text failed"); <del> } <del> return true; <del> }) <del>} <del>exports.updateText = updateText; <del> <del>function deleteText(conn, textId){ <del> var sql; <del> sql = "delete from visit_text where text_id = ?"; <del> return exec(conn, sql, [textId]) <del> .then(function(affected){ <del> if( affected !== 1 ){ <del> throw new Error("delete text failed"); <del> } <del> return true; <del> }) <del>} <del>exports.deleteText = deleteText; <del> <del>function updateVisitHoken(conn, visitId, shahokokuhoId, koukikoureiId, kouhi1Id, kouhi2Id, kouhi3Id){ <del> var sql; <del> sql = "update visit set shahokokuho_id = ?, koukikourei_id = ?, kouhi_1_id = ?, " + <del> " kouhi_2_id = ?, kouhi_3_id = ? where visit_id = ?"; <del> return exec(conn, sql, [shahokokuhoId, koukikoureiId, kouhi1Id, kouhi2Id, kouhi3Id, visitId]) <del> .then(function(affected){ <del> if( affected !== 1 ){ <del> throw new Error("update visit hoken failed"); <del> } <del> return true; <del> }) <del>} <del>exports.updateVisitHoken = updateVisitHoken; <del> <del> <del> <del> <del>
Java
mit
11e271662832e85f71250baf483e4658bf88d8cd
0
CafetCraftTeam/RPG-Software
package cafetcraftteam.rpgsoftware.equipment; import android.support.annotation.NonNull; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Class of the Weapons */ public class Weapon extends Equipment { // the different groups possible for the weapons public enum Group { ORDINARY, CAVALRY, CROSSBOW, ENGINEER, ESTANGLING, FENCING, FLAIL, GUNPOWDER, LONGBOW, PARRYING, SLING, THROWING, TWO_HANDED } public enum Qualities { ARMOUR_PIERCING, BALANCED, DEFENSIVE, EXPERIMENTAL, FAST, IMPACT, PRECISE, PUMMELLING, SHRAPNEL, SLOW, SNARE, SPECIAL, TIRING, UNRELIABLE } // The weapon group of the weapon private final Group mGroup; // the qualities of the weapon private final Qualities mQualities; /** * Constructor of the class weapon * * @param name the name of the weapon * @param encumbering the encumbering of the weapon * @param price the price of the weapon * @param quality the quality of the weapon * @param description the description of the weapon * @param group the group of the weapon * @param qualities the qualities of the weapon */ public Weapon(@NonNull String name, int encumbering, int price, @NonNull Quality quality, @NonNull String description, @NonNull Group group, @NonNull Qualities qualities) { super(name, encumbering, price, quality, description); mGroup = group; mQualities = qualities; } public Group getGroup() { return mGroup; } public Qualities getQualities() { return mQualities; } @Override public boolean equals(Object object) { if (object == null) { return false; } //Verify if it's not the same object if (object == this) { return true; } if (!(object instanceof Weapon)) { return false; } Weapon other = (Weapon) object; return new EqualsBuilder() .appendSuper(super.equals(object)) .append(mGroup, other.mGroup) .append(mQualities, other.mQualities) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(5, 19) .appendSuper(super.hashCode()) .append(mGroup) .append(mQualities) .toHashCode(); } }
app/src/main/java/cafetcraftteam/rpgsoftware/equipment/Weapon.java
package cafetcraftteam.rpgsoftware.equipment; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Class of the Weapons */ public class Weapon extends Equipment { // the different groups possible for the weapons public enum Group { ORDINARY, CAVALRY, CROSSBOW, ENGINEER, ESTANGLING, FENCING, FLAIL, GUNPOWDER, LONGBOW, PARRYING, SLING, THROWING, TWO_HANDED } public enum Qualities { ARMOUR_PIERCING, BALANCED, DEFENSIVE, EXPERIMENTAL, FAST, IMPACT, PRECISE, PUMMELLING, SHRAPNEL, SLOW, SNARE, SPECIAL, TIRING, UNRELIABLE } // The weapon group of the weapon private final Group mGroup; // the qualities of the weapon private final Qualities mQualities; public Weapon(String name, int encumbering, int price, Quality quality, String description, Group group, Qualities qualities) { super(name, encumbering, price, quality, description); mGroup = group; mQualities = qualities; } public Group getGroup() { return mGroup; } public Qualities getQualities() { return mQualities; } @Override public boolean equals(Object object) { if (object == null) { return false; } //Verify if it's not the same object if (object == this) { return true; } if (!(object instanceof Weapon)) { return false; } Weapon other = (Weapon) object; return new EqualsBuilder() .appendSuper(super.equals(object)) .append(mGroup, other.mGroup) .append(mQualities, other.mQualities) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(5, 19) .appendSuper(super.hashCode()) .append(mGroup) .append(mQualities) .toHashCode(); } }
Reformattage du code et ajout des annotations dans le constructeur de Weapon
app/src/main/java/cafetcraftteam/rpgsoftware/equipment/Weapon.java
Reformattage du code et ajout des annotations dans le constructeur de Weapon
<ide><path>pp/src/main/java/cafetcraftteam/rpgsoftware/equipment/Weapon.java <ide> package cafetcraftteam.rpgsoftware.equipment; <add> <add>import android.support.annotation.NonNull; <ide> <ide> import org.apache.commons.lang3.builder.EqualsBuilder; <ide> import org.apache.commons.lang3.builder.HashCodeBuilder; <ide> public class Weapon extends Equipment <ide> { <ide> // the different groups possible for the weapons <del> public enum Group { <add> public enum Group <add> { <ide> ORDINARY, <ide> CAVALRY, <ide> CROSSBOW, <ide> TWO_HANDED <ide> } <ide> <del> public enum Qualities { <add> public enum Qualities <add> { <ide> ARMOUR_PIERCING, <ide> BALANCED, <ide> DEFENSIVE, <ide> // the qualities of the weapon <ide> private final Qualities mQualities; <ide> <del> public Weapon(String name, int encumbering, int price, Quality quality, String description, <del> Group group, Qualities qualities) <add> /** <add> * Constructor of the class weapon <add> * <add> * @param name the name of the weapon <add> * @param encumbering the encumbering of the weapon <add> * @param price the price of the weapon <add> * @param quality the quality of the weapon <add> * @param description the description of the weapon <add> * @param group the group of the weapon <add> * @param qualities the qualities of the weapon <add> */ <add> public Weapon(@NonNull String name, int encumbering, int price, @NonNull Quality quality, <add> @NonNull String description, @NonNull Group group, @NonNull Qualities qualities) <ide> { <ide> super(name, encumbering, price, quality, description); <ide> mGroup = group; <ide> } <ide> <ide> @Override <del> public boolean equals(Object object) { <del> if (object == null) { <add> public boolean equals(Object object) <add> { <add> if (object == null) <add> { <ide> return false; <ide> } <ide> <ide> //Verify if it's not the same object <del> if (object == this) { <add> if (object == this) <add> { <ide> return true; <ide> } <ide> <del> if (!(object instanceof Weapon)) { <add> if (!(object instanceof Weapon)) <add> { <ide> return false; <ide> } <ide> <ide> } <ide> <ide> @Override <del> public int hashCode() { <add> public int hashCode() <add> { <ide> return new HashCodeBuilder(5, 19) <ide> .appendSuper(super.hashCode()) <ide> .append(mGroup)
Java
apache-2.0
e95ce400abf83696f5fa2aaba4436a7d00aad123
0
asiaon123/hsweb-framework,hs-web/hsweb-framework,hs-web/hsweb-framework,asiaon123/hsweb-framework,asiaon123/hsweb-framework,hs-web/hsweb-framework
package org.hsweb.web.controller.file; import org.hsweb.commons.StringUtils; import org.hsweb.web.bean.po.resource.Resources; import org.hsweb.web.core.authorize.annotation.Authorize; import org.hsweb.web.core.exception.NotFoundException; import org.hsweb.web.core.logger.annotation.AccessLogger; import org.hsweb.web.core.message.ResponseMessage; import org.hsweb.web.service.resource.FileService; import org.hsweb.web.service.resource.ResourcesService; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * 文件管理控制器,用于上传和下载资源文件,使用restful。 * Created by 浩 on 2015-08-28 0028. */ @RestController @RequestMapping(value = "/file") @AccessLogger("文件管理") @Authorize public class FileController { private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private ResourcesService resourcesService; @Resource private FileService fileService; //文件名中不允许出现的字符 \ / : | ? < > " private static final Pattern fileNameKeyWordPattern = Pattern.compile("(\\\\)|(/)|(:)(|)|(\\?)|(>)|(<)|(\")"); private static final Map<String, String> mediaTypeMapper = new HashMap<>(); static { mediaTypeMapper.put(".png", MediaType.IMAGE_PNG_VALUE); mediaTypeMapper.put(".jpg", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".jpeg", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".gif", MediaType.IMAGE_GIF_VALUE); mediaTypeMapper.put(".bmp", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".json", MediaType.APPLICATION_JSON_VALUE); mediaTypeMapper.put(".txt", MediaType.TEXT_PLAIN_VALUE); mediaTypeMapper.put(".css", MediaType.TEXT_PLAIN_VALUE); mediaTypeMapper.put(".js", "application/javascript"); mediaTypeMapper.put(".html", MediaType.TEXT_HTML_VALUE); mediaTypeMapper.put(".xml", MediaType.TEXT_XML_VALUE); } /** * 下载文本 */ @RequestMapping(value = "/download-text/{name:.+}", method = {RequestMethod.GET, RequestMethod.POST}) public ResponseMessage downloadTxt(@PathVariable("name") String name, @RequestParam("text") String text, HttpServletResponse response) throws Exception { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); response.getWriter().write(text); return null; } /** * restful风格的文件下载 */ @RequestMapping(value = "/download/{id}/{name:.+}", method = RequestMethod.GET) @AccessLogger("下载文件") public ResponseMessage restDownLoad(@PathVariable("id") String id, @PathVariable("name") String name, HttpServletResponse response, HttpServletRequest request) throws Exception { return downLoad(id, name, response, request); } /** * 下载文件,支持断点下载 * * @param id 要下载资源文件的id * @param name 自定义文件名,该文件名不能存在非法字符 * @return 失败时,会返回失败原因信息{@link ResponseMessage} */ @RequestMapping(value = "/download/{id}", method = RequestMethod.GET) @AccessLogger("下载文件") public ResponseMessage downLoad(@PathVariable("id") String id, @RequestParam(value = "name", required = false) String name, HttpServletResponse response, HttpServletRequest request) throws Exception { Resources resources = resourcesService.selectByPk(id); if (resources == null || resources.getStatus() != 1) { throw new NotFoundException("文件不存在"); } else { if (!"file".equals(resources.getType())) throw new NotFoundException("文件不存在"); String fileBasePath = fileService.getFileBasePath(); File file = new File(fileBasePath.concat(resources.getPath().concat("/".concat(resources.getMd5())))); if (!file.canRead()) { throw new NotFoundException("文件不存在"); } //获取contentType,默认application/octet-stream String contentType = mediaTypeMapper.get(resources.getSuffix().toLowerCase()); if (contentType == null) contentType = "application/octet-stream"; if (StringUtils.isNullOrEmpty(name))//未自定义文件名,则使用上传时的文件名 name = resources.getName(); if (!name.contains("."))//如果未指定文件拓展名,则追加默认的文件拓展名 name = name.concat(".").concat(resources.getSuffix()); //关键字剔除 name = fileNameKeyWordPattern.matcher(name).replaceAll(""); int skip = 0; long fSize = file.length(); //尝试判断是否为断点下载 try { //获取要继续下载的位置 String Range = request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""); skip = StringUtils.toInt(Range); } catch (Exception e) { } response.setContentLength((int) fSize);//文件大小 response.setContentType(contentType); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); //try with resource try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream stream = new BufferedOutputStream(response.getOutputStream())) { //断点下载 if (skip > 0) { inputStream.skip(skip); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String contentRange = new StringBuffer("bytes ").append(skip).append("-").append(fSize - 1).append("/").append(fSize).toString(); response.setHeader("Content-Range", contentRange); } byte b[] = new byte[2048 * 10]; while ((inputStream.read(b)) != -1) { stream.write(b); } stream.flush(); } catch (Exception e) { logger.debug(String.format("download file error%s", e.getMessage())); throw e; } return null; } } /** * 上传文件,进行md5一致性校验,不保存重复文件。成功后返回文件信息{uid,md5,name} * * @param files 文件列表 * @return 上传结果 */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @AccessLogger("上传文件") public Object upload(@RequestParam("file") MultipartFile[] files) throws Exception { if (logger.isInfoEnabled()) logger.info(String.format("start upload , file number:%s", files.length)); List<Resources> resourcesList = new LinkedList<>(); for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; if (!file.isEmpty()) { if (logger.isInfoEnabled()) logger.info("start write file:{}", file.getOriginalFilename()); String fileName = file.getOriginalFilename(); Resources resources = fileService.saveFile(file.getInputStream(), fileName); resourcesList.add(resources); } }//响应上传成功的资源信息 return ResponseMessage.ok(resourcesList) .include(Resources.class, "id", "name", "md5"); } }
hsweb-web-controller/src/main/java/org/hsweb/web/controller/file/FileController.java
package org.hsweb.web.controller.file; import org.hsweb.web.core.exception.NotFoundException; import org.hsweb.web.core.logger.annotation.AccessLogger; import org.hsweb.web.core.authorize.annotation.Authorize; import org.hsweb.web.bean.po.resource.Resources; import org.hsweb.web.core.message.ResponseMessage; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; import org.hsweb.commons.StringUtils; import org.hsweb.web.service.config.ConfigService; import org.hsweb.web.service.resource.FileService; import org.hsweb.web.service.resource.ResourcesService; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.util.*; import java.util.regex.Pattern; /** * 文件管理控制器,用于上传和下载资源文件,使用restful。 * Created by 浩 on 2015-08-28 0028. */ @RestController @RequestMapping(value = "/file") @AccessLogger("文件管理") @Authorize public class FileController { private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); @Resource private ResourcesService resourcesService; @Resource private FileService fileService; //文件名中不允许出现的字符 \ / : | ? < > " private static final Pattern fileNameKeyWordPattern = Pattern.compile("(\\\\)|(/)|(:)(|)|(\\?)|(>)|(<)|(\")"); private static final Map<String, String> mediaTypeMapper = new HashMap<>(); static { mediaTypeMapper.put(".png", MediaType.IMAGE_PNG_VALUE); mediaTypeMapper.put(".jpg", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".jpeg", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".gif", MediaType.IMAGE_GIF_VALUE); mediaTypeMapper.put(".bmp", MediaType.IMAGE_JPEG_VALUE); mediaTypeMapper.put(".json", MediaType.APPLICATION_JSON_VALUE); mediaTypeMapper.put(".txt", MediaType.TEXT_PLAIN_VALUE); mediaTypeMapper.put(".css", MediaType.TEXT_PLAIN_VALUE); mediaTypeMapper.put(".js", "application/javascript"); mediaTypeMapper.put(".html", MediaType.TEXT_HTML_VALUE); mediaTypeMapper.put(".xml", MediaType.TEXT_XML_VALUE); } /** * restful风格的文件下载 */ @RequestMapping(value = "/download/{id}/{name:.+}", method = RequestMethod.GET) @AccessLogger("下载文件") public ResponseMessage restDownLoad(@PathVariable("id") String id, @PathVariable("name") String name, HttpServletResponse response, HttpServletRequest request) throws Exception { return downLoad(id, name, response, request); } /** * 下载文件,支持断点下载 * * @param id 要下载资源文件的id * @param name 自定义文件名,该文件名不能存在非法字符 * @return 失败时,会返回失败原因信息{@link ResponseMessage} */ @RequestMapping(value = "/download/{id}", method = RequestMethod.GET) @AccessLogger("下载文件") public ResponseMessage downLoad(@PathVariable("id") String id, @RequestParam(value = "name", required = false) String name, HttpServletResponse response, HttpServletRequest request) throws Exception { Resources resources = resourcesService.selectByPk(id); if (resources == null || resources.getStatus() != 1) { throw new NotFoundException("文件不存在"); } else { if (!"file".equals(resources.getType())) throw new NotFoundException("文件不存在"); String fileBasePath = fileService.getFileBasePath(); File file = new File(fileBasePath.concat(resources.getPath().concat("/".concat(resources.getMd5())))); if (!file.canRead()) { throw new NotFoundException("文件不存在"); } //获取contentType,默认application/octet-stream String contentType = mediaTypeMapper.get(resources.getSuffix().toLowerCase()); if (contentType == null) contentType = "application/octet-stream"; if (StringUtils.isNullOrEmpty(name))//未自定义文件名,则使用上传时的文件名 name = resources.getName(); if (!name.contains("."))//如果未指定文件拓展名,则追加默认的文件拓展名 name = name.concat(".").concat(resources.getSuffix()); //关键字剔除 name = fileNameKeyWordPattern.matcher(name).replaceAll(""); int skip = 0; long fSize = file.length(); //尝试判断是否为断点下载 try { //获取要继续下载的位置 String Range = request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""); skip = StringUtils.toInt(Range); } catch (Exception e) { } response.setContentLength((int) fSize);//文件大小 response.setContentType(contentType); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); //try with resource try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream stream = new BufferedOutputStream(response.getOutputStream())) { //断点下载 if (skip > 0) { inputStream.skip(skip); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String contentRange = new StringBuffer("bytes ").append(skip).append("-").append(fSize - 1).append("/").append(fSize).toString(); response.setHeader("Content-Range", contentRange); } byte b[] = new byte[2048 * 10]; while ((inputStream.read(b)) != -1) { stream.write(b); } stream.flush(); } catch (Exception e) { logger.debug(String.format("download file error%s", e.getMessage())); throw e; } return null; } } /** * 上传文件,进行md5一致性校验,不保存重复文件。成功后返回文件信息{uid,md5,name} * * @param files 文件列表 * @return 上传结果 */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @AccessLogger("上传文件") public Object upload(@RequestParam("file") MultipartFile[] files) throws Exception { if (logger.isInfoEnabled()) logger.info(String.format("start upload , file number:%s", files.length)); List<Resources> resourcesList = new LinkedList<>(); for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; if (!file.isEmpty()) { if (logger.isInfoEnabled()) logger.info("start write file:{}", file.getOriginalFilename()); String fileName = file.getOriginalFilename(); Resources resources = fileService.saveFile(file.getInputStream(), fileName); resourcesList.add(resources); } }//响应上传成功的资源信息 return ResponseMessage.ok(resourcesList) .include(Resources.class, "id", "name", "md5"); } }
新增text文本下载,传什么参数就下载什么内容.
hsweb-web-controller/src/main/java/org/hsweb/web/controller/file/FileController.java
新增text文本下载,传什么参数就下载什么内容.
<ide><path>sweb-web-controller/src/main/java/org/hsweb/web/controller/file/FileController.java <ide> package org.hsweb.web.controller.file; <ide> <add>import org.hsweb.commons.StringUtils; <add>import org.hsweb.web.bean.po.resource.Resources; <add>import org.hsweb.web.core.authorize.annotation.Authorize; <ide> import org.hsweb.web.core.exception.NotFoundException; <ide> import org.hsweb.web.core.logger.annotation.AccessLogger; <del>import org.hsweb.web.core.authorize.annotation.Authorize; <del>import org.hsweb.web.bean.po.resource.Resources; <ide> import org.hsweb.web.core.message.ResponseMessage; <add>import org.hsweb.web.service.resource.FileService; <add>import org.hsweb.web.service.resource.ResourcesService; <ide> import org.slf4j.LoggerFactory; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.web.bind.annotation.*; <ide> import org.springframework.web.multipart.MultipartFile; <del>import org.springframework.web.multipart.commons.CommonsMultipartFile; <del>import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; <del>import org.hsweb.commons.StringUtils; <del>import org.hsweb.web.service.config.ConfigService; <del>import org.hsweb.web.service.resource.FileService; <del>import org.hsweb.web.service.resource.ResourcesService; <ide> <ide> import javax.annotation.Resource; <ide> import javax.servlet.http.HttpServletRequest; <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.net.URLEncoder; <del>import java.util.*; <add>import java.util.HashMap; <add>import java.util.LinkedList; <add>import java.util.List; <add>import java.util.Map; <ide> import java.util.regex.Pattern; <ide> <ide> /** <ide> mediaTypeMapper.put(".js", "application/javascript"); <ide> mediaTypeMapper.put(".html", MediaType.TEXT_HTML_VALUE); <ide> mediaTypeMapper.put(".xml", MediaType.TEXT_XML_VALUE); <add> } <add> <add> /** <add> * 下载文本 <add> */ <add> @RequestMapping(value = "/download-text/{name:.+}", method = {RequestMethod.GET, RequestMethod.POST}) <add> public ResponseMessage downloadTxt(@PathVariable("name") String name, <add> @RequestParam("text") String text, <add> HttpServletResponse response) throws Exception { <add> response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); <add> response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); <add> response.getWriter().write(text); <add> return null; <ide> } <ide> <ide> /**
Java
apache-2.0
0d72e5819f38cc50b45b10c3c5a01a10daf0efc9
0
jdgwartney/meter-plugin-sdk-java,GabrielNicolasAvellaneda/boundary-plugin-framework-java,boundary/meter-plugin-sdk-java,boundary/boundary-plugin-framework-java,GabrielNicolasAvellaneda/boundary-plugin-framework-java,boundary/boundary-plugin-framework-java,boundary/meter-plugin-sdk-java,boundary/boundary-plugin-framework-java,GabrielNicolasAvellaneda/boundary-plugin-framework-java,boundary/meter-plugin-sdk-java,jdgwartney/meter-plugin-sdk-java,jdgwartney/meter-plugin-sdk-java
// Copyright 2014 Boundary, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.boundary.plugin.sdk.bootstrap; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.boundary.plugin.sdk.PostExtract; /** * Utility class for downloading a plugin from a release in GitHub */ public class DownloadPluginJar implements PostExtract { private final static String POM_PATH="pom.xml"; private final static String JAR_DESTINATION_PATH="config/plugin.jar"; private final static String VERSION_XPATH_EXPRESSION = "/project/version"; private final static String BASE_URL_XPATH_EXPRESSION = "/project/properties/boundary-jar-base-url"; private final static String JAR_BASE_NAME_EXPRESSION = "/project/name"; private String version; private String baseUrl; private String jarBaseName; public DownloadPluginJar() { } /** * Reads the pom.xml file to extract information to find the jar plugin. * * @param pomFile Maven POM file path * @throws ParserConfigurationException Indicates a failure to parse the pom.xml file * @throws SAXException SAX parsing issue * @throws XPathExpressionException Incorrect XPath expression to extract data * @throws IOException Other kind of IO error */ private void readPOM() throws ParserConfigurationException, SAXException, XPathExpressionException, IOException { DocumentBuilder parser = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); try { FileInputStream input = new FileInputStream(new File(POM_PATH)); try { Document document = parser.parse(input); XPath xpath = XPathFactory.newInstance().newXPath(); this.version = (String) xpath.evaluate( VERSION_XPATH_EXPRESSION, document, XPathConstants.STRING); this.baseUrl = (String) xpath.evaluate( BASE_URL_XPATH_EXPRESSION, document, XPathConstants.STRING); this.jarBaseName = (String) xpath.evaluate( JAR_BASE_NAME_EXPRESSION, document, XPathConstants.STRING); input.close(); } catch (IOException e) { throw e; } finally { input.close(); } } catch (FileNotFoundException e) { throw e; } } /** * Downloads a jar file based on pom.xml information * to the configuration directory <code>config</code> * * @throws IOException Any kind of IO error occurs */ private void downloadJAR() throws IOException { OutputStream out = null; try { HttpsURLConnection connection = null; String sUrl = String.format("%s/%s/plugin.jar",this.baseUrl,this.version); URL url = new URL(sUrl); connection = (HttpsURLConnection) url.openConnection(); connection.addRequestProperty("Accept","application/zip"); // Ensure that we follow redirects HttpsURLConnection.setFollowRedirects(true); InputStream in = connection.getInputStream(); System.err.printf("HTTP Response %d%n",connection.getResponseCode()); out = new FileOutputStream(new File(JAR_DESTINATION_PATH)); byte [] b = new byte[1024]; System.err.printf("Downloading %s of %d bytes from %s...", JAR_DESTINATION_PATH,connection.getContentLength(),connection.getURL()); while(in.read(b) != -1) { out.write(b); } out.close(); } catch (IOException e) { System.out.println("IO Exception"); System.err.printf("%s%n",e.getMessage()); System.err.flush(); //out.close(); throw e; } } /** * Downloads the plugins jar file to the configuration directory <code>config/plugin.jar</code> */ public void execute(String[] args) { System.err.println("Running post extract..."); try { readPOM(); downloadJAR(); System.err.println("Download successful"); } catch (XPathExpressionException e) { System.err.printf("%s%n",e.getMessage()); } catch (ParserConfigurationException e) { System.err.printf("%s%n",e.getMessage()); } catch (SAXException e) { System.err.printf("%s%n",e.getMessage()); } catch (FileNotFoundException e) { System.err.printf("%s%n",e.getMessage()); } catch (MalformedURLException e) { System.err.printf("%s%n",e.getMessage()); } catch (IOException e) { System.err.printf("%s%n",e.getMessage()); } // Ensure that the standard error is flushed before exiting. System.err.flush(); } }
src/main/java/com/boundary/plugin/sdk/bootstrap/DownloadPluginJar.java
// Copyright 2014 Boundary, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.boundary.plugin.sdk.bootstrap; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.boundary.plugin.sdk.PostExtract; /** * Utility class for downloading a plugin from a release in GitHub */ public class DownloadPluginJar implements PostExtract { private final static String POM_PATH="pom.xml"; private final static String JAR_DESTINATION_PATH="config/plugin.jar"; private final static String VERSION_XPATH_EXPRESSION = "/project/version"; private final static String BASE_URL_XPATH_EXPRESSION = "/project/properties/boundary-jar-base-url"; private final static String JAR_BASE_NAME_EXPRESSION = "/project/name"; private String version; private String baseUrl; private String jarBaseName; public DownloadPluginJar() { } /** * Reads the pom.xml file to extract information to find the jar plugin. * * @param pomFile Maven POM file path * @throws ParserConfigurationException Indicates a failure to parse the pom.xml file * @throws SAXException SAX parsing issue * @throws XPathExpressionException Incorrect XPath expression to extract data * @throws IOException Other kind of IO error */ private void readPOM() throws ParserConfigurationException, SAXException, XPathExpressionException, IOException { DocumentBuilder parser = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); try { FileInputStream input = new FileInputStream(new File(POM_PATH)); try { Document document = parser.parse(input); XPath xpath = XPathFactory.newInstance().newXPath(); this.version = (String) xpath.evaluate( VERSION_XPATH_EXPRESSION, document, XPathConstants.STRING); this.baseUrl = (String) xpath.evaluate( BASE_URL_XPATH_EXPRESSION, document, XPathConstants.STRING); this.jarBaseName = (String) xpath.evaluate( JAR_BASE_NAME_EXPRESSION, document, XPathConstants.STRING); input.close(); } catch (IOException e) { throw e; } finally { input.close(); } } catch (FileNotFoundException e) { throw e; } } /** * Downloads a jar file based on pom.xml information * to the configuration directory <code>config</code> * * @throws IOException Any kind of IO error occurs */ private void downloadJAR() throws IOException { OutputStream out = null; try { HttpsURLConnection connection = null; String sUrl = String.format("%s/%s/plugin.jar",this.baseUrl,this.version); URL url = new URL(sUrl); connection = (HttpsURLConnection) url.openConnection(); connection.addRequestProperty("Accept","application/zip"); // Ensure that we follow redirects HttpsURLConnection.setFollowRedirects(true); InputStream in = connection.getInputStream(); out = new FileOutputStream(new File(JAR_DESTINATION_PATH)); byte [] b = new byte[1024]; //connection.connect(); System.err.printf("Downloading jar of %d bytes from %s...%n", connection.getContentLength(),connection.getURL()); System.err.printf("to %s%n",JAR_DESTINATION_PATH); int i = 1; while(in.read(b) != -1) { if (i % 1024 == 0) System.err.print("."); out.write(b); i++; } out.close(); } catch (IOException e) { System.out.println("IO Exception"); System.err.printf("%s%n",e.getMessage()); System.err.flush(); //out.close(); throw e; } } /** * Downloads the plugins jar file to the configuration directory <code>config/plugin.jar</code> */ public void execute(String[] args) { System.err.println("Running post extract..."); try { readPOM(); downloadJAR(); System.err.println("Download successful"); } catch (XPathExpressionException e) { System.err.printf("%s%n",e.getMessage()); } catch (ParserConfigurationException e) { System.err.printf("%s%n",e.getMessage()); } catch (SAXException e) { System.err.printf("%s%n",e.getMessage()); } catch (FileNotFoundException e) { System.err.printf("%s%n",e.getMessage()); } catch (MalformedURLException e) { System.err.printf("%s%n",e.getMessage()); } catch (IOException e) { System.err.printf("%s%n",e.getMessage()); } // Ensure that the standard error is flushed before exiting. System.err.flush(); } }
Finalize bootstrap downloader
src/main/java/com/boundary/plugin/sdk/bootstrap/DownloadPluginJar.java
Finalize bootstrap downloader
<ide><path>rc/main/java/com/boundary/plugin/sdk/bootstrap/DownloadPluginJar.java <ide> HttpsURLConnection.setFollowRedirects(true); <ide> <ide> InputStream in = connection.getInputStream(); <add> System.err.printf("HTTP Response %d%n",connection.getResponseCode()); <ide> <ide> out = new FileOutputStream(new File(JAR_DESTINATION_PATH)); <ide> byte [] b = new byte[1024]; <del> <del> //connection.connect(); <del> System.err.printf("Downloading jar of %d bytes from %s...%n", <del> connection.getContentLength(),connection.getURL()); <del> System.err.printf("to %s%n",JAR_DESTINATION_PATH); <del> int i = 1; <add> <add> System.err.printf("Downloading %s of %d bytes from %s...", <add> JAR_DESTINATION_PATH,connection.getContentLength(),connection.getURL()); <add> <ide> while(in.read(b) != -1) { <del> if (i % 1024 == 0) System.err.print("."); <ide> out.write(b); <del> i++; <ide> } <ide> <ide> out.close();
Java
mit
5a44768476a1da94eab7a0c3b1223e41eae08f7e
0
dotwebstack/dotwebstack-framework,dotwebstack/dotwebstack-framework
package org.dotwebstack.framework.service.openapi.response; import static org.dotwebstack.framework.core.helpers.ExceptionHelper.illegalStateException; import static org.dotwebstack.framework.core.jexl.JexlHelper.getJexlContext; import static org.dotwebstack.framework.service.openapi.helper.DwsExtensionHelper.getJexlExpression; import static org.dotwebstack.framework.service.openapi.helper.DwsExtensionHelper.resolveDwsName; import static org.dotwebstack.framework.service.openapi.jexl.JexlUtils.evaluateJexlExpression; import static org.dotwebstack.framework.service.openapi.mapping.MapperUtils.isEnvelope; import static org.dotwebstack.framework.service.openapi.mapping.MapperUtils.isMappable; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLTypeUtil; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import lombok.NonNull; import org.apache.commons.jexl3.JexlContext; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.MapContext; import org.dotwebstack.framework.core.datafetchers.paging.PagingConstants; import org.dotwebstack.framework.core.jexl.JexlHelper; import org.dotwebstack.framework.service.openapi.handler.OperationContext; import org.dotwebstack.framework.service.openapi.handler.OperationRequest; import org.dotwebstack.framework.service.openapi.mapping.EnvironmentProperties; import org.dotwebstack.framework.service.openapi.mapping.MapperUtils; import org.dotwebstack.framework.service.openapi.mapping.TypeMapper; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component public class JsonBodyMapper implements BodyMapper { private static final Pattern MEDIA_TYPE_PATTERN = Pattern.compile("^application/([a-z]+\\+)?json$"); private final GraphQLSchema graphQlSchema; private final JexlHelper jexlHelper; private final EnvironmentProperties environmentProperties; private final Map<String, TypeMapper> typeMappers; public JsonBodyMapper(@NonNull GraphQL graphQL, @NonNull JexlEngine jexlEngine, @NonNull EnvironmentProperties environmentProperties, @NonNull Collection<TypeMapper> typeMappers) { this.graphQlSchema = graphQL.getGraphQLSchema(); this.jexlHelper = new JexlHelper(jexlEngine); this.environmentProperties = environmentProperties; this.typeMappers = typeMappers.stream() .collect(Collectors.toMap(TypeMapper::typeName, Function.identity())); } @Override public Mono<Object> map(OperationRequest operationRequest, Object result) { var queryField = graphQlSchema.getQueryType() .getFieldDefinition(operationRequest.getContext() .getQueryProperties() .getField()); var jexlContext = getJexlContext(environmentProperties.getAllProperties(), operationRequest.getServerRequest(), operationRequest.getParameters()); return Mono.just(mapSchema(operationRequest.getResponseSchema(), queryField, result, jexlContext)); } private Object mapSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { if (data == null) { return emptyValue(schema); } var newContext = updateJexlContext(data, jexlContext); if ("object".equals(schema.getType())) { return mapObjectSchema(schema, fieldDefinition, data, newContext); } if (schema instanceof ArraySchema) { return mapArraySchema((ArraySchema) schema, fieldDefinition, data, newContext); } return evaluateScalarData(schema, data, newContext); } @SuppressWarnings({"unchecked", "rawtypes"}) private Object mapObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { if (MapperUtils.isEnvelope(schema)) { return mapEnvelopeObjectSchema(schema, fieldDefinition, data, jexlContext); } var rawType = GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); if (typeMappers.containsKey(rawType.getName())) { return typeMappers.get(rawType.getName()) .fieldToBody(data, schema); } Map<String, Object> dataMap; if (!(data instanceof Map)) { try { dataMap = new ObjectMapper().convertValue(data, Map.class); } catch (IllegalArgumentException e) { throw illegalStateException("Data is not compatible with object schema.", e); } } else { dataMap = (Map<String, Object>) data; } if (schema.getProperties() == null) { return dataMap; } return schema.getProperties() .entrySet() .stream() .collect(HashMap::new, (acc, entry) -> { var property = resolveDwsName(entry.getValue(), entry.getKey()); var nestedSchema = entry.getValue(); var value = mapObjectSchemaProperty(property, nestedSchema, fieldDefinition, dataMap, jexlContext); if ((schema.getRequired() != null && schema.getRequired() .contains(property)) || !valueIsEmpty(value)) { acc.put(entry.getKey(), value); } }, HashMap::putAll); } @SuppressWarnings({"unchecked", "rawtypes"}) private Object mapEnvelopeObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); var envelopeValue = schema.getProperties() .entrySet() .stream() .collect(HashMap::new, (acc, entry) -> { var property = resolveDwsName(entry.getValue(), entry.getKey()); var nestedSchema = entry.getValue(); var nestedFieldDefinition = rawType.getFieldDefinition(property); Object nestedValue; if (nestedFieldDefinition == null || isEnvelope(nestedSchema)) { nestedValue = mapSchema(nestedSchema, fieldDefinition, data, jexlContext); } else { if (!(data instanceof Map)) { throw illegalStateException("Data is not compatible with object schema."); } var dataMap = (Map<String, Object>) data; nestedValue = mapSchema(nestedSchema, nestedFieldDefinition, dataMap.get(property), jexlContext); } if ((schema.getRequired() != null && schema.getRequired() .contains(property)) || !valueInEnvelopeIsEmpty(nestedValue)) { acc.put(entry.getKey(), nestedValue); } }, HashMap::putAll); return valueInEnvelopeIsEmpty(envelopeValue) && Boolean.TRUE.equals(schema.getNullable()) ? null : envelopeValue; } private Object emptyValue(Schema<?> schema) { if (Boolean.TRUE.equals(schema.getNullable())) { return null; } if (schema instanceof ArraySchema) { return List.of(); } else if (schema instanceof ObjectSchema) { return Map.of(); } else { return null; } } private boolean valueIsEmpty(Object value) { if (value instanceof Collection<?>) { return ((Collection<?>) value).isEmpty(); } else if (value instanceof Map<?, ?>) { return ((Map<?, ?>) value).isEmpty(); } else { return value == null; } } private boolean valueInEnvelopeIsEmpty(Object value) { if (value instanceof Collection<?>) { return ((Collection<?>) value).isEmpty(); } else if (value instanceof Map<?, ?>) { var valueMap = ((Map<?, ?>) value); return valueMap.isEmpty() || valueMap.values() .stream() .allMatch(Objects::isNull); } else { return value == null; } } private Object mapObjectSchemaProperty(String name, Schema<?> schema, GraphQLFieldDefinition parentFieldDefinition, Map<String, Object> data, JexlContext jexlContext) { if (!isMappable(schema)) { return mapSchema(schema, parentFieldDefinition, data, jexlContext); } var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(parentFieldDefinition.getType()); var fieldDefinition = rawType.getFieldDefinition(name); return mapSchema(schema, fieldDefinition, data.get(name), jexlContext); } @SuppressWarnings("unchecked") private Collection<Object> mapArraySchema(ArraySchema schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { var rawType = GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); if (typeMappers.containsKey(rawType.getName())) { return (Collection<Object>) typeMappers.get(rawType.getName()) .fieldToBody(data, schema); } if (MapperUtils.isPageableField(fieldDefinition)) { if (!(data instanceof Map)) { throw illegalStateException("Data is not compatible with pageable array schema."); } var dataMap = (Map<String, Object>) data; var items = dataMap.get(PagingConstants.NODES_FIELD_NAME); if (!(items instanceof Collection)) { throw illegalStateException("Data is not compatible with array schema."); } return ((Collection<Object>) items).stream() .map(item -> mapSchema(schema.getItems(), ((GraphQLObjectType) rawType).getFieldDefinition(PagingConstants.NODES_FIELD_NAME), item, jexlContext)) .collect(Collectors.toList()); } if (!(data instanceof Collection)) { throw illegalStateException("Data is not compatible with array schema."); } return ((Collection<Object>) data).stream() .map(item -> mapSchema(schema.getItems(), fieldDefinition, item, jexlContext)) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") private JexlContext updateJexlContext(Object data, JexlContext jexlContext) { if (!(data instanceof Map)) { return jexlContext; } var newContext = new MapContext(); newContext.set("args", jexlContext.get("args")); environmentProperties.getAllProperties() .forEach((prop, value) -> newContext.set(String.format("env.%s", prop), value)); newContext.set("data", data); return newContext; } private Object evaluateScalarData(Schema<?> schema, Object data, JexlContext jexlContext) { var defaultValue = schema.getDefault(); var optionalJexlExpression = getJexlExpression(schema); if (optionalJexlExpression.isPresent()) { return evaluateJexlExpression(optionalJexlExpression.get(), jexlHelper, jexlContext, Object.class) .orElse(defaultValue); } if (data == null) { return schema.getDefault(); } return data; } @Override public boolean supports(MediaType mediaType, OperationContext operationContext) { var mediaTypeString = mediaType.toString(); var schema = operationContext.getResponse() .getContent() .get(mediaTypeString) .getSchema(); return schema != null && MEDIA_TYPE_PATTERN.matcher(mediaTypeString) .matches(); } }
service/openapi/src/main/java/org/dotwebstack/framework/service/openapi/response/JsonBodyMapper.java
package org.dotwebstack.framework.service.openapi.response; import static org.dotwebstack.framework.core.helpers.ExceptionHelper.illegalStateException; import static org.dotwebstack.framework.core.jexl.JexlHelper.getJexlContext; import static org.dotwebstack.framework.service.openapi.helper.DwsExtensionHelper.getJexlExpression; import static org.dotwebstack.framework.service.openapi.helper.DwsExtensionHelper.resolveDwsName; import static org.dotwebstack.framework.service.openapi.jexl.JexlUtils.evaluateJexlExpression; import static org.dotwebstack.framework.service.openapi.mapping.MapperUtils.isEnvelope; import static org.dotwebstack.framework.service.openapi.mapping.MapperUtils.isMappable; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLTypeUtil; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.ObjectSchema; import io.swagger.v3.oas.models.media.Schema; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import lombok.NonNull; import org.apache.commons.jexl3.JexlContext; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.MapContext; import org.dotwebstack.framework.core.datafetchers.paging.PagingConstants; import org.dotwebstack.framework.core.jexl.JexlHelper; import org.dotwebstack.framework.service.openapi.handler.OperationContext; import org.dotwebstack.framework.service.openapi.handler.OperationRequest; import org.dotwebstack.framework.service.openapi.mapping.EnvironmentProperties; import org.dotwebstack.framework.service.openapi.mapping.MapperUtils; import org.dotwebstack.framework.service.openapi.mapping.TypeMapper; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component public class JsonBodyMapper implements BodyMapper { private static final Pattern MEDIA_TYPE_PATTERN = Pattern.compile("^application/([a-z]+\\+)?json$"); private final GraphQLSchema graphQlSchema; private final JexlHelper jexlHelper; private final EnvironmentProperties environmentProperties; private final Map<String, TypeMapper> typeMappers; public JsonBodyMapper(@NonNull GraphQL graphQL, @NonNull JexlEngine jexlEngine, @NonNull EnvironmentProperties environmentProperties, @NonNull Collection<TypeMapper> typeMappers) { this.graphQlSchema = graphQL.getGraphQLSchema(); this.jexlHelper = new JexlHelper(jexlEngine); this.environmentProperties = environmentProperties; this.typeMappers = typeMappers.stream() .collect(Collectors.toMap(TypeMapper::typeName, Function.identity())); } @Override public Mono<Object> map(OperationRequest operationRequest, Object result) { var queryField = graphQlSchema.getQueryType() .getFieldDefinition(operationRequest.getContext() .getQueryProperties() .getField()); var jexlContext = getJexlContext(environmentProperties.getAllProperties(), operationRequest.getServerRequest(), operationRequest.getParameters()); return Mono.just(mapSchema(operationRequest.getResponseSchema(), queryField, result, jexlContext)); } private Object mapSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { if (data == null) { return emptyValue(schema); } var newContext = updateJexlContext(data, jexlContext); if ("object".equals(schema.getType())) { return mapObjectSchema(schema, fieldDefinition, data, newContext); } if (schema instanceof ArraySchema) { return mapArraySchema((ArraySchema) schema, fieldDefinition, data, newContext); } return evaluateScalarData(schema, data, newContext); } @SuppressWarnings( {"unchecked", "rawtypes"}) private Object mapObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { if (MapperUtils.isEnvelope(schema)) { return mapEnvelopeObjectSchema(schema, fieldDefinition, data, jexlContext); } var rawType = GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); if (typeMappers.containsKey(rawType.getName())) { return typeMappers.get(rawType.getName()) .fieldToBody(data, schema); } Map<String, Object> dataMap; if (!(data instanceof Map)) { try { dataMap = new ObjectMapper().convertValue(data, Map.class); } catch (IllegalArgumentException e) { throw illegalStateException("Data is not compatible with object schema.", e); } } else { dataMap = (Map<String, Object>) data; } if (schema.getProperties() == null) { return dataMap; } return schema.getProperties() .entrySet() .stream() .collect(HashMap::new, (acc, entry) -> { var property = resolveDwsName(entry.getValue(), entry.getKey()); var nestedSchema = entry.getValue(); var value = mapObjectSchemaProperty(property, nestedSchema, fieldDefinition, dataMap, jexlContext); if ((schema.getRequired() != null && schema.getRequired() .contains(property)) || !valueIsEmpty(value)) { acc.put(entry.getKey(), value); } }, HashMap::putAll); } @SuppressWarnings( {"unchecked", "rawtypes"}) private Object mapEnvelopeObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); var envelopeValue = schema.getProperties() .entrySet() .stream() .collect(HashMap::new, (acc, entry) -> { var property = resolveDwsName(entry.getValue(), entry.getKey()); var nestedSchema = entry.getValue(); var nestedFieldDefinition = rawType.getFieldDefinition(property); Object nestedValue; if (nestedFieldDefinition == null || isEnvelope(nestedSchema)) { nestedValue = mapSchema(nestedSchema, fieldDefinition, data, jexlContext); } else { if (!(data instanceof Map)) { throw illegalStateException("Data is not compatible with object schema."); } var dataMap = (Map<String, Object>) data; var childData = dataMap.get(property); addParentData(dataMap, childData); nestedValue = mapSchema(nestedSchema, nestedFieldDefinition, childData, jexlContext); } if ((schema.getRequired() != null && schema.getRequired() .contains(property)) || !valueInEnvelopeIsEmpty(nestedValue)) { acc.put(entry.getKey(), nestedValue); } }, HashMap::putAll); return valueInEnvelopeIsEmpty(envelopeValue) && Boolean.TRUE.equals(schema.getNullable()) ? null : envelopeValue; } private Object emptyValue(Schema<?> schema) { if (Boolean.TRUE.equals(schema.getNullable())) { return null; } if (schema instanceof ArraySchema) { return List.of(); } else if (schema instanceof ObjectSchema) { return Map.of(); } else { return null; } } private boolean valueIsEmpty(Object value) { if (value instanceof Collection<?>) { return ((Collection<?>) value).isEmpty(); } else if (value instanceof Map<?, ?>) { return ((Map<?, ?>) value).isEmpty(); } else { return value == null; } } private boolean valueInEnvelopeIsEmpty(Object value) { if (value instanceof Collection<?>) { return ((Collection<?>) value).isEmpty(); } else if (value instanceof Map<?, ?>) { var valueMap = ((Map<?, ?>) value); return valueMap.isEmpty() || valueMap.values() .stream() .allMatch(Objects::isNull); } else { return value == null; } } private Object mapObjectSchemaProperty(String name, Schema<?> schema, GraphQLFieldDefinition parentFieldDefinition, Map<String, Object> data, JexlContext jexlContext) { if (!isMappable(schema)) { return mapSchema(schema, parentFieldDefinition, data, jexlContext); } var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(parentFieldDefinition.getType()); var fieldDefinition = rawType.getFieldDefinition(name); var childData = data.get(name); addParentData(data, childData); return mapSchema(schema, fieldDefinition, childData, jexlContext); } @SuppressWarnings( {"unchecked", "rawtypes"}) private void addParentData(Map<String, Object> data, Object childData) { if (childData == null) { return; } if (childData instanceof Map) { ((Map<String, Object>) childData).put("_parent", data); } else if (childData instanceof List) { var childDataList = ((List) childData); if (!childDataList.isEmpty() && childDataList.get(0) instanceof Map) { childDataList.forEach(item -> ((Map) item).put("_parent", data)); } } } @SuppressWarnings("unchecked") private Collection<Object> mapArraySchema(ArraySchema schema, GraphQLFieldDefinition fieldDefinition, Object data, JexlContext jexlContext) { var rawType = GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); if (typeMappers.containsKey(rawType.getName())) { return (Collection<Object>) typeMappers.get(rawType.getName()) .fieldToBody(data, schema); } if (MapperUtils.isPageableField(fieldDefinition)) { if (!(data instanceof Map)) { throw illegalStateException("Data is not compatible with pageable array schema."); } var dataMap = (Map<String, Object>) data; var items = dataMap.get(PagingConstants.NODES_FIELD_NAME); if (!(items instanceof Collection)) { throw illegalStateException("Data is not compatible with array schema."); } return ((Collection<Object>) items).stream() .map(item -> mapSchema(schema.getItems(), ((GraphQLObjectType) rawType).getFieldDefinition(PagingConstants.NODES_FIELD_NAME), item, jexlContext)) .collect(Collectors.toList()); } if (!(data instanceof Collection)) { throw illegalStateException("Data is not compatible with array schema."); } return ((Collection<Object>) data).stream() .map(item -> mapSchema(schema.getItems(), fieldDefinition, item, jexlContext)) .collect(Collectors.toList()); } @SuppressWarnings("unchecked") private JexlContext updateJexlContext(Object data, JexlContext jexlContext) { if (!(data instanceof Map)) { return jexlContext; } var newContext = new MapContext(); newContext.set("args", jexlContext.get("args")); environmentProperties.getAllProperties() .forEach((prop, value) -> newContext.set(String.format("env.%s", prop), value)); newContext.set("data", data); return newContext; } private Object evaluateScalarData(Schema<?> schema, Object data, JexlContext jexlContext) { var defaultValue = schema.getDefault(); var optionalJexlExpression = getJexlExpression(schema); if (optionalJexlExpression.isPresent()) { return evaluateJexlExpression(optionalJexlExpression.get(), jexlHelper, jexlContext, Object.class) .orElse(defaultValue); } if (data == null) { return schema.getDefault(); } return data; } @Override public boolean supports(MediaType mediaType, OperationContext operationContext) { var mediaTypeString = mediaType.toString(); var schema = operationContext.getResponse() .getContent() .get(mediaTypeString) .getSchema(); return schema != null && MEDIA_TYPE_PATTERN.matcher(mediaTypeString) .matches(); } }
Revert "[IHR2-7124] - add _parent to jexlcontext" This reverts commit ee42ada4baf4c679838f2bcbeb069aca3fa35044.
service/openapi/src/main/java/org/dotwebstack/framework/service/openapi/response/JsonBodyMapper.java
Revert "[IHR2-7124] - add _parent to jexlcontext"
<ide><path>ervice/openapi/src/main/java/org/dotwebstack/framework/service/openapi/response/JsonBodyMapper.java <ide> import io.swagger.v3.oas.models.media.ArraySchema; <ide> import io.swagger.v3.oas.models.media.ObjectSchema; <ide> import io.swagger.v3.oas.models.media.Schema; <del> <ide> import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.function.Function; <ide> import java.util.regex.Pattern; <ide> import java.util.stream.Collectors; <del> <ide> import lombok.NonNull; <ide> import org.apache.commons.jexl3.JexlContext; <ide> import org.apache.commons.jexl3.JexlEngine; <ide> private final Map<String, TypeMapper> typeMappers; <ide> <ide> public JsonBodyMapper(@NonNull GraphQL graphQL, @NonNull JexlEngine jexlEngine, <del> @NonNull EnvironmentProperties environmentProperties, <del> @NonNull Collection<TypeMapper> typeMappers) { <add> @NonNull EnvironmentProperties environmentProperties, @NonNull Collection<TypeMapper> typeMappers) { <ide> this.graphQlSchema = graphQL.getGraphQLSchema(); <ide> this.jexlHelper = new JexlHelper(jexlEngine); <ide> this.environmentProperties = environmentProperties; <ide> } <ide> <ide> private Object mapSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, <del> JexlContext jexlContext) { <add> JexlContext jexlContext) { <ide> if (data == null) { <ide> return emptyValue(schema); <ide> } <ide> return evaluateScalarData(schema, data, newContext); <ide> } <ide> <del> @SuppressWarnings( {"unchecked", "rawtypes"}) <add> @SuppressWarnings({"unchecked", "rawtypes"}) <ide> private Object mapObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, <del> JexlContext jexlContext) { <add> JexlContext jexlContext) { <ide> if (MapperUtils.isEnvelope(schema)) { <ide> return mapEnvelopeObjectSchema(schema, fieldDefinition, data, jexlContext); <ide> } <ide> }, HashMap::putAll); <ide> } <ide> <del> @SuppressWarnings( {"unchecked", "rawtypes"}) <add> @SuppressWarnings({"unchecked", "rawtypes"}) <ide> private Object mapEnvelopeObjectSchema(Schema<?> schema, GraphQLFieldDefinition fieldDefinition, Object data, <del> JexlContext jexlContext) { <add> JexlContext jexlContext) { <ide> var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); <ide> <ide> var envelopeValue = schema.getProperties() <ide> } <ide> <ide> var dataMap = (Map<String, Object>) data; <del> var childData = dataMap.get(property); <del> addParentData(dataMap, childData); <del> nestedValue = mapSchema(nestedSchema, nestedFieldDefinition, childData, jexlContext); <add> nestedValue = mapSchema(nestedSchema, nestedFieldDefinition, dataMap.get(property), jexlContext); <ide> } <ide> <ide> if ((schema.getRequired() != null && schema.getRequired() <ide> } <ide> <ide> private Object mapObjectSchemaProperty(String name, Schema<?> schema, GraphQLFieldDefinition parentFieldDefinition, <del> Map<String, Object> data, JexlContext jexlContext) { <add> Map<String, Object> data, JexlContext jexlContext) { <ide> if (!isMappable(schema)) { <ide> return mapSchema(schema, parentFieldDefinition, data, jexlContext); <ide> } <ide> var rawType = (GraphQLObjectType) GraphQLTypeUtil.unwrapAll(parentFieldDefinition.getType()); <ide> var fieldDefinition = rawType.getFieldDefinition(name); <ide> <del> var childData = data.get(name); <del> addParentData(data, childData); <del> return mapSchema(schema, fieldDefinition, childData, jexlContext); <del> } <del> <del> @SuppressWarnings( {"unchecked", "rawtypes"}) <del> private void addParentData(Map<String, Object> data, Object childData) { <del> if (childData == null) { <del> return; <del> } <del> if (childData instanceof Map) { <del> ((Map<String, Object>) childData).put("_parent", data); <del> } else if (childData instanceof List) { <del> var childDataList = ((List) childData); <del> if (!childDataList.isEmpty() && childDataList.get(0) instanceof Map) { <del> childDataList.forEach(item -> ((Map) item).put("_parent", data)); <del> } <del> } <add> return mapSchema(schema, fieldDefinition, data.get(name), jexlContext); <ide> } <ide> <ide> @SuppressWarnings("unchecked") <ide> private Collection<Object> mapArraySchema(ArraySchema schema, GraphQLFieldDefinition fieldDefinition, Object data, <del> JexlContext jexlContext) { <add> JexlContext jexlContext) { <ide> <ide> var rawType = GraphQLTypeUtil.unwrapAll(fieldDefinition.getType()); <ide>
JavaScript
mit
66f0779ceee7baa538ef81ec11ff216222966257
0
exponentjs/xdl,exponentjs/xdl,exponentjs/xdl
// @flow import fsp from 'mz/fs'; import mkdirp from 'mkdirp-promise'; import os from 'os'; import path from 'path'; import Config from '../Config'; /* A Cacher is used to wrap a fallible or expensive function and to memoize its results on disk in case it either fails or we don't need fresh results very often. It stores objects in JSON, and parses JSON from disk when returning an object. It's constructed with a "refresher" callback which will be called for the results, a filename to use for the cache, and an optional TTL and boostrap file. The TTL (in milliseconds) can be used to speed up slow calls from the cache (for example checking npm published versions can be very slow). The bootstrap file can be used to "seed" the cache with a particular value stored in a file. If there is a problem calling the refresher function or in performing the cache's disk I/O, errors will be stored in variables on the class. The only times Cacher will throw an exception are if it's not possible to create the cache directory (usually weird home directory permissions), or if getAsync() is called but no value can be provided. The latter will only occur if the refresher fails, no cache is available on disk (i.e. this is the first call or it has been recently cleared), and bootstrapping was not available (either a bootstrap file wasn't provided or reading/writing failed). See src/__tests__/tools/FsCache-test.js for usage examples. */ class Cacher<T> { refresher: () => Promise<T>; filename: string; bootstrapFile: ?string; ttlMilliseconds: number; readError: ?any; writeError: ?any; constructor( refresher: () => Promise<T>, filename: string, ttlMilliseconds: ?number, bootstrapFile: ?string, ) { this.refresher = refresher; this.filename = path.join(getCacheDir(), filename); this.ttlMilliseconds = ttlMilliseconds || 0; this.bootstrapFile = bootstrapFile; } async getAsync(): Promise<T> { await mkdirp(getCacheDir()); let mtime: Date; try { const stats = await fsp.stat(this.filename); mtime = stats.mtime; } catch (e) { if (this.bootstrapFile) { try { const bootstrapContents = (await fsp.readFile(this.bootstrapFile)).toString(); await fsp.writeFile(this.filename, bootstrapContents, 'utf8'); } catch (e) { // intentional no-op } } mtime = new Date(1989, 10, 19); } let fromCache: ?T; let failedRefresh = null; // if mtime + ttl >= now, attempt to fetch the value, otherwise read from disk if (new Date() - mtime > this.ttlMilliseconds) { try { fromCache = await this.refresher(); try { await fsp.writeFile(this.filename, JSON.stringify(fromCache), 'utf8'); } catch (e) { this.writeError = e; // do nothing, if the refresh succeeded it'll be returned, if the persist failed we don't care } } catch (e) { failedRefresh = e; } } if (!fromCache) { try { fromCache = JSON.parse(await fsp.readFile(this.filename)); } catch (e) { this.readError = e; // if this fails then we've exhausted our options and it should remain null } } if (fromCache) { return fromCache; } else { if (failedRefresh) { throw new Error(`Unable to perform cache refresh for ${this.filename}: ${failedRefresh}`); } else { throw new Error(`Unable to read ${this.filename}. ${this.readError || ''}`); } } } async clearAsync(): Promise<void> { try { await fsp.unlink(this.filename); } catch (e) { this.writeError = e; } } } function getCacheDir(): string { const homeDir = os.homedir(); if (process.env.XDG_CACHE_HOME) { return process.env.XDG_CACHE_HOME; } else if (process.platform === 'win32') { return path.join(homeDir, 'AppData', 'Local', 'Exponent'); } else { return path.join(homeDir, '.cache', 'exponent'); } } export { Cacher, getCacheDir };
src/tools/FsCache.js
// @flow import fsp from 'mz/fs'; import mkdirp from 'mkdirp-promise'; import os from 'os'; import path from 'path'; import Config from '../Config'; /* A Cacher is used to wrap a fallible or expensive function and to memoize its results on disk in case it either fails or we don't need fresh results very often. It stores objects in JSON, and parses JSON from disk when returning an object. It's constructed with a "refresher" callback which will be called for the results, a filename to use for the cache, and an optional TTL and boostrap file. The TTL (in milliseconds) can be used to speed up slow calls from the cache (for example checking npm published versions can be very slow). The bootstrap file can be used to "seed" the cache with a particular value stored in a file. If there is a problem calling the refresher function or in performing the cache's disk I/O, errors will be stored in variables on the class. The only times Cacher will throw an exception are if it's not possible to create the cache directory (usually weird home directory permissions), or if getAsync() is called but no value can be provided. The latter will only occur if the refresher fails, no cache is available on disk (i.e. this is the first call or it has been recently cleared), and bootstrapping was not available (either a bootstrap file wasn't provided or reading/writing failed). See src/__tests__/tools/FsCache-test.js for usage examples. */ class Cacher<T> { refresher: () => Promise<T>; filename: string; bootstrapFile: ?string; ttlMilliseconds: number; readError: ?any; writeError: ?any; constructor( refresher: () => Promise<T>, filename: string, ttlMilliseconds: ?number, bootstrapFile: ?string, ) { this.refresher = refresher; this.filename = path.join(getCacheDir(), filename); this.ttlMilliseconds = ttlMilliseconds || 0; this.bootstrapFile = bootstrapFile; } async getAsync(): Promise<T> { await mkdirp(getCacheDir()); let mtime: Date; try { const stats = await fsp.stat(this.filename); mtime = stats.mtime; } catch (e) { if (this.bootstrapFile) { try { const bootstrapContents = (await fsp.readFile(this.bootstrapFile)).toString(); await fsp.writeFile(this.filename, bootstrapContents, 'utf8'); } catch (e) { // intentional no-op } } mtime = new Date(1989, 10, 19); } let fromCache: ?T; // if mtime + ttl >= now, attempt to fetch the value, otherwise read from disk if (new Date() - mtime > this.ttlMilliseconds) { try { fromCache = await this.refresher(); await fsp.writeFile(this.filename, JSON.stringify(fromCache), 'utf8'); } catch (e) { this.writeError = e; // do nothing, if the refresh succeeded it'll be returned, if the persist failed we don't care } } if (!fromCache) { try { fromCache = JSON.parse(await fsp.readFile(this.filename)); } catch (e) { this.readError = e; // if this fails then we've exhausted our options and it should remain null } } if (fromCache) { return fromCache; } else { throw new Error(`Unable to read ${this.filename}. ${this.readError || ''}`); } } async clearAsync(): Promise<void> { try { await fsp.unlink(this.filename); } catch (e) { this.writeError = e; } } } function getCacheDir(): string { const homeDir = os.homedir(); if (process.env.XDG_CACHE_HOME) { return process.env.XDG_CACHE_HOME; } else if (process.platform === 'win32') { return path.join(homeDir, 'AppData', 'Local', 'Exponent'); } else { return path.join(homeDir, '.cache', 'exponent'); } } export { Cacher, getCacheDir };
More informative cache failure error message. fbshipit-source-id: 215570f
src/tools/FsCache.js
More informative cache failure error message.
<ide><path>rc/tools/FsCache.js <ide> } <ide> <ide> let fromCache: ?T; <add> let failedRefresh = null; <ide> <ide> // if mtime + ttl >= now, attempt to fetch the value, otherwise read from disk <ide> if (new Date() - mtime > this.ttlMilliseconds) { <ide> try { <ide> fromCache = await this.refresher(); <del> await fsp.writeFile(this.filename, JSON.stringify(fromCache), 'utf8'); <add> try { <add> await fsp.writeFile(this.filename, JSON.stringify(fromCache), 'utf8'); <add> } catch (e) { <add> this.writeError = e; <add> // do nothing, if the refresh succeeded it'll be returned, if the persist failed we don't care <add> } <ide> } catch (e) { <del> this.writeError = e; <del> // do nothing, if the refresh succeeded it'll be returned, if the persist failed we don't care <add> failedRefresh = e; <ide> } <ide> } <ide> <ide> if (fromCache) { <ide> return fromCache; <ide> } else { <del> throw new Error(`Unable to read ${this.filename}. ${this.readError || ''}`); <add> if (failedRefresh) { <add> throw new Error(`Unable to perform cache refresh for ${this.filename}: ${failedRefresh}`); <add> } else { <add> throw new Error(`Unable to read ${this.filename}. ${this.readError || ''}`); <add> } <ide> } <ide> } <ide>
Java
epl-1.0
560ee0d9bec57934671582a6c0a5d030dbafa3bc
0
whizzosoftware/WZWave
/******************************************************************************* * Copyright (c) 2013 Whizzo Software, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.whizzosoftware.wzwave.frame.parser; import com.whizzosoftware.wzwave.frame.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayDeque; import java.util.NoSuchElementException; /** * Class responsible for receiving bytes from the serial port and converting them into the appropriate calls * to the FrameListener. * * @author Dan Noguerol */ public class FrameParser { private final Logger logger = LoggerFactory.getLogger(getClass()); private final static int STATE_NEW_FRAME = 0; private final static int STATE_FRAME_LENGTH = 1; private final static int STATE_FRAME_DATA = 2; private final static int STATE_CHECKSUM = 3; private FrameListener frameListener; private ArrayDeque<Byte> byteBuffer = new ArrayDeque<Byte>(); private int state = STATE_NEW_FRAME; private byte currentFrameLength; private int currentFrameIndex; private byte[] currentFrameData; public FrameParser(FrameListener frameListener) { this.frameListener = frameListener; } public void addBytes(byte[] bytes, int count) { for (int i=0; i < count; i++) { byteBuffer.add(bytes[i]); } processBuffer(); } protected void processBuffer() { try { Byte b = byteBuffer.pop(); while (b != null) { switch (state) { case STATE_NEW_FRAME: currentFrameLength = 0; currentFrameIndex = 0; currentFrameData = null; switch (b) { case 0x01: state = STATE_FRAME_LENGTH; break; case 0x06: frameListener.onACK(); break; case 0x15: frameListener.onNAK(); break; case 0x18: frameListener.onCAN(); break; default: logger.debug("Ignoring unexpected byte {}", b); break; } break; case STATE_FRAME_LENGTH: currentFrameLength = b; currentFrameData = new byte[currentFrameLength + 2]; currentFrameData[0] = 0x01; currentFrameData[1] = currentFrameLength; currentFrameIndex = 2; state = STATE_FRAME_DATA; break; case STATE_FRAME_DATA: currentFrameData[currentFrameIndex++] = b; if (currentFrameIndex == currentFrameLength + 1) { state = STATE_CHECKSUM; } break; case STATE_CHECKSUM: // TODO: verify the checksum currentFrameData[currentFrameIndex] = b; frameListener.onDataFrame(createDataFrame(currentFrameData)); state = STATE_NEW_FRAME; break; } b = byteBuffer.pop(); } } catch (NoSuchElementException e) { // NO-OP } } protected DataFrame createDataFrame(byte[] buffer) { byte messageType = buffer[3]; switch (messageType) { case Version.ID: return new Version(buffer); case MemoryGetId.ID: return new MemoryGetId(buffer); case InitData.ID: return new InitData(buffer); case NodeProtocolInfo.ID: return new NodeProtocolInfo(buffer); case SendData.ID: return new SendData(buffer); case ApplicationCommand.ID: return new ApplicationCommand(buffer); case ApplicationUpdate.ID: return new ApplicationUpdate(buffer); case RequestNodeInfo.ID: return new RequestNodeInfo(buffer); case GetRoutingInfo.ID: return new GetRoutingInfo(buffer); } return null; } }
src/main/java/com/whizzosoftware/wzwave/frame/parser/FrameParser.java
/******************************************************************************* * Copyright (c) 2013 Whizzo Software, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.whizzosoftware.wzwave.frame.parser; import com.whizzosoftware.wzwave.frame.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayDeque; import java.util.NoSuchElementException; /** * Class responsible for receiving bytes from the serial port and converting them into the appropriate calls * to the FrameListener. * * @author Dan Noguerol */ public class FrameParser { private final Logger logger = LoggerFactory.getLogger(getClass()); private final static int STATE_NEW_FRAME = 0; private final static int STATE_FRAME_LENGTH = 1; private final static int STATE_FRAME_DATA = 2; private final static int STATE_CHECKSUM = 3; private FrameListener frameListener; private ArrayDeque<Byte> byteBuffer = new ArrayDeque<Byte>(); private int state = STATE_NEW_FRAME; private byte currentFrameLength; private int currentFrameIndex; private byte[] currentFrameData; public FrameParser(FrameListener frameListener) { this.frameListener = frameListener; } public void addBytes(byte[] bytes, int count) { for (int i=0; i < count; i++) { byteBuffer.add(bytes[i]); } processBuffer(); } protected void processBuffer() { try { Byte b = byteBuffer.pop(); while (b != null) { switch (state) { case STATE_NEW_FRAME: currentFrameLength = 0; currentFrameIndex = 0; currentFrameData = null; switch (b) { case 0x01: state = STATE_FRAME_LENGTH; break; case 0x06: frameListener.onACK(); break; case 0x15: frameListener.onNAK(); break; case 0x16: frameListener.onCAN(); break; default: logger.debug("Ignoring unexpected byte {}", b); break; } break; case STATE_FRAME_LENGTH: currentFrameLength = b; currentFrameData = new byte[currentFrameLength + 2]; currentFrameData[0] = 0x01; currentFrameData[1] = currentFrameLength; currentFrameIndex = 2; state = STATE_FRAME_DATA; break; case STATE_FRAME_DATA: currentFrameData[currentFrameIndex++] = b; if (currentFrameIndex == currentFrameLength + 1) { state = STATE_CHECKSUM; } break; case STATE_CHECKSUM: // TODO: verify the checksum currentFrameData[currentFrameIndex] = b; frameListener.onDataFrame(createDataFrame(currentFrameData)); state = STATE_NEW_FRAME; break; } b = byteBuffer.pop(); } } catch (NoSuchElementException e) { // NO-OP } } protected DataFrame createDataFrame(byte[] buffer) { byte messageType = buffer[3]; switch (messageType) { case Version.ID: return new Version(buffer); case MemoryGetId.ID: return new MemoryGetId(buffer); case InitData.ID: return new InitData(buffer); case NodeProtocolInfo.ID: return new NodeProtocolInfo(buffer); case SendData.ID: return new SendData(buffer); case ApplicationCommand.ID: return new ApplicationCommand(buffer); case ApplicationUpdate.ID: return new ApplicationUpdate(buffer); case RequestNodeInfo.ID: return new RequestNodeInfo(buffer); case GetRoutingInfo.ID: return new GetRoutingInfo(buffer); } return null; } }
Fixed incorrect CAN byte value.
src/main/java/com/whizzosoftware/wzwave/frame/parser/FrameParser.java
Fixed incorrect CAN byte value.
<ide><path>rc/main/java/com/whizzosoftware/wzwave/frame/parser/FrameParser.java <ide> case 0x15: <ide> frameListener.onNAK(); <ide> break; <del> case 0x16: <add> case 0x18: <ide> frameListener.onCAN(); <ide> break; <ide> default:
Java
agpl-3.0
e7fd6b6a1524c384bc1a27264422a72c8a32b164
0
ErmiasG/hopsworks,ErmiasG/hopsworks,AlexHopsworks/hopsworks,AlexHopsworks/hopsworks,AlexHopsworks/hopsworks,AlexHopsworks/hopsworks,AlexHopsworks/hopsworks,AlexHopsworks/hopsworks,ErmiasG/hopsworks,ErmiasG/hopsworks,ErmiasG/hopsworks,ErmiasG/hopsworks
/* * This file is part of Hopsworks * Copyright (C) 2022, Logical Clocks AB. All rights reserved * * Hopsworks is free software: you can redistribute it and/or modify it under the terms of * the GNU Affero General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * Hopsworks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. */ package io.hops.hopsworks.common.pythonresources; import com.google.common.base.Strings; import com.logicalclocks.servicediscoverclient.exceptions.ServiceDiscoveryException; import com.logicalclocks.servicediscoverclient.service.Service; import io.hops.hopsworks.common.hosts.ServiceDiscoveryController; import io.hops.hopsworks.common.util.PrometheusClient; import io.hops.hopsworks.common.util.Settings; import io.hops.hopsworks.exceptions.ServiceException; import org.json.JSONArray; import org.json.JSONObject; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; @Stateless @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class PythonResourcesController { private final static Logger LOGGER = Logger.getLogger(PythonResourcesController.class.getName()); @EJB private ServiceDiscoveryController serviceDiscoveryController; @EJB private PrometheusClient client; @EJB private Settings settings; private static JSONObject pythonResources = new JSONObject(); private final String DOCKER_TOTAL_ALLOCATABLE_CPU_KEY = "docker_allocatable_cpu"; private final String DOCKER_CURRENT_CPU_USAGE_KEY = "docker_current_cpu_usage"; private final String DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY = "docker_total_memory"; private final String DOCKER_CURRENT_MEMORY_USAGE_KEY = "docker_current_memory_usage"; private final String CLUSTER_TOTAL_MEMORY_CAPACITY = "cluster_total_memory"; private final String CLUSTER_TOTAL_CPU_CAPACITY = "cluster_total_cpu"; private final String CLUSTER_CURRENT_MEMORY_USAGE = "cluster_current_memory_usage"; private final String CLUSTER_CURRENT_CPU_USAGE = "cluster_current_cpu_usage"; private Integer nodeExporterPort; @PostConstruct public void init() { try { Service nodeExporterService = serviceDiscoveryController.getAnyAddressOfServiceWithDNS( ServiceDiscoveryController.HopsworksService.NODE_EXPORTER); nodeExporterPort = nodeExporterService.getPort(); } catch (ServiceDiscoveryException e) { LOGGER.log(Level.INFO, e.getMessage()); } } public JSONObject getPythonResources() throws ServiceDiscoveryException { Map<String, String> pythonResourcesTypesQueries = updatePrometheusQueries(); pythonResourcesTypesQueries.forEach((key, query) -> getResourceValue(key, query)); pythonResources.put(CLUSTER_TOTAL_CPU_CAPACITY, 100); if (!settings.isDockerCgroupEnabled() || settings.getKubeInstalled()) { //use the same values as the cluster pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, 100); pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, pythonResources.get(CLUSTER_TOTAL_MEMORY_CAPACITY)); pythonResources.put(DOCKER_CURRENT_MEMORY_USAGE_KEY, pythonResources.get(CLUSTER_CURRENT_MEMORY_USAGE)); pythonResources.put(DOCKER_CURRENT_CPU_USAGE_KEY, pythonResources.get(CLUSTER_CURRENT_CPU_USAGE)); } return pythonResources; } private void getResourceValue(String resource, String query) { try { JSONObject queryResult = client.execute(query); JSONArray resultObject = queryResult.getJSONObject("data").getJSONArray("result"); if (resultObject.length() > 0) { pythonResources.put(resource, resultObject.getJSONObject(0).getJSONArray("value").getString(1)); } else { pythonResources.put(resource, ""); } } catch (ServiceException e) { pythonResources.put(resource, ""); } } private Map<String, String> updatePrometheusQueries() throws ServiceDiscoveryException { Map<String, String> pythonResourcesTypesQueries = new HashMap<String, String>(); if (nodeExporterPort == null) { Service nodeExporterService = serviceDiscoveryController.getAnyAddressOfServiceWithDNS( ServiceDiscoveryController.HopsworksService.NODE_EXPORTER); nodeExporterPort = nodeExporterService.getPort(); } String nodeQuery = getExcludedNodesInResourceQuery(); String nodeQueryNoAppend = nodeQuery.replaceAll(",", ""); pythonResourcesTypesQueries.put(CLUSTER_CURRENT_CPU_USAGE, "100 - ((sum((avg by (instance) (rate(node_cpu_seconds_total{mode='idle'" + nodeQuery + "}[1m])) * 100)))/" + "(count(node_memory_Active_bytes{" + nodeQueryNoAppend + "})))"); pythonResourcesTypesQueries.put(CLUSTER_CURRENT_MEMORY_USAGE, "sum(node_memory_Active_bytes{" + nodeQueryNoAppend + "})"); pythonResourcesTypesQueries.put(CLUSTER_TOTAL_MEMORY_CAPACITY, "sum(node_memory_MemTotal_bytes{" + nodeQueryNoAppend + "})"); //If cgroups are enabled we use metrics from cadvisor //On Kuberbetes we don't use the configured docker cgroups. if (settings.isDockerCgroupEnabled() && !settings.getKubeInstalled()) { pythonResourcesTypesQueries.put(DOCKER_CURRENT_CPU_USAGE_KEY, "sum(avg by (cpu) (rate(container_cpu_usage_seconds_total{id=~'.*/docker/.*'}[60s]) * 100))"); pythonResourcesTypesQueries.put(DOCKER_CURRENT_MEMORY_USAGE_KEY, "sum(container_memory_working_set_bytes{id=~'.*/docker/.*'})"); pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, "container_spec_memory_limit_bytes{id='/docker'}"); pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, "(container_spec_cpu_quota{id='/docker'}/" + settings.getDockerCgroupCpuPeriod() + ")*100"); } return pythonResourcesTypesQueries; } private String getExcludedNodesInResourceQuery() { if (!settings.getKubeInstalled()) { return ""; } String taintedNodesStr = settings.getKubeTaintedNodes(); List<String> nodes = new ArrayList<>(Arrays.asList(taintedNodesStr.split(",")) .stream().filter(n -> !Strings.isNullOrEmpty(n)).collect(Collectors.toList())); String taintedNodesQuery = ""; for (int i = 0; i < nodes.size(); i++) { if (i == 0) { taintedNodesQuery += ", instance !~ '"; } if (i < nodes.size() - 1) { taintedNodesQuery += nodes.get(i) + ":" + nodeExporterPort + "|"; } else { taintedNodesQuery += nodes.get(i) + ":" + nodeExporterPort + "'"; } } return taintedNodesQuery; } }
hopsworks-common/src/main/java/io/hops/hopsworks/common/pythonresources/PythonResourcesController.java
/* * This file is part of Hopsworks * Copyright (C) 2022, Logical Clocks AB. All rights reserved * * Hopsworks is free software: you can redistribute it and/or modify it under the terms of * the GNU Affero General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * Hopsworks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. */ package io.hops.hopsworks.common.pythonresources; import com.google.common.base.Strings; import com.logicalclocks.servicediscoverclient.exceptions.ServiceDiscoveryException; import com.logicalclocks.servicediscoverclient.service.Service; import io.hops.hopsworks.common.hosts.ServiceDiscoveryController; import io.hops.hopsworks.common.util.PrometheusClient; import io.hops.hopsworks.common.util.Settings; import io.hops.hopsworks.exceptions.ServiceException; import org.json.JSONArray; import org.json.JSONObject; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; @Stateless @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class PythonResourcesController { private final static Logger LOGGER = Logger.getLogger(PythonResourcesController.class.getName()); @EJB private ServiceDiscoveryController serviceDiscoveryController; @EJB private PrometheusClient client; @EJB private Settings settings; private static JSONObject pythonResources = new JSONObject(); private final String DOCKER_TOTAL_ALLOCATABLE_CPU_KEY = "docker_allocatable_cpu"; private final String DOCKER_CURRENT_CPU_USAGE_KEY = "docker_current_cpu_usage"; private final String DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY = "docker_total_memory"; private final String DOCKER_CURRENT_MEMORY_USAGE_KEY = "docker_current_memory_usage"; private final String CLUSTER_TOTAL_MEMORY_CAPACITY = "cluster_total_memory"; private final String CLUSTER_TOTAL_CPU_CAPACITY = "cluster_total_cpu"; private final String CLUSTER_CURRENT_MEMORY_USAGE = "cluster_current_memory_usage"; private final String CLUSTER_CURRENT_CPU_USAGE = "cluster_current_cpu_usage"; private Integer nodeExporterPort; @PostConstruct public void init() { try { Service nodeExporterService = serviceDiscoveryController.getAnyAddressOfServiceWithDNS( ServiceDiscoveryController.HopsworksService.NODE_EXPORTER); nodeExporterPort = nodeExporterService.getPort(); } catch (ServiceDiscoveryException e) { LOGGER.log(Level.INFO, e.getMessage()); } } public JSONObject getPythonResources() throws ServiceDiscoveryException { Map<String, String> pythonResourcesTypesQueries = updatePrometheusQueries(); pythonResourcesTypesQueries.forEach((key, query) -> getResourceValue(key, query)); pythonResources.put(CLUSTER_TOTAL_CPU_CAPACITY, 100); if (!settings.isDockerCgroupEnabled() && !settings.getKubeInstalled()) { //use the same values as the cluster pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, 100); pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, pythonResources.get(CLUSTER_TOTAL_MEMORY_CAPACITY)); pythonResources.put(DOCKER_CURRENT_MEMORY_USAGE_KEY, pythonResources.get(CLUSTER_CURRENT_MEMORY_USAGE)); pythonResources.put(DOCKER_CURRENT_CPU_USAGE_KEY, pythonResources.get(CLUSTER_CURRENT_CPU_USAGE)); } return pythonResources; } private void getResourceValue(String resource, String query) { try { JSONObject queryResult = client.execute(query); JSONArray resultObject = queryResult.getJSONObject("data").getJSONArray("result"); if (resultObject.length() > 0) { pythonResources.put(resource, resultObject.getJSONObject(0).getJSONArray("value").getString(1)); } else { pythonResources.put(resource, ""); } } catch (ServiceException e) { pythonResources.put(resource, ""); } } private Map<String, String> updatePrometheusQueries() throws ServiceDiscoveryException { Map<String, String> pythonResourcesTypesQueries = new HashMap<String, String>(); if (nodeExporterPort == null) { Service nodeExporterService = serviceDiscoveryController.getAnyAddressOfServiceWithDNS( ServiceDiscoveryController.HopsworksService.NODE_EXPORTER); nodeExporterPort = nodeExporterService.getPort(); } String nodeQuery = getExcludedNodesInResourceQuery(); String nodeQueryNoAppend = nodeQuery.replaceAll(",", ""); pythonResourcesTypesQueries.put(CLUSTER_CURRENT_CPU_USAGE, "100 - ((sum((avg by (instance) (rate(node_cpu_seconds_total{mode='idle'" + nodeQuery + "}[1m])) * 100)))/" + "(count(node_memory_Active_bytes{" + nodeQueryNoAppend + "})))"); pythonResourcesTypesQueries.put(CLUSTER_CURRENT_MEMORY_USAGE, "sum(node_memory_Active_bytes{" + nodeQueryNoAppend + "})"); pythonResourcesTypesQueries.put(CLUSTER_TOTAL_MEMORY_CAPACITY, "sum(node_memory_MemTotal_bytes{" + nodeQueryNoAppend + "})"); //If cgroups are enabled we use metrics from cadvisor //On Kuberbetes we don't use the configured docker cgroups. if (settings.isDockerCgroupEnabled() && !settings.getKubeInstalled()) { pythonResourcesTypesQueries.put(DOCKER_CURRENT_CPU_USAGE_KEY, "sum(avg by (cpu) (rate(container_cpu_usage_seconds_total{id=~'.*/docker/.*'}[60s]) * 100))"); pythonResourcesTypesQueries.put(DOCKER_CURRENT_MEMORY_USAGE_KEY, "sum(container_memory_working_set_bytes{id=~'.*/docker/.*'})"); pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, "container_spec_memory_limit_bytes{id='/docker'}"); pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, "(container_spec_cpu_quota{id='/docker'}/" + settings.getDockerCgroupCpuPeriod() + ")*100"); } else { pythonResourcesTypesQueries.put(DOCKER_CURRENT_CPU_USAGE_KEY, "100 - ((sum((avg by (instance) (rate(node_cpu_seconds_total{mode='idle'" + nodeQuery + "}[1m])) * 100)))/" + "(count(node_memory_Active_bytes{" + nodeQueryNoAppend + "})))"); pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, "sum(node_memory_Active_bytes{" + nodeQueryNoAppend + "})"); pythonResourcesTypesQueries.put(CLUSTER_TOTAL_MEMORY_CAPACITY, "sum(node_memory_MemTotal_bytes{" + nodeQueryNoAppend + "})"); } return pythonResourcesTypesQueries; } private String getExcludedNodesInResourceQuery() { if (!settings.getKubeInstalled()) { return ""; } String taintedNodesStr = settings.getKubeTaintedNodes(); List<String> nodes = new ArrayList<>(Arrays.asList(taintedNodesStr.split(",")) .stream().filter(n -> !Strings.isNullOrEmpty(n)).collect(Collectors.toList())); String taintedNodesQuery = ""; for (int i = 0; i < nodes.size(); i++) { if (i == 0) { taintedNodesQuery += ", instance !~ '"; } if (i < nodes.size() - 1) { taintedNodesQuery += nodes.get(i) + ":" + nodeExporterPort + "|"; } else { taintedNodesQuery += nodes.get(i) + ":" + nodeExporterPort + "'"; } } return taintedNodesQuery; } }
Python resources fix (#976) (#1119)
hopsworks-common/src/main/java/io/hops/hopsworks/common/pythonresources/PythonResourcesController.java
Python resources fix (#976) (#1119)
<ide><path>opsworks-common/src/main/java/io/hops/hopsworks/common/pythonresources/PythonResourcesController.java <ide> pythonResourcesTypesQueries.forEach((key, query) -> getResourceValue(key, query)); <ide> <ide> pythonResources.put(CLUSTER_TOTAL_CPU_CAPACITY, 100); <del> if (!settings.isDockerCgroupEnabled() && !settings.getKubeInstalled()) { <add> if (!settings.isDockerCgroupEnabled() || settings.getKubeInstalled()) { <ide> //use the same values as the cluster <ide> pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, 100); <ide> pythonResources.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, pythonResources.get(CLUSTER_TOTAL_MEMORY_CAPACITY)); <ide> "container_spec_memory_limit_bytes{id='/docker'}"); <ide> pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_CPU_KEY, <ide> "(container_spec_cpu_quota{id='/docker'}/" + settings.getDockerCgroupCpuPeriod() + ")*100"); <del> } else { <del> pythonResourcesTypesQueries.put(DOCKER_CURRENT_CPU_USAGE_KEY, <del> "100 - ((sum((avg by (instance) (rate(node_cpu_seconds_total{mode='idle'" + nodeQuery + "}[1m])) * 100)))/" + <del> "(count(node_memory_Active_bytes{" + nodeQueryNoAppend + "})))"); <del> pythonResourcesTypesQueries.put(DOCKER_TOTAL_ALLOCATABLE_MEMORY_KEY, <del> "sum(node_memory_Active_bytes{" + nodeQueryNoAppend + "})"); <del> pythonResourcesTypesQueries.put(CLUSTER_TOTAL_MEMORY_CAPACITY, <del> "sum(node_memory_MemTotal_bytes{" + nodeQueryNoAppend + "})"); <ide> } <ide> <ide> return pythonResourcesTypesQueries;
Java
apache-2.0
da6a7a45b3df2c1237ca3e1b01c8734eaad70ef0
0
cbornet/springfox,zhiqinghuang/springfox,RobWin/springfox,springfox/springfox,jlstrater/springfox,izeye/springfox,kevinconaway/springfox,zorosteven/springfox,zorosteven/springfox,springfox/springfox,arshadalisoomro/springfox,yelhouti/springfox,choiapril6/springfox,RobWin/springfox,izeye/springfox,acourtneybrown/springfox,qq291462491/springfox,vmarusic/springfox,springfox/springfox,thomsonreuters/springfox,thomasdarimont/springfox,erikthered/springfox,qq291462491/springfox,springfox/springfox,wjc133/springfox,thomasdarimont/springfox,ammmze/swagger-springmvc,thomsonreuters/springfox,zhiqinghuang/springfox,yelhouti/springfox,choiapril6/springfox,wjc133/springfox,erikthered/springfox,erikthered/springfox,choiapril6/springfox,acourtneybrown/springfox,maksimu/springfox,arshadalisoomro/springfox,namkee/springfox,thomsonreuters/springfox,thomasdarimont/springfox,arshadalisoomro/springfox,jlstrater/springfox,maksimu/springfox,ammmze/swagger-springmvc,cbornet/springfox,yelhouti/springfox,maksimu/springfox,vmarusic/springfox,RobWin/springfox,acourtneybrown/springfox,qq291462491/springfox,namkee/springfox,vmarusic/springfox,namkee/springfox,kevinconaway/springfox,cbornet/springfox,ammmze/swagger-springmvc,zhiqinghuang/springfox,wjc133/springfox,jlstrater/springfox,izeye/springfox,kevinconaway/springfox,zorosteven/springfox
package com.mangofactory.swagger.spring; import com.mangofactory.swagger.spring.controller.DocumentationController; import com.mangofactory.swagger.spring.sample.configuration.ServicesTestConfiguration; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.server.test.context.WebContextLoader; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.core.IsEqual.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Tests that exercise the documentation * API's and check the JSON returned is valid. * * @author martypitt */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = WebContextLoader.class, classes = ServicesTestConfiguration.class) public class DocumentationRootTest { public static final String BUSINESS_ENTITY_SERVICES = "Services to demonstrate path variable resolution"; @Autowired DocumentationController controller; private MockMvc mockMvc; private MockHttpServletRequestBuilder builder; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); builder = MockMvcRequestBuilders.get("/api-docs").accept(MediaType.APPLICATION_JSON); } @Test public void testDocumentationEndpointServesOk() throws Exception { mockMvc.perform(builder) .andExpect(status().isOk()); } @Test public void testResourcePathNotListed() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.resourcePath").doesNotExist()); } @Test public void testApisContainCorrectApiList() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").exists()) .andExpect(jsonPath("$.apis").isArray()); } @Test public void testApiVersionReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").value(equalTo("2.0"))); } @Test public void testSwaggerVersionReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.swaggerVersion").value(equalTo("1.0"))); } @Test public void testBasePathReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.basePath").value(equalTo("/some-path"))); } @Test @Ignore public void shouldHaveCorrectPathForBusinessServiceController() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").exists()) .andExpect(jsonPath("$.apis[0].path").value(equalTo("/api-docs/business-service"))) .andExpect(jsonPath("$.apis[0].description").value(equalTo(BUSINESS_ENTITY_SERVICES))); } @Test public void shouldRespondWithDocumentOperationsWhenBusinessApiDocsCalled() throws Exception { mockMvc.perform(get("/api-docs/business-service") .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(xpath("controllerDocumentation").exists()) .andExpect(xpath("controllerDocumentation/apiVersion").string("2.0")) .andExpect(xpath("controllerDocumentation/apis[1]/description").string(equalTo(BUSINESS_ENTITY_SERVICES))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/nickname").string(equalTo("getAliasedPathVariable"))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/httpMethod").string(equalTo("GET"))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/summary").string(equalTo("Find a business by its id"))) .andExpect(xpath("controllerDocumentation/apis[1]/path").string(equalTo("/businesses/aliased/{otherId}"))); } }
src/test/java/com/mangofactory/swagger/spring/DocumentationRootTest.java
package com.mangofactory.swagger.spring; import com.mangofactory.swagger.spring.controller.DocumentationController; import com.mangofactory.swagger.spring.sample.configuration.ServicesTestConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.server.test.context.WebContextLoader; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.hamcrest.core.IsEqual.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Tests that exercise the documentation * API's and check the JSON returned is valid. * * @author martypitt */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = WebContextLoader.class, classes = ServicesTestConfiguration.class) public class DocumentationRootTest { public static final String BUSINESS_ENTITY_SERVICES = "Services to demonstrate path variable resolution"; @Autowired DocumentationController controller; private MockMvc mockMvc; private MockHttpServletRequestBuilder builder; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); builder = MockMvcRequestBuilders.get("/api-docs").accept(MediaType.APPLICATION_JSON); } @Test public void testDocumentationEndpointServesOk() throws Exception { mockMvc.perform(builder) .andExpect(status().isOk()); } @Test public void testResourcePathNotListed() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.resourcePath").doesNotExist()); } @Test public void testApisContainCorrectApiList() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").exists()) .andExpect(jsonPath("$.apis").isArray()); } @Test public void testApiVersionReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").value(equalTo("2.0"))); } @Test public void testSwaggerVersionReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.swaggerVersion").value(equalTo("1.0"))); } @Test public void testBasePathReturnedCorrectly() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.basePath").value(equalTo("/some-path"))); } @Test public void shouldHaveCorrectPathForBusinessServiceController() throws Exception { mockMvc.perform(builder) .andExpect(jsonPath("$.apiVersion").exists()) .andExpect(jsonPath("$.apis[0].path").value(equalTo("/api-docs/business-service"))) .andExpect(jsonPath("$.apis[0].description").value(equalTo(BUSINESS_ENTITY_SERVICES))); } @Test public void shouldRespondWithDocumentOperationsWhenBusinessApiDocsCalled() throws Exception { mockMvc.perform(get("/api-docs/business-service") .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(xpath("controllerDocumentation").exists()) .andExpect(xpath("controllerDocumentation/apiVersion").string("2.0")) .andExpect(xpath("controllerDocumentation/apis[1]/description").string(equalTo(BUSINESS_ENTITY_SERVICES))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/nickname").string(equalTo("getAliasedPathVariable"))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/httpMethod").string(equalTo("GET"))) .andExpect(xpath("controllerDocumentation/apis[1]/operations[1]/summary").string(equalTo("Find a business by its id"))) .andExpect(xpath("controllerDocumentation/apis[1]/path").string(equalTo("/businesses/aliased/{otherId}"))); } }
Ignoring failing test that is not deterministic
src/test/java/com/mangofactory/swagger/spring/DocumentationRootTest.java
Ignoring failing test that is not deterministic
<ide><path>rc/test/java/com/mangofactory/swagger/spring/DocumentationRootTest.java <ide> import com.mangofactory.swagger.spring.controller.DocumentationController; <ide> import com.mangofactory.swagger.spring.sample.configuration.ServicesTestConfiguration; <ide> import org.junit.Before; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> } <ide> <ide> @Test <add> @Ignore <ide> public void shouldHaveCorrectPathForBusinessServiceController() throws Exception { <ide> mockMvc.perform(builder) <ide> .andExpect(jsonPath("$.apiVersion").exists())
Java
bsd-3-clause
005564a386919dc40bec830414067738c522a87f
0
ConnCollege/cas,ConnCollege/cas,ConnCollege/cas
/* * Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license * distributed with this file and available online at * http://www.uportal.org/license.html */ package org.jasig.cas.ticket.proxy.support; import java.net.HttpURLConnection; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.cas.authentication.principal.Credentials; import org.jasig.cas.authentication.principal.HttpBasedServiceCredentials; import org.jasig.cas.ticket.proxy.ProxyHandler; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.jasig.cas.util.UniqueTicketIdGenerator; import org.springframework.beans.factory.InitializingBean; /** * Proxy Handler to handle the default callback functionality of CAS 2.0. * <p> * The default behavior as defined in the CAS 2 Specification is to callback the * URL provided and give it a pgtIou and a pgtId. * </p> * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.0 */ public final class Cas20ProxyHandler implements ProxyHandler, InitializingBean { /** The Commons Logging instance. */ private final Log log = LogFactory.getLog(getClass()); /** The PGTIOU ticket prefix. */ private static final String PGTIOU_PREFIX = "PGTIOU"; /** The default status codes we accept. */ private static final int[] DEFAULT_ACCEPTABLE_CODES = new int[] { HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_MODIFIED, HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_ACCEPTED}; /** List of HTTP status codes considered valid by this AuthenticationHandler. */ private int[] acceptableCodes; /** Generate unique ids. */ private UniqueTicketIdGenerator uniqueTicketIdGenerator; /** Instance of Apache Commons HttpClient */ private HttpClient httpClient; public String handle(final Credentials credentials, final String proxyGrantingTicketId) { final HttpBasedServiceCredentials serviceCredentials = (HttpBasedServiceCredentials) credentials; final String proxyIou = this.uniqueTicketIdGenerator .getNewTicketId(PGTIOU_PREFIX); final StringBuffer stringBuffer = new StringBuffer(); synchronized (stringBuffer) { stringBuffer.append(serviceCredentials.getCallbackUrl() .toExternalForm()); if (serviceCredentials.getCallbackUrl().getQuery() != null) { stringBuffer.append("&"); } else { stringBuffer.append("?"); } stringBuffer.append("pgtIou="); stringBuffer.append(proxyIou); stringBuffer.append("&pgtId="); stringBuffer.append(proxyGrantingTicketId); } final GetMethod getMethod = new GetMethod(stringBuffer.toString()); try { this.httpClient.executeMethod(getMethod); final int responseCode = getMethod.getStatusCode(); for (int i = 0; i < this.acceptableCodes.length; i++) { if (responseCode == this.acceptableCodes[i]) { if (log.isDebugEnabled()) { log.debug("Sent ProxyIou of " + proxyIou + " for service: " + serviceCredentials.getCallbackUrl()); } return proxyIou; } } } catch (final Exception e) { log.error(e,e); // do nothing } finally { getMethod.releaseConnection(); } if (log.isDebugEnabled()) { log.debug("Failed to send ProxyIou of " + proxyIou + " for service: " + serviceCredentials.getCallbackUrl()); } return null; } /** * @param uniqueTicketIdGenerator The uniqueTicketIdGenerator to set. */ public void setUniqueTicketIdGenerator( final UniqueTicketIdGenerator uniqueTicketIdGenerator) { this.uniqueTicketIdGenerator = uniqueTicketIdGenerator; } /** * Set the acceptable HTTP status codes that we will use to determine if the * response from the URL was correct. * * @param acceptableCodes an array of status code integers. */ public void setAcceptableCodes(final int[] acceptableCodes) { this.acceptableCodes = acceptableCodes; } public void setHttpClient(final HttpClient httpClient) { this.httpClient = httpClient; } public void afterPropertiesSet() throws Exception { if (this.uniqueTicketIdGenerator == null) { this.uniqueTicketIdGenerator = new DefaultUniqueTicketIdGenerator(); log.info("No UniqueTicketIdGenerator specified for " + this.getClass().getName() + ". Using " + this.uniqueTicketIdGenerator.getClass().getName()); } if (this.httpClient == null) { this.httpClient = new HttpClient(); Protocol myhttps = new Protocol( "https", (ProtocolSocketFactory) new StrictSSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); } if (this.acceptableCodes == null) { this.acceptableCodes = DEFAULT_ACCEPTABLE_CODES; } } }
core/src/main/java/org/jasig/cas/ticket/proxy/support/Cas20ProxyHandler.java
/* * Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license * distributed with this file and available online at * http://www.uportal.org/license.html */ package org.jasig.cas.ticket.proxy.support; import java.net.HttpURLConnection; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.cas.authentication.principal.Credentials; import org.jasig.cas.authentication.principal.HttpBasedServiceCredentials; import org.jasig.cas.ticket.proxy.ProxyHandler; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.jasig.cas.util.UniqueTicketIdGenerator; import org.springframework.beans.factory.InitializingBean; /** * Proxy Handler to handle the default callback functionality of CAS 2.0. * <p> * The default behavior as defined in the CAS 2 Specification is to callback the * URL provided and give it a pgtIou and a pgtId. * </p> * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.0 */ public final class Cas20ProxyHandler implements ProxyHandler, InitializingBean { /** The Commons Logging instance. */ private final Log log = LogFactory.getLog(getClass()); /** The PGTIOU ticket prefix. */ private static final String PGTIOU_PREFIX = "PGTIOU"; /** The default status codes we accept. */ private static final int[] DEFAULT_ACCEPTABLE_CODES = new int[] { HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_MODIFIED, HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_ACCEPTED}; /** List of HTTP status codes considered valid by this AuthenticationHandler. */ private int[] acceptableCodes; /** Generate unique ids. */ private UniqueTicketIdGenerator uniqueTicketIdGenerator; /** Instance of Apache Commons HttpClient */ private HttpClient httpClient; public String handle(final Credentials credentials, final String proxyGrantingTicketId) { final HttpBasedServiceCredentials serviceCredentials = (HttpBasedServiceCredentials) credentials; final String proxyIou = this.uniqueTicketIdGenerator .getNewTicketId(PGTIOU_PREFIX); final StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(serviceCredentials.getCallbackUrl() .toExternalForm()); if (serviceCredentials.getCallbackUrl().getQuery() != null) { stringBuffer.append("&"); } else { stringBuffer.append("?"); } stringBuffer.append("pgtIou="); stringBuffer.append(proxyIou); stringBuffer.append("&pgtId="); stringBuffer.append(proxyGrantingTicketId); final GetMethod getMethod = new GetMethod(stringBuffer.toString()); try { this.httpClient.executeMethod(getMethod); final int responseCode = getMethod.getStatusCode(); for (int i = 0; i < this.acceptableCodes.length; i++) { if (responseCode == this.acceptableCodes[i]) { if (log.isDebugEnabled()) { log.debug("Sent ProxyIou of " + proxyIou + " for service: " + serviceCredentials.getCallbackUrl()); } return proxyIou; } } } catch (final Exception e) { log.error(e,e); // do nothing } finally { getMethod.releaseConnection(); } if (log.isDebugEnabled()) { log.debug("Failed to send ProxyIou of " + proxyIou + " for service: " + serviceCredentials.getCallbackUrl()); } return null; } /** * @param uniqueTicketIdGenerator The uniqueTicketIdGenerator to set. */ public void setUniqueTicketIdGenerator( final UniqueTicketIdGenerator uniqueTicketIdGenerator) { this.uniqueTicketIdGenerator = uniqueTicketIdGenerator; } /** * Set the acceptable HTTP status codes that we will use to determine if the * response from the URL was correct. * * @param acceptableCodes an array of status code integers. */ public void setAcceptableCodes(final int[] acceptableCodes) { this.acceptableCodes = acceptableCodes; } public void setHttpClient(final HttpClient httpClient) { this.httpClient = httpClient; } public void afterPropertiesSet() throws Exception { if (this.uniqueTicketIdGenerator == null) { this.uniqueTicketIdGenerator = new DefaultUniqueTicketIdGenerator(); log.info("No UniqueTicketIdGenerator specified for " + this.getClass().getName() + ". Using " + this.uniqueTicketIdGenerator.getClass().getName()); } if (this.httpClient == null) { this.httpClient = new HttpClient(); Protocol myhttps = new Protocol( "https", (ProtocolSocketFactory) new StrictSSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); } if (this.acceptableCodes == null) { this.acceptableCodes = DEFAULT_ACCEPTABLE_CODES; } } }
added sync block for string buffer
core/src/main/java/org/jasig/cas/ticket/proxy/support/Cas20ProxyHandler.java
added sync block for string buffer
<ide><path>ore/src/main/java/org/jasig/cas/ticket/proxy/support/Cas20ProxyHandler.java <ide> .getNewTicketId(PGTIOU_PREFIX); <ide> final StringBuffer stringBuffer = new StringBuffer(); <ide> <del> stringBuffer.append(serviceCredentials.getCallbackUrl() <del> .toExternalForm()); <del> <del> if (serviceCredentials.getCallbackUrl().getQuery() != null) { <del> stringBuffer.append("&"); <del> } else { <del> stringBuffer.append("?"); <add> synchronized (stringBuffer) { <add> stringBuffer.append(serviceCredentials.getCallbackUrl() <add> .toExternalForm()); <add> <add> if (serviceCredentials.getCallbackUrl().getQuery() != null) { <add> stringBuffer.append("&"); <add> } else { <add> stringBuffer.append("?"); <add> } <add> <add> stringBuffer.append("pgtIou="); <add> stringBuffer.append(proxyIou); <add> stringBuffer.append("&pgtId="); <add> stringBuffer.append(proxyGrantingTicketId); <ide> } <del> <del> stringBuffer.append("pgtIou="); <del> stringBuffer.append(proxyIou); <del> stringBuffer.append("&pgtId="); <del> stringBuffer.append(proxyGrantingTicketId); <ide> <ide> final GetMethod getMethod = new GetMethod(stringBuffer.toString()); <ide> try {
Java
apache-2.0
d27b7deaa3eb9e3f8ba4938aa21a63d7e92f4870
0
craigday/stateless4j
package com.github.oxo42.stateless4j; import com.github.oxo42.stateless4j.delegates.Action1; import com.github.oxo42.stateless4j.delegates.Action2; import com.github.oxo42.stateless4j.delegates.Func; import com.github.oxo42.stateless4j.transitions.Transition; import com.github.oxo42.stateless4j.triggers.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Models behaviour as transitions between a finite set of states * * @param <S> The type used to represent the states * @param <T> The type used to represent the triggers that cause state transitions */ public class StateMachine<S, T> { protected final StateMachineConfig<S, T> config; protected final Func<S> stateAccessor; protected final Action1<S> stateMutator; private final Logger logger = LoggerFactory.getLogger(getClass()); protected Action2<S, T> unhandledTriggerAction = new Action2<S, T>() { public void doIt(S state, T trigger) { throw new IllegalStateException( String.format( "No valid leaving transitions are permitted from state '%s' for trigger '%s'. Consider ignoring the trigger.", state, trigger) ); } }; /** * Construct a state machine * * @param intialState The initial state */ public StateMachine(S intialState) { this(intialState, new StateMachineConfig<S, T>()); } /** * Construct a state machine * * @param initialState The initial state * @param config State machine configuration */ public StateMachine(S initialState, StateMachineConfig<S, T> config) { this.config = config; final StateReference<S, T> reference = new StateReference<>(); reference.setState(initialState); stateAccessor = new Func<S>() { @Override public S call() { return reference.getState(); } }; stateMutator = new Action1<S>() { @Override public void doIt(S s) { reference.setState(s); } }; if (config.isEntryActionOfInitialStateEnabled()) { Transition<S,T> initialTransition = new Transition(initialState, initialState, null); getCurrentRepresentation().enter(initialTransition); } } /** * Construct a state machine with external state storage. * * @param initialState The initial state * @param stateAccessor State accessor * @param stateMutator State mutator */ public StateMachine(S initialState, Func<S> stateAccessor, Action1<S> stateMutator, StateMachineConfig<S, T> config) { this.config = config; this.stateAccessor = stateAccessor; this.stateMutator = stateMutator; stateMutator.doIt(initialState); } public StateConfiguration<S, T> configure(S state) { return config.configure(state); } public StateMachineConfig<S, T> configuration() { return config; } /** * The current state * * @return The current state */ public S getState() { return stateAccessor.call(); } private void setState(S value) { stateMutator.doIt(value); } /** * The currently-permissible trigger values * * @return The currently-permissible trigger values */ public List<T> getPermittedTriggers() { return getCurrentRepresentation().getPermittedTriggers(); } StateRepresentation<S, T> getCurrentRepresentation() { StateRepresentation<S, T> representation = config.getRepresentation(getState()); return representation == null ? new StateRepresentation<S, T>(getState()) : representation; } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked * * @param trigger The trigger to fire */ public void fire(T trigger) { publicFire(trigger); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param <TArg0> Type of the first trigger argument */ public <TArg0> void fire(TriggerWithParameters1<TArg0, S, T> trigger, TArg0 arg0) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param arg1 The second argument * @param <TArg0> Type of the first trigger argument * @param <TArg1> Type of the second trigger argument */ public <TArg0, TArg1> void fire(TriggerWithParameters2<TArg0, TArg1, S, T> trigger, TArg0 arg0, TArg1 arg1) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0, arg1); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param arg1 The second argument * @param arg2 The third argument * @param <TArg0> Type of the first trigger argument * @param <TArg1> Type of the second trigger argument * @param <TArg2> Type of the third trigger argument */ public <TArg0, TArg1, TArg2> void fire(TriggerWithParameters3<TArg0, TArg1, TArg2, S, T> trigger, TArg0 arg0, TArg1 arg1, TArg2 arg2) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0, arg1, arg2); } protected void publicFire(T trigger, Object... args) { logger.debug("Firing {}", trigger); TriggerWithParameters<S, T> configuration = config.getTriggerConfiguration(trigger); if (configuration != null) { configuration.validateParameters(args); } TriggerBehaviour<S, T> triggerBehaviour = getCurrentRepresentation().tryFindHandler(trigger); if (triggerBehaviour == null) { unhandledTriggerAction.doIt(getCurrentRepresentation().getUnderlyingState(), trigger); return; } S source = getState(); OutVar<S> destination = new OutVar<>(); if (triggerBehaviour.resultsInTransitionFrom(source, args, destination)) { Transition<S, T> transition = new Transition<>(source, destination.get(), trigger); getCurrentRepresentation().exit(transition); setState(destination.get()); getCurrentRepresentation().enter(transition, args); } } /** * Override the default behaviour of throwing an exception when an unhandled trigger is fired * * @param unhandledTriggerAction An action to call when an unhandled trigger is fired */ public void onUnhandledTrigger(Action2<S, T> unhandledTriggerAction) { if (unhandledTriggerAction == null) { throw new IllegalStateException("unhandledTriggerAction"); } this.unhandledTriggerAction = unhandledTriggerAction; } /** * Determine if the state machine is in the supplied state * * @param state The state to test for * @return True if the current state is equal to, or a substate of, the supplied state */ public boolean isInState(S state) { return getCurrentRepresentation().isIncludedIn(state); } /** * Returns true if {@code trigger} can be fired in the current state * * @param trigger Trigger to test * @return True if the trigger can be fired, false otherwise */ public boolean canFire(T trigger) { return getCurrentRepresentation().canHandle(trigger); } /** * A human-readable representation of the state machine * * @return A description of the current state and permitted triggers */ @Override public String toString() { List<T> permittedTriggers = getPermittedTriggers(); List<String> parameters = new ArrayList<>(); for (T tTrigger : permittedTriggers) { parameters.add(tTrigger.toString()); } StringBuilder params = new StringBuilder(); String delim = ""; for (String param : parameters) { params.append(delim); params.append(param); delim = ", "; } return String.format( "StateMachine {{ State = %s, PermittedTriggers = {{ %s }}}}", getState(), params.toString()); } }
src/main/java/com/github/oxo42/stateless4j/StateMachine.java
package com.github.oxo42.stateless4j; import com.github.oxo42.stateless4j.delegates.Action1; import com.github.oxo42.stateless4j.delegates.Action2; import com.github.oxo42.stateless4j.delegates.Func; import com.github.oxo42.stateless4j.transitions.Transition; import com.github.oxo42.stateless4j.triggers.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Models behaviour as transitions between a finite set of states * * @param <S> The type used to represent the states * @param <T> The type used to represent the triggers that cause state transitions */ public class StateMachine<S, T> { protected final StateMachineConfig<S, T> config; protected final Func<S> stateAccessor; protected final Action1<S> stateMutator; private final Logger logger = LoggerFactory.getLogger(getClass()); protected Action2<S, T> unhandledTriggerAction = new Action2<S, T>() { public void doIt(S state, T trigger) { throw new IllegalStateException( String.format( "No valid leaving transitions are permitted from state '%s' for trigger '%s'. Consider ignoring the trigger.", state, trigger) ); } }; /** * Construct a state machine * * @param intialState The initial state */ public StateMachine(S intialState) { this(intialState, new StateMachineConfig<S, T>()); } /** * Construct a state machine * * @param initialState The initial state * @param config State machine configuration */ public StateMachine(S initialState, StateMachineConfig<S, T> config) { this.config = config; final StateReference<S, T> reference = new StateReference<>(); reference.setState(initialState); stateAccessor = new Func<S>() { @Override public S call() { return reference.getState(); } }; stateMutator = new Action1<S>() { @Override public void doIt(S s) { reference.setState(s); } }; if (config.isEntryActionOfInitialStateEnabled()) { Transition<S,T> initialTransition = new Transition(initialState, initialState, null); getCurrentRepresentation().enter(initialTransition); } } /** * Construct a state machine with external state storage. * * @param initialState The initial state * @param stateAccessor State accessor * @param stateMutator State mutator */ public StateMachine(S initialState, Func<S> stateAccessor, Action1<S> stateMutator, StateMachineConfig<S, T> config) { this.config = config; this.stateAccessor = stateAccessor; this.stateMutator = stateMutator; stateMutator.doIt(initialState); } public StateConfiguration<S, T> configure(S state) { return config.configure(state); } public StateMachineConfig<S, T> configuration() { return config; } /** * The current state * * @return The current state */ public S getState() { return stateAccessor.call(); } private void setState(S value) { stateMutator.doIt(value); } /** * The currently-permissible trigger values * * @return The currently-permissible trigger values */ public List<T> getPermittedTriggers() { return getCurrentRepresentation().getPermittedTriggers(); } StateRepresentation<S, T> getCurrentRepresentation() { StateRepresentation<S, T> representation = config.getRepresentation(getState()); return representation == null ? new StateRepresentation<S, T>(getState()) : representation; } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked * * @param trigger The trigger to fire */ public void fire(T trigger) { publicFire(trigger); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param <TArg0> Type of the first trigger argument */ public <TArg0> void fire(TriggerWithParameters1<TArg0, S, T> trigger, TArg0 arg0) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param arg1 The second argument * @param <TArg0> Type of the first trigger argument * @param <TArg1> Type of the second trigger argument */ public <TArg0, TArg1> void fire(TriggerWithParameters2<TArg0, TArg1, S, T> trigger, TArg0 arg0, TArg1 arg1) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0, arg1); } /** * Transition from the current state via the specified trigger. * The target state is determined by the configuration of the current state. * Actions associated with leaving the current state and entering the new one * will be invoked. * * @param trigger The trigger to fire * @param arg0 The first argument * @param arg1 The second argument * @param arg2 The third argument * @param <TArg0> Type of the first trigger argument * @param <TArg1> Type of the second trigger argument * @param <TArg2> Type of the third trigger argument */ public <TArg0, TArg1, TArg2> void fire(TriggerWithParameters3<TArg0, TArg1, TArg2, S, T> trigger, TArg0 arg0, TArg1 arg1, TArg2 arg2) { assert trigger != null : "trigger is null"; publicFire(trigger.getTrigger(), arg0, arg1, arg2); } protected void publicFire(T trigger, Object... args) { logger.info("Firing " + trigger); TriggerWithParameters<S, T> configuration = config.getTriggerConfiguration(trigger); if (configuration != null) { configuration.validateParameters(args); } TriggerBehaviour<S, T> triggerBehaviour = getCurrentRepresentation().tryFindHandler(trigger); if (triggerBehaviour == null) { unhandledTriggerAction.doIt(getCurrentRepresentation().getUnderlyingState(), trigger); return; } S source = getState(); OutVar<S> destination = new OutVar<>(); if (triggerBehaviour.resultsInTransitionFrom(source, args, destination)) { Transition<S, T> transition = new Transition<>(source, destination.get(), trigger); getCurrentRepresentation().exit(transition); setState(destination.get()); getCurrentRepresentation().enter(transition, args); } } /** * Override the default behaviour of throwing an exception when an unhandled trigger is fired * * @param unhandledTriggerAction An action to call when an unhandled trigger is fired */ public void onUnhandledTrigger(Action2<S, T> unhandledTriggerAction) { if (unhandledTriggerAction == null) { throw new IllegalStateException("unhandledTriggerAction"); } this.unhandledTriggerAction = unhandledTriggerAction; } /** * Determine if the state machine is in the supplied state * * @param state The state to test for * @return True if the current state is equal to, or a substate of, the supplied state */ public boolean isInState(S state) { return getCurrentRepresentation().isIncludedIn(state); } /** * Returns true if {@code trigger} can be fired in the current state * * @param trigger Trigger to test * @return True if the trigger can be fired, false otherwise */ public boolean canFire(T trigger) { return getCurrentRepresentation().canHandle(trigger); } /** * A human-readable representation of the state machine * * @return A description of the current state and permitted triggers */ @Override public String toString() { List<T> permittedTriggers = getPermittedTriggers(); List<String> parameters = new ArrayList<>(); for (T tTrigger : permittedTriggers) { parameters.add(tTrigger.toString()); } StringBuilder params = new StringBuilder(); String delim = ""; for (String param : parameters) { params.append(delim); params.append(param); delim = ", "; } return String.format( "StateMachine {{ State = %s, PermittedTriggers = {{ %s }}}}", getState(), params.toString()); } }
Moved logging to debug
src/main/java/com/github/oxo42/stateless4j/StateMachine.java
Moved logging to debug
<ide><path>rc/main/java/com/github/oxo42/stateless4j/StateMachine.java <ide> } <ide> <ide> protected void publicFire(T trigger, Object... args) { <del> logger.info("Firing " + trigger); <add> logger.debug("Firing {}", trigger); <ide> TriggerWithParameters<S, T> configuration = config.getTriggerConfiguration(trigger); <ide> if (configuration != null) { <ide> configuration.validateParameters(args);
Java
apache-2.0
4ab074de3a0d3ec3a3bf9223479ae12c423e1d59
0
agilebits/OpenYOLO-Android,openid/OpenYOLO-Android,iainmcgin/OpenYOLO-Android
/* * Copyright 2017 The OpenYOLO Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package org.openyolo.testapp; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnTextChanged; import org.openyolo.protocol.AuthenticationDomain; import org.openyolo.protocol.AuthenticationMethod; import org.openyolo.protocol.AuthenticationMethods; import org.openyolo.protocol.Credential; import org.openyolo.protocol.Hint; import org.openyolo.protocol.PasswordSpecification; import org.valid4j.errors.RequireViolation; public final class CredentialView extends LinearLayout { private static final String TAG = "CredentialView"; @BindView(R.id.generate_id_button) ImageButton mGenerateIdButton; @BindView(R.id.generate_password_button) ImageButton mGeneratePasswordButton; @BindView(R.id.openyolo_email_provider_button) ImageButton mEmailProviderButton; @BindView(R.id.google_provider_button) ImageButton mGenerateProviderButton; @BindView(R.id.facebook_provider_button) ImageButton mFacebookProviderButton; @BindView(R.id.generate_display_name_button) ImageButton mGenerateDisplayNameButton; @BindView(R.id.generate_profile_picture_button) ImageButton mGenerateProfilePictureButton; @BindView(R.id.id_field) EditText mIdField; @BindView(R.id.password_field) EditText mPasswordField; @BindView(R.id.display_name_field) EditText mDisplayNameField; @BindView(R.id.authentication_method_field) EditText mAuthenticationMethodField; @BindView(R.id.profile_picture_field) EditText mProfilePictureField; @BindView(R.id.profile_picture_view) ImageView mProfilePictureView; private RandomData mRandomData; /** * Simple constructor to use when creating a credential view from code. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. */ public CredentialView(Context context) { super(context); initialize(context); } /** * Constructor that is called when inflating a view from XML. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. */ public CredentialView(Context context, AttributeSet attrs) { super(context, attrs); initialize(context); } /** * Perform inflation from XML and apply a class-specific base style from a theme attribute. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. * @param defStyle An attribute in the current theme that contains a reference to a style * resource that supplies default values for the view. Can be 0 to not look for * defaults. */ public CredentialView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(context); } private void initialize(Context context) { View view = View.inflate(context, R.layout.credential_layout, this); mRandomData = new RandomData(); ButterKnife.bind(view); } /** * Hides or shows input generation buttons. */ public void setEnableInputGeneration(boolean isEnabled) { int visibility = View.GONE; if (isEnabled) { visibility = View.VISIBLE; } mGenerateIdButton.setVisibility(visibility); mGeneratePasswordButton.setVisibility(visibility); mGenerateProviderButton.setVisibility(visibility); mEmailProviderButton.setVisibility(visibility); mFacebookProviderButton.setVisibility(visibility); mGenerateDisplayNameButton.setVisibility(visibility); mGenerateProfilePictureButton.setVisibility(visibility); } @OnClick(R.id.generate_id_button) void generateId() { mIdField.setText(mRandomData.generateEmailAddress()); } @OnClick(R.id.generate_password_button) void generatePassword() { mPasswordField.setText(PasswordSpecification.DEFAULT.generate()); } @OnClick(R.id.openyolo_email_provider_button) void setEmailAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.EMAIL.toString()); } @OnClick(R.id.google_provider_button) void setGoogleAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.GOOGLE.toString()); } @OnClick(R.id.facebook_provider_button) void setFacebookAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.FACEBOOK.toString()); } @OnClick(R.id.generate_display_name_button) void generateDisplayName() { mDisplayNameField.setText(mRandomData.generateDisplayName()); } @OnClick(R.id.generate_profile_picture_button) void generateProfilePicture() { mProfilePictureField.setText(mRandomData.generateProfilePictureUri()); } @OnTextChanged(R.id.profile_picture_field) void loadProfilePicture() { String profilePictureUri = mProfilePictureField.getText().toString(); if (profilePictureUri.trim().isEmpty() || !Patterns.WEB_URL.matcher(profilePictureUri).matches()) { mProfilePictureView.setImageDrawable(null); } else { GlideApp.with(getContext()) .load(Uri.parse(profilePictureUri)) .fitCenter() .into(mProfilePictureView); } } /** * Clears all of the credential's fields. */ public void clearFields() { mIdField.setText(""); mPasswordField.setText(""); mDisplayNameField.setText(""); mAuthenticationMethodField.setText(""); mProfilePictureField.setText(""); } /** * Populates the fragment's fields from a given OpenYolo credential. * * @param credential an OpenYolo credential */ public void setFieldsFromCredential(Credential credential) { copyIfNotNull(credential.getIdentifier(), mIdField); copyIfNotNull(credential.getPassword(), mPasswordField); copyIfNotNull(credential.getDisplayName(), mDisplayNameField); copyIfNotNull(credential.getDisplayPicture(), mProfilePictureField); copyIfNotNull(credential.getAuthenticationMethod(), mAuthenticationMethodField); } /** * Populates the fragment's fields from a given OpenYOLO hint. */ public void setFieldsFromHint(Hint hint) { copyIfNotNull(hint.getIdentifier(), mIdField); copyIfNotNull(hint.getGeneratedPassword(), mPasswordField); copyIfNotNull(hint.getDisplayName(), mDisplayNameField); copyIfNotNull(hint.getDisplayPicture(), mProfilePictureField); copyIfNotNull(hint.getAuthenticationMethod(), mAuthenticationMethodField); } /** * Create an OpenYolo credential from the current fragment's fields. * * @return an OpenYolo Credential . */ @Nullable public Credential makeCredentialFromFields() { String authMethodStr = mAuthenticationMethodField.getText().toString(); AuthenticationMethod authMethod; try { authMethod = new AuthenticationMethod(authMethodStr); } catch (RequireViolation ex) { Log.w(TAG, "User entered authentication method " + authMethodStr + " is invalid", ex); return null; } AuthenticationDomain authenticationDomain = AuthenticationDomain.getSelfAuthDomain(getContext()); Credential.Builder credentialBuilder = new Credential.Builder( mIdField.getText().toString(), authMethod, authenticationDomain) .setDisplayName(convertEmptyToNull(mDisplayNameField.getText().toString())) .setDisplayPicture(convertEmptyToNull(mProfilePictureField.getText().toString())); credentialBuilder.setPassword(mPasswordField.getText().toString()); return credentialBuilder.build(); } private static String convertEmptyToNull(@NonNull String str) { if (str.isEmpty()) { return null; } return str; } private static void copyIfNotNull(@Nullable Object value, @NonNull EditText field) { if (value != null) { field.setText(value.toString()); } } }
testapp/java/org/openyolo/testapp/CredentialView.java
/* * Copyright 2017 The OpenYOLO Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package org.openyolo.testapp; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnTextChanged; import org.openyolo.protocol.AuthenticationDomain; import org.openyolo.protocol.AuthenticationMethod; import org.openyolo.protocol.AuthenticationMethods; import org.openyolo.protocol.Credential; import org.openyolo.protocol.Hint; import org.openyolo.protocol.PasswordSpecification; import org.valid4j.errors.RequireViolation; public final class CredentialView extends LinearLayout { private static final String TAG = "CredentialView"; @BindView(R.id.generate_id_button) ImageButton mGenerateIdButton; @BindView(R.id.generate_password_button) ImageButton mGeneratePasswordButton; @BindView(R.id.openyolo_email_provider_button) ImageButton mEmailProviderButton; @BindView(R.id.google_provider_button) ImageButton mGenerateProviderButton; @BindView(R.id.facebook_provider_button) ImageButton mFacebookProviderButton; @BindView(R.id.generate_display_name_button) ImageButton mGenerateDisplayNameButton; @BindView(R.id.generate_profile_picture_button) ImageButton mGenerateProfilePictureButton; @BindView(R.id.id_field) EditText mIdField; @BindView(R.id.password_field) EditText mPasswordField; @BindView(R.id.display_name_field) EditText mDisplayNameField; @BindView(R.id.authentication_method_field) EditText mAuthenticationMethodField; @BindView(R.id.profile_picture_field) EditText mProfilePictureField; @BindView(R.id.profile_picture_view) ImageView mProfilePictureView; private RandomData mRandomData; /** * Simple constructor to use when creating a credential view from code. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. */ public CredentialView(Context context) { super(context); initialize(context); } /** * Constructor that is called when inflating a view from XML. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. */ public CredentialView(Context context, AttributeSet attrs) { super(context, attrs); initialize(context); } /** * Perform inflation from XML and apply a class-specific base style from a theme attribute. * * @param context The Context the view is running in, through which it can access the current * theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. * @param defStyle An attribute in the current theme that contains a reference to a style * resource that supplies default values for the view. Can be 0 to not look for * defaults. */ public CredentialView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(context); } private void initialize(Context context) { View view = View.inflate(context, R.layout.credential_layout, this); mRandomData = new RandomData(); ButterKnife.bind(view); } /** * Hides or shows input generation buttons. */ public void setEnableInputGeneration(boolean isEnabled) { int visibility = View.GONE; if (isEnabled) { visibility = View.VISIBLE; } mGenerateIdButton.setVisibility(visibility); mGeneratePasswordButton.setVisibility(visibility); mGenerateProviderButton.setVisibility(visibility); mEmailProviderButton.setVisibility(visibility); mFacebookProviderButton.setVisibility(visibility); mGenerateDisplayNameButton.setVisibility(visibility); mGenerateProfilePictureButton.setVisibility(visibility); } @OnClick(R.id.generate_id_button) void generateId() { mIdField.setText(mRandomData.generateEmailAddress()); } @OnClick(R.id.generate_password_button) void generatePassword() { mPasswordField.setText(PasswordSpecification.DEFAULT.generate()); } @OnClick(R.id.openyolo_email_provider_button) void setEmailAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.EMAIL.toString()); } @OnClick(R.id.google_provider_button) void setGoogleAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.GOOGLE.toString()); } @OnClick(R.id.facebook_provider_button) void setFacebookAuthenticationMethod() { mAuthenticationMethodField.setText(AuthenticationMethods.FACEBOOK.toString()); } @OnClick(R.id.generate_display_name_button) void generateDisplayName() { mDisplayNameField.setText(mRandomData.generateDisplayName()); } @OnClick(R.id.generate_profile_picture_button) void generateProfilePicture() { mProfilePictureField.setText(mRandomData.generateProfilePictureUri()); } @OnTextChanged(R.id.profile_picture_field) void loadProfilePicture() { GlideApp.with(getContext()) .load(Uri.parse(mProfilePictureField.getText().toString())) .fitCenter() .into(mProfilePictureView); } /** * Clears all of the credential's fields. */ public void clearFields() { mIdField.setText(""); mPasswordField.setText(""); mDisplayNameField.setText(""); mAuthenticationMethodField.setText(""); mProfilePictureField.setText(""); } /** * Populates the fragment's fields from a given OpenYolo credential. * * @param credential an OpenYolo credential */ public void setFieldsFromCredential(Credential credential) { copyIfNotNull(credential.getIdentifier(), mIdField); copyIfNotNull(credential.getPassword(), mPasswordField); copyIfNotNull(credential.getDisplayName(), mDisplayNameField); copyIfNotNull(credential.getDisplayPicture(), mProfilePictureField); copyIfNotNull(credential.getAuthenticationMethod(), mAuthenticationMethodField); } /** * Populates the fragment's fields from a given OpenYOLO hint. */ public void setFieldsFromHint(Hint hint) { copyIfNotNull(hint.getIdentifier(), mIdField); copyIfNotNull(hint.getGeneratedPassword(), mPasswordField); copyIfNotNull(hint.getDisplayName(), mDisplayNameField); copyIfNotNull(hint.getDisplayPicture(), mProfilePictureField); copyIfNotNull(hint.getAuthenticationMethod(), mAuthenticationMethodField); } /** * Create an OpenYolo credential from the current fragment's fields. * * @return an OpenYolo Credential . */ @Nullable public Credential makeCredentialFromFields() { String authMethodStr = mAuthenticationMethodField.getText().toString(); AuthenticationMethod authMethod; try { authMethod = new AuthenticationMethod(authMethodStr); } catch (RequireViolation ex) { Log.w(TAG, "User entered authentication method " + authMethodStr + " is invalid", ex); return null; } AuthenticationDomain authenticationDomain = AuthenticationDomain.getSelfAuthDomain(getContext()); Credential.Builder credentialBuilder = new Credential.Builder( mIdField.getText().toString(), authMethod, authenticationDomain) .setDisplayName(convertEmptyToNull(mDisplayNameField.getText().toString())) .setDisplayPicture(convertEmptyToNull(mProfilePictureField.getText().toString())); credentialBuilder.setPassword(mPasswordField.getText().toString()); return credentialBuilder.build(); } private static String convertEmptyToNull(@NonNull String str) { if (str.isEmpty()) { return null; } return str; } private static void copyIfNotNull(@Nullable Object value, @NonNull EditText field) { if (value != null) { field.setText(value.toString()); } } }
Don't attempt to load unusable profile image URIs (#134) This was causing a red herring stack trace.
testapp/java/org/openyolo/testapp/CredentialView.java
Don't attempt to load unusable profile image URIs (#134)
<ide><path>estapp/java/org/openyolo/testapp/CredentialView.java <ide> import android.support.annotation.Nullable; <ide> import android.util.AttributeSet; <ide> import android.util.Log; <add>import android.util.Patterns; <ide> import android.view.View; <ide> import android.widget.EditText; <ide> import android.widget.ImageButton; <ide> <ide> @OnTextChanged(R.id.profile_picture_field) <ide> void loadProfilePicture() { <del> GlideApp.with(getContext()) <del> .load(Uri.parse(mProfilePictureField.getText().toString())) <del> .fitCenter() <del> .into(mProfilePictureView); <add> String profilePictureUri = mProfilePictureField.getText().toString(); <add> <add> if (profilePictureUri.trim().isEmpty() <add> || !Patterns.WEB_URL.matcher(profilePictureUri).matches()) { <add> mProfilePictureView.setImageDrawable(null); <add> } else { <add> GlideApp.with(getContext()) <add> .load(Uri.parse(profilePictureUri)) <add> .fitCenter() <add> .into(mProfilePictureView); <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
error: pathspec 'behaviour-detector/src/test/java/au/gov/amsa/geo/adhoc/AdHocMain.java' did not match any file(s) known to git
87e218226ccd5894d4da8ea7f79a0a943cb7839b
1
amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky
package au.gov.amsa.geo.adhoc; import java.io.File; import au.gov.amsa.ais.message.AisAidToNavigation; import au.gov.amsa.ais.rx.Streams; public class AdHocMain { public static void main(String[] args) { Streams.extract(Streams.nmeaFrom(new File("/media/an/temp/2015-11-12.txt"))) // .filter(m -> m.getMessage().isPresent()) // .filter(m -> m.getMessage().get().message().getMessageId() == 21) // // .map(m -> (AisShipStatic) m.getMessage().get().message()) // .map(m -> (AisAidToNavigation) m.getMessage().get().message()) // .filter(m -> String.valueOf(m.getMmsi()).startsWith("999")) // .distinct(m -> m.getMmsi()) // .filter(m -> m.getMmsi() == 553111494) // .doOnNext(System.out::println).subscribe(); } private static boolean isAton(String mmsi) { return mmsi.startsWith("99"); } }
behaviour-detector/src/test/java/au/gov/amsa/geo/adhoc/AdHocMain.java
add AdHocMain
behaviour-detector/src/test/java/au/gov/amsa/geo/adhoc/AdHocMain.java
add AdHocMain
<ide><path>ehaviour-detector/src/test/java/au/gov/amsa/geo/adhoc/AdHocMain.java <add>package au.gov.amsa.geo.adhoc; <add> <add>import java.io.File; <add> <add>import au.gov.amsa.ais.message.AisAidToNavigation; <add>import au.gov.amsa.ais.rx.Streams; <add> <add>public class AdHocMain { <add> public static void main(String[] args) { <add> Streams.extract(Streams.nmeaFrom(new File("/media/an/temp/2015-11-12.txt"))) <add> // <add> .filter(m -> m.getMessage().isPresent()) <add> // <add> .filter(m -> m.getMessage().get().message().getMessageId() == 21) <add> // <add> // .map(m -> (AisShipStatic) m.getMessage().get().message()) <add> <add> // <add> .map(m -> (AisAidToNavigation) m.getMessage().get().message()) <add> // <add> .filter(m -> String.valueOf(m.getMmsi()).startsWith("999")) <add> // .distinct(m -> m.getMmsi()) <add> // .filter(m -> m.getMmsi() == 553111494) <add> // <add> .doOnNext(System.out::println).subscribe(); <add> } <add> <add> private static boolean isAton(String mmsi) { <add> return mmsi.startsWith("99"); <add> } <add>}
Java
unlicense
acb187f858cbc0207765ad9c0d4ad5a52180fcaa
0
binkley/binkley
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.util; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; /** * {@code Lists} has methods on {@code java.util.List}. * * @author <a href="mailto:[email protected]">B. K. Oxley (binkley)</a> */ public final class Lists { /** * Partitions the given <var>list</var> into <var>n</var> buckets as evenly as possible. Buckets * are contiguous sublists of <var>list</var>. * * @param list the list to partition, never missing * @param n the bucket count, always positive * @param <T> the list item type * * @return the list of buckets, never missing */ @Nonnull public static <T> List<List<T>> partition(@Nonnull final List<T> list, final int n) { if (1 > n) throw new IllegalArgumentException("Non-positive bucket count: " + n); final int size = list.size(); final int div = size / n; final int mod = size % n; int start = 0; final List<List<T>> buckets = new ArrayList<>(n); for (int i = 0; i < mod; ++i) { final int end = start + div + 1; buckets.add(list.subList(start, end)); start = end; } for (int i = mod; i < n; ++i) { final int end = start + div; buckets.add(list.subList(start, end)); start = end; } return buckets; } private Lists() { } }
util/src/main/java/hm/binkley/util/Lists.java
/* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/>. */ package hm.binkley.util; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; /** * {@code Lists} has methods on {@code java.util.List}l * * @author <a href="mailto:[email protected]">B. K. Oxley (binkley)</a> */ public final class Lists { /** * Partitions the given <var>list</var> into <var>n</var> buckets as evenly as possible. Buckets * are contiguous sublists of <var>list</var>. * * @param list the list to partition, never missing * @param n the bucket count, always positive * @param <T> the list item type * * @return the list of buckets, never missing */ @Nonnull public static <T> List<List<T>> partition(@Nonnull final List<T> list, final int n) { if (1 > n) throw new IllegalArgumentException("Non-positive bucket count: " + n); final int size = list.size(); final int div = size / n; final int mod = size % n; int start = 0; final List<List<T>> buckets = new ArrayList<>(n); for (int i = 0; i < mod; ++i) { final int end = start + div + 1; buckets.add(list.subList(start, end)); start = end; } for (int i = mod; i < n; ++i) { final int end = start + div; buckets.add(list.subList(start, end)); start = end; } return buckets; } private Lists() { } }
Fix doc typo.
util/src/main/java/hm/binkley/util/Lists.java
Fix doc typo.
<ide><path>til/src/main/java/hm/binkley/util/Lists.java <ide> import java.util.List; <ide> <ide> /** <del> * {@code Lists} has methods on {@code java.util.List}l <add> * {@code Lists} has methods on {@code java.util.List}. <ide> * <ide> * @author <a href="mailto:[email protected]">B. K. Oxley (binkley)</a> <ide> */
Java
apache-2.0
17172bfca37dbc8cef0e40aad428280d94415885
0
allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.data.index; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.EmptyConsumer; import com.intellij.util.Processor; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.EmptyIntHashSet; import com.intellij.util.indexing.StorageException; import com.intellij.util.io.*; import com.intellij.vcs.log.*; import com.intellij.vcs.log.data.*; import com.intellij.vcs.log.impl.FatalErrorHandler; import com.intellij.vcs.log.impl.HeavyAwareExecutor; import com.intellij.vcs.log.impl.VcsIndexableDetails; import com.intellij.vcs.log.ui.filter.VcsLogTextFilterImpl; import com.intellij.vcs.log.util.PersistentSet; import com.intellij.vcs.log.util.PersistentSetImpl; import com.intellij.vcs.log.util.StopWatch; import com.intellij.vcs.log.util.TroveUtil; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; import static com.intellij.vcs.log.data.index.VcsLogFullDetailsIndex.INDEX; import static com.intellij.vcs.log.util.PersistentUtil.*; public class VcsLogPersistentIndex implements VcsLogIndex, Disposable { private static final Logger LOG = Logger.getInstance(VcsLogPersistentIndex.class); private static final int VERSION = 3; @NotNull private final Project myProject; @NotNull private final FatalErrorHandler myFatalErrorsConsumer; @NotNull private final VcsLogProgress myProgress; @NotNull private final Map<VirtualFile, VcsLogProvider> myProviders; @NotNull private final VcsLogStorage myStorage; @NotNull private final VcsUserRegistryImpl myUserRegistry; @NotNull private final Set<VirtualFile> myRoots; @NotNull private final VcsLogBigRepositoriesList myBigRepositoriesList; @Nullable private final IndexStorage myIndexStorage; @Nullable private final IndexDataGetter myDataGetter; @NotNull private final SingleTaskController<IndexingRequest, Void> mySingleTaskController; @NotNull private final Map<VirtualFile, AtomicInteger> myNumberOfTasks = ContainerUtil.newHashMap(); @NotNull private final Map<VirtualFile, AtomicLong> myIndexingTime = ContainerUtil.newHashMap(); @NotNull private final Map<VirtualFile, AtomicInteger> myIndexingLimit = ContainerUtil.newHashMap(); @NotNull private final List<IndexingFinishedListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private Map<VirtualFile, TIntHashSet> myCommitsToIndex = ContainerUtil.newHashMap(); public VcsLogPersistentIndex(@NotNull Project project, @NotNull VcsLogStorage storage, @NotNull VcsLogProgress progress, @NotNull Map<VirtualFile, VcsLogProvider> providers, @NotNull FatalErrorHandler fatalErrorsConsumer, @NotNull Disposable disposableParent) { myStorage = storage; myProject = project; myProgress = progress; myProviders = providers; myFatalErrorsConsumer = fatalErrorsConsumer; myRoots = ContainerUtil.newLinkedHashSet(); myBigRepositoriesList = VcsLogBigRepositoriesList.getInstance(); for (Map.Entry<VirtualFile, VcsLogProvider> entry : providers.entrySet()) { if (VcsLogProperties.get(entry.getValue(), VcsLogProperties.SUPPORTS_INDEXING)) { myRoots.add(entry.getKey()); } } myUserRegistry = (VcsUserRegistryImpl)ServiceManager.getService(myProject, VcsUserRegistry.class); myIndexStorage = createIndexStorage(fatalErrorsConsumer, calcLogId(myProject, providers)); if (myIndexStorage != null) { myDataGetter = new IndexDataGetter(myProject, myRoots, myIndexStorage, myStorage, myFatalErrorsConsumer); } else { myDataGetter = null; } for (VirtualFile root : myRoots) { myNumberOfTasks.put(root, new AtomicInteger()); myIndexingTime.put(root, new AtomicLong()); myIndexingLimit.put(root, new AtomicInteger(getIndexingLimit())); } mySingleTaskController = new MySingleTaskController(project, myIndexStorage != null ? myIndexStorage : this); Disposer.register(disposableParent, this); } private static int getIndexingLimit() { return Registry.intValue("vcs.log.index.limit.minutes"); } protected IndexStorage createIndexStorage(@NotNull FatalErrorHandler fatalErrorHandler, @NotNull String logId) { try { return IOUtil.openCleanOrResetBroken(() -> new IndexStorage(logId, myUserRegistry, myRoots, fatalErrorHandler, this), () -> IndexStorage.cleanup(logId)); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return null; } public static int getVersion() { return VcsLogStorageImpl.VERSION + VERSION; } @Override public synchronized void scheduleIndex(boolean full) { if (Disposer.isDisposed(this)) return; if (myCommitsToIndex.isEmpty() || myIndexStorage == null) return; // for fresh index, wait for complete log to load and index everything in one command if (myIndexStorage.isFresh() && !full) return; Map<VirtualFile, TIntHashSet> commitsToIndex = myCommitsToIndex; for (VirtualFile root : commitsToIndex.keySet()) { myNumberOfTasks.get(root).incrementAndGet(); } myCommitsToIndex = ContainerUtil.newHashMap(); boolean isFull = full && myIndexStorage.isFresh(); if (isFull) LOG.debug("Index storage for project " + myProject.getName() + " is fresh, scheduling full reindex"); for (VirtualFile root : commitsToIndex.keySet()) { TIntHashSet commits = commitsToIndex.get(root); if (commits.isEmpty()) continue; if (myBigRepositoriesList.isBig(root)) { myCommitsToIndex.put(root, commits); // put commits back in order to be able to reindex LOG.info("Indexing repository " + root.getName() + " is skipped since it is too big"); continue; } mySingleTaskController.request(new IndexingRequest(root, commits, isFull, false)); } if (isFull) myIndexStorage.unmarkFresh(); } private void storeDetail(@NotNull VcsFullCommitDetails detail) { if (myIndexStorage == null) return; try { int index = myStorage.getCommitIndex(detail.getId(), detail.getRoot()); myIndexStorage.messages.put(index, detail.getFullMessage()); myIndexStorage.trigrams.update(index, detail); myIndexStorage.users.update(index, detail); myIndexStorage.paths.update(index, detail); myIndexStorage.parents.put(index, ContainerUtil.map(detail.getParents(), p -> myStorage.getCommitIndex(p, detail.getRoot()))); // we know the whole graph without timestamps now if (!(detail instanceof VcsIndexableDetails) || ((VcsIndexableDetails)detail).hasRenames()) { myIndexStorage.renames.put(index); } myIndexStorage.commits.put(index); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } } private void flush() { try { if (myIndexStorage != null) { myIndexStorage.messages.force(); myIndexStorage.trigrams.flush(); myIndexStorage.users.flush(); myIndexStorage.paths.flush(); myIndexStorage.parents.force(); myIndexStorage.renames.flush(); myIndexStorage.commits.flush(); } } catch (StorageException e) { myFatalErrorsConsumer.consume(this, e); } } public void markCorrupted() { if (myIndexStorage != null) myIndexStorage.commits.markCorrupted(); } @Override public boolean isIndexed(int commit) { try { return myIndexStorage == null || myIndexStorage.commits.contains(commit); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return false; } private boolean hasRenames(int commit) { try { return myIndexStorage == null || myIndexStorage.renames.contains(commit); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return false; } @Override public synchronized boolean isIndexed(@NotNull VirtualFile root) { return myRoots.contains(root) && !(myBigRepositoriesList.isBig(root)) && (!myCommitsToIndex.containsKey(root) && myNumberOfTasks.get(root).get() == 0); } @Override public synchronized void markForIndexing(int index, @NotNull VirtualFile root) { if (isIndexed(index) || !myRoots.contains(root)) return; TroveUtil.add(myCommitsToIndex, root, index); } @Override public synchronized void reindexWithRenames(int commit, @NotNull VirtualFile root) { LOG.assertTrue(myRoots.contains(root)); if (hasRenames(commit)) return; mySingleTaskController.request(new IndexingRequest(root, TroveUtil.singleton(commit), false, true)); } @NotNull private <T> TIntHashSet filter(@NotNull PersistentMap<Integer, T> map, @NotNull Condition<T> condition) { TIntHashSet result = new TIntHashSet(); if (myIndexStorage == null) return result; try { Processor<Integer> processor = integer -> { try { T value = map.get(integer); if (value != null) { if (condition.value(value)) { result.add(integer); } } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); return false; } return true; }; if (myIndexStorage.messages instanceof PersistentHashMap) { ((PersistentHashMap<Integer, T>)myIndexStorage.messages).processKeysWithExistingMapping(processor); } else { myIndexStorage.messages.processKeys(processor); } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return result; } @NotNull private TIntHashSet filterUsers(@NotNull Set<VcsUser> users) { if (myIndexStorage != null) { try { return myIndexStorage.users.getCommitsForUsers(users); } catch (IOException | StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } } return new TIntHashSet(); } @NotNull private TIntHashSet filterPaths(@NotNull Collection<FilePath> paths) { if (myIndexStorage != null) { try { return myIndexStorage.paths.getCommitsForPaths(paths); } catch (IOException | StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } } return new TIntHashSet(); } @NotNull public TIntHashSet filterMessages(@NotNull VcsLogTextFilter filter) { if (myIndexStorage != null) { try { if (!filter.isRegex()) { TIntHashSet commitsForSearch = myIndexStorage.trigrams.getCommitsForSubstring(filter.getText()); if (commitsForSearch != null) { TIntHashSet result = new TIntHashSet(); commitsForSearch.forEach(commit -> { try { String value = myIndexStorage.messages.get(commit); if (value != null) { if (VcsLogTextFilterImpl.matches(filter, value)) { result.add(commit); } } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); return false; } return true; }); return result; } } } catch (StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } return filter(myIndexStorage.messages, message -> VcsLogTextFilterImpl.matches(filter, message)); } return EmptyIntHashSet.INSTANCE; } private void processRuntimeException(@NotNull RuntimeException e) { if (e instanceof ProcessCanceledException) throw e; if (myIndexStorage != null) myIndexStorage.markCorrupted(); if (e.getCause() instanceof IOException || e.getCause() instanceof StorageException) { myFatalErrorsConsumer.consume(this, e); } else { throw new RuntimeException(e); } } @Override public boolean canFilter(@NotNull List<VcsLogDetailsFilter> filters) { if (filters.isEmpty() || myIndexStorage == null) return false; for (VcsLogDetailsFilter filter : filters) { if (filter instanceof VcsLogTextFilter || filter instanceof VcsLogUserFilter || filter instanceof VcsLogStructureFilter) { continue; } return false; } return true; } @Override @NotNull public Set<Integer> filter(@NotNull List<VcsLogDetailsFilter> detailsFilters) { VcsLogTextFilter textFilter = ContainerUtil.findInstance(detailsFilters, VcsLogTextFilter.class); VcsLogUserFilter userFilter = ContainerUtil.findInstance(detailsFilters, VcsLogUserFilter.class); VcsLogStructureFilter pathFilter = ContainerUtil.findInstance(detailsFilters, VcsLogStructureFilter.class); TIntHashSet filteredByMessage = null; if (textFilter != null) { filteredByMessage = filterMessages(textFilter); } TIntHashSet filteredByUser = null; if (userFilter != null) { Set<VcsUser> users = ContainerUtil.newHashSet(); for (VirtualFile root : myRoots) { users.addAll(userFilter.getUsers(root)); } filteredByUser = filterUsers(users); } TIntHashSet filteredByPath = null; if (pathFilter != null) { filteredByPath = filterPaths(pathFilter.getFiles()); } return TroveUtil.intersect(filteredByMessage, filteredByPath, filteredByUser); } @Nullable @Override public IndexDataGetter getDataGetter() { if (myIndexStorage == null) return null; return myDataGetter; } @Override public void addListener(@NotNull IndexingFinishedListener l) { myListeners.add(l); } @Override public void removeListener(@NotNull IndexingFinishedListener l) { myListeners.remove(l); } @Override public void dispose() { } static class IndexStorage implements Disposable { private static final String COMMITS = "commits"; private static final String MESSAGES = "messages"; private static final String PARENTS = "parents"; private static final String RENAMES = "renames"; private static final int MESSAGES_VERSION = 0; @NotNull public final PersistentSet<Integer> commits; @NotNull public final PersistentMap<Integer, String> messages; @NotNull public final PersistentMap<Integer, List<Integer>> parents; @NotNull public final PersistentSet<Integer> renames; @NotNull public final VcsLogMessagesTrigramIndex trigrams; @NotNull public final VcsLogUserIndex users; @NotNull public final VcsLogPathsIndex paths; private volatile boolean myIsFresh; public IndexStorage(@NotNull String logId, @NotNull VcsUserRegistryImpl userRegistry, @NotNull Set<VirtualFile> roots, @NotNull FatalErrorHandler fatalErrorHandler, @NotNull Disposable parentDisposable) throws IOException { Disposer.register(parentDisposable, this); try { int version = getVersion(); File commitsStorage = getStorageFile(INDEX, COMMITS, logId, version); myIsFresh = !commitsStorage.exists(); commits = new PersistentSetImpl<>(commitsStorage, EnumeratorIntegerDescriptor.INSTANCE, Page.PAGE_SIZE, null, version); Disposer.register(this, () -> catchAndWarn(commits::close)); File messagesStorage = getStorageFile(INDEX, MESSAGES, logId, VcsLogStorageImpl.VERSION + MESSAGES_VERSION); messages = new PersistentHashMap<>(messagesStorage, new IntInlineKeyDescriptor(), EnumeratorStringDescriptor.INSTANCE, Page.PAGE_SIZE); Disposer.register(this, () -> catchAndWarn(messages::close)); trigrams = new VcsLogMessagesTrigramIndex(logId, fatalErrorHandler, this); users = new VcsLogUserIndex(logId, userRegistry, fatalErrorHandler, this); paths = new VcsLogPathsIndex(logId, roots, fatalErrorHandler, this); File parentsStorage = getStorageFile(INDEX, PARENTS, logId, version); parents = new PersistentHashMap<>(parentsStorage, EnumeratorIntegerDescriptor.INSTANCE, new IntListDataExternalizer(), Page.PAGE_SIZE, version); Disposer.register(this, () -> catchAndWarn(parents::close)); File renamesStorage = getStorageFile(INDEX, RENAMES, logId, version); renames = new PersistentSetImpl<>(renamesStorage, EnumeratorIntegerDescriptor.INSTANCE, Page.PAGE_SIZE, null, version); Disposer.register(this, () -> catchAndWarn(renames::close)); } catch (Throwable t) { Disposer.dispose(this); throw t; } } void markCorrupted() { catchAndWarn(commits::markCorrupted); } private static void catchAndWarn(@NotNull ThrowableRunnable<IOException> runnable) { try { runnable.run(); } catch (IOException e) { LOG.warn(e); } } private static void cleanup(@NotNull String logId) { if (!cleanupStorageFiles(INDEX, logId)) { LOG.error("Could not clean up storage files in " + new File(LOG_CACHE, INDEX) + " starting with " + logId); } } public void unmarkFresh() { myIsFresh = false; } public boolean isFresh() { return myIsFresh; } @Override public void dispose() { } } private class MySingleTaskController extends SingleTaskController<IndexingRequest, Void> { private static final int LOW_PRIORITY = Thread.MIN_PRIORITY; @NotNull private final HeavyAwareExecutor myHeavyAwareExecutor; public MySingleTaskController(@NotNull Project project, @NotNull Disposable parent) { super(project, EmptyConsumer.getInstance(), false, parent); myHeavyAwareExecutor = new HeavyAwareExecutor(project, 50, 100, VcsLogPersistentIndex.this); } @NotNull @Override protected ProgressIndicator startNewBackgroundTask() { ProgressIndicator indicator = myProgress.createProgressIndicator(false); ApplicationManager.getApplication().invokeLater(() -> { Task.Backgroundable task = new Task.Backgroundable(VcsLogPersistentIndex.this.myProject, "Indexing Commit Data", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) { @Override public void run(@NotNull ProgressIndicator indicator) { int previousPriority = setMinimumPriority(); try { IndexingRequest request; while ((request = popRequest()) != null) { try { request.run(indicator); indicator.checkCanceled(); } catch (ProcessCanceledException reThrown) { throw reThrown; } catch (Throwable t) { LOG.error("Error while indexing", t); } } } finally { taskCompleted(null); resetPriority(previousPriority); } } }; myHeavyAwareExecutor.executeOutOfHeavyOrPowerSave(task, indicator); }); return indicator; } public void resetPriority(int previousPriority) { if (Thread.currentThread().getPriority() == LOW_PRIORITY) Thread.currentThread().setPriority(previousPriority); } public int setMinimumPriority() { int previousPriority = Thread.currentThread().getPriority(); try { Thread.currentThread().setPriority(LOW_PRIORITY); } catch (SecurityException e) { LOG.debug("Could not set indexing thread priority", e); } return previousPriority; } } private class IndexingRequest { private static final int BATCH_SIZE = 20000; private static final int FLUSHED_COMMITS_NUMBER = 15000; @NotNull private final VirtualFile myRoot; @NotNull private final TIntHashSet myCommits; private final boolean myFull; private final boolean myReindex; @NotNull private final AtomicInteger myNewIndexedCommits = new AtomicInteger(); @NotNull private final AtomicInteger myOldCommits = new AtomicInteger(); private volatile long myStartTime; public IndexingRequest(@NotNull VirtualFile root, @NotNull TIntHashSet commits, boolean full, boolean reindex) { myRoot = root; myCommits = commits; myFull = full; myReindex = reindex; LOG.assertTrue(!myFull || !myReindex); } public void run(@NotNull ProgressIndicator indicator) { if (myBigRepositoriesList.isBig(myRoot)) { LOG.info("Indexing repository " + myRoot.getName() + " is skipped since it is too big"); return; } indicator.setIndeterminate(false); indicator.setFraction(0); myStartTime = getCurrentTimeMillis(); LOG.debug("Indexing " + (myFull ? "full repository" : myCommits.size() + " commits") + " in " + myRoot.getName()); try { try { if (myFull) { indexAll(indicator); } else { IntStream commits = TroveUtil.stream(myCommits).filter(c -> { if (myReindex ? hasRenames(c) : isIndexed(c)) { myOldCommits.incrementAndGet(); return false; } return true; }); indexOneByOne(commits, indicator); } } catch (ProcessCanceledException e) { scheduleReindex(); throw e; } catch (VcsException e) { LOG.error(e); scheduleReindex(); } } finally { if (!myReindex) myNumberOfTasks.get(myRoot).decrementAndGet(); if (isIndexed(myRoot)) { myIndexingTime.get(myRoot).set(0); myListeners.forEach(listener -> listener.indexingFinished(myRoot)); } else { myIndexingTime.get(myRoot).updateAndGet(t -> t + (getCurrentTimeMillis() - myStartTime)); } report(); flush(); } } private long getCurrentTimeMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } private void report() { String formattedTime = StopWatch.formatTime(getCurrentTimeMillis() - myStartTime); if (myFull) { LOG.debug(formattedTime + " for indexing " + myNewIndexedCommits + " commits in " + myRoot.getName()); } else { int leftCommits = myCommits.size() - myNewIndexedCommits.get() - myOldCommits.get(); String leftCommitsMessage = (leftCommits > 0) ? ". " + leftCommits + " commits left" : ""; LOG.debug(formattedTime + " for indexing " + myNewIndexedCommits + " new commits out of " + myCommits.size() + " in " + myRoot.getName() + leftCommitsMessage); } } private void scheduleReindex() { LOG.debug("Schedule reindexing of " + (myCommits.size() - myNewIndexedCommits.get() - myOldCommits.get()) + " commits in " + myRoot.getName()); if (myReindex) { myCommits.forEach(value -> { reindexWithRenames(value, myRoot); return true; }); } else { myCommits.forEach(value -> { markForIndexing(value, myRoot); return true; }); scheduleIndex(false); } } private void indexOneByOne(@NotNull IntStream commits, @NotNull ProgressIndicator indicator) throws VcsException { // We pass hashes to VcsLogProvider#readFullDetails in batches // in order to avoid allocating too much memory for these hashes // a batch of 20k will occupy ~2.4Mb TroveUtil.processBatches(commits, BATCH_SIZE, batch -> { indicator.checkCanceled(); List<String> hashes = TroveUtil.map(batch, value -> myStorage.getCommitId(value).getHash().asString()); myProviders.get(myRoot).readFullDetails(myRoot, hashes, detail -> { storeDetail(detail); myNewIndexedCommits.incrementAndGet(); checkRunningTooLong(indicator); }, !myReindex); displayProgress(indicator); }); } public void indexAll(@NotNull ProgressIndicator indicator) throws VcsException { displayProgress(indicator); myProviders.get(myRoot).readAllFullDetails(myRoot, details -> { storeDetail(details); if (myNewIndexedCommits.incrementAndGet() % FLUSHED_COMMITS_NUMBER == 0) flush(); checkRunningTooLong(indicator); displayProgress(indicator); }); } private void checkRunningTooLong(@NotNull ProgressIndicator indicator) { long time = myIndexingTime.get(myRoot).get() + (getCurrentTimeMillis() - myStartTime); int limit = myIndexingLimit.get(myRoot).get(); if (time >= Math.max(limit, 1) * 60 * 1000 && !myBigRepositoriesList.isBig(myRoot)) { LOG.warn("Indexing " + myRoot.getName() + " was cancelled after " + StopWatch.formatTime(time)); myBigRepositoriesList.addRepository(myRoot); indicator.cancel(); showIndexingNotification(time); } } public void displayProgress(@NotNull ProgressIndicator indicator) { indicator.setFraction(((double)myNewIndexedCommits.get() + myOldCommits.get()) / myCommits.size()); } @Override public String toString() { return "IndexingRequest of " + myCommits.size() + " commits in " + myRoot.getName() + (myFull ? " (full)" : ""); } private void showIndexingNotification(long time) { Notification notification = VcsNotifier.createNotification(VcsNotifier.IMPORTANT_ERROR_NOTIFICATION, "Log Indexing for \"" + myRoot.getName() + "\" Stopped", "Indexing was taking too long (" + StopWatch.formatTime(time - time % 1000) + ")", NotificationType.WARNING, null); notification.addAction(NotificationAction.createSimple("Resume", () -> { if (myBigRepositoriesList.isBig(myRoot)) { LOG.info("Resuming indexing " + myRoot.getName()); myIndexingLimit.get(myRoot).updateAndGet(l -> l + getIndexingLimit()); myBigRepositoriesList.removeRepository(myRoot); scheduleIndex(false); } notification.expire(); })); // if our bg thread is cancelled, calling VcsNotifier.getInstance in it will throw PCE // so using invokeLater here ApplicationManager.getApplication().invokeLater(() -> VcsNotifier.getInstance(myProject).notify(notification)); } } }
platform/vcs-log/impl/src/com/intellij/vcs/log/data/index/VcsLogPersistentIndex.java
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.data.index; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.EmptyConsumer; import com.intellij.util.Processor; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.EmptyIntHashSet; import com.intellij.util.indexing.StorageException; import com.intellij.util.io.*; import com.intellij.vcs.log.*; import com.intellij.vcs.log.data.*; import com.intellij.vcs.log.impl.FatalErrorHandler; import com.intellij.vcs.log.impl.HeavyAwareExecutor; import com.intellij.vcs.log.impl.VcsIndexableDetails; import com.intellij.vcs.log.ui.filter.VcsLogTextFilterImpl; import com.intellij.vcs.log.util.PersistentSet; import com.intellij.vcs.log.util.PersistentSetImpl; import com.intellij.vcs.log.util.StopWatch; import com.intellij.vcs.log.util.TroveUtil; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; import static com.intellij.vcs.log.data.index.VcsLogFullDetailsIndex.INDEX; import static com.intellij.vcs.log.util.PersistentUtil.*; public class VcsLogPersistentIndex implements VcsLogIndex, Disposable { private static final Logger LOG = Logger.getInstance(VcsLogPersistentIndex.class); private static final int VERSION = 3; @NotNull private final Project myProject; @NotNull private final FatalErrorHandler myFatalErrorsConsumer; @NotNull private final VcsLogProgress myProgress; @NotNull private final Map<VirtualFile, VcsLogProvider> myProviders; @NotNull private final VcsLogStorage myStorage; @NotNull private final VcsUserRegistryImpl myUserRegistry; @NotNull private final Set<VirtualFile> myRoots; @NotNull private final VcsLogBigRepositoriesList myBigRepositoriesList; @Nullable private final IndexStorage myIndexStorage; @Nullable private final IndexDataGetter myDataGetter; @NotNull private final SingleTaskController<IndexingRequest, Void> mySingleTaskController; @NotNull private final Map<VirtualFile, AtomicInteger> myNumberOfTasks = ContainerUtil.newHashMap(); @NotNull private final Map<VirtualFile, AtomicLong> myIndexingTime = ContainerUtil.newHashMap(); @NotNull private final Map<VirtualFile, AtomicInteger> myIndexingLimit = ContainerUtil.newHashMap(); @NotNull private final List<IndexingFinishedListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); @NotNull private Map<VirtualFile, TIntHashSet> myCommitsToIndex = ContainerUtil.newHashMap(); public VcsLogPersistentIndex(@NotNull Project project, @NotNull VcsLogStorage storage, @NotNull VcsLogProgress progress, @NotNull Map<VirtualFile, VcsLogProvider> providers, @NotNull FatalErrorHandler fatalErrorsConsumer, @NotNull Disposable disposableParent) { myStorage = storage; myProject = project; myProgress = progress; myProviders = providers; myFatalErrorsConsumer = fatalErrorsConsumer; myRoots = ContainerUtil.newLinkedHashSet(); myBigRepositoriesList = VcsLogBigRepositoriesList.getInstance(); for (Map.Entry<VirtualFile, VcsLogProvider> entry : providers.entrySet()) { if (VcsLogProperties.get(entry.getValue(), VcsLogProperties.SUPPORTS_INDEXING)) { myRoots.add(entry.getKey()); } } myUserRegistry = (VcsUserRegistryImpl)ServiceManager.getService(myProject, VcsUserRegistry.class); myIndexStorage = createIndexStorage(fatalErrorsConsumer, calcLogId(myProject, providers)); if (myIndexStorage != null) { myDataGetter = new IndexDataGetter(myProject, myRoots, myIndexStorage, myStorage, myFatalErrorsConsumer); } else { myDataGetter = null; } for (VirtualFile root : myRoots) { myNumberOfTasks.put(root, new AtomicInteger()); myIndexingTime.put(root, new AtomicLong()); myIndexingLimit.put(root, new AtomicInteger(getIndexingLimit())); } mySingleTaskController = new MySingleTaskController(project, myIndexStorage != null ? myIndexStorage : this); Disposer.register(disposableParent, this); } private static int getIndexingLimit() { return Registry.intValue("vcs.log.index.limit.minutes"); } protected IndexStorage createIndexStorage(@NotNull FatalErrorHandler fatalErrorHandler, @NotNull String logId) { try { return IOUtil.openCleanOrResetBroken(() -> new IndexStorage(logId, myUserRegistry, myRoots, fatalErrorHandler, this), () -> IndexStorage.cleanup(logId)); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return null; } public static int getVersion() { return VcsLogStorageImpl.VERSION + VERSION; } @Override public synchronized void scheduleIndex(boolean full) { if (Disposer.isDisposed(this)) return; if (myCommitsToIndex.isEmpty() || myIndexStorage == null) return; // for fresh index, wait for complete log to load and index everything in one command if (myIndexStorage.isFresh() && !full) return; Map<VirtualFile, TIntHashSet> commitsToIndex = myCommitsToIndex; for (VirtualFile root : commitsToIndex.keySet()) { myNumberOfTasks.get(root).incrementAndGet(); } myCommitsToIndex = ContainerUtil.newHashMap(); boolean isFull = full && myIndexStorage.isFresh(); if (isFull) LOG.debug("Index storage for project " + myProject.getName() + " is fresh, scheduling full reindex"); for (VirtualFile root : commitsToIndex.keySet()) { TIntHashSet commits = commitsToIndex.get(root); if (commits.isEmpty()) continue; if (myBigRepositoriesList.isBig(root)) { myCommitsToIndex.put(root, commits); // put commits back in order to be able to reindex LOG.info("Indexing repository " + root.getName() + " is skipped since it is too big"); continue; } mySingleTaskController.request(new IndexingRequest(root, commits, isFull, false)); } if (isFull) myIndexStorage.unmarkFresh(); } private void storeDetail(@NotNull VcsFullCommitDetails detail) { if (myIndexStorage == null) return; try { int index = myStorage.getCommitIndex(detail.getId(), detail.getRoot()); myIndexStorage.messages.put(index, detail.getFullMessage()); myIndexStorage.trigrams.update(index, detail); myIndexStorage.users.update(index, detail); myIndexStorage.paths.update(index, detail); myIndexStorage.parents.put(index, ContainerUtil.map(detail.getParents(), p -> myStorage.getCommitIndex(p, detail.getRoot()))); // we know the whole graph without timestamps now if (!(detail instanceof VcsIndexableDetails) || ((VcsIndexableDetails)detail).hasRenames()) { myIndexStorage.renames.put(index); } myIndexStorage.commits.put(index); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } } private void flush() { try { if (myIndexStorage != null) { myIndexStorage.messages.force(); myIndexStorage.trigrams.flush(); myIndexStorage.users.flush(); myIndexStorage.paths.flush(); myIndexStorage.parents.force(); myIndexStorage.renames.flush(); myIndexStorage.commits.flush(); } } catch (StorageException e) { myFatalErrorsConsumer.consume(this, e); } } public void markCorrupted() { if (myIndexStorage != null) myIndexStorage.commits.markCorrupted(); } @Override public boolean isIndexed(int commit) { try { return myIndexStorage == null || myIndexStorage.commits.contains(commit); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return false; } private boolean hasRenames(int commit) { try { return myIndexStorage == null || myIndexStorage.renames.contains(commit); } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return false; } @Override public synchronized boolean isIndexed(@NotNull VirtualFile root) { return myRoots.contains(root) && !(myBigRepositoriesList.isBig(root)) && (!myCommitsToIndex.containsKey(root) && myNumberOfTasks.get(root).get() == 0); } @Override public synchronized void markForIndexing(int index, @NotNull VirtualFile root) { if (isIndexed(index) || !myRoots.contains(root)) return; TroveUtil.add(myCommitsToIndex, root, index); } @Override public synchronized void reindexWithRenames(int commit, @NotNull VirtualFile root) { LOG.assertTrue(myRoots.contains(root)); if (hasRenames(commit)) return; mySingleTaskController.request(new IndexingRequest(root, TroveUtil.singleton(commit), false, true)); } @NotNull private <T> TIntHashSet filter(@NotNull PersistentMap<Integer, T> map, @NotNull Condition<T> condition) { TIntHashSet result = new TIntHashSet(); if (myIndexStorage == null) return result; try { Processor<Integer> processor = integer -> { try { T value = map.get(integer); if (value != null) { if (condition.value(value)) { result.add(integer); } } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); return false; } return true; }; if (myIndexStorage.messages instanceof PersistentHashMap) { ((PersistentHashMap<Integer, T>)myIndexStorage.messages).processKeysWithExistingMapping(processor); } else { myIndexStorage.messages.processKeys(processor); } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); } return result; } @NotNull private TIntHashSet filterUsers(@NotNull Set<VcsUser> users) { if (myIndexStorage != null) { try { return myIndexStorage.users.getCommitsForUsers(users); } catch (IOException | StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } } return new TIntHashSet(); } @NotNull private TIntHashSet filterPaths(@NotNull Collection<FilePath> paths) { if (myIndexStorage != null) { try { return myIndexStorage.paths.getCommitsForPaths(paths); } catch (IOException | StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } } return new TIntHashSet(); } @NotNull public TIntHashSet filterMessages(@NotNull VcsLogTextFilter filter) { if (myIndexStorage != null) { try { if (!filter.isRegex()) { TIntHashSet commitsForSearch = myIndexStorage.trigrams.getCommitsForSubstring(filter.getText()); if (commitsForSearch != null) { TIntHashSet result = new TIntHashSet(); commitsForSearch.forEach(commit -> { try { String value = myIndexStorage.messages.get(commit); if (value != null) { if (VcsLogTextFilterImpl.matches(filter, value)) { result.add(commit); } } } catch (IOException e) { myFatalErrorsConsumer.consume(this, e); return false; } return true; }); return result; } } } catch (StorageException e) { myFatalErrorsConsumer.consume(this, e); } catch (RuntimeException e) { processRuntimeException(e); } return filter(myIndexStorage.messages, message -> VcsLogTextFilterImpl.matches(filter, message)); } return EmptyIntHashSet.INSTANCE; } private void processRuntimeException(@NotNull RuntimeException e) { if (e instanceof ProcessCanceledException) throw e; if (myIndexStorage != null) myIndexStorage.markCorrupted(); if (e.getCause() instanceof IOException || e.getCause() instanceof StorageException) { myFatalErrorsConsumer.consume(this, e); } else { throw new RuntimeException(e); } } @Override public boolean canFilter(@NotNull List<VcsLogDetailsFilter> filters) { if (filters.isEmpty() || myIndexStorage == null) return false; for (VcsLogDetailsFilter filter : filters) { if (filter instanceof VcsLogTextFilter || filter instanceof VcsLogUserFilter || filter instanceof VcsLogStructureFilter) { continue; } return false; } return true; } @Override @NotNull public Set<Integer> filter(@NotNull List<VcsLogDetailsFilter> detailsFilters) { VcsLogTextFilter textFilter = ContainerUtil.findInstance(detailsFilters, VcsLogTextFilter.class); VcsLogUserFilter userFilter = ContainerUtil.findInstance(detailsFilters, VcsLogUserFilter.class); VcsLogStructureFilter pathFilter = ContainerUtil.findInstance(detailsFilters, VcsLogStructureFilter.class); TIntHashSet filteredByMessage = null; if (textFilter != null) { filteredByMessage = filterMessages(textFilter); } TIntHashSet filteredByUser = null; if (userFilter != null) { Set<VcsUser> users = ContainerUtil.newHashSet(); for (VirtualFile root : myRoots) { users.addAll(userFilter.getUsers(root)); } filteredByUser = filterUsers(users); } TIntHashSet filteredByPath = null; if (pathFilter != null) { filteredByPath = filterPaths(pathFilter.getFiles()); } return TroveUtil.intersect(filteredByMessage, filteredByPath, filteredByUser); } @Nullable @Override public IndexDataGetter getDataGetter() { if (myIndexStorage == null) return null; return myDataGetter; } @Override public void addListener(@NotNull IndexingFinishedListener l) { myListeners.add(l); } @Override public void removeListener(@NotNull IndexingFinishedListener l) { myListeners.remove(l); } @Override public void dispose() { } static class IndexStorage implements Disposable { private static final String COMMITS = "commits"; private static final String MESSAGES = "messages"; private static final String PARENTS = "parents"; private static final String RENAMES = "renames"; private static final int MESSAGES_VERSION = 0; @NotNull public final PersistentSet<Integer> commits; @NotNull public final PersistentMap<Integer, String> messages; @NotNull public final PersistentMap<Integer, List<Integer>> parents; @NotNull public final PersistentSet<Integer> renames; @NotNull public final VcsLogMessagesTrigramIndex trigrams; @NotNull public final VcsLogUserIndex users; @NotNull public final VcsLogPathsIndex paths; private volatile boolean myIsFresh; public IndexStorage(@NotNull String logId, @NotNull VcsUserRegistryImpl userRegistry, @NotNull Set<VirtualFile> roots, @NotNull FatalErrorHandler fatalErrorHandler, @NotNull Disposable parentDisposable) throws IOException { Disposer.register(parentDisposable, this); try { int version = getVersion(); File commitsStorage = getStorageFile(INDEX, COMMITS, logId, version); myIsFresh = !commitsStorage.exists(); commits = new PersistentSetImpl<>(commitsStorage, EnumeratorIntegerDescriptor.INSTANCE, Page.PAGE_SIZE, null, version); Disposer.register(this, () -> catchAndWarn(commits::close)); File messagesStorage = getStorageFile(INDEX, MESSAGES, logId, VcsLogStorageImpl.VERSION + MESSAGES_VERSION); messages = new PersistentHashMap<>(messagesStorage, new IntInlineKeyDescriptor(), EnumeratorStringDescriptor.INSTANCE, Page.PAGE_SIZE); Disposer.register(this, () -> catchAndWarn(messages::close)); trigrams = new VcsLogMessagesTrigramIndex(logId, fatalErrorHandler, this); users = new VcsLogUserIndex(logId, userRegistry, fatalErrorHandler, this); paths = new VcsLogPathsIndex(logId, roots, fatalErrorHandler, this); File parentsStorage = getStorageFile(INDEX, PARENTS, logId, version); parents = new PersistentHashMap<>(parentsStorage, EnumeratorIntegerDescriptor.INSTANCE, new IntListDataExternalizer(), Page.PAGE_SIZE, version); Disposer.register(this, () -> catchAndWarn(parents::close)); File renamesStorage = getStorageFile(INDEX, RENAMES, logId, version); renames = new PersistentSetImpl<>(renamesStorage, EnumeratorIntegerDescriptor.INSTANCE, Page.PAGE_SIZE, null, version); Disposer.register(this, () -> catchAndWarn(renames::close)); } catch (Throwable t) { Disposer.dispose(this); throw t; } } void markCorrupted() { catchAndWarn(commits::markCorrupted); } private static void catchAndWarn(@NotNull ThrowableRunnable<IOException> runnable) { try { runnable.run(); } catch (IOException e) { LOG.warn(e); } } private static void cleanup(@NotNull String logId) { if (!cleanupStorageFiles(INDEX, logId)) { LOG.error("Could not clean up storage files in " + new File(LOG_CACHE, INDEX) + " starting with " + logId); } } public void unmarkFresh() { myIsFresh = false; } public boolean isFresh() { return myIsFresh; } @Override public void dispose() { } } private class MySingleTaskController extends SingleTaskController<IndexingRequest, Void> { private static final int LOW_PRIORITY = Thread.MIN_PRIORITY; @NotNull private final HeavyAwareExecutor myHeavyAwareExecutor; public MySingleTaskController(@NotNull Project project, @NotNull Disposable parent) { super(project, EmptyConsumer.getInstance(), false, parent); myHeavyAwareExecutor = new HeavyAwareExecutor(project, 50, 100, VcsLogPersistentIndex.this); } @NotNull @Override protected ProgressIndicator startNewBackgroundTask() { ProgressIndicator indicator = myProgress.createProgressIndicator(false); ApplicationManager.getApplication().invokeLater(() -> { Task.Backgroundable task = new Task.Backgroundable(VcsLogPersistentIndex.this.myProject, "Indexing Commit Data", true, PerformInBackgroundOption.ALWAYS_BACKGROUND) { @Override public void run(@NotNull ProgressIndicator indicator) { int previousPriority = setMinimumPriority(); try { IndexingRequest request; while ((request = popRequest()) != null) { try { request.run(indicator); indicator.checkCanceled(); } catch (ProcessCanceledException reThrown) { throw reThrown; } catch (Throwable t) { LOG.error("Error while indexing", t); } } } finally { taskCompleted(null); resetPriority(previousPriority); } } }; myHeavyAwareExecutor.executeOutOfHeavyOrPowerSave(task, indicator); }); return indicator; } public void resetPriority(int previousPriority) { if (Thread.currentThread().getPriority() == LOW_PRIORITY) Thread.currentThread().setPriority(previousPriority); } public int setMinimumPriority() { int previousPriority = Thread.currentThread().getPriority(); try { Thread.currentThread().setPriority(LOW_PRIORITY); } catch (SecurityException e) { LOG.debug("Could not set indexing thread priority", e); } return previousPriority; } } private class IndexingRequest { private static final int BATCH_SIZE = 20000; private static final int FLUSHED_COMMITS_NUMBER = 15000; @NotNull private final VirtualFile myRoot; @NotNull private final TIntHashSet myCommits; private final boolean myFull; private final boolean myReindex; @NotNull private final AtomicInteger myNewIndexedCommits = new AtomicInteger(); @NotNull private final AtomicInteger myOldCommits = new AtomicInteger(); private volatile long myStartTime; public IndexingRequest(@NotNull VirtualFile root, @NotNull TIntHashSet commits, boolean full, boolean reindex) { myRoot = root; myCommits = commits; myFull = full; myReindex = reindex; LOG.assertTrue(!myFull || !myReindex); } public void run(@NotNull ProgressIndicator indicator) { if (myBigRepositoriesList.isBig(myRoot)) { LOG.info("Indexing repository " + myRoot.getName() + " is skipped since it is too big"); return; } indicator.setIndeterminate(false); indicator.setFraction(0); myStartTime = getCurrentTimeMillis(); LOG.debug("Indexing " + (myFull ? "full repository" : myCommits.size() + " commits") + " in " + myRoot.getName()); try { try { if (myFull) { indexAll(indicator); } else { IntStream commits = TroveUtil.stream(myCommits).filter(c -> { if (myReindex ? hasRenames(c) : isIndexed(c)) { myOldCommits.incrementAndGet(); return false; } return true; }); indexOneByOne(commits, indicator); } } catch (ProcessCanceledException e) { scheduleReindex(); throw e; } catch (VcsException e) { LOG.error(e); scheduleReindex(); } } finally { if (!myReindex) myNumberOfTasks.get(myRoot).decrementAndGet(); if (isIndexed(myRoot)) { myIndexingTime.get(myRoot).set(0); myListeners.forEach(listener -> listener.indexingFinished(myRoot)); } else { myIndexingTime.get(myRoot).updateAndGet(t -> t + (getCurrentTimeMillis() - myStartTime)); } report(); flush(); } } private long getCurrentTimeMillis() { return TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); } private void report() { String formattedTime = StopWatch.formatTime(getCurrentTimeMillis() - myStartTime); if (myFull) { LOG.debug(formattedTime + " for indexing " + myNewIndexedCommits + " commits in " + myRoot.getName()); } else { int leftCommits = myCommits.size() - myNewIndexedCommits.get() - myOldCommits.get(); String leftCommitsMessage = (leftCommits > 0) ? ". " + leftCommits + " commits left" : ""; LOG.debug(formattedTime + " for indexing " + myNewIndexedCommits + " new commits out of " + myCommits.size() + " in " + myRoot.getName() + leftCommitsMessage); } } private void scheduleReindex() { LOG.debug("Schedule reindexing of " + (myCommits.size() - myNewIndexedCommits.get() - myOldCommits.get()) + " commits in " + myRoot.getName()); if (myReindex) { myCommits.forEach(value -> { reindexWithRenames(value, myRoot); return true; }); } else { myCommits.forEach(value -> { markForIndexing(value, myRoot); return true; }); scheduleIndex(false); } } private void indexOneByOne(@NotNull IntStream commits, @NotNull ProgressIndicator indicator) throws VcsException { // We pass hashes to VcsLogProvider#readFullDetails in batches // in order to avoid allocating too much memory for these hashes // a batch of 20k will occupy ~2.4Mb TroveUtil.processBatches(commits, BATCH_SIZE, batch -> { indicator.checkCanceled(); List<String> hashes = TroveUtil.map(batch, value -> myStorage.getCommitId(value).getHash().asString()); myProviders.get(myRoot).readFullDetails(myRoot, hashes, detail -> { storeDetail(detail); myNewIndexedCommits.incrementAndGet(); checkRunningTooLong(indicator); }, !myReindex); displayProgress(indicator); }); } public void indexAll(@NotNull ProgressIndicator indicator) throws VcsException { displayProgress(indicator); myProviders.get(myRoot).readAllFullDetails(myRoot, details -> { storeDetail(details); if (myNewIndexedCommits.incrementAndGet() % FLUSHED_COMMITS_NUMBER == 0) flush(); checkRunningTooLong(indicator); displayProgress(indicator); }); } private void checkRunningTooLong(@NotNull ProgressIndicator indicator) { long time = myIndexingTime.get(myRoot).get() + (getCurrentTimeMillis() - myStartTime); int limit = myIndexingLimit.get(myRoot).get(); if (time >= Math.max(limit, 1) * 60 * 1000 && !myBigRepositoriesList.isBig(myRoot)) { LOG.warn("Indexing " + myRoot.getName() + " was cancelled after " + StopWatch.formatTime(time)); myBigRepositoriesList.addRepository(myRoot); indicator.cancel(); showIndexingNotification(time); } } public void displayProgress(@NotNull ProgressIndicator indicator) { indicator.setFraction(((double)myNewIndexedCommits.get() + myOldCommits.get()) / myCommits.size()); } @Override public String toString() { return "IndexingRequest of " + myCommits.size() + " commits in " + myRoot.getName() + (myFull ? " (full)" : ""); } private void showIndexingNotification(long time) { Notification notification = VcsNotifier.createNotification(VcsNotifier.IMPORTANT_ERROR_NOTIFICATION, "Log Indexing for \"" + myRoot.getName() + "\" Stopped", "Indexing was taking too long (" + StopWatch.formatTime(time - time % 1000) + ")", NotificationType.WARNING, null); notification.addAction(NotificationAction.createSimple("Resume", () -> { if (myBigRepositoriesList.isBig(myRoot)) { LOG.info("Resuming indexing " + myRoot.getName()); myIndexingLimit.get(myRoot).updateAndGet(l -> l + getIndexingLimit()); myBigRepositoriesList.removeRepository(myRoot); scheduleIndex(false); } notification.expire(); })); // if out bg thread is cancelled, calling VcsNotifier.getInstance in it will throw PCE // so using invokeLater here ApplicationManager.getApplication().invokeLater(() -> VcsNotifier.getInstance(myProject).notify(notification)); } } }
[vcs-log] fix typo
platform/vcs-log/impl/src/com/intellij/vcs/log/data/index/VcsLogPersistentIndex.java
[vcs-log] fix typo
<ide><path>latform/vcs-log/impl/src/com/intellij/vcs/log/data/index/VcsLogPersistentIndex.java <ide> } <ide> notification.expire(); <ide> })); <del> // if out bg thread is cancelled, calling VcsNotifier.getInstance in it will throw PCE <add> // if our bg thread is cancelled, calling VcsNotifier.getInstance in it will throw PCE <ide> // so using invokeLater here <ide> ApplicationManager.getApplication().invokeLater(() -> VcsNotifier.getInstance(myProject).notify(notification)); <ide> }
Java
apache-2.0
cf5e01a20b3ffb242c667cc0915f544026821275
0
Jonathan727/javarosa,Jonathan727/javarosa,Jonathan727/javarosa
package org.javarosa.services.transport.impl; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import org.javarosa.services.transport.api.TransportMessage; import de.enough.polish.io.RmsStorage; /** * A TransportMessageStore is necessary since not all attempts to send succeed. * * Every message given to the TransportService is persisted immediately, but * distinctions are made when querying the TransportMessageStore based on the * message status (i.e. the number of "cached" messages is not equal to the * number of messages in the store, but the number of messages in the store with * the status CACHED) * */ public class TransportMessageStore { /** * These constants are used to identify objects in persistent storage * * Q_STORENAME - the queue of messages to be sent RECENTLY_SENT_STORENAME - * messages recently sent QID_STORENAME - storage for the message id counter * */ private static final String Q_STORENAME = "JavaROSATransQ"; private static final String QID_STORENAME = "JavaROSATransQId"; private static final String RECENTLY_SENT_STORENAME = "JavaROSATransQSent"; private static final int RECENTLY_SENT_STORE_MAXSIZE = 15; /** * The persistent store - it is partitioned into three corresponding to the * three constants above */ private RmsStorage storage = new RmsStorage(); /** * We cache the size (in terms of numbers of records) of each of the * persistent store partitions */ private Hashtable cachedCounts = new Hashtable(); /** * @param testing */ public TransportMessageStore() { updateCachedCounts(); } /** * @return */ public int getCachedMessagesSize() { Integer size = (Integer) this.cachedCounts.get(Integer .toString(TransportMessageStatus.CACHED)); return size.intValue(); } /** * @return A Vector of TransportMessages waiting to be sent */ public Vector getCachedMessages() { Vector messages = readAll(Q_STORENAME); Vector cached = new Vector(); for (int i = 0; i < messages.size(); i++) { TransportMessage message = (TransportMessage) messages.elementAt(i); cached.addElement(message); } return messages; } /** * @return A Vector of TransportMessages recently sent */ public Vector getRecentlySentMessages() { return readAll(RECENTLY_SENT_STORENAME); } public void clearCache() { try { storage.delete(Q_STORENAME); storage.save(new Vector(),Q_STORENAME); } catch (IOException e) { throw new RuntimeException("Problem clearing the cache of TransportMessages."); } } /** * * Add a new message to the send queue * * @param message * @throws IOException */ public String enqueue(TransportMessage message) throws TransportException { //First ensure that the provided message is not already in the queue; if (message.getCacheId() != null && this.findMessage(message.getCacheId()) != null) { String id = this.getNextCacheIdentifier(); Vector records = readAll(Q_STORENAME); message.setCacheId(id); records.addElement(message); saveAll(records, Q_STORENAME); return id; } else { return message.getCacheId(); } } /** * * Remove a message from the send queue * * * @param success * @throws IOException */ public void dequeue(TransportMessage message) throws TransportException { Vector records = readAll(Q_STORENAME); TransportMessage m = find(message.getCacheId(), records); if (m == null) { throw new IllegalArgumentException("No queued message with id=" + message.getCacheId()); } records.removeElement(m); saveAll(records, Q_STORENAME); // if we're dequeuing a successfully sent message // then transfer it to the recently sent list if (message.getStatus() == TransportMessageStatus.COMPLETED) { Vector recentlySent = readAll(RECENTLY_SENT_STORENAME); if (recentlySent == null) { recentlySent = new Vector(); } // ensure that the recently sent store doesn't grow indefinitely // by limiting its size if (recentlySent.size() == RECENTLY_SENT_STORE_MAXSIZE) { recentlySent.removeElementAt(0); } recentlySent.addElement(message); saveAll(recentlySent, RECENTLY_SENT_STORENAME); } } /** * * * Given a vector of messages, find the message with the given id * * * @param id * @param records * @return */ private TransportMessage find(String id, Vector records) { for (int i = 0; i < records.size(); i++) { TransportMessage message = (TransportMessage) records.elementAt(i); if (message.getCacheId().equals(id)) return message; } return null; } /** * Given an id, look in the send queue and the recently sent queue, * returning the message if it is found (null otherwise) * * If the message is in the transport queue, then the success parameter will * be false (and if found in the recentlySent queue, it will be set to true) * * * @param id A string id corresponding to the record to be retrieved. May * be null. * @return */ public TransportMessage findMessage(String id) { Vector records = readAll(Q_STORENAME); for (int i = 0; i < records.size(); i++) { TransportMessage message = (TransportMessage) records.elementAt(i); if (message.getCacheId().equals(id)) return message; } Vector sentRecords = readAll(RECENTLY_SENT_STORENAME); for (int i = 0; i < sentRecords.size(); i++) { TransportMessage message = (TransportMessage) sentRecords .elementAt(i); if (message.getCacheId().equals(id)) return message; } return null; } /** * * Get the next available queue identifier to assign to a newly queued * message * * * @return * @throws IOException */ private String getNextCacheIdentifier() throws TransportException { // get the most recently used id Vector v = readAll(QID_STORENAME); if ((v == null) || (v.size() == 0)) { // null means there wasn't one, so create, save and return one Integer i = new Integer(1); v = new Vector(); v.addElement(i); saveAll(v, QID_STORENAME); return i.toString(); } else { Integer i = (Integer) v.firstElement(); // increment the count to create a new one, save it and return it Integer newI = new Integer(i.intValue() + 1); v.removeAllElements(); v.addElement(newI); saveAll(v, QID_STORENAME); return newI.toString(); } } /** * @param store * @return */ public Vector readAll(String store) { Vector records = new Vector(); try { records = (Vector) storage.read(store); } catch (IOException e) { // storage doesn't yet exist (according to Polish) } return records; } /** * @param records * @param c * @throws IOException */ private void saveAll(Vector records, String store) throws TransportException { try { this.storage.delete(store); } catch (IOException e) { // storage didn't exist (according to Polish) } try { this.storage.save(records, store); } catch (IOException e) { throw new TransportException(e); } updateCachedCounts(); } /** * */ private void updateCachedCounts() { int cached = 0; // cache the counts first Vector messages = readAll(Q_STORENAME); for (int i = 0; i < messages.size(); i++) { TransportMessage message = (TransportMessage) messages.elementAt(i); if (message.getStatus() == TransportMessageStatus.COMPLETED) throw new RuntimeException("Sent message in the queue"); cached++; } this.cachedCounts.put(Integer.toString(TransportMessageStatus.CACHED), new Integer(cached)); // sent messages in another store int recentlySentSize = readAll(RECENTLY_SENT_STORENAME).size(); this.cachedCounts.put(Integer .toString(TransportMessageStatus.COMPLETED), new Integer( recentlySentSize)); } }
javarosa-transport/transport2/main/src/org/javarosa/services/transport/impl/TransportMessageStore.java
package org.javarosa.services.transport.impl; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; import org.javarosa.services.transport.api.TransportMessage; import de.enough.polish.io.RmsStorage; /** * A TransportMessageStore is necessary since not all attempts to send succeed. * * Every message given to the TransportService is persisted immediately, but * distinctions are made when querying the TransportMessageStore based on the * message status (i.e. the number of "cached" messages is not equal to the * number of messages in the store, but the number of messages in the store with * the status CACHED) * */ public class TransportMessageStore { /** * These constants are used to identify objects in persistent storage * * Q_STORENAME - the queue of messages to be sent RECENTLY_SENT_STORENAME - * messages recently sent QID_STORENAME - storage for the message id counter * */ private static final String Q_STORENAME = "JavaROSATransQ"; private static final String QID_STORENAME = "JavaROSATransQId"; private static final String RECENTLY_SENT_STORENAME = "JavaROSATransQSent"; private static final int RECENTLY_SENT_STORE_MAXSIZE = 15; /** * The persistent store - it is partitioned into three corresponding to the * three constants above */ private RmsStorage storage = new RmsStorage(); /** * We cache the size (in terms of numbers of records) of each of the * persistent store partitions */ private Hashtable cachedCounts = new Hashtable(); /** * @param testing */ public TransportMessageStore() { updateCachedCounts(); } /** * @return */ public int getCachedMessagesSize() { Integer size = (Integer) this.cachedCounts.get(Integer .toString(TransportMessageStatus.CACHED)); return size.intValue(); } /** * @return A Vector of TransportMessages waiting to be sent */ public Vector getCachedMessages() { Vector messages = readAll(Q_STORENAME); Vector cached = new Vector(); for (int i = 0; i < messages.size(); i++) { TransportMessage message = (TransportMessage) messages.elementAt(i); cached.addElement(message); } return messages; } /** * @return A Vector of TransportMessages recently sent */ public Vector getRecentlySentMessages() { return readAll(RECENTLY_SENT_STORENAME); } /** * * Add a new message to the send queue * * @param message * @throws IOException */ public String enqueue(TransportMessage message) throws TransportException { String id = this.getNextCacheIdentifier(); Vector records = readAll(Q_STORENAME); message.setCacheId(id); records.addElement(message); saveAll(records, Q_STORENAME); return id; } /** * * Remove a message from the send queue * * * @param success * @throws IOException */ public void dequeue(TransportMessage message) throws TransportException { Vector records = readAll(Q_STORENAME); TransportMessage m = find(message.getCacheId(), records); if (m == null) { throw new IllegalArgumentException("No queued message with id=" + message.getCacheId()); } records.removeElement(m); saveAll(records, Q_STORENAME); // if we're dequeuing a successfully sent message // then transfer it to the recently sent list if (message.getStatus() == TransportMessageStatus.COMPLETED) { Vector recentlySent = readAll(RECENTLY_SENT_STORENAME); if (recentlySent == null) { recentlySent = new Vector(); } // ensure that the recently sent store doesn't grow indefinitely // by limiting its size if (recentlySent.size() == RECENTLY_SENT_STORE_MAXSIZE) { recentlySent.removeElementAt(0); } recentlySent.addElement(message); saveAll(recentlySent, RECENTLY_SENT_STORENAME); } } /** * * * Given a vector of messages, find the message with the given id * * * @param id * @param records * @return */ private TransportMessage find(String id, Vector records) { for (int i = 0; i < records.size(); i++) { TransportMessage message = (TransportMessage) records.elementAt(i); if (message.getCacheId().equals(id)) return message; } return null; } /** * Given an id, look in the send queue and the recently sent queue, * returning the message if it is found (null otherwise) * * If the message is in the transport queue, then the success parameter will * be false (and if found in the recentlySent queue, it will be set to true) * * * @param id * @return */ public TransportMessage findMessage(String id) { Vector records = readAll(Q_STORENAME); for (int i = 0; i < records.size(); i++) { TransportMessage message = (TransportMessage) records.elementAt(i); if (message.getCacheId().equals(id)) return message; } Vector sentRecords = readAll(RECENTLY_SENT_STORENAME); for (int i = 0; i < sentRecords.size(); i++) { TransportMessage message = (TransportMessage) sentRecords .elementAt(i); if (message.getCacheId().equals(id)) return message; } return null; } /** * * Get the next available queue identifier to assign to a newly queued * message * * * @return * @throws IOException */ private String getNextCacheIdentifier() throws TransportException { // get the most recently used id Vector v = readAll(QID_STORENAME); if ((v == null) || (v.size() == 0)) { // null means there wasn't one, so create, save and return one Integer i = new Integer(1); v = new Vector(); v.addElement(i); saveAll(v, QID_STORENAME); return i.toString(); } else { Integer i = (Integer) v.firstElement(); // increment the count to create a new one, save it and return it Integer newI = new Integer(i.intValue() + 1); v.removeAllElements(); v.addElement(newI); saveAll(v, QID_STORENAME); return newI.toString(); } } /** * @param store * @return */ public Vector readAll(String store) { Vector records = new Vector(); try { records = (Vector) storage.read(store); } catch (IOException e) { // storage doesn't yet exist (according to Polish) } return records; } /** * @param records * @param c * @throws IOException */ private void saveAll(Vector records, String store) throws TransportException { try { this.storage.delete(store); } catch (IOException e) { // storage didn't exist (according to Polish) } try { this.storage.save(records, store); } catch (IOException e) { throw new TransportException(e); } updateCachedCounts(); } /** * */ private void updateCachedCounts() { int cached = 0; // cache the counts first Vector messages = readAll(Q_STORENAME); for (int i = 0; i < messages.size(); i++) { TransportMessage message = (TransportMessage) messages.elementAt(i); if (message.getStatus() == TransportMessageStatus.COMPLETED) throw new RuntimeException("Sent message in the queue"); cached++; } this.cachedCounts.put(Integer.toString(TransportMessageStatus.CACHED), new Integer(cached)); // sent messages in another store int recentlySentSize = readAll(RECENTLY_SENT_STORENAME).size(); this.cachedCounts.put(Integer .toString(TransportMessageStatus.COMPLETED), new Integer( recentlySentSize)); } }
following merge
javarosa-transport/transport2/main/src/org/javarosa/services/transport/impl/TransportMessageStore.java
following merge
<ide><path>avarosa-transport/transport2/main/src/org/javarosa/services/transport/impl/TransportMessageStore.java <ide> public Vector getRecentlySentMessages() { <ide> return readAll(RECENTLY_SENT_STORENAME); <ide> } <add> <add> public void clearCache() { <add> try { <add> storage.delete(Q_STORENAME); <add> storage.save(new Vector(),Q_STORENAME); <add> } catch (IOException e) { <add> throw new RuntimeException("Problem clearing the cache of TransportMessages."); <add> } <add> } <ide> <ide> /** <ide> * <ide> * @throws IOException <ide> */ <ide> public String enqueue(TransportMessage message) throws TransportException { <del> String id = this.getNextCacheIdentifier(); <del> Vector records = readAll(Q_STORENAME); <del> message.setCacheId(id); <del> records.addElement(message); <del> saveAll(records, Q_STORENAME); <del> return id; <add> //First ensure that the provided message is not already in the queue; <add> if (message.getCacheId() != null && this.findMessage(message.getCacheId()) != null) { <add> String id = this.getNextCacheIdentifier(); <add> Vector records = readAll(Q_STORENAME); <add> message.setCacheId(id); <add> records.addElement(message); <add> saveAll(records, Q_STORENAME); <add> return id; <add> } else { <add> return message.getCacheId(); <add> } <ide> } <ide> <ide> /** <ide> * be false (and if found in the recentlySent queue, it will be set to true) <ide> * <ide> * <del> * @param id <add> * @param id A string id corresponding to the record to be retrieved. May <add> * be null. <ide> * @return <ide> */ <ide> public TransportMessage findMessage(String id) {
Java
mit
67880e5534a8398e934ac9f89b8cb35b5a433b24
0
AgriCraft/AgriCraft,HenryLoenwind/AgriCraft,InfinityRaider/AgriCraft,CodesCubesAndCrashes/AgriCraft,HenryLoenwind/AgriCraft
package com.InfinityRaider.AgriCraft.items; import com.InfinityRaider.AgriCraft.blocks.BlockCrop; import com.InfinityRaider.AgriCraft.creativetab.AgriCraftTab; import com.InfinityRaider.AgriCraft.reference.Names; import com.InfinityRaider.AgriCraft.tileentity.TileEntityCrop; import com.InfinityRaider.AgriCraft.utility.LogHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import java.util.List; public class ItemTrowel extends ModItem { private IIcon[] icons = new IIcon[2]; public ItemTrowel() { super(); this.setCreativeTab(AgriCraftTab.agriCraftTab); this.maxStackSize=1; } //I'm overriding this just to be sure @Override public boolean canItemEditBlocks() {return true;} //this is called when you right click with this item in hand @Override public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { if(!world.isRemote) { if (world.getBlock(x, y, z) != null && world.getBlock(x, y, z) instanceof BlockCrop) { TileEntity te = world.getTileEntity(x, y, z); if (te != null && te instanceof TileEntityCrop) { TileEntityCrop crop = (TileEntityCrop) te; //clear weed if (crop.weed) { crop.clearWeed(); } //put plant on trowel else if (crop.hasPlant() && stack.getItemDamage() == 0) { //put plant on trowel NBTTagCompound tag = new NBTTagCompound(); tag.setShort(Names.NBT.growth, (short) crop.growth); tag.setShort(Names.NBT.gain, (short) crop.gain); tag.setShort(Names.NBT.strength, (short) crop.strength); tag.setBoolean(Names.NBT.analyzed, crop.analyzed); tag.setString(Names.Objects.seed, crop.getSeedString()); tag.setShort(Names.NBT.meta, (short) crop.seedMeta); tag.setShort(Names.NBT.materialMeta, (short) world.getBlockMetadata(x, y, z)); stack.setTagCompound(tag); stack.setItemDamage(1); //clear crop crop.growth = 0; crop.gain = 0; crop.strength = 0; crop.analyzed = false; crop.seed = null; crop.seedMeta = 0; crop.markDirty(); world.setBlockMetadataWithNotify(x, y, z, 0, 3); //return true to avoid further processing return true; } //plant crop from trowel else if (!crop.hasPlant() && !crop.crossCrop && stack.getItemDamage() == 1) { //set crop NBTTagCompound tag = stack.getTagCompound(); crop.growth = tag.getShort(Names.NBT.growth); crop.gain = tag.getShort(Names.NBT.gain); crop.strength = tag.getShort(Names.NBT.strength); crop.analyzed = tag.getBoolean(Names.NBT.analyzed); crop.setSeed(tag.getString(Names.Objects.seed)); crop.seedMeta = tag.getShort(Names.NBT.meta); world.setBlockMetadataWithNotify(x, y, z, tag.getShort(Names.NBT.materialMeta), 3); crop.markDirty(); //clear trowel stack.setTagCompound(null); stack.setItemDamage(0); //return true to avoid further processing return true; } } } } return false; //return false or else no other use methods will be called (for instance "onBlockActivated" on the crops block) } @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean flag) { if(stack.getItemDamage()==0) { list.add(StatCollector.translateToLocal("agricraft_tooltip.trowel")); } else if(stack.hasTagCompound() && stack.stackTagCompound.hasKey(Names.Objects.seed) && stack.stackTagCompound.hasKey(Names.NBT.meta)) { NBTTagCompound tag = stack.getTagCompound(); ItemStack seed = new ItemStack((Item) Item.itemRegistry.getObject(tag.getString(Names.Objects.seed)), 1, tag.getShort(Names.NBT.meta)); list.add(StatCollector.translateToLocal("agricraft_tooltip.seed")+": "+ seed.getItem().getItemStackDisplayName(seed)); } } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister reg) { LogHelper.debug("registering icon for: " + this.getUnlocalizedName()); icons[0] = reg.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf('.')+1)+"_empty"); icons[1] = reg.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf('.')+1)+"_full"); } @Override @SideOnly(Side.CLIENT) public IIcon getIconFromDamage(int meta) { if(meta<=1) { return this.icons[meta]; } return null; } }
src/main/java/com/InfinityRaider/AgriCraft/items/ItemTrowel.java
package com.InfinityRaider.AgriCraft.items; import com.InfinityRaider.AgriCraft.blocks.BlockCrop; import com.InfinityRaider.AgriCraft.creativetab.AgriCraftTab; import com.InfinityRaider.AgriCraft.reference.Names; import com.InfinityRaider.AgriCraft.tileentity.TileEntityCrop; import com.InfinityRaider.AgriCraft.utility.LogHelper; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import java.util.List; public class ItemTrowel extends ModItem { private IIcon[] icons = new IIcon[2]; public ItemTrowel() { super(); this.setCreativeTab(AgriCraftTab.agriCraftTab); this.maxStackSize=1; } //I'm overriding this just to be sure @Override public boolean canItemEditBlocks() {return true;} //this is called when you right click with this item in hand @Override public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { if(world.getBlock(x, y, z)!=null && world.getBlock(x, y, z) instanceof BlockCrop) { TileEntity te = world.getTileEntity(x, y, z); if(te!=null && te instanceof TileEntityCrop) { TileEntityCrop crop = (TileEntityCrop) te; //clear weed if(crop.weed) { crop.clearWeed(); } //put plant on trowel else if(crop.hasPlant() && stack.getItemDamage()==0) { //put plant on trowel NBTTagCompound tag = new NBTTagCompound(); tag.setShort(Names.NBT.growth, (short) crop.growth); tag.setShort(Names.NBT.gain, (short) crop.gain); tag.setShort(Names.NBT.strength, (short) crop.strength); tag.setBoolean(Names.NBT.analyzed, crop.analyzed); tag.setString(Names.Objects.seed, crop.getSeedString()); tag.setShort(Names.NBT.meta, (short) crop.seedMeta); tag.setShort(Names.NBT.materialMeta, (short) world.getBlockMetadata(x, y, z)); stack.setTagCompound(tag); stack.setItemDamage(1); //clear crop crop.growth=0; crop.gain=0; crop.strength=0; crop.analyzed=false; crop.seed=null; crop.seedMeta=0; crop.markDirty(); world.setBlockMetadataWithNotify(x, y, z, 0, 3); //return true to avoid further processing return true; } //plant crop from trowel else if(!crop.hasPlant() && !crop.crossCrop && stack.getItemDamage()==1) { //set crop NBTTagCompound tag = stack.getTagCompound(); crop.growth = tag.getShort(Names.NBT.growth); crop.gain = tag.getShort(Names.NBT.gain); crop.strength = tag.getShort(Names.NBT.strength); crop.analyzed = tag.getBoolean(Names.NBT.analyzed); crop.setSeed(tag.getString(Names.Objects.seed)); crop.seedMeta = tag.getShort(Names.NBT.meta); world.setBlockMetadataWithNotify(x, y, z, tag.getShort(Names.NBT.materialMeta), 3); crop.markDirty(); //clear trowel stack.setTagCompound(null); stack.setItemDamage(0); //return true to avoid further processing return true; } } } return false; //return false or else no other use methods will be called (for instance "onBlockActivated" on the crops block) } @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean flag) { if(stack.getItemDamage()==0) { list.add(StatCollector.translateToLocal("agricraft_tooltip.trowel")); } else if(stack.hasTagCompound() && stack.stackTagCompound.hasKey(Names.Objects.seed) && stack.stackTagCompound.hasKey(Names.NBT.meta)) { NBTTagCompound tag = stack.getTagCompound(); ItemStack seed = new ItemStack((Item) Item.itemRegistry.getObject(tag.getString(Names.Objects.seed)), 1, tag.getShort(Names.NBT.meta)); list.add(StatCollector.translateToLocal("agricraft_tooltip.seed")+": "+ seed.getItem().getItemStackDisplayName(seed)); } } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister reg) { LogHelper.debug("registering icon for: " + this.getUnlocalizedName()); icons[0] = reg.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf('.')+1)+"_empty"); icons[1] = reg.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf('.')+1)+"_full"); } @Override @SideOnly(Side.CLIENT) public IIcon getIconFromDamage(int meta) { if(meta<=1) { return this.icons[meta]; } return null; } }
Trowel bug
src/main/java/com/InfinityRaider/AgriCraft/items/ItemTrowel.java
Trowel bug
<ide><path>rc/main/java/com/InfinityRaider/AgriCraft/items/ItemTrowel.java <ide> //this is called when you right click with this item in hand <ide> @Override <ide> public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { <del> if(world.getBlock(x, y, z)!=null && world.getBlock(x, y, z) instanceof BlockCrop) { <del> TileEntity te = world.getTileEntity(x, y, z); <del> if(te!=null && te instanceof TileEntityCrop) { <del> TileEntityCrop crop = (TileEntityCrop) te; <del> //clear weed <del> if(crop.weed) { <del> crop.clearWeed(); <del> } <del> //put plant on trowel <del> else if(crop.hasPlant() && stack.getItemDamage()==0) { <add> if(!world.isRemote) { <add> if (world.getBlock(x, y, z) != null && world.getBlock(x, y, z) instanceof BlockCrop) { <add> TileEntity te = world.getTileEntity(x, y, z); <add> if (te != null && te instanceof TileEntityCrop) { <add> TileEntityCrop crop = (TileEntityCrop) te; <add> //clear weed <add> if (crop.weed) { <add> crop.clearWeed(); <add> } <ide> //put plant on trowel <del> NBTTagCompound tag = new NBTTagCompound(); <del> tag.setShort(Names.NBT.growth, (short) crop.growth); <del> tag.setShort(Names.NBT.gain, (short) crop.gain); <del> tag.setShort(Names.NBT.strength, (short) crop.strength); <del> tag.setBoolean(Names.NBT.analyzed, crop.analyzed); <del> tag.setString(Names.Objects.seed, crop.getSeedString()); <del> tag.setShort(Names.NBT.meta, (short) crop.seedMeta); <del> tag.setShort(Names.NBT.materialMeta, (short) world.getBlockMetadata(x, y, z)); <del> stack.setTagCompound(tag); <del> stack.setItemDamage(1); <del> //clear crop <del> crop.growth=0; <del> crop.gain=0; <del> crop.strength=0; <del> crop.analyzed=false; <del> crop.seed=null; <del> crop.seedMeta=0; <del> crop.markDirty(); <del> world.setBlockMetadataWithNotify(x, y, z, 0, 3); <del> //return true to avoid further processing <del> return true; <del> } <del> //plant crop from trowel <del> else if(!crop.hasPlant() && !crop.crossCrop && stack.getItemDamage()==1) { <del> //set crop <del> NBTTagCompound tag = stack.getTagCompound(); <del> crop.growth = tag.getShort(Names.NBT.growth); <del> crop.gain = tag.getShort(Names.NBT.gain); <del> crop.strength = tag.getShort(Names.NBT.strength); <del> crop.analyzed = tag.getBoolean(Names.NBT.analyzed); <del> crop.setSeed(tag.getString(Names.Objects.seed)); <del> crop.seedMeta = tag.getShort(Names.NBT.meta); <del> world.setBlockMetadataWithNotify(x, y, z, tag.getShort(Names.NBT.materialMeta), 3); <del> crop.markDirty(); <del> //clear trowel <del> stack.setTagCompound(null); <del> stack.setItemDamage(0); <del> //return true to avoid further processing <del> return true; <add> else if (crop.hasPlant() && stack.getItemDamage() == 0) { <add> //put plant on trowel <add> NBTTagCompound tag = new NBTTagCompound(); <add> tag.setShort(Names.NBT.growth, (short) crop.growth); <add> tag.setShort(Names.NBT.gain, (short) crop.gain); <add> tag.setShort(Names.NBT.strength, (short) crop.strength); <add> tag.setBoolean(Names.NBT.analyzed, crop.analyzed); <add> tag.setString(Names.Objects.seed, crop.getSeedString()); <add> tag.setShort(Names.NBT.meta, (short) crop.seedMeta); <add> tag.setShort(Names.NBT.materialMeta, (short) world.getBlockMetadata(x, y, z)); <add> stack.setTagCompound(tag); <add> stack.setItemDamage(1); <add> //clear crop <add> crop.growth = 0; <add> crop.gain = 0; <add> crop.strength = 0; <add> crop.analyzed = false; <add> crop.seed = null; <add> crop.seedMeta = 0; <add> crop.markDirty(); <add> world.setBlockMetadataWithNotify(x, y, z, 0, 3); <add> //return true to avoid further processing <add> return true; <add> } <add> //plant crop from trowel <add> else if (!crop.hasPlant() && !crop.crossCrop && stack.getItemDamage() == 1) { <add> //set crop <add> NBTTagCompound tag = stack.getTagCompound(); <add> crop.growth = tag.getShort(Names.NBT.growth); <add> crop.gain = tag.getShort(Names.NBT.gain); <add> crop.strength = tag.getShort(Names.NBT.strength); <add> crop.analyzed = tag.getBoolean(Names.NBT.analyzed); <add> crop.setSeed(tag.getString(Names.Objects.seed)); <add> crop.seedMeta = tag.getShort(Names.NBT.meta); <add> world.setBlockMetadataWithNotify(x, y, z, tag.getShort(Names.NBT.materialMeta), 3); <add> crop.markDirty(); <add> //clear trowel <add> stack.setTagCompound(null); <add> stack.setItemDamage(0); <add> //return true to avoid further processing <add> return true; <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
fbec3bb55c99f48729970f4ca854105a8a606d18
0
BasinMC/minecraft-maven-plugin
/* * Copyright 2016 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.maven.plugins.minecraft.patch; import com.google.common.io.ByteStreams; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.basinmc.maven.plugins.minecraft.AbstractMappingMojo; import org.basinmc.maven.plugins.minecraft.access.AccessTransformationMap; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.jboss.forge.roaster.Roaster; import org.jboss.forge.roaster.model.JavaType; import org.jboss.forge.roaster.model.source.FieldHolderSource; import org.jboss.forge.roaster.model.source.FieldSource; import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.MethodHolderSource; import org.jboss.forge.roaster.model.source.MethodSource; import org.jboss.forge.roaster.model.source.VisibilityScopedSource; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.annotation.Nonnull; /** * Provides a Mojo which initializes the local git repository with its respective contents. * * @author <a href="mailto:[email protected]">Johannes Donath</a> */ @Mojo( name = "initialize-repository", requiresProject = false, threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_SOURCES ) public class InitializeRepositoryMojo extends AbstractMappingMojo { private static final String ROOT_COMMIT_AUTHOR_NAME = "Basin"; private static final String ROOT_COMMIT_AUTHOR_EMAIL = "[email protected]"; /** * Applies access transformations to a parsed type and all of its nested members. * * TODO: Add support for inheritance to reduce the size of AT configs. */ @SuppressWarnings("unchecked") private void applyAccessTransformation(@Nonnull AccessTransformationMap transformationMap, @Nonnull JavaType classSource) { this.getLog().info("Applying access transformations to " + classSource.getQualifiedName()); transformationMap.getTypeMappings(classSource.getQualifiedName()).ifPresent((t) -> { if (classSource instanceof VisibilityScopedSource) { t.getVisibility().ifPresent(((VisibilityScopedSource) classSource)::setVisibility); } if (classSource instanceof FieldHolderSource) { ((List<FieldSource>) ((FieldHolderSource) classSource).getFields()).forEach((f) -> t.getFieldVisibility(f.getName()).ifPresent(f::setVisibility)); } if (classSource instanceof MethodHolderSource) { ((List<MethodSource>) ((MethodHolderSource) classSource).getMethods()).forEach((m) -> t.getMethodVisibility(m.getName()).ifPresent(m::setVisibility)); } ((List<JavaType>) classSource.getNestedClasses()).forEach((c) -> this.applyAccessTransformation(transformationMap, c)); }); } /** * {@inheritDoc} */ @Override public void execute() throws MojoExecutionException, MojoFailureException { this.verifyProperties("module", "gameVersion", "mappingVersion", "sourceDirectory"); this.getLog().info("Initializing repository at " + this.getSourceDirectory().getAbsolutePath()); try { if (Files.notExists(this.getSourceDirectory().toPath()) || Files.notExists(this.getSourceDirectory().toPath().resolve(".git"))) { this.initializeRepository(); } else { this.getLog().info("Skipping repository initialization - Cached"); } this.getProject().addCompileSourceRoot(this.getSourceDirectory().toString()); } catch (ArtifactResolutionException ex) { throw new MojoFailureException("Failed to resolve artifact: " + ex.getMessage(), ex); } } /** * Initializes the local repository with its default state. */ private void initializeRepository() throws ArtifactResolutionException, MojoFailureException { final Path sourceArtifact; { Artifact a = this.createArtifactWithClassifier(MINECRAFT_GROUP_ID, this.getModule(), this.getMappingArtifactVersion(), "source"); sourceArtifact = this.findArtifact(a).orElseThrow(() -> new MojoFailureException("Could not locate artifact " + this.getArtifactCoordinateString(a))); } try { Files.createDirectories(this.getSourceDirectory().toPath()); Git git = Git.init().setDirectory(this.getSourceDirectory()).call(); AccessTransformationMap transformationMap = null; if (this.getAccessTransformation() != null) { transformationMap = AccessTransformationMap.read(this.getAccessTransformation().toPath()); } try (ZipFile file = new ZipFile(sourceArtifact.toFile())) { Enumeration<? extends ZipEntry> enumeration = file.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = enumeration.nextElement(); String name = entry.getName(); if (!name.endsWith(".java")) { continue; } Path outputPath = this.getSourceDirectory().toPath().resolve(name); if (!Files.isDirectory(outputPath.getParent())) { Files.createDirectories(outputPath.getParent()); } try (InputStream inputStream = file.getInputStream(entry)) { try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { if (transformationMap != null) { if (transformationMap.getTypeMappings(name).isPresent()) { JavaClassSource classSource = Roaster.parse(JavaClassSource.class, inputStream); this.applyAccessTransformation(transformationMap, classSource); outputChannel.write(ByteBuffer.wrap(classSource.toString().getBytes(StandardCharsets.UTF_8))); } } else { try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { ByteStreams.copy(channel, outputChannel); } } } } git.add().addFilepattern(name).call(); } } git.commit() .setAuthor(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setCommitter(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setMessage("Added decompiled sources.") .call(); git.branchCreate() .setName("upstream") .call(); } catch (GitAPIException ex) { throw new MojoFailureException("Failed to execute Git command: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoFailureException("Failed to access source artifact or write target file: " + ex.getMessage(), ex); } } }
src/main/java/org/basinmc/maven/plugins/minecraft/patch/InitializeRepositoryMojo.java
/* * Copyright 2016 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.basinmc.maven.plugins.minecraft.patch; import com.google.common.io.ByteStreams; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.basinmc.maven.plugins.minecraft.AbstractMappingMojo; import org.basinmc.maven.plugins.minecraft.access.AccessTransformationMap; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.jboss.forge.roaster.Roaster; import org.jboss.forge.roaster.model.JavaType; import org.jboss.forge.roaster.model.source.FieldHolderSource; import org.jboss.forge.roaster.model.source.FieldSource; import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.MethodHolderSource; import org.jboss.forge.roaster.model.source.MethodSource; import org.jboss.forge.roaster.model.source.VisibilityScopedSource; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.annotation.Nonnull; /** * Provides a Mojo which initializes the local git repository with its respective contents. * * @author <a href="mailto:[email protected]">Johannes Donath</a> */ @Mojo( name = "initialize-repository", requiresProject = false, threadSafe = true, defaultPhase = LifecyclePhase.GENERATE_SOURCES ) public class InitializeRepositoryMojo extends AbstractMappingMojo { private static final String ROOT_COMMIT_AUTHOR_NAME = "Basin"; private static final String ROOT_COMMIT_AUTHOR_EMAIL = "[email protected]"; /** * Applies access transformations to a parsed type and all of its nested members. * * TODO: Add support for inheritance to reduce the size of AT configs. */ @SuppressWarnings("unchecked") private void applyAccessTransformation(@Nonnull AccessTransformationMap transformationMap, @Nonnull JavaType classSource) { this.getLog().info("Applying access transformations to " + classSource.getQualifiedName()); transformationMap.getTypeMappings(classSource.getQualifiedName()).ifPresent((t) -> { if (classSource instanceof VisibilityScopedSource) { t.getVisibility().ifPresent(((VisibilityScopedSource) classSource)::setVisibility); } if (classSource instanceof FieldHolderSource) { ((List<FieldSource>) ((FieldHolderSource) classSource).getFields()).forEach((f) -> t.getFieldVisibility(f.getName()).ifPresent(f::setVisibility)); } if (classSource instanceof MethodHolderSource) { ((List<MethodSource>) ((MethodHolderSource) classSource).getMethods()).forEach((m) -> t.getMethodVisibility(m.getName()).ifPresent(m::setVisibility)); } ((List<JavaType>) classSource.getNestedClasses()).forEach((c) -> this.applyAccessTransformation(transformationMap, c)); }); } /** * {@inheritDoc} */ @Override public void execute() throws MojoExecutionException, MojoFailureException { this.verifyProperties("module", "gameVersion", "mappingVersion", "sourceDirectory"); this.getLog().info("Initializing repository at " + this.getSourceDirectory().getAbsolutePath()); try { if (Files.notExists(this.getSourceDirectory().toPath()) || Files.notExists(this.getSourceDirectory().toPath().resolve(".git"))) { this.initializeRepository(); } else { this.getLog().info("Skipping repository initialization - Cached"); } this.getProject().addCompileSourceRoot(this.getSourceDirectory().toString()); } catch (ArtifactResolutionException ex) { throw new MojoFailureException("Failed to resolve artifact: " + ex.getMessage(), ex); } } /** * Initializes the local repository with its default state. */ private void initializeRepository() throws ArtifactResolutionException, MojoFailureException { final Path sourceArtifact; { Artifact a = this.createArtifactWithClassifier(MINECRAFT_GROUP_ID, this.getModule(), this.getMappingArtifactVersion(), "source"); sourceArtifact = this.findArtifact(a).orElseThrow(() -> new MojoFailureException("Could not locate artifact " + this.getArtifactCoordinateString(a))); } try { Files.createDirectories(this.getSourceDirectory().toPath()); Git git = Git.init().setDirectory(this.getSourceDirectory()).call(); AccessTransformationMap transformationMap = null; if (this.getAccessTransformation() != null) { transformationMap = AccessTransformationMap.read(this.getAccessTransformation().toPath()); } try (ZipFile file = new ZipFile(sourceArtifact.toFile())) { Enumeration<? extends ZipEntry> enumeration = file.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = enumeration.nextElement(); String name = entry.getName(); if (!name.endsWith(".java")) { continue; } Path outputPath = this.getSourceDirectory().toPath().resolve(name); if (!Files.isDirectory(outputPath.getParent())) { Files.createDirectories(outputPath.getParent()); } try (InputStream inputStream = file.getInputStream(entry)) { try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { if (transformationMap != null) { if (transformationMap.getTypeMappings(name).isPresent()) { JavaClassSource classSource = Roaster.parse(JavaClassSource.class, inputStream); this.applyAccessTransformation(transformationMap, classSource); outputChannel.write(ByteBuffer.wrap(classSource.toString().getBytes(StandardCharsets.UTF_8))); continue; } } try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { ByteStreams.copy(channel, outputChannel); } } } git.add().addFilepattern(name).call(); } } git.commit() .setAuthor(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setCommitter(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setMessage("Added decompiled sources.") .call(); git.branchCreate() .setName("upstream") .call(); } catch (GitAPIException ex) { throw new MojoFailureException("Failed to execute Git command: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoFailureException("Failed to access source artifact or write target file: " + ex.getMessage(), ex); } } }
Fixed an issue where access transformed types are not added to the repository.
src/main/java/org/basinmc/maven/plugins/minecraft/patch/InitializeRepositoryMojo.java
Fixed an issue where access transformed types are not added to the repository.
<ide><path>rc/main/java/org/basinmc/maven/plugins/minecraft/patch/InitializeRepositoryMojo.java <ide> JavaClassSource classSource = Roaster.parse(JavaClassSource.class, inputStream); <ide> this.applyAccessTransformation(transformationMap, classSource); <ide> outputChannel.write(ByteBuffer.wrap(classSource.toString().getBytes(StandardCharsets.UTF_8))); <del> <del> continue; <ide> } <del> } <del> <del> try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { <del> ByteStreams.copy(channel, outputChannel); <add> } else { <add> try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { <add> ByteStreams.copy(channel, outputChannel); <add> } <ide> } <ide> } <ide> }
Java
apache-2.0
ec045823f1917ecabbd3b456aa6ff1b38379e2cd
0
nosceon/titanite,nosceon/titanite,nosceon/titanite
package org.nosceon.titanite; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * @author Johan Siebens */ public final class HttpServer extends AbstractHttpServerBuilder<HttpServer> { private static final AtomicInteger COUNTER = new AtomicInteger(); private int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2; private int maxRequestSize = 1024 * 1024 * 10; public HttpServer() { } public HttpServer(int ioWorkerCount) { this.ioWorkerCount = ioWorkerCount; } public HttpServer(int ioWorkerCount, int maxRequestSize) { this.ioWorkerCount = ioWorkerCount; this.maxRequestSize = maxRequestSize; } public Shutdownable start(int port) { String id = Strings.padStart(String.valueOf(COUNTER.incrementAndGet()), 3, '0'); Titanite.LOG.info("Http Server [" + id + "] starting"); Router router = router(id); ViewRenderer renderer = new ViewRenderer(); ObjectMapper mapper = mapper(); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount, new NamedThreadFactory("Titanite HttpServer [" + id + "] - ")); newHttpServerBootstrap(eventLoopGroup, maxRequestSize, router, renderer, mapper).bind(port).syncUninterruptibly(); Titanite.LOG.info("Http Server [" + id + "] started, listening on port " + port); return eventLoopGroup::shutdownGracefully; } @Override protected HttpServer self() { return this; } private static class NamedThreadFactory implements ThreadFactory { private final AtomicLong counter = new AtomicLong(); private final String prefix; public NamedThreadFactory(String prefix) { this.prefix = prefix; } @Override public Thread newThread(Runnable r) { return new Thread(r, prefix + counter.incrementAndGet()); } } }
src/main/java/org/nosceon/titanite/HttpServer.java
package org.nosceon.titanite; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import java.util.concurrent.atomic.AtomicInteger; /** * @author Johan Siebens */ public final class HttpServer extends AbstractHttpServerBuilder<HttpServer> { private static final AtomicInteger COUNTER = new AtomicInteger(); private int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2; private int maxRequestSize = 1024 * 1024 * 10; public HttpServer() { } public HttpServer(int ioWorkerCount) { this.ioWorkerCount = ioWorkerCount; } public HttpServer(int ioWorkerCount, int maxRequestSize) { this.ioWorkerCount = ioWorkerCount; this.maxRequestSize = maxRequestSize; } public Shutdownable start(int port) { String id = Strings.padStart(String.valueOf(COUNTER.incrementAndGet()), 3, '0'); Titanite.LOG.info("Http Server [" + id + "] starting"); Router router = router(id); ViewRenderer renderer = new ViewRenderer(); ObjectMapper mapper = mapper(); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount); newHttpServerBootstrap(eventLoopGroup, maxRequestSize, router, renderer, mapper).bind(port).syncUninterruptibly(); Titanite.LOG.info("Http Server [" + id + "] started, listening on port " + port); return eventLoopGroup::shutdownGracefully; } @Override protected HttpServer self() { return this; } }
naming threads of HttpServer
src/main/java/org/nosceon/titanite/HttpServer.java
naming threads of HttpServer
<ide><path>rc/main/java/org/nosceon/titanite/HttpServer.java <ide> import io.netty.channel.EventLoopGroup; <ide> import io.netty.channel.nio.NioEventLoopGroup; <ide> <add>import java.util.concurrent.ThreadFactory; <ide> import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.concurrent.atomic.AtomicLong; <ide> <ide> /** <ide> * @author Johan Siebens <ide> Router router = router(id); <ide> ViewRenderer renderer = new ViewRenderer(); <ide> ObjectMapper mapper = mapper(); <del> EventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount); <add> EventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount, new NamedThreadFactory("Titanite HttpServer [" + id + "] - ")); <ide> <ide> newHttpServerBootstrap(eventLoopGroup, maxRequestSize, router, renderer, mapper).bind(port).syncUninterruptibly(); <ide> <ide> return this; <ide> } <ide> <add> private static class NamedThreadFactory implements ThreadFactory { <add> <add> private final AtomicLong counter = new AtomicLong(); <add> <add> private final String prefix; <add> <add> public NamedThreadFactory(String prefix) { <add> this.prefix = prefix; <add> } <add> <add> @Override <add> public Thread newThread(Runnable r) { <add> return new Thread(r, prefix + counter.incrementAndGet()); <add> } <add> <add> } <add> <ide> }
Java
mit
error: pathspec 'src/test/java/com/decentralizeddatabase/reno/filetable/FileTableTest.java' did not match any file(s) known to git
d19977f97d2987007b08c25dc0122a9772b121fb
1
rthotakura97/decentralized-database
package com.decentralizeddatabase.reno.filetable; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.ExpectedException; import org.junit.Test; import com.decentralizeddatabase.errors.FileNotFoundError; public final class FileTableTest { private static final String USER = "TEST_USER"; private static final List<String> FILES = Arrays.asList("file0.file", "file1.file"); private static final long FILE_SIZE = 10000; @Rule public ExpectedException thrown = ExpectedException.none(); private FileTable fileTable; @Before public void setup() { fileTable = new FileTable(); } private void addFileHelper(final String user, final String filename, final long fileSize) { fileTable.addFile(user, filename, fileSize); } @Test public void testGetFiles() { addFileHelper(USER, FILES.get(0), FILE_SIZE); addFileHelper(USER, FILES.get(1), FILE_SIZE); final Collection<FileData> actual = fileTable.getFiles(USER); Assert.assertEquals(2, actual.size()); for (FileData data : actual) { Assert.assertTrue(FILES.get(0).equals(data.getFilename()) || FILES.get(1).equals(data.getFilename())); } } @Test public void testGetFilesWithDuplicates() { addFileHelper(USER, FILES.get(0), FILE_SIZE); addFileHelper(USER, FILES.get(0), FILE_SIZE + 5); final Collection<FileData> actual = fileTable.getFiles(USER); Assert.assertEquals(1, actual.size()); for (FileData file : actual) { Assert.assertEquals(FILE_SIZE + 5, file.getFileSize()); Assert.assertEquals(FILES.get(0), file.getFilename()); } } @Test public void testGetFilesWithNoFiles() { final Collection<FileData> actual = fileTable.getFiles("invalid"); Assert.assertEquals(0, actual.size()); } @Test public void testGetFile() throws FileNotFoundError { addFileHelper(USER, FILES.get(0), FILE_SIZE); final FileData actual = fileTable.getFile(USER, FILES.get(0)); Assert.assertEquals(FILES.get(0), actual.getFilename()); Assert.assertEquals(FILE_SIZE, actual.getFileSize()); } @Test public void testGetNonExistantFile() throws FileNotFoundError { thrown.expect(FileNotFoundError.class); final FileData actual = fileTable.getFile(USER, FILES.get(0)); Assert.fail("No file should have been found"); } @Test public void testRemoveFile() throws FileNotFoundError { addFileHelper(USER, FILES.get(0), FILE_SIZE); final boolean removed = fileTable.removeFile(USER, FILES.get(0)); Assert.assertTrue(removed); thrown.expect(FileNotFoundError.class); fileTable.getFile(USER, FILES.get(0)); Assert.fail("File still in file table"); } @Test public void testRemoveNonExistantFile() throws FileNotFoundError { thrown.expect(FileNotFoundError.class); fileTable.removeFile(USER, FILES.get(0)); Assert.fail("FileNotFoundError not thrown"); } @Test public void testRemoveUser() { addFileHelper(USER, FILES.get(0), FILE_SIZE); addFileHelper(USER, FILES.get(1), FILE_SIZE); final boolean removed = fileTable.removeUser(USER); Assert.assertTrue(removed); final Collection<FileData> actual = fileTable.getFiles(USER); Assert.assertEquals(0, actual.size()); } }
src/test/java/com/decentralizeddatabase/reno/filetable/FileTableTest.java
Add FileTable unit tests
src/test/java/com/decentralizeddatabase/reno/filetable/FileTableTest.java
Add FileTable unit tests
<ide><path>rc/test/java/com/decentralizeddatabase/reno/filetable/FileTableTest.java <add>package com.decentralizeddatabase.reno.filetable; <add> <add>import java.util.Arrays; <add>import java.util.Collection; <add>import java.util.List; <add> <add>import org.junit.Assert; <add>import org.junit.Before; <add>import org.junit.Rule; <add>import org.junit.rules.ExpectedException; <add>import org.junit.Test; <add> <add>import com.decentralizeddatabase.errors.FileNotFoundError; <add> <add>public final class FileTableTest { <add> <add> private static final String USER = "TEST_USER"; <add> private static final List<String> FILES = Arrays.asList("file0.file", <add> "file1.file"); <add> private static final long FILE_SIZE = 10000; <add> <add> @Rule <add> public ExpectedException thrown = ExpectedException.none(); <add> <add> private FileTable fileTable; <add> <add> @Before <add> public void setup() { <add> fileTable = new FileTable(); <add> } <add> <add> private void addFileHelper(final String user, final String filename, final long fileSize) { <add> fileTable.addFile(user, filename, fileSize); <add> } <add> <add> @Test <add> public void testGetFiles() { <add> addFileHelper(USER, FILES.get(0), FILE_SIZE); <add> addFileHelper(USER, FILES.get(1), FILE_SIZE); <add> <add> final Collection<FileData> actual = fileTable.getFiles(USER); <add> <add> Assert.assertEquals(2, actual.size()); <add> <add> for (FileData data : actual) { <add> Assert.assertTrue(FILES.get(0).equals(data.getFilename()) || FILES.get(1).equals(data.getFilename())); <add> } <add> } <add> <add> @Test <add> public void testGetFilesWithDuplicates() { <add> addFileHelper(USER, FILES.get(0), FILE_SIZE); <add> addFileHelper(USER, FILES.get(0), FILE_SIZE + 5); <add> <add> final Collection<FileData> actual = fileTable.getFiles(USER); <add> <add> Assert.assertEquals(1, actual.size()); <add> for (FileData file : actual) { <add> Assert.assertEquals(FILE_SIZE + 5, file.getFileSize()); <add> Assert.assertEquals(FILES.get(0), file.getFilename()); <add> } <add> } <add> <add> @Test <add> public void testGetFilesWithNoFiles() { <add> final Collection<FileData> actual = fileTable.getFiles("invalid"); <add> <add> Assert.assertEquals(0, actual.size()); <add> } <add> <add> @Test <add> public void testGetFile() throws FileNotFoundError { <add> addFileHelper(USER, FILES.get(0), FILE_SIZE); <add> <add> final FileData actual = fileTable.getFile(USER, FILES.get(0)); <add> <add> Assert.assertEquals(FILES.get(0), actual.getFilename()); <add> Assert.assertEquals(FILE_SIZE, actual.getFileSize()); <add> } <add> <add> @Test <add> public void testGetNonExistantFile() throws FileNotFoundError { <add> thrown.expect(FileNotFoundError.class); <add> final FileData actual = fileTable.getFile(USER, FILES.get(0)); <add> <add> Assert.fail("No file should have been found"); <add> } <add> <add> @Test <add> public void testRemoveFile() throws FileNotFoundError { <add> addFileHelper(USER, FILES.get(0), FILE_SIZE); <add> <add> final boolean removed = fileTable.removeFile(USER, FILES.get(0)); <add> Assert.assertTrue(removed); <add> <add> thrown.expect(FileNotFoundError.class); <add> fileTable.getFile(USER, FILES.get(0)); <add> <add> Assert.fail("File still in file table"); <add> } <add> <add> @Test <add> public void testRemoveNonExistantFile() throws FileNotFoundError { <add> thrown.expect(FileNotFoundError.class); <add> fileTable.removeFile(USER, FILES.get(0)); <add> <add> Assert.fail("FileNotFoundError not thrown"); <add> } <add> <add> @Test <add> public void testRemoveUser() { <add> addFileHelper(USER, FILES.get(0), FILE_SIZE); <add> addFileHelper(USER, FILES.get(1), FILE_SIZE); <add> <add> final boolean removed = fileTable.removeUser(USER); <add> Assert.assertTrue(removed); <add> <add> final Collection<FileData> actual = fileTable.getFiles(USER); <add> Assert.assertEquals(0, actual.size()); <add> } <add>}
Java
apache-2.0
4fa89f0260b8933eed7438104564f66c7fc7deb4
0
wso2/product-is,mefarazath/product-is,wso2/product-is,mefarazath/product-is,mefarazath/product-is,mefarazath/product-is,madurangasiriwardena/product-is,madurangasiriwardena/product-is,mefarazath/product-is,wso2/product-is,madurangasiriwardena/product-is,wso2/product-is,wso2/product-is,madurangasiriwardena/product-is,madurangasiriwardena/product-is
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.identity.integration.test.rest.api.server.configs.v1; import io.restassured.RestAssured; import io.restassured.response.Response; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; import java.io.IOException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; /** * Test class for Server Configuration Management REST APIs success paths. */ public class ConfigSuccessTest extends ConfigTestBase { @Factory(dataProvider = "restAPIUserConfigProvider") public ConfigSuccessTest(TestUserMode userMode) throws Exception { super.init(userMode); this.context = isServer; this.authenticatingUserName = context.getContextTenant().getTenantAdmin().getUserName(); this.authenticatingCredential = context.getContextTenant().getTenantAdmin().getPassword(); this.tenant = context.getContextTenant().getDomain(); } @BeforeClass(alwaysRun = true) public void init() throws IOException { super.testInit(API_VERSION, swaggerDefinition, tenant); } @AfterClass(alwaysRun = true) public void testConclude() { super.conclude(); } @BeforeMethod(alwaysRun = true) public void testInit() { RestAssured.basePath = basePath; } @AfterMethod(alwaysRun = true) public void testFinish() { RestAssured.basePath = StringUtils.EMPTY; } @DataProvider(name = "restAPIUserConfigProvider") public static Object[][] restAPIUserConfigProvider() { return new Object[][]{ {TestUserMode.SUPER_TENANT_ADMIN}, {TestUserMode.TENANT_ADMIN} }; } @Test public void testGetAuthenticator() throws Exception { Response response = getResponseOfGet( CONFIGS_AUTHENTICATOR_API_BASE_PATH + PATH_SEPARATOR + SAMPLE_AUTHENTICATOR_ID); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("id", equalTo(SAMPLE_AUTHENTICATOR_ID)) .body("name", equalTo("BasicAuthenticator")) .body("displayName", equalTo("basic")) .body("isEnabled", equalTo(true)) .body("properties", notNullValue()); } @Test(dependsOnMethods = {"testGetAuthenticator"}) public void testGetAuthenticators() throws Exception { String baseIdentifier = "find{ it.id == '" + SAMPLE_AUTHENTICATOR_ID + "' }."; Response response = getResponseOfGet(CONFIGS_AUTHENTICATOR_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body(baseIdentifier + "name", equalTo("BasicAuthenticator")) .body(baseIdentifier + "displayName", equalTo("basic")) .body(baseIdentifier + "isEnabled", equalTo(true)); } @Test(dependsOnMethods = {"testGetAuthenticators"}) public void testGetConfigs() throws Exception { Response response = getResponseOfGet( CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("idleSessionTimeoutPeriod", notNullValue()) .body("rememberMePeriod", notNullValue()) .body("homeRealmIdentifiers", notNullValue()) .body("provisioning", notNullValue()) .body("authenticators", notNullValue()); } @Test(dependsOnMethods = {"testGetConfigs"}) public void testPatchConfigs() throws Exception { String body = readResource("patch-replace-configs.json"); Response response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("idleSessionTimeoutPeriod", equalTo("20")); body = readResource("patch-add-configs.json"); response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("homeRealmIdentifiers.contains(\"test-realm\")", equalTo(true)); body = readResource("patch-remove-configs.json"); response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("homeRealmIdentifiers.contains(\"test-realm\")", equalTo(false)); } @Test(dependsOnMethods = {"testPatchConfigs"}) public void testUpdateScimConfigs() throws Exception { String body = readResource("update-scim-configs.json"); Response response = getResponseOfPut(CONFIGS_INBOUND_SCIM_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("provisioning", notNullValue()) .body("provisioning.inbound.scim.provisioningUserstore", equalTo("PRIMARY")) .body("provisioning.inbound.scim.enableProxyMode", equalTo(false)); } }
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/configs/v1/ConfigSuccessTest.java
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.identity.integration.test.rest.api.server.configs.v1; import io.restassured.RestAssured; import io.restassured.response.Response; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; import java.io.IOException; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; /** * Test class for Server Configuration Management REST APIs success paths. */ public class ConfigSuccessTest extends ConfigTestBase { @Factory(dataProvider = "restAPIUserConfigProvider") public ConfigSuccessTest(TestUserMode userMode) throws Exception { super.init(userMode); this.context = isServer; this.authenticatingUserName = context.getContextTenant().getTenantAdmin().getUserName(); this.authenticatingCredential = context.getContextTenant().getTenantAdmin().getPassword(); this.tenant = context.getContextTenant().getDomain(); } @BeforeClass(alwaysRun = true) public void init() throws IOException { super.testInit(API_VERSION, swaggerDefinition, tenant); } @AfterClass(alwaysRun = true) public void testConclude() { super.conclude(); } @BeforeMethod(alwaysRun = true) public void testInit() { RestAssured.basePath = basePath; } @AfterMethod(alwaysRun = true) public void testFinish() { RestAssured.basePath = StringUtils.EMPTY; } @DataProvider(name = "restAPIUserConfigProvider") public static Object[][] restAPIUserConfigProvider() { return new Object[][]{ {TestUserMode.SUPER_TENANT_ADMIN}, {TestUserMode.TENANT_ADMIN} }; } @Test public void testGetAuthenticator() throws Exception { Response response = getResponseOfGet( CONFIGS_AUTHENTICATOR_API_BASE_PATH + PATH_SEPARATOR + SAMPLE_AUTHENTICATOR_ID); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("id", equalTo(SAMPLE_AUTHENTICATOR_ID)) .body("name", equalTo("BasicAuthenticator")) .body("displayName", equalTo("basic")) .body("isEnabled", equalTo(false)) .body("properties", notNullValue()); } @Test(dependsOnMethods = {"testGetAuthenticator"}) public void testGetAuthenticators() throws Exception { String baseIdentifier = "find{ it.id == '" + SAMPLE_AUTHENTICATOR_ID + "' }."; Response response = getResponseOfGet(CONFIGS_AUTHENTICATOR_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body(baseIdentifier + "name", equalTo("BasicAuthenticator")) .body(baseIdentifier + "displayName", equalTo("basic")) .body(baseIdentifier + "isEnabled", equalTo(false)); } @Test(dependsOnMethods = {"testGetAuthenticators"}) public void testGetConfigs() throws Exception { Response response = getResponseOfGet( CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("idleSessionTimeoutPeriod", notNullValue()) .body("rememberMePeriod", notNullValue()) .body("homeRealmIdentifiers", notNullValue()) .body("provisioning", notNullValue()) .body("authenticators", notNullValue()); } @Test(dependsOnMethods = {"testGetConfigs"}) public void testPatchConfigs() throws Exception { String body = readResource("patch-replace-configs.json"); Response response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("idleSessionTimeoutPeriod", equalTo("20")); body = readResource("patch-add-configs.json"); response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("homeRealmIdentifiers.contains(\"test-realm\")", equalTo(true)); body = readResource("patch-remove-configs.json"); response = getResponseOfPatch( CONFIGS_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("homeRealmIdentifiers.contains(\"test-realm\")", equalTo(false)); } @Test(dependsOnMethods = {"testPatchConfigs"}) public void testUpdateScimConfigs() throws Exception { String body = readResource("update-scim-configs.json"); Response response = getResponseOfPut(CONFIGS_INBOUND_SCIM_API_BASE_PATH, body); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK); response = getResponseOfGet(CONFIGS_API_BASE_PATH); response.then() .log().ifValidationFails() .assertThat() .statusCode(HttpStatus.SC_OK) .body("provisioning", notNullValue()) .body("provisioning.inbound.scim.provisioningUserstore", equalTo("PRIMARY")) .body("provisioning.inbound.scim.enableProxyMode", equalTo(false)); } }
Fix configs test case
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/configs/v1/ConfigSuccessTest.java
Fix configs test case
<ide><path>odules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/configs/v1/ConfigSuccessTest.java <ide> .body("id", equalTo(SAMPLE_AUTHENTICATOR_ID)) <ide> .body("name", equalTo("BasicAuthenticator")) <ide> .body("displayName", equalTo("basic")) <del> .body("isEnabled", equalTo(false)) <add> .body("isEnabled", equalTo(true)) <ide> .body("properties", notNullValue()); <ide> } <ide> <ide> .statusCode(HttpStatus.SC_OK) <ide> .body(baseIdentifier + "name", equalTo("BasicAuthenticator")) <ide> .body(baseIdentifier + "displayName", equalTo("basic")) <del> .body(baseIdentifier + "isEnabled", equalTo(false)); <add> .body(baseIdentifier + "isEnabled", equalTo(true)); <ide> } <ide> <ide> @Test(dependsOnMethods = {"testGetAuthenticators"})
JavaScript
mit
42fe8b9905a0af2d470d45c79118c959d8e856bb
0
KyperTech/matter,KyperTech/matter-library,KyperTech/matter-library,KyperTech/matter
var matter = new Matter('exampleApp', {localServer:true}); console.log('matter:', matter); //Set logged in status when dom is loaded document.addEventListener("DOMContentLoaded", function(event) { setStatus(); }); //Set status styles function setStatus() { var statusEl = document.getElementById("status"); var logoutButton = document.getElementById("logout-btn"); if(matter.isLoggedIn){ statusEl.innerHTML = "True"; statusEl.style.color = 'green'; // statusEl.className = statusEl.className ? ' status-loggedIn' : 'status-loggedIn'; logoutButton.style.display='inline'; } else { statusEl.innerHTML = "False"; statusEl.style.color = 'red'; logoutButton.style.display='none'; } } function login(loginData){ if(!loginData){ var loginData = {}; loginData.username = document.getElementById('login-username').value; loginData.password = document.getElementById('login-password').value; } matter.login(loginData).then(function(loginInfo){ console.log('successful login:', loginInfo); setStatus(); }, function(err){ console.error('login() : Error logging in:', err); }); } function logout(){ matter.logout().then(function(){ console.log('successful logout'); setStatus(); }, function(err){ console.error('logout() : Error logging out:', err); }); } function signup(signupData){ if(!signupData){ var signupData = {}; signupData.name = document.getElementById('signup-name').value; signupData.username = document.getElementById('signup-username').value; signupData.email = document.getElementById('signup-email').value; signupData.password = document.getElementById('signup-password').value; } matter.signup(signupData).then(function(signupRes){ console.log('successful signup', signupRes); setStatus(); }, function(err){ console.error('logout() : Error signing up:', err); }); }
examples/browser/app.js
var matter = new Matter('cloudbrain', {localServer:false}); console.log('matter:', matter); //Set logged in status when dom is loaded document.addEventListener("DOMContentLoaded", function(event) { setStatus(); }); //Set status styles function setStatus() { var statusEl = document.getElementById("status"); var logoutButton = document.getElementById("logout-btn"); if(matter.isLoggedIn){ statusEl.innerHTML = "True"; statusEl.style.color = 'green'; // statusEl.className = statusEl.className ? ' status-loggedIn' : 'status-loggedIn'; logoutButton.style.display='inline'; } else { statusEl.innerHTML = "False"; statusEl.style.color = 'red'; logoutButton.style.display='none'; } } function login(loginData){ if(!loginData){ var loginData = {}; loginData.username = document.getElementById('login-username').value; loginData.password = document.getElementById('login-password').value; } matter.login(loginData).then(function(loginInfo){ console.log('successful login:', loginInfo); setStatus(); }, function(err){ console.error('login() : Error logging in:', err); }); } function logout(){ matter.logout().then(function(){ console.log('successful logout'); setStatus(); }, function(err){ console.error('logout() : Error logging out:', err); }); } function signup(signupData){ if(!signupData){ var signupData = {}; signupData.name = document.getElementById('signup-name').value; signupData.username = document.getElementById('signup-username').value; signupData.email = document.getElementById('signup-email').value; signupData.password = document.getElementById('signup-password').value; } matter.signup(signupData).then(function(signupRes){ console.log('successful signup', signupRes); setStatus(); }, function(err){ console.error('logout() : Error signing up:', err); }); }
Switched example to using exampleApp instead of cloudbrain.
examples/browser/app.js
Switched example to using exampleApp instead of cloudbrain.
<ide><path>xamples/browser/app.js <del>var matter = new Matter('cloudbrain', {localServer:false}); <add>var matter = new Matter('exampleApp', {localServer:true}); <ide> console.log('matter:', matter); <ide> //Set logged in status when dom is loaded <del>document.addEventListener("DOMContentLoaded", function(event) { <add>document.addEventListener("DOMContentLoaded", function(event) { <ide> setStatus(); <ide> }); <ide> //Set status styles <ide> setStatus(); <ide> }, function(err){ <ide> console.error('login() : Error logging in:', err); <del> }); <add> }); <ide> } <ide> function logout(){ <ide> matter.logout().then(function(){ <ide> setStatus(); <ide> }, function(err){ <ide> console.error('logout() : Error logging out:', err); <del> }); <add> }); <ide> } <ide> function signup(signupData){ <ide> if(!signupData){ <ide> }, function(err){ <ide> console.error('logout() : Error signing up:', err); <ide> }); <del> <add> <ide> }
Java
apache-2.0
9238d2542f88860deacf6af21334de2da94a845d
0
iiordanov/BSSH,galexander1/connectbot,lotan/connectbot,nemobis/connectbot,Lekensteyn/connectbot,jklein24/connectbot,ipmobiletech/connectbot,zeldin/connectbot,trygveaa/connectbot,Lekensteyn/connectbot,alescdb/connectbot,rhansby/connectbot,redshodan/connectbot,connectbot/connectbot,Potass/ConnectBot,zeldin/connectbot,ipmobiletech/connectbot,iiordanov/BSSH,trygveaa/connectbot,khorimoto/connectbot,lotan/connectbot,alescdb/connectbot,zeldin/connectbot,changjiashuai/connectbot,lotan/connectbot,kruton/connectbot,nemobis/connectbot,rhansby/connectbot,galexander1/connectbot,connectbot/connectbot,redshodan/connectbot,Shedings/connectbot,brunodles/connectbot,kruton/connectbot,ipmobiletech/connectbot,windowhero0/connectbot,jklein24/connectbot,iiordanov/BSSH,windowhero0/connectbot,FauxFaux/connectbot,Potass/ConnectBot,jklein24/connectbot,zeldin/connectbot,Lekensteyn/connectbot,Shedings/connectbot,ipmobiletech/connectbot,redshodan/connectbot,galexander1/connectbot,changjiashuai/connectbot,brunodles/connectbot,nemobis/connectbot,Shedings/connectbot,FauxFaux/connectbot,connectbot/connectbot,Potass/ConnectBot,khorimoto/connectbot,kruton/connectbot,nixomose/connectbot,changjiashuai/connectbot,FauxFaux/connectbot,khorimoto/connectbot,Lekensteyn/connectbot,alescdb/connectbot,rhansby/connectbot,brunodles/connectbot,nixomose/connectbot,nixomose/connectbot,windowhero0/connectbot,trygveaa/connectbot
/* * ConnectBot: simple, powerful, open-source SSH client for Android * Copyright 2007 Kenny Root, Jeffrey Sharkey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.connectbot; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collections; import java.util.EventListener; import java.util.LinkedList; import java.util.List; import org.connectbot.bean.PubkeyBean; import org.connectbot.service.TerminalManager; import org.connectbot.util.PubkeyDatabase; import org.connectbot.util.PubkeyUtils; import org.openintents.intents.FileManagerIntents; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.text.ClipboardManager; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.trilead.ssh2.crypto.Base64; import com.trilead.ssh2.crypto.PEMDecoder; import com.trilead.ssh2.crypto.PEMStructure; /** * List public keys in database by nickname and describe their properties. Allow users to import, * generate, rename, and delete key pairs. * * @author Kenny Root */ public class PubkeyListActivity extends ListActivity implements EventListener { public final static String TAG = "ConnectBot.PubkeyListActivity"; private static final int MAX_KEYFILE_SIZE = 8192; private static final int REQUEST_CODE_PICK_FILE = 1; // Constants for AndExplorer's file picking intent private static final String ANDEXPLORER_TITLE = "explorer_title"; private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file"; protected PubkeyDatabase pubkeydb; private List<PubkeyBean> pubkeys; protected ClipboardManager clipboard; protected LayoutInflater inflater = null; protected TerminalManager bound = null; private MenuItem onstartToggle = null; private MenuItem confirmUse = null; private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { bound = ((TerminalManager.TerminalBinder) service).getService(); // update our listview binder to find the service updateList(); } public void onServiceDisconnected(ComponentName className) { bound = null; updateList(); } }; @Override public void onStart() { super.onStart(); bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE); if(pubkeydb == null) pubkeydb = new PubkeyDatabase(this); } @Override public void onStop() { super.onStop(); unbindService(connection); if(pubkeydb != null) { pubkeydb.close(); pubkeydb = null; } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.act_pubkeylist); this.setTitle(String.format("%s: %s", getResources().getText(R.string.app_name), getResources().getText(R.string.title_pubkey_list))); // connect with hosts database and populate list pubkeydb = new PubkeyDatabase(this); updateList(); registerForContextMenu(getListView()); getListView().setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position); boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname()); // handle toggling key in-memory on/off if(loaded) { bound.removeKey(pubkey.getNickname()); updateList(); } else { handleAddKey(pubkey); } } }); clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); inflater = LayoutInflater.from(this); } /** * Read given file into memory as <code>byte[]</code>. */ protected static byte[] readRaw(File file) throws Exception { InputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); int bytesRead; byte[] buffer = new byte[1024]; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); is.close(); return os.toByteArray(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem generatekey = menu.add(R.string.pubkey_generate); generatekey.setIcon(android.R.drawable.ic_menu_manage); generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class)); MenuItem importkey = menu.add(R.string.pubkey_import); importkey.setIcon(android.R.drawable.ic_menu_upload); importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory()); String pickerTitle = getString(R.string.pubkey_list_pick); // Try to use OpenIntent's file browser to pick a file Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE); intent.setData(sdcard); intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle); intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok)); try { startActivityForResult(intent, REQUEST_CODE_PICK_FILE); } catch (ActivityNotFoundException e) { // If OI didn't work, try AndExplorer intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE); intent.putExtra(ANDEXPLORER_TITLE, pickerTitle); try { startActivityForResult(intent, REQUEST_CODE_PICK_FILE); } catch (ActivityNotFoundException e1) { pickFileSimple(); } } return true; } }); return true; } protected void handleAddKey(final PubkeyBean pubkey) { if (pubkey.isEncrypted()) { final View view = inflater.inflate(R.layout.dia_password, null); final EditText passwordField = (EditText)view.findViewById(android.R.id.text1); new AlertDialog.Builder(PubkeyListActivity.this) .setView(view) .setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { handleAddKey(pubkey, passwordField.getText().toString()); } }) .setNegativeButton(android.R.string.cancel, null).create().show(); } else { handleAddKey(pubkey, null); } } protected void handleAddKey(PubkeyBean keybean, String password) { KeyPair pair = null; if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(keybean.getType())) { // load specific key using pem format try { pair = PEMDecoder.decode(new String(keybean.getPrivateKey()).toCharArray(), password); } catch(Exception e) { String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname()); Log.e(TAG, message, e); Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show(); } } else { // load using internal generated format try { PrivateKey privKey = PubkeyUtils.decodePrivate(keybean.getPrivateKey(), keybean.getType(), password); PublicKey pubKey = PubkeyUtils.decodePublic(keybean.getPublicKey(), keybean.getType()); Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey)); pair = new KeyPair(pubKey, privKey); } catch (Exception e) { String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname()); Log.e(TAG, message, e); Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show(); return; } } if (pair == null) { return; } Log.d(TAG, String.format("Unlocked key '%s'", keybean.getNickname())); // save this key in memory bound.addKey(keybean, pair, true); updateList(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { // Create menu to handle deleting and editing pubkey AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position); menu.setHeaderTitle(pubkey.getNickname()); // TODO: option load/unload key from in-memory list // prompt for password as needed for passworded keys // cant change password or clipboard imported keys final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType()); final boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname()); MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load); load.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if(loaded) { bound.removeKey(pubkey.getNickname()); updateList(); } else { handleAddKey(pubkey); //bound.addKey(nickname, trileadKey); } return true; } }); onstartToggle = menu.add(R.string.pubkey_load_on_start); onstartToggle.setEnabled(!pubkey.isEncrypted()); onstartToggle.setCheckable(true); onstartToggle.setChecked(pubkey.isStartup()); onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // toggle onstart status pubkey.setStartup(!pubkey.isStartup()); pubkeydb.savePubkey(pubkey); updateList(); return true; } }); MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public); copyPublicToClipboard.setEnabled(!imported); copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { try { PublicKey pk = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType()); String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname()); clipboard.setText(openSSHPubkey); } catch (Exception e) { e.printStackTrace(); } return true; } }); MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private); copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported); copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { try { String data = null; if (imported) data = new String(pubkey.getPrivateKey()); else { PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType()); data = PubkeyUtils.exportPEM(pk, null); } clipboard.setText(data); } catch (Exception e) { e.printStackTrace(); } return true; } }); MenuItem changePassword = menu.add(R.string.pubkey_change_password); changePassword.setEnabled(!imported); changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false); ((TableRow)changePasswordView.findViewById(R.id.old_password_prompt)) .setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE); new AlertDialog.Builder(PubkeyListActivity.this) .setView(changePasswordView) .setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String oldPassword = ((EditText)changePasswordView.findViewById(R.id.old_password)).getText().toString(); String password1 = ((EditText)changePasswordView.findViewById(R.id.password1)).getText().toString(); String password2 = ((EditText)changePasswordView.findViewById(R.id.password2)).getText().toString(); if (!password1.equals(password2)) { new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_passwords_do_not_match_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); return; } try { if (!pubkey.changePassword(oldPassword, password1)) new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_wrong_password_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); else { pubkeydb.savePubkey(pubkey); updateList(); } } catch (Exception e) { Log.e(TAG, "Could not change private key password", e); new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_key_corrupted_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); } } }) .setNegativeButton(android.R.string.cancel, null).create().show(); return true; } }); confirmUse = menu.add(R.string.pubkey_confirm_use); confirmUse.setCheckable(true); confirmUse.setChecked(pubkey.isConfirmUse()); confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // toggle confirm use pubkey.setConfirmUse(!pubkey.isConfirmUse()); pubkeydb.savePubkey(pubkey); updateList(); return true; } }); MenuItem delete = menu.add(R.string.pubkey_delete); delete.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // prompt user to make sure they really want this new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(getString(R.string.delete_message, pubkey.getNickname())) .setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // dont forget to remove from in-memory if(loaded) bound.removeKey(pubkey.getNickname()); // delete from backend database and update gui pubkeydb.deletePubkey(pubkey); updateList(); } }) .setNegativeButton(R.string.delete_neg, null).create().show(); return true; } }); } protected void updateList() { if (pubkeydb == null) return; pubkeys = pubkeydb.allPubkeys(); PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys); this.setListAdapter(adapter); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case REQUEST_CODE_PICK_FILE: if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); try { if (uri != null) { readKeyFromFile(new File(URI.create(uri.toString()))); } else { String filename = intent.getDataString(); if (filename != null) readKeyFromFile(new File(URI.create(filename))); } } catch (IllegalArgumentException e) { Log.e(TAG, "Couldn't read from picked file", e); } } break; } } /** * @param name */ private void readKeyFromFile(File file) { PubkeyBean pubkey = new PubkeyBean(); // find the exact file selected pubkey.setNickname(file.getName()); if (file.length() > MAX_KEYFILE_SIZE) { Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); return; } // parse the actual key once to check if its encrypted // then save original file contents into our database try { byte[] raw = readRaw(file); String data = new String(raw); if (data.startsWith(PubkeyUtils.PKCS8_START)) { int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length(); int end = data.indexOf(PubkeyUtils.PKCS8_END); if (end > start) { char[] encoded = data.substring(start, end - 1).toCharArray(); Log.d(TAG, "encoded: " + new String(encoded)); byte[] decoded = Base64.decode(encoded); KeyPair kp = PubkeyUtils.recoverKeyPair(decoded); pubkey.setType(kp.getPrivate().getAlgorithm()); pubkey.setPrivateKey(kp.getPrivate().getEncoded()); pubkey.setPublicKey(kp.getPublic().getEncoded()); } else { Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?"); Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); } } else { PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray()); pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct)); pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED); pubkey.setPrivateKey(raw); } // write new value into database if (pubkeydb == null) pubkeydb = new PubkeyDatabase(this); pubkeydb.savePubkey(pubkey); updateList(); } catch(Exception e) { Log.e(TAG, "Problem parsing imported private key", e); Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); } } /** * */ private void pickFileSimple() { // build list of all files in sdcard root final File sdcard = Environment.getExternalStorageDirectory(); Log.d(TAG, sdcard.toString()); // Don't show a dialog if the SD card is completely absent. final String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) && !Environment.MEDIA_MOUNTED.equals(state)) { new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_sdcard_absent) .setNegativeButton(android.R.string.cancel, null).create().show(); return; } List<String> names = new LinkedList<String>(); { File[] files = sdcard.listFiles(); if (files != null) { for(File file : sdcard.listFiles()) { if(file.isDirectory()) continue; names.add(file.getName()); } } } Collections.sort(names); final String[] namesList = names.toArray(new String[] {}); Log.d(TAG, names.toString()); // prompt user to select any file from the sdcard root new AlertDialog.Builder(PubkeyListActivity.this) .setTitle(R.string.pubkey_list_pick) .setItems(namesList, new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { String name = namesList[arg1]; readKeyFromFile(new File(sdcard, name)); } }) .setNegativeButton(android.R.string.cancel, null).create().show(); } class PubkeyAdapter extends ArrayAdapter<PubkeyBean> { private List<PubkeyBean> pubkeys; class ViewHolder { public TextView nickname; public TextView caption; public ImageView icon; } public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) { super(context, R.layout.item_pubkey, pubkeys); this.pubkeys = pubkeys; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.item_pubkey, null, false); holder = new ViewHolder(); holder.nickname = (TextView) convertView.findViewById(android.R.id.text1); holder.caption = (TextView) convertView.findViewById(android.R.id.text2); holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); PubkeyBean pubkey = pubkeys.get(position); holder.nickname.setText(pubkey.getNickname()); boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType()); if (imported) { try { PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray()); String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA"; holder.caption.setText(String.format("%s unknown-bit", type)); } catch (IOException e) { Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e); } } else { try { holder.caption.setText(pubkey.getDescription()); } catch (Exception e) { Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e); holder.caption.setText(R.string.pubkey_unknown_format); } } if (bound == null) { holder.icon.setVisibility(View.GONE); } else { holder.icon.setVisibility(View.VISIBLE); if (bound.isKeyLoaded(pubkey.getNickname())) holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true); else holder.icon.setImageState(new int[] { }, true); } return convertView; } } }
src/org/connectbot/PubkeyListActivity.java
/* * ConnectBot: simple, powerful, open-source SSH client for Android * Copyright 2007 Kenny Root, Jeffrey Sharkey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.connectbot; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collections; import java.util.EventListener; import java.util.LinkedList; import java.util.List; import org.connectbot.bean.PubkeyBean; import org.connectbot.service.TerminalManager; import org.connectbot.util.PubkeyDatabase; import org.connectbot.util.PubkeyUtils; import org.openintents.intents.FileManagerIntents; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.text.ClipboardManager; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.trilead.ssh2.crypto.Base64; import com.trilead.ssh2.crypto.PEMDecoder; import com.trilead.ssh2.crypto.PEMStructure; /** * List public keys in database by nickname and describe their properties. Allow users to import, * generate, rename, and delete key pairs. * * @author Kenny Root */ public class PubkeyListActivity extends ListActivity implements EventListener { public final static String TAG = "ConnectBot.PubkeyListActivity"; private static final int MAX_KEYFILE_SIZE = 8192; private static final int REQUEST_CODE_PICK_FILE = 1; // Constants for AndExplorer's file picking intent private static final String ANDEXPLORER_TITLE = "explorer_title"; private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file"; protected PubkeyDatabase pubkeydb; private List<PubkeyBean> pubkeys; protected ClipboardManager clipboard; protected LayoutInflater inflater = null; protected TerminalManager bound = null; private MenuItem onstartToggle = null; private MenuItem confirmUse = null; private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { bound = ((TerminalManager.TerminalBinder) service).getService(); // update our listview binder to find the service updateList(); } public void onServiceDisconnected(ComponentName className) { bound = null; updateList(); } }; @Override public void onStart() { super.onStart(); bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE); if(pubkeydb == null) pubkeydb = new PubkeyDatabase(this); } @Override public void onStop() { super.onStop(); unbindService(connection); if(pubkeydb != null) { pubkeydb.close(); pubkeydb = null; } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.act_pubkeylist); this.setTitle(String.format("%s: %s", getResources().getText(R.string.app_name), getResources().getText(R.string.title_pubkey_list))); // connect with hosts database and populate list pubkeydb = new PubkeyDatabase(this); updateList(); registerForContextMenu(getListView()); getListView().setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position); boolean loaded = bound.isKeyLoaded(pubkey.getNickname()); // handle toggling key in-memory on/off if(loaded) { bound.removeKey(pubkey.getNickname()); updateList(); } else { handleAddKey(pubkey); } } }); clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); inflater = LayoutInflater.from(this); } /** * Read given file into memory as <code>byte[]</code>. */ protected static byte[] readRaw(File file) throws Exception { InputStream is = new FileInputStream(file); ByteArrayOutputStream os = new ByteArrayOutputStream(); int bytesRead; byte[] buffer = new byte[1024]; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); is.close(); return os.toByteArray(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem generatekey = menu.add(R.string.pubkey_generate); generatekey.setIcon(android.R.drawable.ic_menu_manage); generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class)); MenuItem importkey = menu.add(R.string.pubkey_import); importkey.setIcon(android.R.drawable.ic_menu_upload); importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory()); String pickerTitle = getString(R.string.pubkey_list_pick); // Try to use OpenIntent's file browser to pick a file Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE); intent.setData(sdcard); intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle); intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok)); try { startActivityForResult(intent, REQUEST_CODE_PICK_FILE); } catch (ActivityNotFoundException e) { // If OI didn't work, try AndExplorer intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE); intent.putExtra(ANDEXPLORER_TITLE, pickerTitle); try { startActivityForResult(intent, REQUEST_CODE_PICK_FILE); } catch (ActivityNotFoundException e1) { pickFileSimple(); } } return true; } }); return true; } protected void handleAddKey(final PubkeyBean pubkey) { if (pubkey.isEncrypted()) { final View view = inflater.inflate(R.layout.dia_password, null); final EditText passwordField = (EditText)view.findViewById(android.R.id.text1); new AlertDialog.Builder(PubkeyListActivity.this) .setView(view) .setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { handleAddKey(pubkey, passwordField.getText().toString()); } }) .setNegativeButton(android.R.string.cancel, null).create().show(); } else { handleAddKey(pubkey, null); } } protected void handleAddKey(PubkeyBean keybean, String password) { KeyPair pair = null; if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(keybean.getType())) { // load specific key using pem format try { pair = PEMDecoder.decode(new String(keybean.getPrivateKey()).toCharArray(), password); } catch(Exception e) { String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname()); Log.e(TAG, message, e); Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show(); } } else { // load using internal generated format try { PrivateKey privKey = PubkeyUtils.decodePrivate(keybean.getPrivateKey(), keybean.getType(), password); PublicKey pubKey = PubkeyUtils.decodePublic(keybean.getPublicKey(), keybean.getType()); Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey)); pair = new KeyPair(pubKey, privKey); } catch (Exception e) { String message = getResources().getString(R.string.pubkey_failed_add, keybean.getNickname()); Log.e(TAG, message, e); Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG).show(); return; } } if (pair == null) { return; } Log.d(TAG, String.format("Unlocked key '%s'", keybean.getNickname())); // save this key in memory bound.addKey(keybean, pair, true); updateList(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { // Create menu to handle deleting and editing pubkey AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position); menu.setHeaderTitle(pubkey.getNickname()); // TODO: option load/unload key from in-memory list // prompt for password as needed for passworded keys // cant change password or clipboard imported keys final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType()); final boolean loaded = bound.isKeyLoaded(pubkey.getNickname()); MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load); load.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { if(loaded) { bound.removeKey(pubkey.getNickname()); updateList(); } else { handleAddKey(pubkey); //bound.addKey(nickname, trileadKey); } return true; } }); onstartToggle = menu.add(R.string.pubkey_load_on_start); onstartToggle.setEnabled(!pubkey.isEncrypted()); onstartToggle.setCheckable(true); onstartToggle.setChecked(pubkey.isStartup()); onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // toggle onstart status pubkey.setStartup(!pubkey.isStartup()); pubkeydb.savePubkey(pubkey); updateList(); return true; } }); MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public); copyPublicToClipboard.setEnabled(!imported); copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { try { PublicKey pk = PubkeyUtils.decodePublic(pubkey.getPublicKey(), pubkey.getType()); String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname()); clipboard.setText(openSSHPubkey); } catch (Exception e) { e.printStackTrace(); } return true; } }); MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private); copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported); copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { try { String data = null; if (imported) data = new String(pubkey.getPrivateKey()); else { PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType()); data = PubkeyUtils.exportPEM(pk, null); } clipboard.setText(data); } catch (Exception e) { e.printStackTrace(); } return true; } }); MenuItem changePassword = menu.add(R.string.pubkey_change_password); changePassword.setEnabled(!imported); changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false); ((TableRow)changePasswordView.findViewById(R.id.old_password_prompt)) .setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE); new AlertDialog.Builder(PubkeyListActivity.this) .setView(changePasswordView) .setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String oldPassword = ((EditText)changePasswordView.findViewById(R.id.old_password)).getText().toString(); String password1 = ((EditText)changePasswordView.findViewById(R.id.password1)).getText().toString(); String password2 = ((EditText)changePasswordView.findViewById(R.id.password2)).getText().toString(); if (!password1.equals(password2)) { new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_passwords_do_not_match_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); return; } try { if (!pubkey.changePassword(oldPassword, password1)) new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_wrong_password_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); else { pubkeydb.savePubkey(pubkey); updateList(); } } catch (Exception e) { Log.e(TAG, "Could not change private key password", e); new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_key_corrupted_msg) .setPositiveButton(android.R.string.ok, null) .create().show(); } } }) .setNegativeButton(android.R.string.cancel, null).create().show(); return true; } }); confirmUse = menu.add(R.string.pubkey_confirm_use); confirmUse.setCheckable(true); confirmUse.setChecked(pubkey.isConfirmUse()); confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // toggle confirm use pubkey.setConfirmUse(!pubkey.isConfirmUse()); pubkeydb.savePubkey(pubkey); updateList(); return true; } }); MenuItem delete = menu.add(R.string.pubkey_delete); delete.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // prompt user to make sure they really want this new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(getString(R.string.delete_message, pubkey.getNickname())) .setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // dont forget to remove from in-memory if(loaded) bound.removeKey(pubkey.getNickname()); // delete from backend database and update gui pubkeydb.deletePubkey(pubkey); updateList(); } }) .setNegativeButton(R.string.delete_neg, null).create().show(); return true; } }); } protected void updateList() { if (pubkeydb == null) return; pubkeys = pubkeydb.allPubkeys(); PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys); this.setListAdapter(adapter); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case REQUEST_CODE_PICK_FILE: if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); try { if (uri != null) { readKeyFromFile(new File(URI.create(uri.toString()))); } else { String filename = intent.getDataString(); if (filename != null) readKeyFromFile(new File(URI.create(filename))); } } catch (IllegalArgumentException e) { Log.e(TAG, "Couldn't read from picked file", e); } } break; } } /** * @param name */ private void readKeyFromFile(File file) { PubkeyBean pubkey = new PubkeyBean(); // find the exact file selected pubkey.setNickname(file.getName()); if (file.length() > MAX_KEYFILE_SIZE) { Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); return; } // parse the actual key once to check if its encrypted // then save original file contents into our database try { byte[] raw = readRaw(file); String data = new String(raw); if (data.startsWith(PubkeyUtils.PKCS8_START)) { int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length(); int end = data.indexOf(PubkeyUtils.PKCS8_END); if (end > start) { char[] encoded = data.substring(start, end - 1).toCharArray(); Log.d(TAG, "encoded: " + new String(encoded)); byte[] decoded = Base64.decode(encoded); KeyPair kp = PubkeyUtils.recoverKeyPair(decoded); pubkey.setType(kp.getPrivate().getAlgorithm()); pubkey.setPrivateKey(kp.getPrivate().getEncoded()); pubkey.setPublicKey(kp.getPublic().getEncoded()); } else { Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?"); Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); } } else { PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray()); pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct)); pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED); pubkey.setPrivateKey(raw); } // write new value into database if (pubkeydb == null) pubkeydb = new PubkeyDatabase(this); pubkeydb.savePubkey(pubkey); updateList(); } catch(Exception e) { Log.e(TAG, "Problem parsing imported private key", e); Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show(); } } /** * */ private void pickFileSimple() { // build list of all files in sdcard root final File sdcard = Environment.getExternalStorageDirectory(); Log.d(TAG, sdcard.toString()); // Don't show a dialog if the SD card is completely absent. final String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) && !Environment.MEDIA_MOUNTED.equals(state)) { new AlertDialog.Builder(PubkeyListActivity.this) .setMessage(R.string.alert_sdcard_absent) .setNegativeButton(android.R.string.cancel, null).create().show(); return; } List<String> names = new LinkedList<String>(); { File[] files = sdcard.listFiles(); if (files != null) { for(File file : sdcard.listFiles()) { if(file.isDirectory()) continue; names.add(file.getName()); } } } Collections.sort(names); final String[] namesList = names.toArray(new String[] {}); Log.d(TAG, names.toString()); // prompt user to select any file from the sdcard root new AlertDialog.Builder(PubkeyListActivity.this) .setTitle(R.string.pubkey_list_pick) .setItems(namesList, new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { String name = namesList[arg1]; readKeyFromFile(new File(sdcard, name)); } }) .setNegativeButton(android.R.string.cancel, null).create().show(); } class PubkeyAdapter extends ArrayAdapter<PubkeyBean> { private List<PubkeyBean> pubkeys; class ViewHolder { public TextView nickname; public TextView caption; public ImageView icon; } public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) { super(context, R.layout.item_pubkey, pubkeys); this.pubkeys = pubkeys; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(R.layout.item_pubkey, null, false); holder = new ViewHolder(); holder.nickname = (TextView) convertView.findViewById(android.R.id.text1); holder.caption = (TextView) convertView.findViewById(android.R.id.text2); holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); PubkeyBean pubkey = pubkeys.get(position); holder.nickname.setText(pubkey.getNickname()); boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType()); if (imported) { try { PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray()); String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA"; holder.caption.setText(String.format("%s unknown-bit", type)); } catch (IOException e) { Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e); } } else { try { holder.caption.setText(pubkey.getDescription()); } catch (Exception e) { Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e); holder.caption.setText(R.string.pubkey_unknown_format); } } if (bound == null) { holder.icon.setVisibility(View.GONE); } else { holder.icon.setVisibility(View.VISIBLE); if (bound.isKeyLoaded(pubkey.getNickname())) holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true); else holder.icon.setImageState(new int[] { }, true); } return convertView; } } }
Fixing possible NPE in PubkeyListActivity
src/org/connectbot/PubkeyListActivity.java
Fixing possible NPE in PubkeyListActivity
<ide><path>rc/org/connectbot/PubkeyListActivity.java <ide> getListView().setOnItemClickListener(new OnItemClickListener() { <ide> public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { <ide> PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position); <del> boolean loaded = bound.isKeyLoaded(pubkey.getNickname()); <add> boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname()); <ide> <ide> // handle toggling key in-memory on/off <ide> if(loaded) { <ide> <ide> // cant change password or clipboard imported keys <ide> final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType()); <del> final boolean loaded = bound.isKeyLoaded(pubkey.getNickname()); <add> final boolean loaded = bound != null && bound.isKeyLoaded(pubkey.getNickname()); <ide> <ide> MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load); <ide> load.setOnMenuItemClickListener(new OnMenuItemClickListener() {
Java
lgpl-2.1
18410ac4449d846323de1a50a01e547bc2b9bf7b
0
davidB/yuicompressor-maven-plugin,davidB/yuicompressor-maven-plugin
package net_alchim31_maven_yuicompressor; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.IOUtil; public class Aggregation { public File inputDir; public File output; public String[] includes; public String[] excludes; public boolean removeIncluded = false; public boolean insertNewLine = false; public boolean insertFileHeader = false; public boolean fixLastSemicolon = false; public void run() throws Exception { defineInputDir(); List<File> files = getIncludedFiles(); if (files.size() != 0) { output = output.getCanonicalFile(); output.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(output); try { for (File file : files) { if (file.getCanonicalPath().equals(output.getCanonicalPath())) { continue; } FileInputStream in = new FileInputStream(file); try { if (insertFileHeader) { out.write(createFileHeader(file).getBytes()); } IOUtil.copy(in, out); if (fixLastSemicolon) { out.write(';'); } if (insertNewLine) { out.write('\n'); } } finally { IOUtil.close(in); in = null; } if (removeIncluded) { file.delete(); } } } finally { IOUtil.close(out); out = null; } } } private String createFileHeader(File file) { StringBuilder header = new StringBuilder(); header.append("/*"); header.append(file.getName()); header.append("*/"); if (insertNewLine) { header.append('\n'); } return header.toString(); } private void defineInputDir() throws Exception { if (inputDir == null) { inputDir = output.getParentFile(); } inputDir = inputDir.getCanonicalFile(); } private List<File> getIncludedFiles() throws Exception { ArrayList<File> back = new ArrayList<File>(); if (includes != null) { for (String include : includes) { addInto(include, back); } } return back; } private void addInto(String include, List<File> includedFiles) throws Exception { if (include.indexOf('*') > -1) { DirectoryScanner scanner = newScanner(); scanner.setIncludes(new String[] { include }); scanner.scan(); String[] rpaths = scanner.getIncludedFiles(); Arrays.sort(rpaths); for (String rpath : rpaths) { File file = new File(scanner.getBasedir(), rpath); if (!includedFiles.contains(file)) { includedFiles.add(file); } } } else { File file = new File(include); if (!file.isAbsolute()) { file = new File(inputDir, include); } if (!includedFiles.contains(file)) { includedFiles.add(file); } } } private DirectoryScanner newScanner() throws Exception { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(inputDir); if ((excludes != null) && (excludes.length != 0)) { scanner.setExcludes(excludes); } scanner.addDefaultExcludes(); return scanner; } }
src/main/java/net_alchim31_maven_yuicompressor/Aggregation.java
package net_alchim31_maven_yuicompressor; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.IOUtil; public class Aggregation { public File inputDir; public File output; public String[] includes; public String[] excludes; public boolean removeIncluded = false; public boolean insertNewLine = false; public boolean fixLastSemicolon = false; public void run() throws Exception { defineInputDir(); List<File> files = getIncludedFiles(); if (files.size() != 0) { output = output.getCanonicalFile(); output.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(output); try { for (File file : files) { if (file.getCanonicalPath().equals(output.getCanonicalPath())) { continue; } FileInputStream in = new FileInputStream(file); try { IOUtil.copy(in, out); if (fixLastSemicolon) { out.write(';'); } if (insertNewLine) { out.write('\n'); } } finally { IOUtil.close(in); in = null; } if (removeIncluded) { file.delete(); } } } finally { IOUtil.close(out); out = null; } } } private void defineInputDir() throws Exception { if (inputDir == null) { inputDir = output.getParentFile(); } inputDir = inputDir.getCanonicalFile(); } private List<File> getIncludedFiles() throws Exception { ArrayList<File> back = new ArrayList<File>(); if (includes != null) { for (String include : includes) { addInto(include, back); } } return back; } private void addInto(String include, List<File> includedFiles) throws Exception { if (include.indexOf('*') > -1) { DirectoryScanner scanner = newScanner(); scanner.setIncludes(new String[] { include }); scanner.scan(); String[] rpaths = scanner.getIncludedFiles(); Arrays.sort(rpaths); for (String rpath : rpaths) { File file = new File(scanner.getBasedir(), rpath); if (!includedFiles.contains(file)) { includedFiles.add(file); } } } else { File file = new File(include); if (!file.isAbsolute()) { file = new File(inputDir, include); } if (!includedFiles.contains(file)) { includedFiles.add(file); } } } private DirectoryScanner newScanner() throws Exception { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(inputDir); if ((excludes != null) && (excludes.length != 0)) { scanner.setExcludes(excludes); } scanner.addDefaultExcludes(); return scanner; } }
Add insertFileHeader parameter to Aggregation.
src/main/java/net_alchim31_maven_yuicompressor/Aggregation.java
Add insertFileHeader parameter to Aggregation.
<ide><path>rc/main/java/net_alchim31_maven_yuicompressor/Aggregation.java <ide> public String[] excludes; <ide> public boolean removeIncluded = false; <ide> public boolean insertNewLine = false; <add> public boolean insertFileHeader = false; <ide> public boolean fixLastSemicolon = false; <del> <add> <ide> public void run() throws Exception { <ide> defineInputDir(); <ide> List<File> files = getIncludedFiles(); <ide> } <ide> FileInputStream in = new FileInputStream(file); <ide> try { <add> if (insertFileHeader) { <add> out.write(createFileHeader(file).getBytes()); <add> } <ide> IOUtil.copy(in, out); <ide> if (fixLastSemicolon) { <del> out.write(';'); <add> out.write(';'); <ide> } <ide> if (insertNewLine) { <ide> out.write('\n'); <ide> } <ide> } <ide> <add> private String createFileHeader(File file) { <add> StringBuilder header = new StringBuilder(); <add> header.append("/*"); <add> header.append(file.getName()); <add> header.append("*/"); <add> <add> if (insertNewLine) { <add> header.append('\n'); <add> } <add> <add> return header.toString(); <add> } <add> <ide> private void defineInputDir() throws Exception { <ide> if (inputDir == null) { <ide> inputDir = output.getParentFile(); <ide> } <ide> inputDir = inputDir.getCanonicalFile(); <ide> } <del> <add> <ide> private List<File> getIncludedFiles() throws Exception { <ide> ArrayList<File> back = new ArrayList<File>(); <ide> if (includes != null) {
Java
apache-2.0
f623a900d67da3b1595c17aa5074f28d04df67d9
0
kevinmdavis/cloud-trace-java,erikmcc/cloud-trace-java,GoogleCloudPlatform/cloud-trace-java
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.cloud.trace.util; import java.security.SecureRandom; /** * An factory for generating span identifiers. This factory uses a {@link SecureRandom} to produce * span identifiers. * * @see AbstractSpanIdFactory * @see IdFactory * @see SecureRandom * @see SpanId */ public class RandomSpanIdFactory extends AbstractSpanIdFactory { private final SecureRandom random; /** * Creates a new span identifier factory. This constructor generates a {@code SecureRandom} using * a default seed. */ public RandomSpanIdFactory() { this.random = new SecureRandom(); } /** * Creates a new span identifier factory. This constructor generates a {@code SecureRandom} using * the given seed. * * @param seed a byte array used as the seed. */ public RandomSpanIdFactory(byte[] seed) { this.random = new SecureRandom(seed); } /** * Creates a new span identifier factory. * * @param random a secure random used to generate span identifiers. */ public RandomSpanIdFactory(SecureRandom random) { this.random = random; } /** * Generates a new span identifier. * * @return the new span identifier. */ @Override public SpanId nextId() { return new SpanId(random.nextLong()); } }
sdk/core/src/main/java/com/google/cloud/trace/util/RandomSpanIdFactory.java
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.cloud.trace.util; import java.security.SecureRandom; /** * An factory for generating span identifiers. This factory uses a {@link SecureRandom} to produce * span identifiers. * * @see AbstractSpanIdFactory * @see IdFactory * @see SecureRandom * @see SpanId */ public class RandomSpanIdFactory extends AbstractSpanIdFactory { private static final int SPAN_ID_BIT_LENGTH = 64; private final SecureRandom random; /** * Creates a new span identifier factory. This constructor generates a {@code SecureRandom} using * a default seed. */ public RandomSpanIdFactory() { this.random = new SecureRandom(); } /** * Creates a new span identifier factory. This constructor generates a {@code SecureRandom} using * the given seed. * * @param seed a byte array used as the seed. */ public RandomSpanIdFactory(byte[] seed) { this.random = new SecureRandom(seed); } /** * Creates a new span identifier factory. * * @param random a secure random used to generate span identifiers. */ public RandomSpanIdFactory(SecureRandom random) { this.random = random; } /** * Generates a new span identifier. * * @return the new span identifier. */ @Override public SpanId nextId() { return new SpanId(random.nextLong()); } }
Cleanup unused const.
sdk/core/src/main/java/com/google/cloud/trace/util/RandomSpanIdFactory.java
Cleanup unused const.
<ide><path>dk/core/src/main/java/com/google/cloud/trace/util/RandomSpanIdFactory.java <ide> * @see SpanId <ide> */ <ide> public class RandomSpanIdFactory extends AbstractSpanIdFactory { <del> private static final int SPAN_ID_BIT_LENGTH = 64; <del> <ide> private final SecureRandom random; <ide> <ide> /**
Java
agpl-3.0
1ebef532284e2811fa5ddc2ce50dc5de4c8ac30e
0
jar1karp/rstudio,edrogers/rstudio,sfloresm/rstudio,sfloresm/rstudio,thklaus/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,pssguy/rstudio,pssguy/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,sfloresm/rstudio,edrogers/rstudio,sfloresm/rstudio,JanMarvin/rstudio,pssguy/rstudio,JanMarvin/rstudio,jrnold/rstudio,tbarrongh/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,jar1karp/rstudio,brsimioni/rstudio,thklaus/rstudio,pssguy/rstudio,brsimioni/rstudio,more1/rstudio,jar1karp/rstudio,vbelakov/rstudio,jar1karp/rstudio,more1/rstudio,brsimioni/rstudio,jzhu8803/rstudio,jar1karp/rstudio,vbelakov/rstudio,JanMarvin/rstudio,suribes/rstudio,thklaus/rstudio,brsimioni/rstudio,jrnold/rstudio,vbelakov/rstudio,sfloresm/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,suribes/rstudio,edrogers/rstudio,jar1karp/rstudio,thklaus/rstudio,JanMarvin/rstudio,suribes/rstudio,jar1karp/rstudio,edrogers/rstudio,more1/rstudio,john-r-mcpherson/rstudio,tbarrongh/rstudio,pssguy/rstudio,githubfun/rstudio,jzhu8803/rstudio,piersharding/rstudio,sfloresm/rstudio,john-r-mcpherson/rstudio,more1/rstudio,vbelakov/rstudio,jrnold/rstudio,pssguy/rstudio,suribes/rstudio,pssguy/rstudio,jar1karp/rstudio,jzhu8803/rstudio,edrogers/rstudio,jzhu8803/rstudio,jzhu8803/rstudio,JanMarvin/rstudio,githubfun/rstudio,jar1karp/rstudio,piersharding/rstudio,jrnold/rstudio,jrnold/rstudio,githubfun/rstudio,tbarrongh/rstudio,suribes/rstudio,piersharding/rstudio,jrnold/rstudio,suribes/rstudio,vbelakov/rstudio,edrogers/rstudio,more1/rstudio,brsimioni/rstudio,tbarrongh/rstudio,pssguy/rstudio,JanMarvin/rstudio,sfloresm/rstudio,john-r-mcpherson/rstudio,thklaus/rstudio,more1/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,jzhu8803/rstudio,vbelakov/rstudio,tbarrongh/rstudio,githubfun/rstudio,sfloresm/rstudio,jzhu8803/rstudio,githubfun/rstudio,githubfun/rstudio,thklaus/rstudio,brsimioni/rstudio,jrnold/rstudio,githubfun/rstudio,more1/rstudio,jzhu8803/rstudio,thklaus/rstudio,githubfun/rstudio,piersharding/rstudio,thklaus/rstudio,piersharding/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,piersharding/rstudio,suribes/rstudio,piersharding/rstudio,jrnold/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,john-r-mcpherson/rstudio,vbelakov/rstudio,piersharding/rstudio,brsimioni/rstudio,vbelakov/rstudio,more1/rstudio
/* * DocTabLayoutPanel.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.theme; import org.rstudio.core.client.Debug; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.DomUtils.NodePredicate; import org.rstudio.core.client.events.HasTabCloseHandlers; import org.rstudio.core.client.events.HasTabClosedHandlers; import org.rstudio.core.client.events.HasTabClosingHandlers; import org.rstudio.core.client.events.HasTabReorderHandlers; import org.rstudio.core.client.events.TabCloseEvent; import org.rstudio.core.client.events.TabCloseHandler; import org.rstudio.core.client.events.TabClosedEvent; import org.rstudio.core.client.events.TabClosedHandler; import org.rstudio.core.client.events.TabClosingEvent; import org.rstudio.core.client.events.TabClosingHandler; import org.rstudio.core.client.events.TabReorderEvent; import org.rstudio.core.client.events.TabReorderHandler; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Float; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.DragEvent; import com.google.gwt.event.dom.client.DragHandler; import com.google.gwt.event.dom.client.DragStartEvent; import com.google.gwt.event.dom.client.DragStartHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.EventListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.Widget; /** * A tab panel that is styled for document tabs. */ public class DocTabLayoutPanel extends TabLayoutPanel implements HasTabClosingHandlers, HasTabCloseHandlers, HasTabClosedHandlers, HasTabReorderHandlers { public interface TabCloseObserver { public void onTabClose(); } public interface TabMoveObserver { public void onTabMove(Widget tab, int oldPos, int newPos); } public DocTabLayoutPanel(boolean closeableTabs, int padding, int rightMargin) { super(BAR_HEIGHT, Style.Unit.PX); closeableTabs_ = closeableTabs; padding_ = padding; rightMargin_ = rightMargin; styles_ = ThemeResources.INSTANCE.themeStyles(); addStyleName(styles_.docTabPanel()); addStyleName(styles_.moduleTabPanel()); dragManager_ = new DragManager(); // sink drag-related events on the tab bar element; unfortunately // GWT does not provide bits for the drag-related events, and Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { Element tabBar = getTabBarElement(); DOM.sinkBitlessEvent(tabBar, "drag"); DOM.sinkBitlessEvent(tabBar, "dragstart"); DOM.sinkBitlessEvent(tabBar, "dragenter"); DOM.sinkBitlessEvent(tabBar, "dragover"); DOM.sinkBitlessEvent(tabBar, "drop"); Event.setEventListener(tabBar, dragManager_); } }); } @Override public void add(final Widget child, String text) { add(child, null, text, null); } public void add(final Widget child, ImageResource icon, final String text, String tooltip) { if (closeableTabs_) { DocTab tab = new DocTab(icon, text, tooltip, new TabCloseObserver() { public void onTabClose() { int index = getWidgetIndex(child); if (index >= 0) { tryCloseTab(index, null); } } }); super.add(child, tab); } else { super.add(child, text); } } public boolean tryCloseTab(int index, Command onClosed) { TabClosingEvent event = new TabClosingEvent(index); fireEvent(event); if (event.isCancelled()) return false; closeTab(index, onClosed); return true; } public void closeTab(int index, Command onClosed) { if (remove(index)) { if (onClosed != null) onClosed.execute(); } } @Override public void selectTab(int index) { super.selectTab(index); ensureSelectedTabIsVisible(true); } public void ensureSelectedTabIsVisible(boolean animate) { if (currentAnimation_ != null) { currentAnimation_.cancel(); currentAnimation_ = null; } Element selectedTab = (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTab-selected"); } }); if (selectedTab == null) { return; } selectedTab = selectedTab.getFirstChildElement() .getFirstChildElement(); Element tabBar = getTabBarElement(); if (!isVisible() || !isAttached() || tabBar.getOffsetWidth() == 0) return; // not yet loaded final Element tabBarParent = tabBar.getParentElement(); final int start = tabBarParent.getScrollLeft(); int end = DomUtils.ensureVisibleHoriz(tabBarParent, selectedTab, padding_, padding_ + rightMargin_, true); // When tabs are closed, the overall width shrinks, and this can lead // to cases where there's too much empty space on the screen Node lastTab = getLastChildElement(tabBar); if (lastTab == null || lastTab.getNodeType() != Node.ELEMENT_NODE) return; int edge = DomUtils.getRelativePosition(tabBarParent, Element.as(lastTab)).x + Element.as(lastTab).getOffsetWidth(); end = Math.min(end, Math.max(0, edge - (tabBarParent.getOffsetWidth() - rightMargin_))); if (edge <= tabBarParent.getOffsetWidth() - rightMargin_) end = 0; if (start != end) { if (!animate) { tabBarParent.setScrollLeft(end); } else { final int finalEnd = end; currentAnimation_ = new Animation() { @Override protected void onUpdate(double progress) { double delta = (finalEnd - start) * progress; tabBarParent.setScrollLeft((int) (start + delta)); } @Override protected void onComplete() { if (this == currentAnimation_) { tabBarParent.setScrollLeft(finalEnd); currentAnimation_ = null; } } }; currentAnimation_.run(Math.max(200, Math.min(1500, Math.abs(end - start)*2))); } } } @Override public void onResize() { super.onResize(); ensureSelectedTabIsVisible(false); } @Override public boolean remove(int index) { if ((index < 0) || (index >= getWidgetCount())) { return false; } fireEvent(new TabCloseEvent(index)); if (getSelectedIndex() == index) { boolean closingLastTab = index == getWidgetCount() - 1; int indexToSelect = closingLastTab ? index - 1 : index + 1; if (indexToSelect >= 0) selectTab(indexToSelect); } if (!super.remove(index)) return false; fireEvent(new TabClosedEvent(index)); ensureSelectedTabIsVisible(true); return true; } @Override public void add(Widget child, String text, boolean asHtml) { if (asHtml) throw new UnsupportedOperationException("HTML tab names not supported"); add(child, text); } @Override public void add(Widget child, Widget tab) { throw new UnsupportedOperationException("Not supported"); } private class DragManager implements EventListener { @Override public void onBrowserEvent(Event event) { Debug.devlog("got " + event.getType() + " @ " + event.getClientX() + ", " + event.getClientY()); if (event.getType() == "drag") { drag(event); } else if (event.getType() == "dragstart") { } else if (event.getType() == "dragenter") { event.preventDefault(); } else if (event.getType() == "dragover") { event.preventDefault(); } else if (event.getType() == "drop") { endDrag(event); } } public void beginDrag(DocTab srcTab, DragStartEvent evt) { // set drag element state dragging_ = true; dragElement_ = srcTab.getElement().getParentElement().getParentElement(); dragTabsHost_ = dragElement_.getParentElement(); dragScrollHost_ = dragTabsHost_.getParentElement(); outOfBounds_ = 0; candidatePos_ = 0; // find the current position of this tab among its siblings--we'll use // this later to determine whether to shift siblings left or right for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { Node node = dragTabsHost_.getChild(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (Element.as(node) == dragElement_) { candidatePos_ = i; destPos_ = i; } // the relative position of the last node determines how far we // can drag--add 10px so it stretches a little dragMax_ = DomUtils.leftRelativeTo(dragTabsHost_, Element.as(node)) + (Element.as(node).getClientWidth() - dragElement_.getClientWidth()) + 10; } } startPos_ = candidatePos_; // snap the element out of the tabset lastElementX_ = DomUtils.leftRelativeTo(dragTabsHost_, dragElement_); lastCursorX_= evt.getNativeEvent().getClientX(); dragElement_.getStyle().setPosition(Position.ABSOLUTE); dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); dragElement_.getStyle().setZIndex(100); DOM.setCapture(getElement()); // create the placeholder that shows where this tab will go when the // mouse is released dragPlaceholder_ = Document.get().createDivElement(); dragPlaceholder_.getStyle().setWidth(dragElement_.getClientWidth(), Unit.PX); dragPlaceholder_.getStyle().setHeight(2, Unit.PX); dragPlaceholder_.getStyle().setDisplay(Display.INLINE_BLOCK); dragPlaceholder_.getStyle().setPosition(Position.RELATIVE); dragPlaceholder_.getStyle().setFloat(Float.LEFT); dragTabsHost_.insertAfter(dragPlaceholder_, dragElement_); } private void drag(Event evt) { int offset = evt.getClientX() - lastCursorX_; lastCursorX_ = evt.getClientX(); // cursor is outside the tab area if (outOfBounds_ != 0) { // did the cursor move back in bounds? if (outOfBounds_ + offset > 0 != outOfBounds_ > 0) { outOfBounds_ = 0; offset = outOfBounds_ + offset; } else { // cursor is still out of bounds outOfBounds_ += offset; return; } } int targetLeft = lastElementX_ + offset; int targetRight = targetLeft + dragElement_.getClientWidth(); int scrollLeft = dragScrollHost_.getScrollLeft(); if (targetLeft < 0) { // dragged past the beginning - lock to beginning targetLeft = 0; outOfBounds_ += offset; } else if (targetLeft > dragMax_) { // dragged past the end - lock to the end targetLeft = dragMax_; outOfBounds_ += offset; } if (targetLeft - scrollLeft < SCROLL_THRESHOLD && scrollLeft > 0) { // dragged past scroll threshold, to the left--autoscroll outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD; targetLeft = scrollLeft + SCROLL_THRESHOLD; Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(-1); } }, 5); } else if (targetRight + SCROLL_THRESHOLD > scrollLeft + dragScrollHost_.getClientWidth() && scrollLeft < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth()) { // dragged past scroll threshold, to the right--autoscroll outOfBounds_ = (targetRight + SCROLL_THRESHOLD) - (scrollLeft + dragScrollHost_.getClientWidth()); targetLeft = scrollLeft + dragScrollHost_.getClientWidth() - (dragElement_.getClientWidth() + SCROLL_THRESHOLD); Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(1); } }, 5); } commitPosition(targetLeft); } private void commitPosition(int pos) { lastElementX_ = pos; // move element to its new position dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); // check to see if we're overlapping with another tab for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { // skip non-element DOM nodes Node node = dragTabsHost_.getChild(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } // skip the element we're dragging and elements that are not tabs Element ele = (Element)node; if (ele == dragElement_ || ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0) { continue; } int left = DomUtils.leftRelativeTo(dragTabsHost_, ele); int right = left + ele.getClientWidth(); int minOverlap = Math.min(dragElement_.getClientWidth() / 2, ele.getClientWidth() / 2); // a little complicated: compute the number of overlapping pixels // with this element; if the overlap is more than half of our width // (or the width of the candidate), it's swapping time if (Math.min(lastElementX_ + dragElement_.getClientWidth(), right) - Math.max(lastElementX_, left) >= minOverlap) { dragTabsHost_.removeChild(dragPlaceholder_); if (candidatePos_ > i) { dragTabsHost_.insertBefore(dragPlaceholder_, ele); } else { dragTabsHost_.insertAfter(dragPlaceholder_, ele); } candidatePos_ = i; // account for the extra element when moving to the right of the // original location destPos_ = startPos_ <= candidatePos_ ? candidatePos_ - 1 : candidatePos_; } } } private boolean autoScroll(int dir) { // move while the mouse is still out of bounds if (dragging_ && outOfBounds_ != 0) { // if mouse is far out of bounds, use it to accelerate movement if (Math.abs(outOfBounds_) > 100) { dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75); } // move if there's moving to be done if (dir < 0 && lastElementX_ > 0 || dir > 0 && lastElementX_ < dragMax_) { commitPosition(lastElementX_ + dir); // scroll if there's scrolling to be done int left = dragScrollHost_.getScrollLeft(); if ((dir < 0 && left > 0) || (dir > 0 && left < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth())) { dragScrollHost_.setScrollLeft(left + dir); } } return true; } return false; } private void endDrag(final Event evt) { // remove the properties used to position for dragging dragElement_.getStyle().clearLeft(); dragElement_.getStyle().clearPosition(); dragElement_.getStyle().clearZIndex(); // insert this tab where the placeholder landed dragTabsHost_.removeChild(dragElement_); dragTabsHost_.insertAfter(dragElement_, dragPlaceholder_); dragTabsHost_.removeChild(dragPlaceholder_); // finish dragging DOM.releaseCapture(getElement()); dragging_ = false; // unsink mousedown/mouseup and simulate a click to activate the tab simulateClick(evt); // let observer know we moved; adjust the destination position one to // the left if we're right of the start position to account for the // position of the tab prior to movement if (startPos_ != destPos_) { TabReorderEvent event = new TabReorderEvent(startPos_, destPos_); fireEvent(event); } } private void simulateClick(Event evt) { /* DomEvent.fireNativeEvent(Document.get().createClickEvent(0, evt.getScreenX(), evt.getScreenY(), evt.getClientX(), evt.getClientY(), evt.getCtrlKey(), evt.getAltKey(), evt.getShiftKey(), evt.getMetaKey()), this.getParent()); */ } private boolean dragging_ = false; private int lastCursorX_ = 0; private int lastElementX_ = 0; private int startPos_ = 0; private int candidatePos_ = 0; private int destPos_ = 0; private int dragMax_ = 0; private int outOfBounds_ = 0; private Element dragElement_; private Element dragTabsHost_; private Element dragScrollHost_; private Element dragPlaceholder_; private final static int SCROLL_THRESHOLD = 25; } private class DocTab extends Composite { private DocTab(ImageResource icon, String title, String tooltip, TabCloseObserver closeHandler) { HorizontalPanel layoutPanel = new HorizontalPanel(); layoutPanel.setStylePrimaryName(styles_.tabLayout()); layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM); layoutPanel.getElement().setDraggable("true"); final DocTab tab = this; layoutPanel.addDomHandler(new DragStartHandler() { @Override public void onDragStart(DragStartEvent evt) { evt.setData("text", "foo"); dragManager_.beginDrag(tab, evt); } }, DragStartEvent.getType()); HTML left = new HTML(); left.setStylePrimaryName(styles_.tabLayoutLeft()); layoutPanel.add(left); contentPanel_ = new HorizontalPanel(); contentPanel_.setTitle(tooltip); contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter()); contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); if (icon != null) contentPanel_.add(imageForIcon(icon)); label_ = new Label(title, false); label_.addStyleName(styles_.docTabLabel()); contentPanel_.add(label_); appendDirtyMarker(); Image img = new Image(ThemeResources.INSTANCE.closeTab()); img.setStylePrimaryName(styles_.closeTabButton()); img.addStyleName(ThemeStyles.INSTANCE.handCursor()); contentPanel_.add(img); layoutPanel.add(contentPanel_); HTML right = new HTML(); right.setStylePrimaryName(styles_.tabLayoutRight()); layoutPanel.add(right); initWidget(layoutPanel); this.sinkEvents(Event.ONMOUSEMOVE | Event.ONMOUSEUP | Event.ONLOSECAPTURE); closeHandler_ = closeHandler; closeElement_ = img.getElement(); } private void appendDirtyMarker() { Label marker = new Label("*"); marker.setStyleName(styles_.dirtyTabIndicator()); contentPanel_.insert(marker, 2); } public void replaceTitle(String title) { label_.setText(title); } public void replaceTooltip(String tooltip) { contentPanel_.setTitle(tooltip); } public void replaceIcon(ImageResource icon) { if (contentPanel_.getWidget(0) instanceof Image) contentPanel_.remove(0); contentPanel_.insert(imageForIcon(icon), 0); } private Image imageForIcon(ImageResource icon) { Image image = new Image(icon); image.setStylePrimaryName(styles_.docTabIcon()); return image; } @Override public void onBrowserEvent(Event event) { switch(DOM.eventGetType(event)) { case Event.ONMOUSEUP: { // middlemouse should close a tab if (event.getButton() == Event.BUTTON_MIDDLE) { event.stopPropagation(); event.preventDefault(); closeHandler_.onTabClose(); break; } // note: fallthrough } case Event.ONLOSECAPTURE: { if (Element.as(event.getEventTarget()) == closeElement_) { // handle click on close button closeHandler_.onTabClose(); } event.preventDefault(); event.stopPropagation(); break; } } super.onBrowserEvent(event); } private TabCloseObserver closeHandler_; private Element closeElement_; private final Label label_; private final HorizontalPanel contentPanel_; } public void replaceDocName(int index, ImageResource icon, String title, String tooltip) { DocTab tab = (DocTab) getTabWidget(index); tab.replaceIcon(icon); tab.replaceTitle(title); tab.replaceTooltip(tooltip); } public HandlerRegistration addTabClosingHandler(TabClosingHandler handler) { return addHandler(handler, TabClosingEvent.TYPE); } @Override public HandlerRegistration addTabCloseHandler( TabCloseHandler handler) { return addHandler(handler, TabCloseEvent.TYPE); } public HandlerRegistration addTabClosedHandler(TabClosedHandler handler) { return addHandler(handler, TabClosedEvent.TYPE); } @Override public HandlerRegistration addTabReorderHandler(TabReorderHandler handler) { return addHandler(handler, TabReorderEvent.TYPE); } public int getTabsEffectiveWidth() { if (getWidgetCount() == 0) return 0; Element parent = getTabBarElement(); if (parent == null) { return 0; } Element lastChild = getLastChildElement(parent); if (lastChild == null) { return 0; } return lastChild.getOffsetLeft() + lastChild.getOffsetWidth(); } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); } private Element getTabBarElement() { return (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTabs"); } }); } private Element getLastChildElement(Element parent) { Node lastTab = parent.getLastChild(); while (lastTab.getNodeType() != Node.ELEMENT_NODE) { lastTab = lastTab.getPreviousSibling(); } return Element.as(lastTab); } public static final int BAR_HEIGHT = 24; private final boolean closeableTabs_; private int padding_; private int rightMargin_; private final ThemeStyles styles_; private Animation currentAnimation_; private DragManager dragManager_; }
src/gwt/src/org/rstudio/core/client/theme/DocTabLayoutPanel.java
/* * DocTabLayoutPanel.java * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.theme; import org.rstudio.core.client.Debug; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.DomUtils.NodePredicate; import org.rstudio.core.client.events.HasTabCloseHandlers; import org.rstudio.core.client.events.HasTabClosedHandlers; import org.rstudio.core.client.events.HasTabClosingHandlers; import org.rstudio.core.client.events.HasTabReorderHandlers; import org.rstudio.core.client.events.TabCloseEvent; import org.rstudio.core.client.events.TabCloseHandler; import org.rstudio.core.client.events.TabClosedEvent; import org.rstudio.core.client.events.TabClosedHandler; import org.rstudio.core.client.events.TabClosingEvent; import org.rstudio.core.client.events.TabClosingHandler; import org.rstudio.core.client.events.TabReorderEvent; import org.rstudio.core.client.events.TabReorderHandler; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Float; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.DomEvent; import com.google.gwt.event.dom.client.DragEnterEvent; import com.google.gwt.event.dom.client.DragEnterHandler; import com.google.gwt.event.dom.client.DragEvent; import com.google.gwt.event.dom.client.DragHandler; import com.google.gwt.event.dom.client.DragOverEvent; import com.google.gwt.event.dom.client.DragOverHandler; import com.google.gwt.event.dom.client.DragStartEvent; import com.google.gwt.event.dom.client.DragStartHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.Widget; /** * A tab panel that is styled for document tabs. */ public class DocTabLayoutPanel extends TabLayoutPanel implements HasTabClosingHandlers, HasTabCloseHandlers, HasTabClosedHandlers, HasTabReorderHandlers { public interface TabCloseObserver { public void onTabClose(); } public interface TabMoveObserver { public void onTabMove(Widget tab, int oldPos, int newPos); } public DocTabLayoutPanel(boolean closeableTabs, int padding, int rightMargin) { super(BAR_HEIGHT, Style.Unit.PX); closeableTabs_ = closeableTabs; padding_ = padding; rightMargin_ = rightMargin; styles_ = ThemeResources.INSTANCE.themeStyles(); addStyleName(styles_.docTabPanel()); addStyleName(styles_.moduleTabPanel()); Element tabBar = getTabBarElement(); DOM.sinkBitlessEvent(tabBar, "drag"); DOM.sinkBitlessEvent(tabBar, "dragstart"); DOM.sinkBitlessEvent(tabBar, "dragenter"); DOM.sinkBitlessEvent(tabBar, "dragover"); DOM.sinkBitlessEvent(tabBar, "drop"); } @Override public void add(final Widget child, String text) { add(child, null, text, null); } public void add(final Widget child, ImageResource icon, final String text, String tooltip) { if (closeableTabs_) { DocTab tab = new DocTab(icon, text, tooltip, new TabCloseObserver() { public void onTabClose() { int index = getWidgetIndex(child); if (index >= 0) { tryCloseTab(index, null); } } }, new TabMoveObserver() { @Override public void onTabMove(Widget tab, int oldPos, int newPos) { TabReorderEvent event = new TabReorderEvent(oldPos, newPos); fireEvent(event); } }); super.add(child, tab); } else { super.add(child, text); } } public boolean tryCloseTab(int index, Command onClosed) { TabClosingEvent event = new TabClosingEvent(index); fireEvent(event); if (event.isCancelled()) return false; closeTab(index, onClosed); return true; } public void closeTab(int index, Command onClosed) { if (remove(index)) { if (onClosed != null) onClosed.execute(); } } @Override public void selectTab(int index) { super.selectTab(index); ensureSelectedTabIsVisible(true); } public void ensureSelectedTabIsVisible(boolean animate) { if (currentAnimation_ != null) { currentAnimation_.cancel(); currentAnimation_ = null; } Element selectedTab = (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTab-selected"); } }); if (selectedTab == null) { return; } selectedTab = selectedTab.getFirstChildElement() .getFirstChildElement(); Element tabBar = getTabBarElement(); if (!isVisible() || !isAttached() || tabBar.getOffsetWidth() == 0) return; // not yet loaded final Element tabBarParent = tabBar.getParentElement(); final int start = tabBarParent.getScrollLeft(); int end = DomUtils.ensureVisibleHoriz(tabBarParent, selectedTab, padding_, padding_ + rightMargin_, true); // When tabs are closed, the overall width shrinks, and this can lead // to cases where there's too much empty space on the screen Node lastTab = getLastChildElement(tabBar); if (lastTab == null || lastTab.getNodeType() != Node.ELEMENT_NODE) return; int edge = DomUtils.getRelativePosition(tabBarParent, Element.as(lastTab)).x + Element.as(lastTab).getOffsetWidth(); end = Math.min(end, Math.max(0, edge - (tabBarParent.getOffsetWidth() - rightMargin_))); if (edge <= tabBarParent.getOffsetWidth() - rightMargin_) end = 0; if (start != end) { if (!animate) { tabBarParent.setScrollLeft(end); } else { final int finalEnd = end; currentAnimation_ = new Animation() { @Override protected void onUpdate(double progress) { double delta = (finalEnd - start) * progress; tabBarParent.setScrollLeft((int) (start + delta)); } @Override protected void onComplete() { if (this == currentAnimation_) { tabBarParent.setScrollLeft(finalEnd); currentAnimation_ = null; } } }; currentAnimation_.run(Math.max(200, Math.min(1500, Math.abs(end - start)*2))); } } } @Override public void onResize() { super.onResize(); ensureSelectedTabIsVisible(false); } @Override public boolean remove(int index) { if ((index < 0) || (index >= getWidgetCount())) { return false; } fireEvent(new TabCloseEvent(index)); if (getSelectedIndex() == index) { boolean closingLastTab = index == getWidgetCount() - 1; int indexToSelect = closingLastTab ? index - 1 : index + 1; if (indexToSelect >= 0) selectTab(indexToSelect); } if (!super.remove(index)) return false; fireEvent(new TabClosedEvent(index)); ensureSelectedTabIsVisible(true); return true; } @Override public void add(Widget child, String text, boolean asHtml) { if (asHtml) throw new UnsupportedOperationException("HTML tab names not supported"); add(child, text); } @Override public void add(Widget child, Widget tab) { throw new UnsupportedOperationException("Not supported"); } private class DocTab extends Composite { private DocTab(ImageResource icon, String title, String tooltip, TabCloseObserver closeHandler, TabMoveObserver moveHandler) { HorizontalPanel layoutPanel = new HorizontalPanel(); layoutPanel.setStylePrimaryName(styles_.tabLayout()); layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM); layoutPanel.getElement().setDraggable("true"); layoutPanel.addDomHandler(new DragStartHandler() { @Override public void onDragStart(DragStartEvent evt) { evt.setData("text", "foo"); beginDrag(evt); } }, DragStartEvent.getType()); layoutPanel.addDomHandler(new DragHandler() { @Override public void onDrag(DragEvent evt) { drag(evt); } }, DragEvent.getType()); HTML left = new HTML(); left.setStylePrimaryName(styles_.tabLayoutLeft()); layoutPanel.add(left); contentPanel_ = new HorizontalPanel(); contentPanel_.setTitle(tooltip); contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter()); contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); if (icon != null) contentPanel_.add(imageForIcon(icon)); label_ = new Label(title, false); label_.addStyleName(styles_.docTabLabel()); contentPanel_.add(label_); appendDirtyMarker(); Image img = new Image(ThemeResources.INSTANCE.closeTab()); img.setStylePrimaryName(styles_.closeTabButton()); img.addStyleName(ThemeStyles.INSTANCE.handCursor()); contentPanel_.add(img); layoutPanel.add(contentPanel_); HTML right = new HTML(); right.setStylePrimaryName(styles_.tabLayoutRight()); layoutPanel.add(right); initWidget(layoutPanel); this.sinkEvents(Event.ONMOUSEMOVE | Event.ONMOUSEUP | Event.ONLOSECAPTURE); closeHandler_ = closeHandler; moveHandler_ = moveHandler; closeElement_ = img.getElement(); } private void appendDirtyMarker() { Label marker = new Label("*"); marker.setStyleName(styles_.dirtyTabIndicator()); contentPanel_.insert(marker, 2); } public void replaceTitle(String title) { label_.setText(title); } public void replaceTooltip(String tooltip) { contentPanel_.setTitle(tooltip); } public void replaceIcon(ImageResource icon) { if (contentPanel_.getWidget(0) instanceof Image) contentPanel_.remove(0); contentPanel_.insert(imageForIcon(icon), 0); } private Image imageForIcon(ImageResource icon) { Image image = new Image(icon); image.setStylePrimaryName(styles_.docTabIcon()); return image; } @Override public void onBrowserEvent(Event event) { switch(DOM.eventGetType(event)) { case Event.ONMOUSEUP: { // middlemouse should close a tab if (event.getButton() == Event.BUTTON_MIDDLE) { event.stopPropagation(); event.preventDefault(); closeHandler_.onTabClose(); break; } // note: fallthrough } case Event.ONLOSECAPTURE: { if (Element.as(event.getEventTarget()) == closeElement_) { // handle click on close button closeHandler_.onTabClose(); } else if (dragging_) { // complete dragging endDrag(event); } event.preventDefault(); event.stopPropagation(); break; } } super.onBrowserEvent(event); } public void beginDrag(DragStartEvent evt) { // set drag element state dragging_ = true; dragElement_ = getElement().getParentElement().getParentElement(); dragTabsHost_ = dragElement_.getParentElement(); dragScrollHost_ = dragTabsHost_.getParentElement(); outOfBounds_ = 0; candidatePos_ = 0; // find the current position of this tab among its siblings--we'll use // this later to determine whether to shift siblings left or right for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { Node node = dragTabsHost_.getChild(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (Element.as(node) == dragElement_) { candidatePos_ = i; destPos_ = i; } // the relative position of the last node determines how far we // can drag--add 10px so it stretches a little dragMax_ = DomUtils.leftRelativeTo(dragTabsHost_, Element.as(node)) + (Element.as(node).getClientWidth() - dragElement_.getClientWidth()) + 10; } } startPos_ = candidatePos_; // snap the element out of the tabset lastElementX_ = DomUtils.leftRelativeTo(dragTabsHost_, dragElement_); lastCursorX_= evt.getNativeEvent().getClientX(); dragElement_.getStyle().setPosition(Position.ABSOLUTE); dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); dragElement_.getStyle().setZIndex(100); DOM.setCapture(getElement()); // create the placeholder that shows where this tab will go when the // mouse is released dragPlaceholder_ = Document.get().createDivElement(); dragPlaceholder_.getStyle().setWidth(dragElement_.getClientWidth(), Unit.PX); dragPlaceholder_.getStyle().setHeight(2, Unit.PX); dragPlaceholder_.getStyle().setDisplay(Display.INLINE_BLOCK); dragPlaceholder_.getStyle().setPosition(Position.RELATIVE); dragPlaceholder_.getStyle().setFloat(Float.LEFT); dragTabsHost_.insertAfter(dragPlaceholder_, dragElement_); } private void endDrag(final Event evt) { // remove the properties used to position for dragging dragElement_.getStyle().clearLeft(); dragElement_.getStyle().clearPosition(); dragElement_.getStyle().clearZIndex(); // insert this tab where the placeholder landed dragTabsHost_.removeChild(dragElement_); dragTabsHost_.insertAfter(dragElement_, dragPlaceholder_); dragTabsHost_.removeChild(dragPlaceholder_); // finish dragging DOM.releaseCapture(getElement()); dragging_ = false; // unsink mousedown/mouseup and simulate a click to activate the tab simulateClick(evt); // let observer know we moved; adjust the destination position one to // the left if we're right of the start position to account for the // position of the tab prior to movement if (startPos_ != destPos_) { moveHandler_.onTabMove(this, startPos_, destPos_); } } private void simulateClick(Event evt) { this.unsinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP); DomEvent.fireNativeEvent(Document.get().createClickEvent(0, evt.getScreenX(), evt.getScreenY(), evt.getClientX(), evt.getClientY(), evt.getCtrlKey(), evt.getAltKey(), evt.getShiftKey(), evt.getMetaKey()), this.getParent()); this.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP); } private boolean autoScroll(int dir) { // move while the mouse is still out of bounds if (dragging_ && outOfBounds_ != 0) { // if mouse is far out of bounds, use it to accelerate movement if (Math.abs(outOfBounds_) > 100) { dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75); } // move if there's moving to be done if (dir < 0 && lastElementX_ > 0 || dir > 0 && lastElementX_ < dragMax_) { commitPosition(lastElementX_ + dir); // scroll if there's scrolling to be done int left = dragScrollHost_.getScrollLeft(); if ((dir < 0 && left > 0) || (dir > 0 && left < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth())) { dragScrollHost_.setScrollLeft(left + dir); } } return true; } return false; } private void drag(DragEvent evt) { int offset = evt.getNativeEvent().getClientX() - lastCursorX_; lastCursorX_ = evt.getNativeEvent().getClientX(); // cursor is outside the tab area if (outOfBounds_ != 0) { // did the cursor move back in bounds? if (outOfBounds_ + offset > 0 != outOfBounds_ > 0) { outOfBounds_ = 0; offset = outOfBounds_ + offset; } else { // cursor is still out of bounds outOfBounds_ += offset; return; } } int targetLeft = lastElementX_ + offset; int targetRight = targetLeft + dragElement_.getClientWidth(); int scrollLeft = dragScrollHost_.getScrollLeft(); if (targetLeft < 0) { // dragged past the beginning - lock to beginning targetLeft = 0; outOfBounds_ += offset; } else if (targetLeft > dragMax_) { // dragged past the end - lock to the end targetLeft = dragMax_; outOfBounds_ += offset; } if (targetLeft - scrollLeft < SCROLL_THRESHOLD && scrollLeft > 0) { // dragged past scroll threshold, to the left--autoscroll outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD; targetLeft = scrollLeft + SCROLL_THRESHOLD; Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(-1); } }, 5); } else if (targetRight + SCROLL_THRESHOLD > scrollLeft + dragScrollHost_.getClientWidth() && scrollLeft < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth()) { // dragged past scroll threshold, to the right--autoscroll outOfBounds_ = (targetRight + SCROLL_THRESHOLD) - (scrollLeft + dragScrollHost_.getClientWidth()); targetLeft = scrollLeft + dragScrollHost_.getClientWidth() - (dragElement_.getClientWidth() + SCROLL_THRESHOLD); Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(1); } }, 5); } commitPosition(targetLeft); } private void commitPosition(int pos) { lastElementX_ = pos; // move element to its new position dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); // check to see if we're overlapping with another tab for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { // skip non-element DOM nodes Node node = dragTabsHost_.getChild(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } // skip the element we're dragging and elements that are not tabs Element ele = (Element)node; if (ele == dragElement_ || ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0) { continue; } int left = DomUtils.leftRelativeTo(dragTabsHost_, ele); int right = left + ele.getClientWidth(); int minOverlap = Math.min(dragElement_.getClientWidth() / 2, ele.getClientWidth() / 2); // a little complicated: compute the number of overlapping pixels // with this element; if the overlap is more than half of our width // (or the width of the candidate), it's swapping time if (Math.min(lastElementX_ + dragElement_.getClientWidth(), right) - Math.max(lastElementX_, left) >= minOverlap) { dragTabsHost_.removeChild(dragPlaceholder_); if (candidatePos_ > i) { dragTabsHost_.insertBefore(dragPlaceholder_, ele); } else { dragTabsHost_.insertAfter(dragPlaceholder_, ele); } candidatePos_ = i; // account for the extra element when moving to the right of the // original location destPos_ = startPos_ <= candidatePos_ ? candidatePos_ - 1 : candidatePos_; } } } private TabCloseObserver closeHandler_; private TabMoveObserver moveHandler_; private Element closeElement_; private boolean dragging_ = false; private int lastCursorX_ = 0; private int lastElementX_ = 0; private int startPos_ = 0; private int candidatePos_ = 0; private int destPos_ = 0; private int dragMax_ = 0; private int outOfBounds_ = 0; private Element dragElement_; private Element dragTabsHost_; private Element dragScrollHost_; private Element dragPlaceholder_; private final Label label_; private final static int SCROLL_THRESHOLD = 25; private final HorizontalPanel contentPanel_; } public void replaceDocName(int index, ImageResource icon, String title, String tooltip) { DocTab tab = (DocTab) getTabWidget(index); tab.replaceIcon(icon); tab.replaceTitle(title); tab.replaceTooltip(tooltip); } public HandlerRegistration addTabClosingHandler(TabClosingHandler handler) { return addHandler(handler, TabClosingEvent.TYPE); } @Override public HandlerRegistration addTabCloseHandler( TabCloseHandler handler) { return addHandler(handler, TabCloseEvent.TYPE); } public HandlerRegistration addTabClosedHandler(TabClosedHandler handler) { return addHandler(handler, TabClosedEvent.TYPE); } @Override public HandlerRegistration addTabReorderHandler(TabReorderHandler handler) { return addHandler(handler, TabReorderEvent.TYPE); } public int getTabsEffectiveWidth() { if (getWidgetCount() == 0) return 0; Element parent = getTabBarElement(); if (parent == null) { return 0; } Element lastChild = getLastChildElement(parent); if (lastChild == null) { return 0; } return lastChild.getOffsetLeft() + lastChild.getOffsetWidth(); } @Override public void onBrowserEvent(Event event) { Debug.devlog("got " + event.getType() + " @ " + event.getClientX() + ", " + event.getClientY()); if (event.getType() == "drag") { } else if (event.getType() == "dragstart") { } else if (event.getType() == "dragenter") { event.preventDefault(); } else if (event.getType() == "dragover") { event.preventDefault(); } else if (event.getType() == "drop") { } super.onBrowserEvent(event); } private Element getTabBarElement() { return (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTabs"); } }); } private Element getLastChildElement(Element parent) { Node lastTab = parent.getLastChild(); while (lastTab.getNodeType() != Node.ELEMENT_NODE) { lastTab = lastTab.getPreviousSibling(); } return Element.as(lastTab); } public static final int BAR_HEIGHT = 24; private final boolean closeableTabs_; private int padding_; private int rightMargin_; private final ThemeStyles styles_; private Animation currentAnimation_; }
use drag manager to encapsulate dragging state; terminate on drop
src/gwt/src/org/rstudio/core/client/theme/DocTabLayoutPanel.java
use drag manager to encapsulate dragging state; terminate on drop
<ide><path>rc/gwt/src/org/rstudio/core/client/theme/DocTabLayoutPanel.java <ide> import com.google.gwt.animation.client.Animation; <ide> import com.google.gwt.core.client.Scheduler; <ide> import com.google.gwt.core.client.Scheduler.RepeatingCommand; <add>import com.google.gwt.core.client.Scheduler.ScheduledCommand; <ide> import com.google.gwt.dom.client.Document; <ide> import com.google.gwt.dom.client.Element; <ide> import com.google.gwt.dom.client.Node; <ide> import com.google.gwt.dom.client.Style.Position; <ide> import com.google.gwt.dom.client.Style.Unit; <ide> import com.google.gwt.event.dom.client.DomEvent; <del>import com.google.gwt.event.dom.client.DragEnterEvent; <del>import com.google.gwt.event.dom.client.DragEnterHandler; <ide> import com.google.gwt.event.dom.client.DragEvent; <ide> import com.google.gwt.event.dom.client.DragHandler; <del>import com.google.gwt.event.dom.client.DragOverEvent; <del>import com.google.gwt.event.dom.client.DragOverHandler; <ide> import com.google.gwt.event.dom.client.DragStartEvent; <ide> import com.google.gwt.event.dom.client.DragStartHandler; <ide> import com.google.gwt.event.shared.HandlerRegistration; <ide> import com.google.gwt.user.client.Command; <ide> import com.google.gwt.user.client.DOM; <ide> import com.google.gwt.user.client.Event; <add>import com.google.gwt.user.client.EventListener; <ide> import com.google.gwt.user.client.ui.Composite; <ide> import com.google.gwt.user.client.ui.HTML; <ide> import com.google.gwt.user.client.ui.HasVerticalAlignment; <ide> { <ide> public void onTabMove(Widget tab, int oldPos, int newPos); <ide> } <del> <add> <ide> public DocTabLayoutPanel(boolean closeableTabs, <ide> int padding, <ide> int rightMargin) <ide> styles_ = ThemeResources.INSTANCE.themeStyles(); <ide> addStyleName(styles_.docTabPanel()); <ide> addStyleName(styles_.moduleTabPanel()); <add> dragManager_ = new DragManager(); <ide> <del> Element tabBar = getTabBarElement(); <del> DOM.sinkBitlessEvent(tabBar, "drag"); <del> DOM.sinkBitlessEvent(tabBar, "dragstart"); <del> DOM.sinkBitlessEvent(tabBar, "dragenter"); <del> DOM.sinkBitlessEvent(tabBar, "dragover"); <del> DOM.sinkBitlessEvent(tabBar, "drop"); <add> // sink drag-related events on the tab bar element; unfortunately <add> // GWT does not provide bits for the drag-related events, and <add> Scheduler.get().scheduleDeferred(new ScheduledCommand() <add> { <add> @Override <add> public void execute() <add> { <add> Element tabBar = getTabBarElement(); <add> DOM.sinkBitlessEvent(tabBar, "drag"); <add> DOM.sinkBitlessEvent(tabBar, "dragstart"); <add> DOM.sinkBitlessEvent(tabBar, "dragenter"); <add> DOM.sinkBitlessEvent(tabBar, "dragover"); <add> DOM.sinkBitlessEvent(tabBar, "drop"); <add> Event.setEventListener(tabBar, dragManager_); <add> } <add> }); <ide> } <ide> <ide> @Override <ide> { <ide> tryCloseTab(index, null); <ide> } <del> } <del> }, <del> new TabMoveObserver() <del> { <del> @Override <del> public void onTabMove(Widget tab, int oldPos, int newPos) <del> { <del> TabReorderEvent event = new TabReorderEvent(oldPos, newPos); <del> fireEvent(event); <ide> } <ide> }); <ide> super.add(child, tab); <ide> throw new UnsupportedOperationException("Not supported"); <ide> } <ide> <del> private class DocTab extends Composite <del> { <del> <del> private DocTab(ImageResource icon, <del> String title, <del> String tooltip, <del> TabCloseObserver closeHandler, <del> TabMoveObserver moveHandler) <del> { <del> HorizontalPanel layoutPanel = new HorizontalPanel(); <del> layoutPanel.setStylePrimaryName(styles_.tabLayout()); <del> layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM); <del> layoutPanel.getElement().setDraggable("true"); <del> layoutPanel.addDomHandler(new DragStartHandler() <del> { <del> @Override <del> public void onDragStart(DragStartEvent evt) <del> { <del> evt.setData("text", "foo"); <del> beginDrag(evt); <del> } <del> }, DragStartEvent.getType()); <del> layoutPanel.addDomHandler(new DragHandler() <del> { <del> <del> @Override <del> public void onDrag(DragEvent evt) <del> { <del> drag(evt); <del> } <del> }, DragEvent.getType()); <del> <del> HTML left = new HTML(); <del> left.setStylePrimaryName(styles_.tabLayoutLeft()); <del> layoutPanel.add(left); <del> <del> contentPanel_ = new HorizontalPanel(); <del> contentPanel_.setTitle(tooltip); <del> contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter()); <del> contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); <del> <del> if (icon != null) <del> contentPanel_.add(imageForIcon(icon)); <del> <del> label_ = new Label(title, false); <del> label_.addStyleName(styles_.docTabLabel()); <del> contentPanel_.add(label_); <del> <del> appendDirtyMarker(); <del> <del> Image img = new Image(ThemeResources.INSTANCE.closeTab()); <del> img.setStylePrimaryName(styles_.closeTabButton()); <del> img.addStyleName(ThemeStyles.INSTANCE.handCursor()); <del> contentPanel_.add(img); <del> <del> layoutPanel.add(contentPanel_); <del> <del> HTML right = new HTML(); <del> right.setStylePrimaryName(styles_.tabLayoutRight()); <del> layoutPanel.add(right); <del> <del> initWidget(layoutPanel); <del> <del> this.sinkEvents(Event.ONMOUSEMOVE | <del> Event.ONMOUSEUP | <del> Event.ONLOSECAPTURE); <del> closeHandler_ = closeHandler; <del> moveHandler_ = moveHandler; <del> closeElement_ = img.getElement(); <add> private class DragManager implements EventListener <add> { <add> @Override <add> public void onBrowserEvent(Event event) <add> { <add> Debug.devlog("got " + event.getType() + " @ " + event.getClientX() + ", " + event.getClientY()); <add> if (event.getType() == "drag") <add> { <add> drag(event); <add> } <add> else if (event.getType() == "dragstart") <add> { <add> } <add> else if (event.getType() == "dragenter") <add> { <add> event.preventDefault(); <add> } <add> else if (event.getType() == "dragover") <add> { <add> event.preventDefault(); <add> } <add> else if (event.getType() == "drop") <add> { <add> endDrag(event); <add> } <ide> } <ide> <del> private void appendDirtyMarker() <del> { <del> Label marker = new Label("*"); <del> marker.setStyleName(styles_.dirtyTabIndicator()); <del> contentPanel_.insert(marker, 2); <del> } <del> <del> public void replaceTitle(String title) <del> { <del> label_.setText(title); <del> } <del> <del> public void replaceTooltip(String tooltip) <del> { <del> contentPanel_.setTitle(tooltip); <del> } <del> <del> public void replaceIcon(ImageResource icon) <del> { <del> if (contentPanel_.getWidget(0) instanceof Image) <del> contentPanel_.remove(0); <del> contentPanel_.insert(imageForIcon(icon), 0); <del> } <del> <del> private Image imageForIcon(ImageResource icon) <del> { <del> Image image = new Image(icon); <del> image.setStylePrimaryName(styles_.docTabIcon()); <del> return image; <del> } <del> <del> @Override <del> public void onBrowserEvent(Event event) <del> { <del> switch(DOM.eventGetType(event)) <del> { <del> case Event.ONMOUSEUP: <del> { <del> // middlemouse should close a tab <del> if (event.getButton() == Event.BUTTON_MIDDLE) <del> { <del> event.stopPropagation(); <del> event.preventDefault(); <del> closeHandler_.onTabClose(); <del> break; <del> } <del> <del> // note: fallthrough <del> } <del> case Event.ONLOSECAPTURE: <del> { <del> if (Element.as(event.getEventTarget()) == closeElement_) <del> { <del> // handle click on close button <del> closeHandler_.onTabClose(); <del> } <del> else if (dragging_) <del> { <del> // complete dragging <del> endDrag(event); <del> } <del> event.preventDefault(); <del> event.stopPropagation(); <del> break; <del> } <del> } <del> super.onBrowserEvent(event); <del> } <del> <del> public void beginDrag(DragStartEvent evt) <add> public void beginDrag(DocTab srcTab, DragStartEvent evt) <ide> { <ide> // set drag element state <ide> dragging_ = true; <del> dragElement_ = getElement().getParentElement().getParentElement(); <add> dragElement_ = srcTab.getElement().getParentElement().getParentElement(); <ide> dragTabsHost_ = dragElement_.getParentElement(); <ide> dragScrollHost_ = dragTabsHost_.getParentElement(); <ide> outOfBounds_ = 0; <ide> dragPlaceholder_.getStyle().setPosition(Position.RELATIVE); <ide> dragPlaceholder_.getStyle().setFloat(Float.LEFT); <ide> dragTabsHost_.insertAfter(dragPlaceholder_, dragElement_); <add> } <add> <add> private void drag(Event evt) <add> { <add> int offset = evt.getClientX() - lastCursorX_; <add> lastCursorX_ = evt.getClientX(); <add> // cursor is outside the tab area <add> if (outOfBounds_ != 0) <add> { <add> // did the cursor move back in bounds? <add> if (outOfBounds_ + offset > 0 != outOfBounds_ > 0) <add> { <add> outOfBounds_ = 0; <add> offset = outOfBounds_ + offset; <add> } <add> else <add> { <add> // cursor is still out of bounds <add> outOfBounds_ += offset; <add> return; <add> } <add> } <add> int targetLeft = lastElementX_ + offset; <add> int targetRight = targetLeft + dragElement_.getClientWidth(); <add> int scrollLeft = dragScrollHost_.getScrollLeft(); <add> if (targetLeft < 0) <add> { <add> // dragged past the beginning - lock to beginning <add> targetLeft = 0; <add> outOfBounds_ += offset; <add> } <add> else if (targetLeft > dragMax_) <add> { <add> // dragged past the end - lock to the end <add> targetLeft = dragMax_; <add> outOfBounds_ += offset; <add> } <add> <add> if (targetLeft - scrollLeft < SCROLL_THRESHOLD && <add> scrollLeft > 0) <add> { <add> // dragged past scroll threshold, to the left--autoscroll <add> outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD; <add> targetLeft = scrollLeft + SCROLL_THRESHOLD; <add> Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() <add> { <add> @Override <add> public boolean execute() <add> { <add> return autoScroll(-1); <add> } <add> }, 5); <add> } <add> else if (targetRight + SCROLL_THRESHOLD > scrollLeft + <add> dragScrollHost_.getClientWidth() && <add> scrollLeft < dragScrollHost_.getScrollWidth() - <add> dragScrollHost_.getClientWidth()) <add> { <add> // dragged past scroll threshold, to the right--autoscroll <add> outOfBounds_ = (targetRight + SCROLL_THRESHOLD) - <add> (scrollLeft + dragScrollHost_.getClientWidth()); <add> targetLeft = scrollLeft + dragScrollHost_.getClientWidth() - <add> (dragElement_.getClientWidth() + SCROLL_THRESHOLD); <add> Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() <add> { <add> @Override <add> public boolean execute() <add> { <add> return autoScroll(1); <add> } <add> }, 5); <add> } <add> commitPosition(targetLeft); <add> } <add> <add> private void commitPosition(int pos) <add> { <add> lastElementX_ = pos; <add> <add> // move element to its new position <add> dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); <add> <add> // check to see if we're overlapping with another tab <add> for (int i = 0; i < dragTabsHost_.getChildCount(); i++) <add> { <add> // skip non-element DOM nodes <add> Node node = dragTabsHost_.getChild(i); <add> if (node.getNodeType() != Node.ELEMENT_NODE) <add> { <add> continue; <add> } <add> // skip the element we're dragging and elements that are not tabs <add> Element ele = (Element)node; <add> if (ele == dragElement_ || <add> ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0) <add> { <add> continue; <add> } <add> <add> int left = DomUtils.leftRelativeTo(dragTabsHost_, ele); <add> int right = left + ele.getClientWidth(); <add> int minOverlap = Math.min(dragElement_.getClientWidth() / 2, <add> ele.getClientWidth() / 2); <add> <add> // a little complicated: compute the number of overlapping pixels <add> // with this element; if the overlap is more than half of our width <add> // (or the width of the candidate), it's swapping time <add> if (Math.min(lastElementX_ + dragElement_.getClientWidth(), right) - <add> Math.max(lastElementX_, left) >= minOverlap) <add> { <add> dragTabsHost_.removeChild(dragPlaceholder_); <add> if (candidatePos_ > i) <add> { <add> dragTabsHost_.insertBefore(dragPlaceholder_, ele); <add> } <add> else <add> { <add> dragTabsHost_.insertAfter(dragPlaceholder_, ele); <add> } <add> candidatePos_ = i; <add> <add> // account for the extra element when moving to the right of the <add> // original location <add> destPos_ = startPos_ <= candidatePos_ ? <add> candidatePos_ - 1 : candidatePos_; <add> } <add> } <add> } <add> <add> private boolean autoScroll(int dir) <add> { <add> // move while the mouse is still out of bounds <add> if (dragging_ && outOfBounds_ != 0) <add> { <add> // if mouse is far out of bounds, use it to accelerate movement <add> if (Math.abs(outOfBounds_) > 100) <add> { <add> dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75); <add> } <add> // move if there's moving to be done <add> if (dir < 0 && lastElementX_ > 0 || <add> dir > 0 && lastElementX_ < dragMax_) <add> { <add> commitPosition(lastElementX_ + dir); <add> <add> // scroll if there's scrolling to be done <add> int left = dragScrollHost_.getScrollLeft(); <add> if ((dir < 0 && left > 0) || <add> (dir > 0 && left < dragScrollHost_.getScrollWidth() - <add> dragScrollHost_.getClientWidth())) <add> { <add> dragScrollHost_.setScrollLeft(left + dir); <add> } <add> } <add> return true; <add> } <add> return false; <ide> } <ide> <ide> private void endDrag(final Event evt) <ide> // position of the tab prior to movement <ide> if (startPos_ != destPos_) <ide> { <del> moveHandler_.onTabMove(this, startPos_, destPos_); <del> } <del> } <del> <add> TabReorderEvent event = new TabReorderEvent(startPos_, destPos_); <add> fireEvent(event); <add> } <add> } <add> <ide> private void simulateClick(Event evt) <ide> { <del> this.unsinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP); <add> /* <ide> DomEvent.fireNativeEvent(Document.get().createClickEvent(0, <ide> evt.getScreenX(), evt.getScreenY(), <ide> evt.getClientX(), evt.getClientY(), <ide> evt.getCtrlKey(), evt.getAltKey(), <ide> evt.getShiftKey(), evt.getMetaKey()), this.getParent()); <del> this.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP); <del> <add> */ <ide> } <ide> <del> private boolean autoScroll(int dir) <del> { <del> // move while the mouse is still out of bounds <del> if (dragging_ && outOfBounds_ != 0) <del> { <del> // if mouse is far out of bounds, use it to accelerate movement <del> if (Math.abs(outOfBounds_) > 100) <del> { <del> dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75); <del> } <del> // move if there's moving to be done <del> if (dir < 0 && lastElementX_ > 0 || <del> dir > 0 && lastElementX_ < dragMax_) <del> { <del> commitPosition(lastElementX_ + dir); <del> <del> // scroll if there's scrolling to be done <del> int left = dragScrollHost_.getScrollLeft(); <del> if ((dir < 0 && left > 0) || <del> (dir > 0 && left < dragScrollHost_.getScrollWidth() - <del> dragScrollHost_.getClientWidth())) <del> { <del> dragScrollHost_.setScrollLeft(left + dir); <del> } <del> } <del> return true; <del> } <del> return false; <del> } <del> <del> private void drag(DragEvent evt) <del> { <del> int offset = evt.getNativeEvent().getClientX() - lastCursorX_; <del> lastCursorX_ = evt.getNativeEvent().getClientX(); <del> // cursor is outside the tab area <del> if (outOfBounds_ != 0) <del> { <del> // did the cursor move back in bounds? <del> if (outOfBounds_ + offset > 0 != outOfBounds_ > 0) <del> { <del> outOfBounds_ = 0; <del> offset = outOfBounds_ + offset; <del> } <del> else <del> { <del> // cursor is still out of bounds <del> outOfBounds_ += offset; <del> return; <del> } <del> } <del> int targetLeft = lastElementX_ + offset; <del> int targetRight = targetLeft + dragElement_.getClientWidth(); <del> int scrollLeft = dragScrollHost_.getScrollLeft(); <del> if (targetLeft < 0) <del> { <del> // dragged past the beginning - lock to beginning <del> targetLeft = 0; <del> outOfBounds_ += offset; <del> } <del> else if (targetLeft > dragMax_) <del> { <del> // dragged past the end - lock to the end <del> targetLeft = dragMax_; <del> outOfBounds_ += offset; <del> } <del> if (targetLeft - scrollLeft < SCROLL_THRESHOLD && <del> scrollLeft > 0) <del> { <del> // dragged past scroll threshold, to the left--autoscroll <del> outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD; <del> targetLeft = scrollLeft + SCROLL_THRESHOLD; <del> Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() <del> { <del> @Override <del> public boolean execute() <del> { <del> return autoScroll(-1); <del> } <del> }, 5); <del> } <del> else if (targetRight + SCROLL_THRESHOLD > scrollLeft + <del> dragScrollHost_.getClientWidth() && <del> scrollLeft < dragScrollHost_.getScrollWidth() - <del> dragScrollHost_.getClientWidth()) <del> { <del> // dragged past scroll threshold, to the right--autoscroll <del> outOfBounds_ = (targetRight + SCROLL_THRESHOLD) - <del> (scrollLeft + dragScrollHost_.getClientWidth()); <del> targetLeft = scrollLeft + dragScrollHost_.getClientWidth() - <del> (dragElement_.getClientWidth() + SCROLL_THRESHOLD); <del> Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() <del> { <del> @Override <del> public boolean execute() <del> { <del> return autoScroll(1); <del> } <del> }, 5); <del> } <del> commitPosition(targetLeft); <del> } <del> <del> private void commitPosition(int pos) <del> { <del> lastElementX_ = pos; <del> <del> // move element to its new position <del> dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); <del> <del> // check to see if we're overlapping with another tab <del> for (int i = 0; i < dragTabsHost_.getChildCount(); i++) <del> { <del> // skip non-element DOM nodes <del> Node node = dragTabsHost_.getChild(i); <del> if (node.getNodeType() != Node.ELEMENT_NODE) <del> { <del> continue; <del> } <del> // skip the element we're dragging and elements that are not tabs <del> Element ele = (Element)node; <del> if (ele == dragElement_ || <del> ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0) <del> { <del> continue; <del> } <del> <del> int left = DomUtils.leftRelativeTo(dragTabsHost_, ele); <del> int right = left + ele.getClientWidth(); <del> int minOverlap = Math.min(dragElement_.getClientWidth() / 2, <del> ele.getClientWidth() / 2); <del> <del> // a little complicated: compute the number of overlapping pixels <del> // with this element; if the overlap is more than half of our width <del> // (or the width of the candidate), it's swapping time <del> if (Math.min(lastElementX_ + dragElement_.getClientWidth(), right) - <del> Math.max(lastElementX_, left) >= minOverlap) <del> { <del> dragTabsHost_.removeChild(dragPlaceholder_); <del> if (candidatePos_ > i) <del> { <del> dragTabsHost_.insertBefore(dragPlaceholder_, ele); <del> } <del> else <del> { <del> dragTabsHost_.insertAfter(dragPlaceholder_, ele); <del> } <del> candidatePos_ = i; <del> <del> // account for the extra element when moving to the right of the <del> // original location <del> destPos_ = startPos_ <= candidatePos_ ? <del> candidatePos_ - 1 : candidatePos_; <del> } <del> } <del> <del> } <del> <del> private TabCloseObserver closeHandler_; <del> private TabMoveObserver moveHandler_; <del> private Element closeElement_; <ide> private boolean dragging_ = false; <ide> private int lastCursorX_ = 0; <ide> private int lastElementX_ = 0; <ide> private Element dragTabsHost_; <ide> private Element dragScrollHost_; <ide> private Element dragPlaceholder_; <add> private final static int SCROLL_THRESHOLD = 25; <add> } <add> <add> private class DocTab extends Composite <add> { <add> <add> private DocTab(ImageResource icon, <add> String title, <add> String tooltip, <add> TabCloseObserver closeHandler) <add> { <add> HorizontalPanel layoutPanel = new HorizontalPanel(); <add> layoutPanel.setStylePrimaryName(styles_.tabLayout()); <add> layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM); <add> layoutPanel.getElement().setDraggable("true"); <add> final DocTab tab = this; <add> layoutPanel.addDomHandler(new DragStartHandler() <add> { <add> @Override <add> public void onDragStart(DragStartEvent evt) <add> { <add> evt.setData("text", "foo"); <add> dragManager_.beginDrag(tab, evt); <add> } <add> }, DragStartEvent.getType()); <add> <add> HTML left = new HTML(); <add> left.setStylePrimaryName(styles_.tabLayoutLeft()); <add> layoutPanel.add(left); <add> <add> contentPanel_ = new HorizontalPanel(); <add> contentPanel_.setTitle(tooltip); <add> contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter()); <add> contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); <add> <add> if (icon != null) <add> contentPanel_.add(imageForIcon(icon)); <add> <add> label_ = new Label(title, false); <add> label_.addStyleName(styles_.docTabLabel()); <add> contentPanel_.add(label_); <add> <add> appendDirtyMarker(); <add> <add> Image img = new Image(ThemeResources.INSTANCE.closeTab()); <add> img.setStylePrimaryName(styles_.closeTabButton()); <add> img.addStyleName(ThemeStyles.INSTANCE.handCursor()); <add> contentPanel_.add(img); <add> <add> layoutPanel.add(contentPanel_); <add> <add> HTML right = new HTML(); <add> right.setStylePrimaryName(styles_.tabLayoutRight()); <add> layoutPanel.add(right); <add> <add> initWidget(layoutPanel); <add> <add> this.sinkEvents(Event.ONMOUSEMOVE | <add> Event.ONMOUSEUP | <add> Event.ONLOSECAPTURE); <add> closeHandler_ = closeHandler; <add> closeElement_ = img.getElement(); <add> } <add> <add> private void appendDirtyMarker() <add> { <add> Label marker = new Label("*"); <add> marker.setStyleName(styles_.dirtyTabIndicator()); <add> contentPanel_.insert(marker, 2); <add> } <add> <add> public void replaceTitle(String title) <add> { <add> label_.setText(title); <add> } <add> <add> public void replaceTooltip(String tooltip) <add> { <add> contentPanel_.setTitle(tooltip); <add> } <add> <add> public void replaceIcon(ImageResource icon) <add> { <add> if (contentPanel_.getWidget(0) instanceof Image) <add> contentPanel_.remove(0); <add> contentPanel_.insert(imageForIcon(icon), 0); <add> } <add> <add> private Image imageForIcon(ImageResource icon) <add> { <add> Image image = new Image(icon); <add> image.setStylePrimaryName(styles_.docTabIcon()); <add> return image; <add> } <add> <add> @Override <add> public void onBrowserEvent(Event event) <add> { <add> switch(DOM.eventGetType(event)) <add> { <add> case Event.ONMOUSEUP: <add> { <add> // middlemouse should close a tab <add> if (event.getButton() == Event.BUTTON_MIDDLE) <add> { <add> event.stopPropagation(); <add> event.preventDefault(); <add> closeHandler_.onTabClose(); <add> break; <add> } <add> <add> // note: fallthrough <add> } <add> case Event.ONLOSECAPTURE: <add> { <add> if (Element.as(event.getEventTarget()) == closeElement_) <add> { <add> // handle click on close button <add> closeHandler_.onTabClose(); <add> } <add> event.preventDefault(); <add> event.stopPropagation(); <add> break; <add> } <add> } <add> super.onBrowserEvent(event); <add> } <add> <add> <add> private TabCloseObserver closeHandler_; <add> private Element closeElement_; <ide> private final Label label_; <del> private final static int SCROLL_THRESHOLD = 25; <ide> <ide> private final HorizontalPanel contentPanel_; <ide> } <ide> @Override <ide> public void onBrowserEvent(Event event) <ide> { <del> Debug.devlog("got " + event.getType() + " @ " + event.getClientX() + ", " + event.getClientY()); <del> if (event.getType() == "drag") <del> { <del> } <del> else if (event.getType() == "dragstart") <del> { <del> } <del> else if (event.getType() == "dragenter") <del> { <del> event.preventDefault(); <del> } <del> else if (event.getType() == "dragover") <del> { <del> event.preventDefault(); <del> } <del> else if (event.getType() == "drop") <del> { <del> } <ide> super.onBrowserEvent(event); <ide> } <ide> <ide> private int rightMargin_; <ide> private final ThemeStyles styles_; <ide> private Animation currentAnimation_; <add> private DragManager dragManager_; <ide> }
Java
apache-2.0
05ce701198a0df077990903b902f95e143454d6e
0
digipost/digipost-api-client-java,digipost/digipost-api-client-java
/** * Copyright (C) Posten Norge AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.digipost.api.client.representations; public enum Relation { SELF, ADD_CONTENT_AND_SEND, ADD_CONTENT, SEND, ADD_ATTACHMENT, SEARCH, AUTOCOMPLETE, CREATE_MESSAGE, API_DOCUMENTATION, GET_ENCRYPTION_KEY }
src/main/java/no/digipost/api/client/representations/Relation.java
/** * Copyright (C) Posten Norge AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.digipost.api.client.representations; public enum Relation { SELF, ADD_CONTENT_AND_SEND, SEARCH, AUTOCOMPLETE, CREATE_MESSAGE, API_DOCUMENTATION, GET_ENCRYPTION_KEY }
Added new relations
src/main/java/no/digipost/api/client/representations/Relation.java
Added new relations
<ide><path>rc/main/java/no/digipost/api/client/representations/Relation.java <ide> public enum Relation { <ide> SELF, <ide> ADD_CONTENT_AND_SEND, <add> ADD_CONTENT, <add> SEND, <add> ADD_ATTACHMENT, <ide> SEARCH, <ide> AUTOCOMPLETE, <ide> CREATE_MESSAGE,
Java
bsd-3-clause
4daf136224cd75f35f11f697b278bf3217a2f434
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.dto.characterization.physical; import gov.nih.nci.calab.domain.Measurement; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.physical.SurfaceChemistry; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.composition.SurfaceGroupBean; import gov.nih.nci.calab.service.util.CananoConstants; import java.util.ArrayList; import java.util.List; /** * This class represents the size characterization information to be shown in * the view page. * * @author pansu * */ public class SurfaceBean extends CharacterizationBean { private String surfaceArea; private String surfaceAreaUnit; private String zetaPotential; private String charge; private String chargeUnit; private String isHydrophobic; private int numberOfSurfaceChemistry; private List<SurfaceChemistryBean> surfaceChemistries = new ArrayList<SurfaceChemistryBean>(); public SurfaceBean() { super(); surfaceChemistries = new ArrayList<SurfaceChemistryBean>(); initSetup(); } public SurfaceBean(Surface aChar) { super(aChar); this.charge = (aChar.getCharge() != null)?aChar.getCharge().getValue():""; this.chargeUnit = (aChar.getCharge() != null)?aChar.getCharge().getUnitOfMeasurement():""; this.isHydrophobic = aChar.getIsHydrophobic().toString(); this.surfaceArea = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getValue().toString():""; this.surfaceAreaUnit = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getUnitOfMeasurement():""; //this.zetaPotential = (aChar.getZetaPotential() != null)?aChar.getZetaPotential().getValue():""; this.zetaPotential = (aChar.getZetaPotential() != null) ? aChar.getZetaPotential().toString() : ""; for (SurfaceChemistry surfaceChemistry : aChar.getSurfaceChemistryCollection()) { SurfaceChemistryBean surfaceChemistryBean = new SurfaceChemistryBean(surfaceChemistry); surfaceChemistries.add(surfaceChemistryBean); } this.numberOfSurfaceChemistry = surfaceChemistries.size(); } public String getCharge() { return charge; } public void setCharge(String charge) { this.charge = charge; } public String getIsHydrophobic() { return isHydrophobic; } public void setIsHydrophobic(String isHydrophobic) { this.isHydrophobic = isHydrophobic; } public String getSurfaceArea() { return surfaceArea; } public void setSurfaceArea(String surfaceArea) { this.surfaceArea = surfaceArea; } public String getZetaPotential() { return zetaPotential; } public void setZetaPotential(String zetaPotential) { this.zetaPotential = zetaPotential; } public void setDerivedBioAssayData( List<DerivedBioAssayDataBean> derivedBioAssayData) { super.setDerivedBioAssayData(derivedBioAssayData); initSetup(); } public String getChargeUnit() { return chargeUnit; } public void setChargeUnit(String chargeUnit) { this.chargeUnit = chargeUnit; } public List<SurfaceChemistryBean> getSurfaceChemistries() { return surfaceChemistries; } public void setSurfaceChemistries(List<SurfaceChemistryBean> surfaceGroups) { this.surfaceChemistries = surfaceGroups; } public String getSurfaceAreaUnit() { return surfaceAreaUnit; } public void setSurfaceAreaUnit(String surfaceAreaUnit) { this.surfaceAreaUnit = surfaceAreaUnit; } public void initSetup() { // for (DerivedBioAssayDataBean table : getDerivedBioAssayData()) { // DatumBean average = new DatumBean(); // average.setType("Average"); // average.setValueUnit("nm"); // DatumBean zaverage = new DatumBean(); // zaverage.setType("Z-Average"); // zaverage.setValueUnit("nm"); // DatumBean pdi = new DatumBean(); // pdi.setType("PDI"); // table.getDatumList().add(average); // table.getDatumList().add(zaverage); // table.getDatumList().add(pdi); // } } public Surface getDomainObj() { Surface surface = new Surface(); super.updateDomainObj(surface); boolean hycrophobicStatus = (isHydrophobic.equalsIgnoreCase(CananoConstants.BOOLEAN_YES)) ? true : false; surface.setIsHydrophobic(hycrophobicStatus); surface.setCharge(new Measurement(charge,chargeUnit)); //surface.setZetaPotential(new Measurement(zetaPotential, "mV")); surface.setZetaPotential(new Float(zetaPotential)); surface.setSurfaceArea(new Measurement(surfaceArea, surfaceAreaUnit)); for (SurfaceChemistryBean surfaceChemistry : surfaceChemistries) { surface.getSurfaceChemistryCollection().add(surfaceChemistry.getDomainObj()); } return surface; } public int getNumberOfSurfaceChemistry() { return numberOfSurfaceChemistry; } public void setNumberOfSurfaceChemistry(int numberOfSurfaceChemistry) { this.numberOfSurfaceChemistry = numberOfSurfaceChemistry; } }
src/gov/nih/nci/calab/dto/characterization/physical/SurfaceBean.java
package gov.nih.nci.calab.dto.characterization.physical; import gov.nih.nci.calab.domain.Measurement; import gov.nih.nci.calab.domain.nano.characterization.physical.Surface; import gov.nih.nci.calab.domain.nano.characterization.physical.SurfaceChemistry; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.composition.SurfaceGroupBean; import gov.nih.nci.calab.service.util.CananoConstants; import java.util.ArrayList; import java.util.List; /** * This class represents the size characterization information to be shown in * the view page. * * @author pansu * */ public class SurfaceBean extends CharacterizationBean { private String surfaceArea; private String surfaceAreaUnit; private String zetaPotential; private String charge; private String chargeUnit; private String isHydrophobic; private int numberOfSurfaceChemistry; private List<SurfaceChemistryBean> surfaceChemistries = new ArrayList<SurfaceChemistryBean>(); public SurfaceBean() { super(); surfaceChemistries = new ArrayList<SurfaceChemistryBean>(); initSetup(); } public SurfaceBean(Surface aChar) { super(aChar); this.charge = (aChar.getCharge() != null)?aChar.getCharge().getValue():""; this.chargeUnit = (aChar.getCharge() != null)?aChar.getCharge().getUnitOfMeasurement():""; this.isHydrophobic = aChar.getIsHydrophobic().toString(); this.surfaceArea = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getValue().toString():""; this.surfaceAreaUnit = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getUnitOfMeasurement():""; this.zetaPotential = (aChar.getZetaPotential() != null)?aChar.getZetaPotential().getValue():""; for (SurfaceChemistry surfaceChemistry : aChar.getSurfaceChemistryCollection()) { SurfaceChemistryBean surfaceChemistryBean = new SurfaceChemistryBean(surfaceChemistry); surfaceChemistries.add(surfaceChemistryBean); } this.numberOfSurfaceChemistry = surfaceChemistries.size(); } public String getCharge() { return charge; } public void setCharge(String charge) { this.charge = charge; } public String getIsHydrophobic() { return isHydrophobic; } public void setIsHydrophobic(String isHydrophobic) { this.isHydrophobic = isHydrophobic; } public String getSurfaceArea() { return surfaceArea; } public void setSurfaceArea(String surfaceArea) { this.surfaceArea = surfaceArea; } public String getZetaPotential() { return zetaPotential; } public void setZetaPotential(String zetaPotential) { this.zetaPotential = zetaPotential; } public void setDerivedBioAssayData( List<DerivedBioAssayDataBean> derivedBioAssayData) { super.setDerivedBioAssayData(derivedBioAssayData); initSetup(); } public String getChargeUnit() { return chargeUnit; } public void setChargeUnit(String chargeUnit) { this.chargeUnit = chargeUnit; } public List<SurfaceChemistryBean> getSurfaceChemistries() { return surfaceChemistries; } public void setSurfaceChemistries(List<SurfaceChemistryBean> surfaceGroups) { this.surfaceChemistries = surfaceGroups; } public String getSurfaceAreaUnit() { return surfaceAreaUnit; } public void setSurfaceAreaUnit(String surfaceAreaUnit) { this.surfaceAreaUnit = surfaceAreaUnit; } public void initSetup() { // for (DerivedBioAssayDataBean table : getDerivedBioAssayData()) { // DatumBean average = new DatumBean(); // average.setType("Average"); // average.setValueUnit("nm"); // DatumBean zaverage = new DatumBean(); // zaverage.setType("Z-Average"); // zaverage.setValueUnit("nm"); // DatumBean pdi = new DatumBean(); // pdi.setType("PDI"); // table.getDatumList().add(average); // table.getDatumList().add(zaverage); // table.getDatumList().add(pdi); // } } public Surface getDomainObj() { Surface surface = new Surface(); super.updateDomainObj(surface); boolean hycrophobicStatus = (isHydrophobic.equalsIgnoreCase(CananoConstants.BOOLEAN_YES)) ? true : false; surface.setIsHydrophobic(hycrophobicStatus); surface.setCharge(new Measurement(charge,chargeUnit)); surface.setZetaPotential(new Measurement(zetaPotential, "mV")); surface.setSurfaceArea(new Measurement(surfaceArea, surfaceAreaUnit)); for (SurfaceChemistryBean surfaceChemistry : surfaceChemistries) { surface.getSurfaceChemistryCollection().add(surfaceChemistry.getDomainObj()); } return surface; } public int getNumberOfSurfaceChemistry() { return numberOfSurfaceChemistry; } public void setNumberOfSurfaceChemistry(int numberOfSurfaceChemistry) { this.numberOfSurfaceChemistry = numberOfSurfaceChemistry; } }
zetaPotential is Float type. SVN-Revision: 2094
src/gov/nih/nci/calab/dto/characterization/physical/SurfaceBean.java
zetaPotential is Float type.
<ide><path>rc/gov/nih/nci/calab/dto/characterization/physical/SurfaceBean.java <ide> this.isHydrophobic = aChar.getIsHydrophobic().toString(); <ide> this.surfaceArea = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getValue().toString():""; <ide> this.surfaceAreaUnit = (aChar.getSurfaceArea() != null)?aChar.getSurfaceArea().getUnitOfMeasurement():""; <del> this.zetaPotential = (aChar.getZetaPotential() != null)?aChar.getZetaPotential().getValue():""; <add> //this.zetaPotential = (aChar.getZetaPotential() != null)?aChar.getZetaPotential().getValue():""; <add> this.zetaPotential = (aChar.getZetaPotential() != null) ? aChar.getZetaPotential().toString() : ""; <ide> <ide> for (SurfaceChemistry surfaceChemistry : aChar.getSurfaceChemistryCollection()) { <ide> SurfaceChemistryBean surfaceChemistryBean = new SurfaceChemistryBean(surfaceChemistry); <ide> : false; <ide> surface.setIsHydrophobic(hycrophobicStatus); <ide> surface.setCharge(new Measurement(charge,chargeUnit)); <del> surface.setZetaPotential(new Measurement(zetaPotential, "mV")); <add> //surface.setZetaPotential(new Measurement(zetaPotential, "mV")); <add> surface.setZetaPotential(new Float(zetaPotential)); <ide> <ide> surface.setSurfaceArea(new Measurement(surfaceArea, surfaceAreaUnit)); <ide>
Java
apache-2.0
41e891c18a6ae0e0104ada12c2cdaccff93fa987
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2002-2011 Ausenco Engineering Canada Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.basicsim; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; /** * Class encapsulating file input/output methods and file access. */ public class FileEntity { private File backingFileObject; private BufferedWriter outputStream; public FileEntity(String fileName) { this(fileName, false); } public FileEntity(String fileName, boolean append) { backingFileObject = new File(fileName); try { backingFileObject.createNewFile(); outputStream = new BufferedWriter( new FileWriter(backingFileObject, append) ); } catch (IOException e) { throw new InputErrorException("IOException thrown trying to open file: '%s'%n%s", fileName, e.getMessage()); } catch (IllegalArgumentException e) { throw new InputErrorException("IllegalArgumentException thrown trying to open file: " + "'%s'%n%s", fileName, e.getMessage()); } catch (SecurityException e) { throw new InputErrorException("SecurityException thrown trying to open file: '%s'%n%s", fileName, e.getMessage()); } } public void close() { try { if( outputStream != null ) { outputStream.flush(); outputStream.close(); outputStream = null; } } catch( IOException e ) { outputStream = null; InputAgent.logMessage( "Unable to close FileEntity: " + backingFileObject.getName() ); } } public void flush() { try { if( outputStream != null ) { outputStream.flush(); } } catch( IOException e ) { throw new ErrorException( "Unable to flush FileEntity: " + e ); } } public void format(String format, Object... args) { write(String.format(format, args)); } public void newLine() { try { outputStream.newLine(); } catch( IOException e ) { return; } } public void write( String text ) { try { outputStream.write( text ); } catch( IOException e ) { return; } } /** * Delete the file */ public void delete() { try { if( backingFileObject.exists() ) { if( !backingFileObject.delete() ) { throw new ErrorException( "Failed to delete " + backingFileObject.getName() ); } } } catch( SecurityException e ) { throw new ErrorException( "Unable to delete " + backingFileObject.getName() + "(" + e.getMessage() + ")" ); } } }
src/main/java/com/jaamsim/basicsim/FileEntity.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2002-2011 Ausenco Engineering Canada Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.basicsim; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; /** * Class encapsulating file input/output methods and file access. */ public class FileEntity { private File backingFileObject; private BufferedWriter outputStream; public FileEntity(String fileName) { this(fileName, false); } public FileEntity(String fileName, boolean append) { backingFileObject = new File(fileName); try { backingFileObject.createNewFile(); outputStream = new BufferedWriter( new FileWriter(backingFileObject, append) ); } catch (IOException e) { throw new InputErrorException("IOException thrown trying to open FileEntity %s%n%s", fileName, e.getMessage()); } catch (IllegalArgumentException e) { throw new InputErrorException("IllegalArgumentException thrown trying to open " + "FileEntity %s (Should not happen)%n%s", fileName, e.getMessage()); } catch (SecurityException e) { throw new InputErrorException("SecurityException thrown trying to open " + "FileEntity %s%n%s", fileName, e.getMessage()); } } public void close() { try { if( outputStream != null ) { outputStream.flush(); outputStream.close(); outputStream = null; } } catch( IOException e ) { outputStream = null; InputAgent.logMessage( "Unable to close FileEntity: " + backingFileObject.getName() ); } } public void flush() { try { if( outputStream != null ) { outputStream.flush(); } } catch( IOException e ) { throw new ErrorException( "Unable to flush FileEntity: " + e ); } } public void format(String format, Object... args) { write(String.format(format, args)); } public void newLine() { try { outputStream.newLine(); } catch( IOException e ) { return; } } public void write( String text ) { try { outputStream.write( text ); } catch( IOException e ) { return; } } /** * Delete the file */ public void delete() { try { if( backingFileObject.exists() ) { if( !backingFileObject.delete() ) { throw new ErrorException( "Failed to delete " + backingFileObject.getName() ); } } } catch( SecurityException e ) { throw new ErrorException( "Unable to delete " + backingFileObject.getName() + "(" + e.getMessage() + ")" ); } } }
JS: minor revisions to the error messages generated by opening a file Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/basicsim/FileEntity.java
JS: minor revisions to the error messages generated by opening a file
<ide><path>rc/main/java/com/jaamsim/basicsim/FileEntity.java <ide> outputStream = new BufferedWriter( new FileWriter(backingFileObject, append) ); <ide> } <ide> catch (IOException e) { <del> throw new InputErrorException("IOException thrown trying to open FileEntity %s%n%s", <add> throw new InputErrorException("IOException thrown trying to open file: '%s'%n%s", <ide> fileName, e.getMessage()); <ide> } <ide> catch (IllegalArgumentException e) { <del> throw new InputErrorException("IllegalArgumentException thrown trying to open " <del> + "FileEntity %s (Should not happen)%n%s", <add> throw new InputErrorException("IllegalArgumentException thrown trying to open file: " <add> + "'%s'%n%s", <ide> fileName, e.getMessage()); <ide> } <ide> catch (SecurityException e) { <del> throw new InputErrorException("SecurityException thrown trying to open " <del> + "FileEntity %s%n%s", <add> throw new InputErrorException("SecurityException thrown trying to open file: '%s'%n%s", <ide> fileName, e.getMessage()); <ide> } <ide> }
Java
epl-1.0
ef3f6b0e5d6fbf34d83a50709c367d30f21f9534
0
ERPNowe/erpNowe,ERPNowe/erpNowe,ERPNowe/erpNowe
/** * Clase ventanaPrincipal * @author curso14/7803 * @version 1.0 * @since 19/11/2015 * <br> * <p> * Esta clase corresponde a la pantalla principal del programa y sus mens * </p> */ package ventanaPrincipal; import java.awt.Color; import java.awt.Container; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import java.io.File; import alumnos.VentanaCalificaciones; import alumnos.VentanaInteresado; import cursos.VentanaCursos; import cursos.VentanaGrupos; import cursos.ventanaModulo; import gestion.VentanaGestion; import matricula.VentanaFormaPago; import matricula.VentanaMatricula; public class VentanaPrincipal extends JFrame implements ActionListener { private JMenuBar barraMenu; private JMenu menuAlumnos, menuCursos, menuCalificacion, menuMatricula, menuGestion, menuAyuda, menuSalir; private JMenuItem matriculado, interesado, cursos, grupos, modulos, calificacion, matricula, formaPago, consulta, modificacion, ayuda, salir; public static String usuario = "root"; public static String pwd = "root"; public static String bd = "nowedb"; public static basedatos.ConexionBaseDatos conexion = null; public VentanaPrincipal () { setLayout(null); Fondo fondo; Toolkit t = Toolkit.getDefaultToolkit(); Dimension tamaoPantalla = Toolkit.getDefaultToolkit().getScreenSize(); this.setLayout(null); Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/logo_nowe.gif")); setIconImage(icon); this.setTitle("Programa de Gestin Nowe"); setSize(tamaoPantalla.width, tamaoPantalla.height); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); fondo = new Fondo(); add(fondo); barraMenu = new JMenuBar(); setJMenuBar(barraMenu); // Men Alumnos menuAlumnos = new JMenu ("Alumnos"); barraMenu.add(menuAlumnos); matriculado = new JMenuItem("Matriculado"); matriculado.addActionListener(this); menuAlumnos.add(matriculado); interesado = new JMenuItem("Interesado"); interesado.addActionListener(this); menuAlumnos.add(interesado); // Men Cursos menuCursos = new JMenu ("Cursos"); barraMenu.add(menuCursos); cursos = new JMenuItem("Cursos"); cursos.addActionListener(this); menuCursos.add(cursos); grupos = new JMenuItem("Grupos"); grupos.addActionListener(this); menuCursos.add(grupos); modulos = new JMenuItem("Mdulos"); modulos.addActionListener(this); menuCursos.add(modulos); // Men Calificacin menuCalificacion = new JMenu ("Calificacin"); barraMenu.add(menuCalificacion); calificacion = new JMenuItem("Calificacin"); calificacion.addActionListener(this); menuCalificacion.add(calificacion); // Men Matricula menuMatricula = new JMenu ("Matrcula"); barraMenu.add(menuMatricula); matricula = new JMenuItem("Matrcula"); matricula.addActionListener(this); menuMatricula.add(matricula); formaPago = new JMenuItem("Forma de Pago"); formaPago.addActionListener(this); menuMatricula.add(formaPago); // Men Gestin menuGestion = new JMenu ("Gestin"); barraMenu.add(menuGestion); consulta = new JMenuItem("Consulta"); consulta.addActionListener(this); menuGestion.add(consulta); // modificacion = new JMenuItem("Modificacin"); // modificacion.addActionListener(this); // menuGestion.add(modificacion); // Men Ayuda menuAyuda = new JMenu ("Ayuda"); barraMenu.add(menuAyuda); ayuda = new JMenuItem("?"); ayuda.addActionListener(this); menuAyuda.add(ayuda); // Men Salir menuSalir = new JMenu ("Salir"); barraMenu.add(menuSalir); salir = new JMenuItem("Salir"); salir.addActionListener(this); menuSalir.add(salir);} /** * Acciones definidas para los distintos items de los mens */ public void actionPerformed(ActionEvent e) { if (e.getSource()== cursos) { conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCursos ventana=new VentanaCursos(); ventana.setVisible(true); } if (e.getSource()== modulos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); ventanaModulo ventana = new ventanaModulo(); ventana.setVisible(true); } if (e.getSource()== interesado){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaInteresado ne = new VentanaInteresado(); ne.setVisible(true); } if (e.getSource()== grupos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGrupos ne = new VentanaGrupos(); ne.setVisible(true); } if (e.getSource()== matricula){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaMatricula ventana = new VentanaMatricula(); ventana.setVisible(true); } if (e.getSource()== calificacion){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCalificaciones ventana = new VentanaCalificaciones(); ventana.setVisible(true); } if (e.getSource()== formaPago){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaFormaPago ventana = new VentanaFormaPago(); ventana.setVisible(true); } if (e.getSource()== consulta){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGestion ventana = new VentanaGestion('C'); ventana.setVisible(true); } if (e.getSource()== ayuda){ String cadena; File fichero = new File("file:///../doc/index.html"); cadena = fichero.getAbsolutePath(); try{ Runtime rt = Runtime.getRuntime(); String[] callAndArgs = {"C:/WINDOWS/hh.exe",cadena}; Process child = rt.exec(callAndArgs); }catch(Exception eee){ System.out.println("UPS! Ha ocurrido un error"); } } if (e.getSource()== salir){ System.exit(0); } } }
erpNowe/src/ventanaPrincipal/VentanaPrincipal.java
/** * Clase ventanaPrincipal * @author curso14/7803 * @version 1.0 * @since 19/11/2015 * <br> * <p> * Esta clase corresponde a la pantalla principal del programa y sus mens * </p> */ package ventanaPrincipal; import java.awt.Color; import java.awt.Container; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import java.io.File; import alumnos.VentanaCalificaciones; import alumnos.VentanaInteresado; import cursos.VentanaCursos; import cursos.VentanaGrupos; import cursos.ventanaModulo; import gestion.VentanaGestion; import matricula.VentanaFormaPago; import matricula.VentanaMatricula; public class VentanaPrincipal extends JFrame implements ActionListener { private JMenuBar barraMenu; private JMenu menuAlumnos, menuCursos, menuCalificacion, menuMatricula, menuGestion, menuAyuda, menuSalir; private JMenuItem matriculado, interesado, cursos, grupos, modulos, calificacion, matricula, formaPago, consulta, modificacion, ayuda, salir; public static String usuario = "root"; public static String pwd = "root"; public static String bd = "nowedb"; public static basedatos.ConexionBaseDatos conexion = null; public VentanaPrincipal () { setLayout(null); Fondo fondo; Toolkit t = Toolkit.getDefaultToolkit(); Dimension tamaoPantalla = Toolkit.getDefaultToolkit().getScreenSize(); this.setLayout(null); Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/logo_nowe.gif")); setIconImage(icon); this.setTitle("Programa de Gestin Nowe"); setSize(tamaoPantalla.width, tamaoPantalla.height); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); fondo = new Fondo(); add(fondo); barraMenu = new JMenuBar(); setJMenuBar(barraMenu); // Men Alumnos menuAlumnos = new JMenu ("Alumnos"); barraMenu.add(menuAlumnos); matriculado = new JMenuItem("Matriculado"); matriculado.addActionListener(this); menuAlumnos.add(matriculado); interesado = new JMenuItem("Interesado"); interesado.addActionListener(this); menuAlumnos.add(interesado); // Men Cursos menuCursos = new JMenu ("Cursos"); barraMenu.add(menuCursos); cursos = new JMenuItem("Cursos"); cursos.addActionListener(this); menuCursos.add(cursos); grupos = new JMenuItem("Grupos"); grupos.addActionListener(this); menuCursos.add(grupos); modulos = new JMenuItem("Mdulos"); modulos.addActionListener(this); menuCursos.add(modulos); // Men Calificacin menuCalificacion = new JMenu ("Calificacin"); barraMenu.add(menuCalificacion); calificacion = new JMenuItem("Calificacin"); calificacion.addActionListener(this); menuCalificacion.add(calificacion); // Men Matricula menuMatricula = new JMenu ("Matrcula"); barraMenu.add(menuMatricula); matricula = new JMenuItem("Matrcula"); matricula.addActionListener(this); menuMatricula.add(matricula); formaPago = new JMenuItem("Forma de Pago"); formaPago.addActionListener(this); menuMatricula.add(formaPago); // Men Gestin menuGestion = new JMenu ("Gestin"); barraMenu.add(menuGestion); consulta = new JMenuItem("Consulta"); consulta.addActionListener(this); menuGestion.add(consulta); modificacion = new JMenuItem("Modificacin"); modificacion.addActionListener(this); menuGestion.add(modificacion); // Men Ayuda menuAyuda = new JMenu ("Ayuda"); barraMenu.add(menuAyuda); ayuda = new JMenuItem("?"); ayuda.addActionListener(this); menuAyuda.add(ayuda); // Men Salir menuSalir = new JMenu ("Salir"); barraMenu.add(menuSalir); salir = new JMenuItem("Salir"); salir.addActionListener(this); menuSalir.add(salir);} /** * Acciones definidas para los distintos items de los mens */ public void actionPerformed(ActionEvent e) { if (e.getSource()== cursos) { conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCursos ventana=new VentanaCursos(); ventana.setVisible(true); } if (e.getSource()== modulos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); ventanaModulo ventana = new ventanaModulo(); ventana.setVisible(true); } if (e.getSource()== interesado){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaInteresado ne = new VentanaInteresado(); ne.setVisible(true); } if (e.getSource()== grupos){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGrupos ne = new VentanaGrupos(); ne.setVisible(true); } if (e.getSource()== matricula){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaMatricula ventana = new VentanaMatricula(); ventana.setVisible(true); } if (e.getSource()== calificacion){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaCalificaciones ventana = new VentanaCalificaciones(); ventana.setVisible(true); } if (e.getSource()== formaPago){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaFormaPago ventana = new VentanaFormaPago(); ventana.setVisible(true); } if (e.getSource()== consulta){ conexion = new basedatos.ConexionBaseDatos(bd, usuario, pwd); VentanaGestion ventana = new VentanaGestion('C'); ventana.setVisible(true); } if (e.getSource()== ayuda){ String cadena; File fichero = new File("file:///../doc/index.html"); cadena = fichero.getAbsolutePath(); try{ Runtime rt = Runtime.getRuntime(); String[] callAndArgs = {"C:/WINDOWS/hh.exe",cadena}; Process child = rt.exec(callAndArgs); }catch(Exception eee){ System.out.println("UPS! Ha ocurrido un error"); } } if (e.getSource()== salir){ System.exit(0); } } }
Modificaciones en el menú
erpNowe/src/ventanaPrincipal/VentanaPrincipal.java
Modificaciones en el menú
<ide><path>rpNowe/src/ventanaPrincipal/VentanaPrincipal.java <ide> consulta.addActionListener(this); <ide> menuGestion.add(consulta); <ide> <del> modificacion = new JMenuItem("Modificacin"); <del> modificacion.addActionListener(this); <del> menuGestion.add(modificacion); <add>// modificacion = new JMenuItem("Modificacin"); <add>// modificacion.addActionListener(this); <add>// menuGestion.add(modificacion); <ide> <ide> // Men Ayuda <ide> menuAyuda = new JMenu ("Ayuda");
JavaScript
mit
185ae3769d7c6a40f864653d7d95d70a3f16126e
0
yWorks/svg2pdf.js,yWorks/svg2pdf.js,yWorks/svg2pdf.js
// Karma configuration 'use strict' module.exports = (config) => { const testCoverage = process.argv.indexOf('--coverage') >= 0 const preprocessors = { 'tests/tests.js': 'babel' }; // currently it is not possible to have both coverage and browserify, so a coverage run needs to have the files // pre-bundled in dist/ (as the npm script does) if (testCoverage) { preprocessors['dist/svg2pdf.js'] = 'coverage' } else { preprocessors['tests/runTests.js'] = 'webpack' } config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai']/* .concat(testCoverage ? [] : ['']) */, webpack: require('./webpack.config.js'), // list of files / patterns to load in the browser files: [ 'node_modules/jspdf-yworks/dist/jspdf.debug.js', 'tests/utils/compare.js', { pattern: 'tests/runTests.js', included: true, served: true, watched: true, type: "module" }, { pattern: 'tests/**/spec.svg', included: false, served: true }, { pattern: 'tests/**/reference.pdf', included: false, watched: false, served: true } ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: preprocessors, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'].concat(testCoverage ? ['coverage'] : []), // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: testCoverage, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, coverageReporter: { reporters: [ { type: 'lcov', dir: 'coverage/' }, { type: 'text' } ] } }) }
karma.conf.js
// Karma configuration 'use strict' module.exports = (config) => { const testCoverage = process.argv.indexOf('--coverage') >= 0 const preprocessors = { 'tests/tests.js': 'babel' }; // currently it is not possible to have both coverage and browserify, so a coverage run needs to have the files // pre-bundled in dist/ (as the npm script does) if (testCoverage) { preprocessors['dist/svg2pdf.js'] = 'coverage' } else { preprocessors['tests/runTests.js'] = 'webpack' } config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai']/* .concat(testCoverage ? [] : ['']) */, webpack: require('./webpack.config.js'), // list of files / patterns to load in the browser files: [ 'node_modules/jspdf-yworks/dist/jspdf.min.js', 'tests/utils/compare.js', { pattern: 'tests/runTests.js', included: true, served: true, watched: true, type: "module" }, { pattern: 'tests/**/spec.svg', included: false, served: true }, { pattern: 'tests/**/reference.pdf', included: false, watched: false, served: true } ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: preprocessors, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'].concat(testCoverage ? ['coverage'] : []), // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: testCoverage, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, coverageReporter: { reporters: [ { type: 'lcov', dir: 'coverage/' }, { type: 'text' } ] } }) }
Load jspdf debug version in the browser while testing
karma.conf.js
Load jspdf debug version in the browser while testing
<ide><path>arma.conf.js <ide> <ide> // list of files / patterns to load in the browser <ide> files: [ <del> 'node_modules/jspdf-yworks/dist/jspdf.min.js', <add> 'node_modules/jspdf-yworks/dist/jspdf.debug.js', <ide> <ide> 'tests/utils/compare.js', <ide>
JavaScript
agpl-3.0
ad507bf2612042f2f308f9e81f6a37976f9abb85
0
PaulBeaudet/Stranger_Danger,PaulBeaudet/Stranger_Danger
// serve.js ~ Copyright 2015 Paul Beaudet ~ Licence Affero GPL ~ See LICENCE_AFFERO for details // This serves a test application that lets people talk to strangers // Constant factors const WAIT_TIME = 30; // time topic displayed const NUM_ENTRIES = 6; // number of dialog rows allowed client side const FREQUENCY = WAIT_TIME * 2000 / NUM_ENTRIES; // frequency of topic send out // temp options const DEFAULT_SUB = [0,1,2,3]; // defualt subscriptions for temp users const DEFAULT_SUBIDS = false; // abstract persistent and temporary topic data var topicDB = { // depends on mongo temp: [], // in ram topic data init: function(number){ // populates topic array, init feed zero mongo.topic.findOne({index: number}, function(err, topick){ if(err){console.log(err + '-topicDB.init');} else if(topick){ topicDB.temp.push(topick.text); // add topic to temp list topicDB.init(number+1); // recursively load individual topics !!BLOCKING!! } }); }, onCreate: function(text, ID){ if(ID.email){ // given this is an official user var doc = new mongo.topic({text: text}); // grab a schema for a new document mongo.topic.count().exec(function(err, count){ // find out which topic this will be doc.index = count; // add unique count property to document doc.author = ID.email; // note the author of the topic var objectID = doc._id; doc.save(function(err){ // write new topic to database if(err){console.log(err + ' onCreate');} else { var userNum = userDB.grabIndex(ID.socket); // not the index number of this user topicDB.temp.push(text); // also add topic in temorary array userDB.temp[userNum].subIDs.push(objectID); // add to cached user subscriptions userDB.temp[userNum].sub.push(count) // add to cached user subscriptions } }); }); } }, } // abstract persistent and temporary user data var userDB = { // requires mongo and topic temp: [], // in ram user data logout: function(ID){ if(ID.email){ var userNum = userDB.grabIndex(ID.socket); var dataUpdate = { subscribed: userDB.temp[userNum].sub, toSub: userDB.temp[userNum].toSub, subIDs: userDB.temp[userNum].subIDs, avgSpeed: userDB.temp[userNum].speed }; mongo.user.findOneAndUpdate({email: ID.email}, dataUpdate, function(err, doc){ if(err){ console.log(err + '-userDB.logout'); } else if (doc){ // save users session information when their socket disconects userDB.temp.splice(userDB.grabIndex(ID.socket), 1); } }) } }, grabIndex: function(socket){return userDB.temp.map(function(each){return each.socket;}).indexOf(socket);}, checkIn: function(ID) { // create temporary persistence entry for online users mongo.user.findOne({email: ID.email}, function(err, doc){ if(err){ console.log(err + '-userDB.checkin'); // users must be signed up } else if (doc){ userDB.temp.push({ // toMatch & Sub default to 0 socket: ID.socket, toSub: doc.toSub, // known details sub: doc.subscribed, subIDs: doc.subIDs, // persistant details toMatch: 0, // temp details speed: doc.avgSpeed, // IDs of subscriptions }); topic.propose(ID.socket); match.topic(ID.socket); sock.io.to(ID.socket).emit('speed', doc.avgSpeed); // give client last speed } }); }, fake: function(socketID){ userDB.temp.push({ socket: socketID, sub: DEFAULT_SUB, toSub: 0, subIDs: DEFAULT_SUBIDS, speed: 0, toMatch: 0, }); topic.propose(socketID); match.topic(socketID); }, toggle: function(socket){ // stop prop and match NOTE: takes an array of sockets normally [two, sockets] for(var i=0; socket[i]; i++){ var userNum = userDB.grabIndex(socket[i]); if(userNum > -1){ if(userDB.temp[userNum].pTimer){ // given the timer was counting down to add topics clearTimeout(userDB.temp[userNum].mTimer); clearTimeout(userDB.temp[userNum].pTimer); userDB.temp[userNum].mTimer = 0; userDB.temp[userNum].pTimer = 0; } else { topic.propose(socket[i]); match.topic(socket[i]); } // other wise we are resubbing user to feed } } }, speed: function(socket, avg){userDB.temp[userDB.grabIndex(socket)].speed = avg;} } // distribute topics: does two things- proposes topics and matches users based on topics var topic = { // depends on: userDB and topicDB action: function(command, user, data){console.log(command + '-' + user + '-' + data);}, // replace with real command propose: function(socket){ var userNum = userDB.grabIndex(socket); if(userNum > -1){ if(userDB.temp[userNum].toSub < topicDB.temp.length){userDB.temp[userNum].toSub++;} // increment else{userDB.temp[userNum].toSub = 0;} // set back to zero if reached end for( var i = 0; userDB.temp[userNum].sub[i] !== undefined; i++ ){ // for every user sub if(userDB.temp[userNum].toSub === userDB.temp[userNum].sub[i]){ // if matches topic, avoid process.nextTick(function(){topic.propose(socket);}); // try again on next tick return; // don't propose / short curcuit } } // else user is not subscribbed to this topic, propose it to them if(topicDB.temp[userDB.temp[userNum].toSub]){ topic.action('topic', socket, {user:userDB.temp[userNum].toSub, text:topicDB.temp[userDB.temp[userNum].toSub]}); } userDB.temp[userNum].pTimer = setTimeout(function(){topic.propose(socket);}, FREQUENCY); } } } // match users based on similar topics var match = { // depends on: userDB, topic, topicDB topic: function ( socket, targetID ){ // find a user with a the same topic var userNum = userDB.grabIndex(socket); // find users possition in array if(userNum && userDB.temp.length > 1){ // Should we be looking? zeroth and undefined users never look var targetNum = userNum - 1; // if no target is provide, target user before us if(targetID){targetNum = userDB.grabIndex(targetID);} // else target the user before last we looked at if(userDB.temp[targetNum].pTimer){ // So long as this target is also looking userDB.temp[userNum].toMatch++; // increment match target var matchSub = userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]; // read match target if(matchSub === undefined){ // if match target does not exist userDB.temp[userNum].toMatch = 0; // set target back to zero matchSub = userDB.temp[userNum].sub[0]; // set match sub to reflect new target if(matchSub === undefined){matchSub = 0;} // default to first topic if subscribed to none } for (var i = 0; userDB.temp[targetNum].sub[i] !== undefined; i++){ // for every topic prospect has if(userDB.temp[targetNum].sub[i] === matchSub){ // if their topic matches up with ours var found = userDB.temp[targetNum].socket; // who matched? topic.action('topic', socket, {user:found, text: topicDB.temp[matchSub], code:matchSub}); topic.action('topic', found, {user:socket, text: topicDB.temp[matchSub], code:matchSub}); } } } if(targetNum){ // given we just searched someone other than the zeroth user, search the next target before them userDB.temp[userNum].mTimer = setTimeout(function (){match.topic(socket, userDB.temp[targetNum-1].user);}, FREQUENCY); } else { userDB.temp[userNum].mTimer = setTimeout(function(){match.topic(socket);}, FREQUENCY); } } } } // determines how sockets react to changes var reaction = { // depends on topic onConnect: function(socket){ // returns unique id to hold in closure for socket.on events var usrInfo = false; if(socket.request.headers.cookie){ // if cookie exist var cookieCrums = socket.request.headers.cookie.split('='); // split correct cookie out usrInfo = cookie.user(cookieCrums[cookieCrums.length - 1]); // decrypt email from cookie, make it userID if(usrInfo.accountType === 'temp'){ // check if this is a temp user userDB.fake(socket.id); // temp user creation } else if (usrInfo.email){ // given an assosiated email userDB.checkIn({email:usrInfo.email, socket:socket.id}); // Create real user } } return {email: usrInfo.email, type: usrInfo.accountType}; }, toSub: function(socket, topicID){ var userID = userDB.grabIndex(socket); userDB.temp[userID].sub.push(topicID); }, readyToChat: [], timeToTalk: function(socketID, matchID){ // logic that determines who responds first var first = true; for(var i = 0; reaction.readyToChat[i]; i++){ // for all ready to chat if(reaction.readyToChat[i] === matchID){ // did this socket's match check in yet first = false; // yes? than that person got here first reaction.readyToChat.splice(i, 1); // they are about to talk with us remove that person from list } } if(first){ // given this sockets match has yet to check in, this socket is first reaction.readyToChat.push(socketID); // check in return false; // not ready to chat } else { userDB.toggle([matchID, socketID]); // stop feed return true; // ready to chat } }, } // socket.io logic var sock = { // depends on socket.io, reaction, and topic io: require('socket.io'), listen: function (server){ sock.io = sock.io(server); sock.io.on('connection', function(socket){ // whenever a new user is connected var userInfo = reaction.onConnect(socket); // returns potential user information in session cookie if(userInfo.type){ // ------ Creating topics --------- socket.on('create', function(text){topicDB.onCreate(text, {email: userInfo.email, socket: socket.id});}); socket.on('sub', function(topicID){reaction.toSub(socket.id, topicID);}); socket.on('initTopic', function(matchID){ // will be called by both clients at zero time out if(sock.io.sockets.connected[matchID]){ if(reaction.timeToTalk(socket.id, matchID)){ // once both sockets check in sock.io.to(matchID).emit('chatInit', {id: socket.id, first: true}); sock.io.to(socket.id).emit('chatInit', {id: matchID, first: false}); } } }); // -- Real time chat -- socket.on('chat', function (rtt){sock.io.to(rtt.id).emit('toMe', {text: rtt.text, row: 0});}); socket.on('toOther', function (id){sock.io.to(id).emit('yourTurn');}); // signal turn socket.on('endChat', function (id){ userDB.toggle([id, socket.id]); sock.io.to(id).emit('endChat'); // tell the user they are talking with that chat is over }); // -- speed reporting -- socket.on('speed', function(avg){userDB.speed(socket.id, avg);}); // -- disconnect event ------- socket.on('disconnect', function(){userDB.logout({email: userInfo.email, socket: socket.id});}); } else { // cookie expiration event sock.io.to(socket.id).emit('redirect', '/login'); // point the client to login page to get a valid cookie } }); }, emitTo: function(command, user, data){sock.io.to(user).emit(command, data);}, } var mongo = { // depends on: mongoose SEVER: process.env.DB_ADDRESS, db: require('mongoose'), hash: require('bcryptjs'), user: null, topic: null, connect: function (){ mongo.db.connect(mongo.SEVER); var Schema = mongo.db.Schema; var ObjectId = Schema.ObjectId; mongo.user = mongo.db.model('user', new Schema({ id: ObjectId, email: { type: String, required: '{PATH} is required', unique: true }, password: { type: String, required: '{PATH} is required' }, subscribed: [Number], // topic ids user is subscribed to subIDs: [String], // IDs of subscriptions (objectId of topic) toSub: { type: Number, default: 0 }, // search possition for subscription (w/user) accountType: { type: String }, // temp, premium, moderator, admin, ect avgSpeed: { type: Number, default: 0}, // averaged out speed of user })); mongo.topic = mongo.db.model('topic', new Schema({ id: ObjectId, author: {type: String}, index: {type: Number, unique: true}, text: {type: String, unique: true} })); topicDB.init(0); // pull global topics into ram } } // actions for creating users var userAct = { // dep: mongo signup: function(req, res){ var user = new mongo.user({ // prepare to save userdata email: req.body.email, // grab email password: mongo.hash.hashSync(req.body.password, mongo.hash.genSaltSync(10)), // hash password accountType: 'free', // default acount type }); user.save(function(err){ // save user data (to mongo) if(err){console.log(err + '-userAct.signup'); } // log out possible err else { res.redirect('/login');} // point to login after signup }); }, auth: function ( render ){ return function(req, res){ if(req.session && req.session.user){ mongo.user.findOne({email: req.session.user.email}, function(err, user){ if(user){ // if this is valid user data res.render(render, {accountType: user.accountType}); // render page for this account } else { req.session.reset(); res.redirect('/#signup'); } }); } else { // given there is no session user, make one with a temp account req.session.user = {accountType: 'temp'}; // require temp in cookie res.render(render, {accountType: 'temp'}); // respond rendering with type } } }, login: function ( req, res ){ mongo.user.findOne({email: req.body.email}, function(err, user){ if(user && mongo.hash.compareSync(req.body.password, user.password)){ user.password = ':-p'; // Hide hashed password req.session.user = user; // All user data is stored in this cookie res.redirect('/topic'); // redirect to activity window } else {res.redirect('/#signup');} // redirect to signup if wrong password }); } } var cookie = { // depends on client-sessions and mongo session: require('client-sessions'), ingredients: { cookieName: 'session', secret: process.env.SESSION_SECRET, duration: 8 * 60 * 60 * 1000, // cookie times out in 8 hours activeDuration: 5 * 60 * 1000, // activity extends durration 5 minutes httpOnly: true, // block browser access to cookies... defaults to this anyhow //secure: true, // only allow cookies over HTTPS }, meWant: function (){return cookie.session(cookie.ingredients);}, user: function (content){ var result = cookie.session.util.decode(cookie.ingredients, content); return result.content.user; }, } // Express server var serve = { // depends on everything express: require('express'), parse: require('body-parser'), theSite: function (){ var app = serve.express(); var http = require('http').Server(app); // http server for express framework app.set('view engine', 'jade'); // template with jade mongo.connect(); // connect to mongo.db app.use(require('compression')()); // gzipping for requested pages app.use(serve.parse.json()); // support JSON-encoded bodies app.use(serve.parse.urlencoded({extended: true})); // support URL-encoded bodies app.use(cookie.meWant()); // support for cookies app.use(require('csurf')()); // Cross site request forgery tokens app.use(serve.express.static(__dirname + '/views')); // serve page dependancies (sockets, jquery, bootstrap) var router = serve.express.Router(); router.get('/', function ( req, res ){res.render('beta', {csrfToken: req.csrfToken()});}); router.post('/', userAct.signup); // handle logins router.get('/beta', function ( req, res ){res.render('beta', {csrfToken: req.csrfToken()});}); router.post('/beta', userAct.signup); // handle sign-ups router.get('/about', function ( req, res ){res.render('about');}); router.get('/login', function ( req, res ){res.render('login', {csrfToken: req.csrfToken()});}); router.post('/login', userAct.login); // handle logins router.get('/topic', userAct.auth('topic')); // must be authenticated for this page app.use(router); // tell app what router to use topic.action = sock.emitTo; // assign how topics are sent sock.listen(http); // listen for socket connections http.listen(process.env.PORT); // listen on specified PORT enviornment variable } } // Initiate the site serve.theSite();
serve.js
// serve.js ~ Copyright 2015 Paul Beaudet ~ Licence Affero GPL ~ See LICENCE_AFFERO for details // This serves a test application that lets people talk to strangers // Constant factors const WAIT_TIME = 30; // time topic displayed const NUM_ENTRIES = 6; // number of dialog rows allowed client side const FREQUENCY = WAIT_TIME * 1000 / NUM_ENTRIES; // frequency of topic send out // temp options const DEFAULT_SUB = [0,1,2,3]; // defualt subscriptions for temp users const DEFAULT_SUBIDS = false; // abstract persistent and temporary topic data var topicDB = { // depends on mongo temp: [], // in ram topic data init: function(number){ // populates topic array, init feed zero mongo.topic.findOne({index: number}, function(err, topick){ if(err){console.log(err + '-topicDB.init');} else if(topick){ topicDB.temp.push(topick.text); // add topic to temp list topicDB.init(number+1); // recursively load individual topics !!BLOCKING!! } }); }, onCreate: function(text, ID){ if(ID.email){ // given this is an official user var doc = new mongo.topic({text: text}); // grab a schema for a new document mongo.topic.count().exec(function(err, count){ // find out which topic this will be doc.index = count; // add unique count property to document doc.author = ID.email; // note the author of the topic var objectID = doc._id; doc.save(function(err){ // write new topic to database if(err){console.log(err + ' onCreate');} else { var userNum = userDB.grabIndex(ID.socket); // not the index number of this user topicDB.temp.push(text); // also add topic in temorary array userDB.temp[userNum].subIDs.push(objectID); // add to cached user subscriptions userDB.temp[userNum].sub.push(count) // add to cached user subscriptions } }); }); } }, } // abstract persistent and temporary user data var userDB = { // requires mongo and topic temp: [], // in ram user data logout: function(ID){ if(ID.email){ var userNum = userDB.grabIndex(ID.socket); var dataUpdate = { subscribed: userDB.temp[userNum].sub, toSub: userDB.temp[userNum].toSub, subIDs: userDB.temp[userNum].subIDs, avgSpeed: userDB.temp[userNum].speed }; mongo.user.findOneAndUpdate({email: ID.email}, dataUpdate, function(err, doc){ if(err){ console.log(err + '-userDB.logout'); } else if (doc){ // save users session information when their socket disconects userDB.temp.splice(userDB.grabIndex(ID.socket), 1); } }) } }, grabIndex: function(socket){return userDB.temp.map(function(each){return each.socket;}).indexOf(socket);}, checkIn: function(ID) { // create temporary persistence entry for online users mongo.user.findOne({email: ID.email}, function(err, doc){ if(err){ console.log(err + '-userDB.checkin'); // users must be signed up } else if (doc){ userDB.temp.push({ // toMatch & Sub default to 0 socket: ID.socket, toSub: doc.toSub, // known details sub: doc.subscribed, subIDs: doc.subIDs, // persistant details toMatch: 0, timer: 0, // temp details speed: doc.avgSpeed, // IDs of subscriptions }); topic.get(ID.socket, true); // get topic AFTER db quary sock.io.to(ID.socket).emit('speed', doc.avgSpeed); // give client last speed } }); }, fake: function(socketID){ userDB.temp.push({ socket: socketID, sub: DEFAULT_SUB, toSub: 0, subIDs: DEFAULT_SUBIDS, speed: 0, toMatch: 0, timer: 0, }); topic.get(socketID, true); // get topic AFTER db quary }, toggle: function(socket){ // stop topic.get NOTE: takes an array of sockets normally [two, sockets] for(var i=0; socket[i]; i++){ var userNum = userDB.grabIndex(socket[i]); if(userNum > -1){ if(userDB.temp[userNum].timer){ // given the timer was counting down to add topics clearTimeout(userDB.temp[userNum].timer); userDB.temp[userNum].timer = 0; } else { topic.get(socket[i]); } // other wise we are resubbing user to feed } } }, speed: function(socket, avg){userDB.temp[userDB.grabIndex(socket)].speed = avg;} } // distribute topics: does two things- proposes topics and matches users based on topics var topic = { // depends on: userDB and topicDB action: function(command, user, data){console.log(command + '-' + user + '-' + data);}, // replace with real command get: function(socket, flipbit){ // starts search for topics (both to sub and to have) var userNum = userDB.grabIndex(socket); // figures which element of db array for users if(userNum > -1){ if(flipbit){ // alternate flipbit for new sub or potential match topic.propose(socket); } else if (userNum && userDB.temp.length > 1){ // users beside first and more than one user process.nextTick(function(){match.topic(socket, 0);}); // next loop search for a match to interest } userDB.temp[userNum].timer = setTimeout(function(){topic.get(socket, !flipbit)}, FREQUENCY); // TODO: create a propose and match timer and run the clocks async } }, propose: function(socket){ var userNum = userDB.grabIndex(socket); if(userNum > -1){ if(userDB.temp[userNum].toSub < topicDB.temp.length){userDB.temp[userNum].toSub++;} // increment else{userDB.temp[userNum].toSub = 0;} // set back to zero if reached end for( var i = 0; userDB.temp[userNum].sub[i] !== undefined; i++ ){ // for every user sub if(userDB.temp[userNum].toSub === userDB.temp[userNum].sub[i]){ // if matches topic, avoid process.nextTick(function(){topic.propose(socket);}); // try again on next tick return; // don't propose } } // else user is not subscribbed to this topic, propose it to them if(topicDB.temp[userDB.temp[userNum].toSub]){ topic.action('topic', socket, {user:userDB.temp[userNum].toSub, text:topicDB.temp[userDB.temp[userNum].toSub]}); } } } } // match users based on similar topics var match = { // depends on: userDB, topic, topicDB topic: function ( socket, targetMatch ){ // find a user with a the same topic var userNum = userDB.grabIndex(socket); // find users possition in array if(userNum && userDB.temp.length > 1){ // Question our own existence and whether its worth the effort if(targetMatch){ // should always have something after first run var targetNum = userDB.grabIndex(targetMatch); // find array possition of target if(targetNum > -1){ // sanity check: is target availible if(targetNum < userNum){match.search(socket, userNum, targetNum);} else { match.search(socket, userNum, userNum - 1);} } } else { match.search(socket, userNum, userNum - 1); } // starting search (user before this user) } }, search: function ( socket, userNum, targetNum ){ // BLOCKING, Focus is searching one topic per prospect var matchSub = userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]; if(matchSub !== undefined){ if(userDB.temp[targetNum].timer){ // So long as this target is also looking for (var i = 0; userDB.temp[targetNum].sub[i] !== undefined; i++){ // for every topic prospect has if(userDB.temp[targetNum].sub[i] === matchSub){ // if their topic matches up with ours var found = userDB.temp[targetNum].socket; // who matched? userDB.temp[userNum].toMatch++; // increment to the next possible match topic.action('topic', socket, {user:found, text: topicDB.temp[matchSub], code:matchSub}); topic.action('topic', found, {user:socket, text: topicDB.temp[matchSub], code:matchSub}); return; // stop recursion, end madness! } } } } else { return;} // given no topic we have nothing further todo if(targetNum){ // so long as target id greater than being first user process.nextTick(function (){match.topic(socket, topic.db[targetNum-1].user);}); // TODO: WTF? //return; } else { // If we got to first user, loop back up to imediate previous user userDB.temp[userNum].toMatch++; // change what is being searched for to match if(userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]){ // if this user has an interest in this slot process.nextTick(function(){match.topic(socket, userDB.temp[userNum-1].socket);}); } } } } // determines how sockets react to changes var reaction = { // depends on topic onConnect: function(socket){ // returns unique id to hold in closure for socket.on events var usrInfo = false; if(socket.request.headers.cookie){ // if cookie exist var cookieCrums = socket.request.headers.cookie.split('='); // split correct cookie out usrInfo = cookie.user(cookieCrums[cookieCrums.length - 1]); // decrypt email from cookie, make it userID if(usrInfo.accountType === 'temp'){ // check if this is a temp user userDB.fake(socket.id); // temp user creation } else if (usrInfo.email){ // given an assosiated email userDB.checkIn({email:usrInfo.email, socket:socket.id}); // Create real user } } return {email: usrInfo.email, type: usrInfo.accountType}; }, toSub: function(socket, topicID){ var userID = userDB.grabIndex(socket); userDB.temp[userID].sub.push(topicID); }, readyToChat: [], timeToTalk: function(socketID, matchID){ // logic that determines who responds first var first = true; for(var i = 0; reaction.readyToChat[i]; i++){ // for all ready to chat if(reaction.readyToChat[i] === matchID){ // did this socket's match check in yet first = false; // yes? than that person got here first reaction.readyToChat.splice(i, 1); // they are about to talk with us remove that person from list } } if(first){ // given this sockets match has yet to check in, this socket is first reaction.readyToChat.push(socketID); // check in return false; // not ready to chat } else { userDB.toggle([matchID, socketID]); // stop feed return true; // ready to chat } }, } // socket.io logic var sock = { // depends on socket.io, reaction, and topic io: require('socket.io'), listen: function (server){ sock.io = sock.io(server); sock.io.on('connection', function(socket){ // whenever a new user is connected var userInfo = reaction.onConnect(socket); // returns potential user information in session cookie if(userInfo.type){ // ------ Creating topics --------- socket.on('create', function(text){topicDB.onCreate(text, {email: userInfo.email, socket: socket.id});}); socket.on('sub', function(topicID){reaction.toSub(socket.id, topicID);}); socket.on('initTopic', function(matchID){ // will be called by both clients at zero time out if(sock.io.sockets.connected[matchID]){ if(reaction.timeToTalk(socket.id, matchID)){ // once both sockets check in sock.io.to(matchID).emit('chatInit', {id: socket.id, first: true}); sock.io.to(socket.id).emit('chatInit', {id: matchID, first: false}); } } }); // -- Real time chat -- socket.on('chat', function (rtt){sock.io.to(rtt.id).emit('toMe', {text: rtt.text, row: 0});}); socket.on('toOther', function (id){sock.io.to(id).emit('yourTurn');}); // signal turn socket.on('endChat', function (id){ userDB.toggle([id, socket.id]); sock.io.to(id).emit('endChat'); // tell the user they are talking with that chat is over }); // -- speed reporting -- socket.on('speed', function(avg){userDB.speed(socket.id, avg);}); // -- disconnect event ------- socket.on('disconnect', function(){userDB.logout({email: userInfo.email, socket: socket.id});}); } else { // cookie expiration event sock.io.to(socket.id).emit('redirect', '/login'); // point the client to login page to get a valid cookie } }); }, emitTo: function(command, user, data){sock.io.to(user).emit(command, data);}, } var mongo = { // depends on: mongoose SEVER: process.env.DB_ADDRESS, db: require('mongoose'), hash: require('bcryptjs'), user: null, topic: null, connect: function (){ mongo.db.connect(mongo.SEVER); var Schema = mongo.db.Schema; var ObjectId = Schema.ObjectId; mongo.user = mongo.db.model('user', new Schema({ id: ObjectId, email: { type: String, required: '{PATH} is required', unique: true }, password: { type: String, required: '{PATH} is required' }, subscribed: [Number], // topic ids user is subscribed to subIDs: [String], // IDs of subscriptions (objectId of topic) toSub: { type: Number, default: 0 }, // search possition for subscription (w/user) accountType: { type: String }, // temp, premium, moderator, admin, ect avgSpeed: { type: Number, default: 0}, // averaged out speed of user })); mongo.topic = mongo.db.model('topic', new Schema({ id: ObjectId, author: {type: String}, index: {type: Number, unique: true}, text: {type: String, unique: true} })); topicDB.init(0); // pull global topics into ram } } // actions for creating users var userAct = { // dep: mongo signup: function(req, res){ var user = new mongo.user({ // prepare to save userdata email: req.body.email, // grab email password: mongo.hash.hashSync(req.body.password, mongo.hash.genSaltSync(10)), // hash password accountType: 'free', // default acount type }); user.save(function(err){ // save user data (to mongo) if(err){console.log(err + '-userAct.signup'); } // log out possible err else { res.redirect('/login');} // point to login after signup }); }, auth: function ( render ){ return function(req, res){ if(req.session && req.session.user){ mongo.user.findOne({email: req.session.user.email}, function(err, user){ if(user){ // if this is valid user data res.render(render, {accountType: user.accountType}); // render page for this account } else { req.session.reset(); res.redirect('/#signup'); } }); } else { // given there is no session user, make one with a temp account req.session.user = {accountType: 'temp'}; // require temp in cookie res.render(render, {accountType: 'temp'}); // respond rendering with type } } }, login: function ( req, res ){ mongo.user.findOne({email: req.body.email}, function(err, user){ if(user && mongo.hash.compareSync(req.body.password, user.password)){ user.password = ':-p'; // Hide hashed password req.session.user = user; // All user data is stored in this cookie res.redirect('/topic'); // redirect to activity window } else {res.redirect('/#signup');} // redirect to signup if wrong password }); } } var cookie = { // depends on client-sessions and mongo session: require('client-sessions'), ingredients: { cookieName: 'session', secret: process.env.SESSION_SECRET, duration: 8 * 60 * 60 * 1000, // cookie times out in 8 hours activeDuration: 5 * 60 * 1000, // activity extends durration 5 minutes httpOnly: true, // block browser access to cookies... defaults to this anyhow //secure: true, // only allow cookies over HTTPS }, meWant: function (){return cookie.session(cookie.ingredients);}, user: function (content){ var result = cookie.session.util.decode(cookie.ingredients, content); return result.content.user; }, } // Express server var serve = { // depends on everything express: require('express'), parse: require('body-parser'), theSite: function (){ var app = serve.express(); var http = require('http').Server(app); // http server for express framework app.set('view engine', 'jade'); // template with jade mongo.connect(); // connect to mongo.db app.use(require('compression')()); // gzipping for requested pages app.use(serve.parse.json()); // support JSON-encoded bodies app.use(serve.parse.urlencoded({extended: true})); // support URL-encoded bodies app.use(cookie.meWant()); // support for cookies app.use(require('csurf')()); // Cross site request forgery tokens app.use(serve.express.static(__dirname + '/views')); // serve page dependancies (sockets, jquery, bootstrap) var router = serve.express.Router(); router.get('/', function ( req, res ){res.render('beta', {csrfToken: req.csrfToken()});}); router.post('/', userAct.signup); // handle logins router.get('/beta', function ( req, res ){res.render('beta', {csrfToken: req.csrfToken()});}); router.post('/beta', userAct.signup); // handle sign-ups router.get('/about', function ( req, res ){res.render('about');}); router.get('/login', function ( req, res ){res.render('login', {csrfToken: req.csrfToken()});}); router.post('/login', userAct.login); // handle logins router.get('/topic', userAct.auth('topic')); // must be authenticated for this page app.use(router); // tell app what router to use topic.action = sock.emitTo; // assign how topics are sent sock.listen(http); // listen for socket connections http.listen(process.env.PORT); // listen on specified PORT enviornment variable } } // Initiate the site serve.theSite();
debug topic matching and run it async of propositions
serve.js
debug topic matching and run it async of propositions
<ide><path>erve.js <ide> // Constant factors <ide> const WAIT_TIME = 30; // time topic displayed <ide> const NUM_ENTRIES = 6; // number of dialog rows allowed client side <del>const FREQUENCY = WAIT_TIME * 1000 / NUM_ENTRIES; // frequency of topic send out <add>const FREQUENCY = WAIT_TIME * 2000 / NUM_ENTRIES; // frequency of topic send out <ide> // temp options <ide> const DEFAULT_SUB = [0,1,2,3]; // defualt subscriptions for temp users <ide> const DEFAULT_SUBIDS = false; <ide> userDB.temp.push({ // toMatch & Sub default to 0 <ide> socket: ID.socket, toSub: doc.toSub, // known details <ide> sub: doc.subscribed, subIDs: doc.subIDs, // persistant details <del> toMatch: 0, timer: 0, // temp details <add> toMatch: 0, // temp details <ide> speed: doc.avgSpeed, // IDs of subscriptions <ide> }); <del> topic.get(ID.socket, true); // get topic AFTER db quary <add> topic.propose(ID.socket); <add> match.topic(ID.socket); <ide> sock.io.to(ID.socket).emit('speed', doc.avgSpeed); // give client last speed <ide> } <ide> }); <ide> socket: socketID, sub: DEFAULT_SUB, <ide> toSub: 0, subIDs: DEFAULT_SUBIDS, <ide> speed: 0, toMatch: 0, <del> timer: 0, <del> }); <del> topic.get(socketID, true); // get topic AFTER db quary <del> }, <del> toggle: function(socket){ // stop topic.get NOTE: takes an array of sockets normally [two, sockets] <add> }); <add> topic.propose(socketID); <add> match.topic(socketID); <add> }, <add> toggle: function(socket){ // stop prop and match NOTE: takes an array of sockets normally [two, sockets] <ide> for(var i=0; socket[i]; i++){ <ide> var userNum = userDB.grabIndex(socket[i]); <ide> if(userNum > -1){ <del> if(userDB.temp[userNum].timer){ // given the timer was counting down to add topics <del> clearTimeout(userDB.temp[userNum].timer); <del> userDB.temp[userNum].timer = 0; <add> if(userDB.temp[userNum].pTimer){ // given the timer was counting down to add topics <add> clearTimeout(userDB.temp[userNum].mTimer); <add> clearTimeout(userDB.temp[userNum].pTimer); <add> userDB.temp[userNum].mTimer = 0; <add> userDB.temp[userNum].pTimer = 0; <ide> } else { <del> topic.get(socket[i]); <add> topic.propose(socket[i]); <add> match.topic(socket[i]); <ide> } // other wise we are resubbing user to feed <ide> } <ide> } <ide> // distribute topics: does two things- proposes topics and matches users based on topics <ide> var topic = { // depends on: userDB and topicDB <ide> action: function(command, user, data){console.log(command + '-' + user + '-' + data);}, // replace with real command <del> get: function(socket, flipbit){ // starts search for topics (both to sub and to have) <del> var userNum = userDB.grabIndex(socket); // figures which element of db array for users <del> if(userNum > -1){ <del> if(flipbit){ // alternate flipbit for new sub or potential match <del> topic.propose(socket); <del> } else if (userNum && userDB.temp.length > 1){ // users beside first and more than one user <del> process.nextTick(function(){match.topic(socket, 0);}); // next loop search for a match to interest <del> } <del> userDB.temp[userNum].timer = setTimeout(function(){topic.get(socket, !flipbit)}, FREQUENCY); <del> // TODO: create a propose and match timer and run the clocks async <del> } <del> }, <ide> propose: function(socket){ <ide> var userNum = userDB.grabIndex(socket); <ide> if(userNum > -1){ <ide> for( var i = 0; userDB.temp[userNum].sub[i] !== undefined; i++ ){ // for every user sub <ide> if(userDB.temp[userNum].toSub === userDB.temp[userNum].sub[i]){ // if matches topic, avoid <ide> process.nextTick(function(){topic.propose(socket);}); // try again on next tick <del> return; // don't propose <add> return; // don't propose / short curcuit <ide> } <ide> } // else user is not subscribbed to this topic, propose it to them <ide> if(topicDB.temp[userDB.temp[userNum].toSub]){ <ide> topic.action('topic', socket, {user:userDB.temp[userNum].toSub, text:topicDB.temp[userDB.temp[userNum].toSub]}); <ide> } <add> userDB.temp[userNum].pTimer = setTimeout(function(){topic.propose(socket);}, FREQUENCY); <ide> } <ide> } <ide> } <ide> <ide> // match users based on similar topics <ide> var match = { // depends on: userDB, topic, topicDB <del> topic: function ( socket, targetMatch ){ // find a user with a the same topic <del> var userNum = userDB.grabIndex(socket); // find users possition in array <del> if(userNum && userDB.temp.length > 1){ // Question our own existence and whether its worth the effort <del> if(targetMatch){ // should always have something after first run <del> var targetNum = userDB.grabIndex(targetMatch); // find array possition of target <del> if(targetNum > -1){ // sanity check: is target availible <del> if(targetNum < userNum){match.search(socket, userNum, targetNum);} <del> else { match.search(socket, userNum, userNum - 1);} <add> topic: function ( socket, targetID ){ // find a user with a the same topic <add> var userNum = userDB.grabIndex(socket); // find users possition in array <add> if(userNum && userDB.temp.length > 1){ // Should we be looking? zeroth and undefined users never look <add> var targetNum = userNum - 1; // if no target is provide, target user before us <add> if(targetID){targetNum = userDB.grabIndex(targetID);} // else target the user before last we looked at <add> if(userDB.temp[targetNum].pTimer){ // So long as this target is also looking <add> userDB.temp[userNum].toMatch++; // increment match target <add> var matchSub = userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]; // read match target <add> if(matchSub === undefined){ // if match target does not exist <add> userDB.temp[userNum].toMatch = 0; // set target back to zero <add> matchSub = userDB.temp[userNum].sub[0]; // set match sub to reflect new target <add> if(matchSub === undefined){matchSub = 0;} // default to first topic if subscribed to none <ide> } <del> } else { match.search(socket, userNum, userNum - 1); } // starting search (user before this user) <del> } <del> }, <del> search: function ( socket, userNum, targetNum ){ // BLOCKING, Focus is searching one topic per prospect <del> var matchSub = userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]; <del> if(matchSub !== undefined){ <del> if(userDB.temp[targetNum].timer){ // So long as this target is also looking <ide> for (var i = 0; userDB.temp[targetNum].sub[i] !== undefined; i++){ // for every topic prospect has <del> if(userDB.temp[targetNum].sub[i] === matchSub){ // if their topic matches up with ours <del> var found = userDB.temp[targetNum].socket; // who matched? <del> userDB.temp[userNum].toMatch++; // increment to the next possible match <add> if(userDB.temp[targetNum].sub[i] === matchSub){ // if their topic matches up with ours <add> var found = userDB.temp[targetNum].socket; // who matched? <ide> topic.action('topic', socket, {user:found, text: topicDB.temp[matchSub], code:matchSub}); <ide> topic.action('topic', found, {user:socket, text: topicDB.temp[matchSub], code:matchSub}); <del> return; // stop recursion, end madness! <ide> } <ide> } <ide> } <del> } else { return;} // given no topic we have nothing further todo <del> if(targetNum){ // so long as target id greater than being first user <del> process.nextTick(function (){match.topic(socket, topic.db[targetNum-1].user);}); // TODO: WTF? <del> //return; <del> } else { // If we got to first user, loop back up to imediate previous user <del> userDB.temp[userNum].toMatch++; // change what is being searched for to match <del> if(userDB.temp[userNum].sub[userDB.temp[userNum].toMatch]){ // if this user has an interest in this slot <del> process.nextTick(function(){match.topic(socket, userDB.temp[userNum-1].socket);}); <del> } <add> if(targetNum){ // given we just searched someone other than the zeroth user, search the next target before them <add> userDB.temp[userNum].mTimer = setTimeout(function (){match.topic(socket, userDB.temp[targetNum-1].user);}, FREQUENCY); <add> } else { userDB.temp[userNum].mTimer = setTimeout(function(){match.topic(socket);}, FREQUENCY); } <ide> } <ide> } <ide> }
Java
apache-2.0
e42daa78761e4df5071807a575bb2d2146cbdedc
0
symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager,symbiote-h2020/AuthenticationAuthorizationManager
package eu.h2020.symbiote.security.integration; import eu.h2020.symbiote.security.AbstractAAMTestSuite; import eu.h2020.symbiote.security.commons.Certificate; import eu.h2020.symbiote.security.commons.exceptions.custom.InvalidArgumentsException; import eu.h2020.symbiote.security.commons.exceptions.custom.NotExistingUserException; import eu.h2020.symbiote.security.commons.exceptions.custom.ValidationException; import eu.h2020.symbiote.security.commons.exceptions.custom.WrongCredentialsException; import eu.h2020.symbiote.security.helpers.PlatformAAMCertificateKeyStoreFactory; import eu.h2020.symbiote.security.repositories.entities.Platform; import eu.h2020.symbiote.security.repositories.entities.User; import org.junit.Test; import org.springframework.test.context.TestPropertySource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.*; import java.security.cert.CertificateException; import java.util.HashMap; import static junit.framework.TestCase.assertTrue; import static org.hibernate.validator.internal.util.Contracts.assertNotNull; @TestPropertySource("/core.properties") public class PlatformCertificateKeyStoreTests extends AbstractAAMTestSuite { private final String KEY_STORE_PATH = "./src/test/resources/new.p12"; private final String KEY_STORE_PASSWORD = "1234567"; @Test public void PlatformCertificateKeyStoreSuccess() throws IOException, CertificateException, NoSuchAlgorithmException, ValidationException, KeyStoreException, InvalidArgumentsException, InvalidAlgorithmParameterException, NotExistingUserException, WrongCredentialsException, NoSuchProviderException, UnrecoverableKeyException { //platformOwner and platform registration User platformOwner = savePlatformOwner(); Platform platform = new Platform(platformId, "", "", platformOwner, new Certificate(), new HashMap<>()); platformRepository.save(platform); platformOwner.getOwnedPlatforms().add(platformId); userRepository.save(platformOwner); PlatformAAMCertificateKeyStoreFactory.getPlatformAAMKeystore( serverAddress, platformOwnerUsername, platformOwnerPassword, platformId, KEY_STORE_PATH, KEY_STORE_PASSWORD, "root_cert", "aam_cert" ); //keyStore checking if proper Certificates exists KeyStore trustStore = KeyStore.getInstance("PKCS12", "BC"); try ( FileInputStream fIn = new FileInputStream(KEY_STORE_PATH)) { trustStore.load(fIn, KEY_STORE_PASSWORD.toCharArray()); fIn.close(); assertNotNull(trustStore.getCertificate("root_cert")); assertNotNull(trustStore.getCertificate("aam_cert")); } //cleanup File file = new File(KEY_STORE_PATH); assertTrue(file.delete()); } }
src/test/java/eu/h2020/symbiote/security/integration/PlatformCertificateKeyStoreTests.java
package eu.h2020.symbiote.security.integration; import eu.h2020.symbiote.security.AbstractAAMTestSuite; import eu.h2020.symbiote.security.commons.Certificate; import eu.h2020.symbiote.security.commons.exceptions.custom.InvalidArgumentsException; import eu.h2020.symbiote.security.commons.exceptions.custom.NotExistingUserException; import eu.h2020.symbiote.security.commons.exceptions.custom.ValidationException; import eu.h2020.symbiote.security.commons.exceptions.custom.WrongCredentialsException; import eu.h2020.symbiote.security.helpers.PlatformAAMCertificateKeyStoreFactory; import eu.h2020.symbiote.security.repositories.entities.Platform; import eu.h2020.symbiote.security.repositories.entities.User; import org.junit.Test; import org.springframework.test.context.TestPropertySource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.*; import java.security.cert.CertificateException; import java.util.HashMap; import static junit.framework.TestCase.assertTrue; import static org.hibernate.validator.internal.util.Contracts.assertNotNull; @TestPropertySource("/core.properties") public class PlatformCertificateKeyStoreTests extends AbstractAAMTestSuite { private final String KEY_STORE_PATH = "./src/test/resources/new.p12"; private final String KEY_STORE_PASSWORD = "1234567"; @Test public void PlatformCertificateKeyStoreSuccess() throws IOException, CertificateException, NoSuchAlgorithmException, ValidationException, KeyStoreException, InvalidArgumentsException, InvalidAlgorithmParameterException, NotExistingUserException, WrongCredentialsException, NoSuchProviderException { //platformOwner and platform registration User platformOwner = savePlatformOwner(); Platform platform = new Platform(platformId, "", "", platformOwner, new Certificate(), new HashMap<>()); platformRepository.save(platform); platformOwner.getOwnedPlatforms().add(platformId); userRepository.save(platformOwner); PlatformAAMCertificateKeyStoreFactory.getPlatformAAMKeystore( serverAddress, platformOwnerUsername, platformOwnerPassword, platformId, KEY_STORE_PATH, KEY_STORE_PASSWORD, "root_cert", "aam_cert", PV_KEY_PASSWORD ); //keyStore checking if proper Certificates exists KeyStore trustStore = KeyStore.getInstance("PKCS12", "BC"); try ( FileInputStream fIn = new FileInputStream(KEY_STORE_PATH)) { trustStore.load(fIn, KEY_STORE_PASSWORD.toCharArray()); fIn.close(); assertNotNull(trustStore.getCertificate("root_cert")); assertNotNull(trustStore.getCertificate("aam_cert")); } //cleanup File file = new File(KEY_STORE_PATH); assertTrue(file.delete()); } }
dirty fix to PAAM keystore generator
src/test/java/eu/h2020/symbiote/security/integration/PlatformCertificateKeyStoreTests.java
dirty fix to PAAM keystore generator
<ide><path>rc/test/java/eu/h2020/symbiote/security/integration/PlatformCertificateKeyStoreTests.java <ide> <ide> <ide> @Test <del> public void PlatformCertificateKeyStoreSuccess() throws IOException, CertificateException, NoSuchAlgorithmException, ValidationException, KeyStoreException, InvalidArgumentsException, InvalidAlgorithmParameterException, NotExistingUserException, WrongCredentialsException, NoSuchProviderException { <add> public void PlatformCertificateKeyStoreSuccess() throws <add> IOException, <add> CertificateException, <add> NoSuchAlgorithmException, <add> ValidationException, <add> KeyStoreException, <add> InvalidArgumentsException, <add> InvalidAlgorithmParameterException, <add> NotExistingUserException, <add> WrongCredentialsException, <add> NoSuchProviderException, <add> UnrecoverableKeyException { <ide> //platformOwner and platform registration <ide> User platformOwner = savePlatformOwner(); <ide> Platform platform = new Platform(platformId, "", "", platformOwner, new Certificate(), new HashMap<>()); <ide> userRepository.save(platformOwner); <ide> <ide> PlatformAAMCertificateKeyStoreFactory.getPlatformAAMKeystore( <del> serverAddress, platformOwnerUsername, platformOwnerPassword, platformId, KEY_STORE_PATH, <add> serverAddress, <add> platformOwnerUsername, <add> platformOwnerPassword, <add> platformId, <add> KEY_STORE_PATH, <ide> KEY_STORE_PASSWORD, <del> "root_cert", "aam_cert", PV_KEY_PASSWORD <add> "root_cert", <add> "aam_cert" <ide> ); <ide> //keyStore checking if proper Certificates exists <ide> KeyStore trustStore = KeyStore.getInstance("PKCS12", "BC");
JavaScript
agpl-3.0
8a97d6091311b7c75161da9f3b3d08fff70eda11
0
archesproject/arches,archesproject/arches,archesproject/arches,archesproject/arches
define(['knockout', 'underscore', 'uuid'], function (ko, _, uuid) { /** * A viewmodel used for generic widgets * * @constructor * @name WidgetViewModel * * @param {string} params - a configuration object */ var WidgetViewModel = function(params) { var self = this; this.state = params.state || 'form'; var expanded = params.expanded || ko.observable(false); var nodeid = params.node ? params.node.nodeid : uuid.generate(); this.expanded = ko.computed({ read: function() { return nodeid === expanded(); }, write: function(val) { if (val) { expanded(nodeid); } else { expanded(false); } } }); this.value = params.value || ko.observable(null); this.formData = params.formData || new FormData(); this.form = params.form || null; this.tile = params.tile || null; this.results = params.results || null; this.displayValue = ko.computed(function() { return ko.unwrap(self.value); }); this.disabled = params.disabled || ko.observable(false); this.node = params.node || null; this.configForm = params.configForm || false; this.config = params.config || ko.observable({}); this.configObservables = params.configObservables || {}; this.configKeys = params.configKeys || []; this.configKeys.push('label'); this.configKeys.push('required'); if (this.node) { this.required = this.node.isrequired; } if (typeof this.config !== 'function') { this.config = ko.observable(this.config); } var subscribeConfigObservable = function (obs, key) { self[key] = obs; self[key].subscribe(function(val) { var configObj = self.config(); configObj[key] = val; self.config(configObj); }); self.config.subscribe(function(val) { if (val[key] !== self[key]()) { self[key](val[key]); } }); }; _.each(this.configObservables, subscribeConfigObservable); _.each(this.configKeys, function(key) { var obs = ko.observable(self.config()[key]); subscribeConfigObservable(obs, key); }); if (ko.isObservable(this.defaultValue)) { var defaultValue = this.defaultValue(); if (this.tile && this.tile.tileid() == "" && defaultValue != null && defaultValue != "") { this.value(defaultValue); } if (!self.form) { if (ko.isObservable(self.value)) { self.value.subscribe(function(val){ if (self.defaultValue() != val) { self.defaultValue(val) }; }); self.defaultValue.subscribe(function(val){ if (self.value() != val) { self.value(val) }; }); } }; }; }; return WidgetViewModel; });
arches/app/media/js/viewmodels/widget.js
define(['knockout', 'underscore', 'uuid'], function (ko, _, uuid) { /** * A viewmodel used for generic widgets * * @constructor * @name WidgetViewModel * * @param {string} params - a configuration object */ var WidgetViewModel = function(params) { var self = this; this.state = params.state || 'form'; var expanded = params.expanded || ko.observable(false); var nodeid = params.node ? params.node.nodeid : uuid.generate(); this.expanded = ko.computed({ read: function() { return nodeid === expanded(); }, write: function(val) { if (val) { expanded(nodeid); } else { expanded(false); } } }); this.value = params.value || ko.observable(null); this.formData = params.formData || new FormData(); this.form = params.form || null; this.tile = params.tile || null; this.results = params.results || null; this.displayValue = ko.computed(function() { return ko.unwrap(self.value); }); this.disabled = params.disabled || ko.observable(false); this.node = params.node || null; this.configForm = params.configForm || false; this.config = params.config || ko.observable({}); this.configObservables = params.configObservables || {}; this.configKeys = params.configKeys || []; this.configKeys.push('label'); this.configKeys.push('required'); if (this.node) { this.required = this.node.isrequired; } if (typeof this.config !== 'function') { this.config = ko.observable(this.config); } var subscribeConfigObservable = function (obs, key) { self[key] = obs; self[key].subscribe(function(val) { var configObj = self.config(); configObj[key] = val; self.config(configObj); }); self.config.subscribe(function(val) { if (val[key] !== self[key]()) { self[key](val[key]); } }); }; _.each(this.configObservables, subscribeConfigObservable); _.each(this.configKeys, function(key) { var obs = ko.observable(self.config()[key]); subscribeConfigObservable(obs, key); }); if (ko.isObservable(this.defaultValue)) { var defaultValue = this.defaultValue(); if (this.tile && this.tile.tileid() == "" && defaultValue != null && defaultValue != "") { this.value(defaultValue); } if (!self.form) { self.value.subscribe(function(val){ if (self.defaultValue() != val) { self.defaultValue(val) }; }); self.defaultValue.subscribe(function(val){ if (self.value() != val) { self.value(val) }; }); }; }; }; return WidgetViewModel; });
Prevents error in cases when value is not observable - like when a report loads. #2709
arches/app/media/js/viewmodels/widget.js
Prevents error in cases when value is not observable - like when a report loads. #2709
<ide><path>rches/app/media/js/viewmodels/widget.js <ide> } <ide> <ide> if (!self.form) { <del> self.value.subscribe(function(val){ <del> if (self.defaultValue() != val) { <del> self.defaultValue(val) <del> }; <del> }); <del> self.defaultValue.subscribe(function(val){ <del> if (self.value() != val) { <del> self.value(val) <del> }; <del> }); <add> if (ko.isObservable(self.value)) { <add> self.value.subscribe(function(val){ <add> if (self.defaultValue() != val) { <add> self.defaultValue(val) <add> }; <add> }); <add> self.defaultValue.subscribe(function(val){ <add> if (self.value() != val) { <add> self.value(val) <add> }; <add> }); <add> } <ide> }; <ide> }; <ide> };
Java
agpl-3.0
c4f096dd5214cde2516dfbabc5f12724ac644f4a
0
sindice/sparqled,sindice/sparqled
/** * Copyright (c) 2012 National University of Ireland, Galway. All Rights Reserved. * * * This project is a free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This project is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this project. If not, see <http://www.gnu.org/licenses/>. */ package org.sindice.analytics.queryProcessor; import java.io.StringWriter; import org.openrdf.query.MalformedQueryException; import org.openrdf.sindice.query.parser.sparql.ast.ASTConstraint; import org.openrdf.sindice.query.parser.sparql.ast.ASTQueryContainer; import org.openrdf.sindice.query.parser.sparql.ast.ParseException; import org.openrdf.sindice.query.parser.sparql.ast.SyntaxTreeBuilder; import org.openrdf.sindice.query.parser.sparql.ast.VisitorException; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; /** * */ public class DGSQueryProcessor implements QueryProcessor { /** Default name of the template */ public static final String TEMPLATE_NAME = "translate.mustache"; private final Mustache mustache; private ASTQueryContainer ast; private String dgsQuery; private final SparqlToDGSQuery dgs = new SparqlToDGSQuery(); private final StringWriter writer = new StringWriter(); public DGSQueryProcessor() { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(TEMPLATE_NAME); } /** * Create a new instance with a custom {@link Mustache} template * @param pathToTemplate the path to the Mustache template for the SPARQL query translation */ public DGSQueryProcessor(String pathToTemplate) { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(pathToTemplate); } /** * Create a new instance with the given {@link Mustache} instance */ public DGSQueryProcessor(Mustache template) { if (template == null) { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(TEMPLATE_NAME); } else { mustache = template; } } @Override public String getDGSQueryWithLimit(int limit, ASTConstraint... contraints) throws DGSException { dgs.getRecommendationQuery().setLimit(limit); return this.getDGSQuery(contraints); } @Override public String getDGSQuery(ASTConstraint... contraints) throws DGSException { if (dgsQuery == null) { if (contraints != null && contraints.length != 0) { // TODO: add possible constraints to the query ast.getQuery().getWhereClause(); } writer.getBuffer().setLength(0); dgsQuery = mustache.execute(writer, dgs.getRecommendationQuery()).toString(); } return dgsQuery; } @Override public void load(String query) throws DGSException { try { dgsQuery = null; ast = SyntaxTreeBuilder.parseQuery(query); dgs.process(ast); } catch (Exception e) { throw new DGSException(e); } } @Override public POFMetadata getPofASTMetadata() { return dgs.getPOFMetadata(); } @Override public RecommendationType getRecommendationType() { return dgs.getRecommendationType(); } }
recommendation-servlet/src/main/java/org/sindice/analytics/queryProcessor/DGSQueryProcessor.java
/** * Copyright (c) 2012 National University of Ireland, Galway. All Rights Reserved. * * * This project is a free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This project is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this project. If not, see <http://www.gnu.org/licenses/>. */ package org.sindice.analytics.queryProcessor; import java.io.StringWriter; import org.openrdf.query.MalformedQueryException; import org.openrdf.sindice.query.parser.sparql.ast.ASTConstraint; import org.openrdf.sindice.query.parser.sparql.ast.ASTQueryContainer; import org.openrdf.sindice.query.parser.sparql.ast.ParseException; import org.openrdf.sindice.query.parser.sparql.ast.SyntaxTreeBuilder; import org.openrdf.sindice.query.parser.sparql.ast.VisitorException; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; /** * */ public class DGSQueryProcessor implements QueryProcessor { /** Default name of the template */ public static final String TEMPLATE_NAME = "translate.mustache"; private final Mustache mustache; private ASTQueryContainer ast; private String dgsQuery; private final SparqlToDGSQuery dgs = new SparqlToDGSQuery(); private final StringWriter writer = new StringWriter(); public DGSQueryProcessor() { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(TEMPLATE_NAME); } public DGSQueryProcessor(String pathToTemplate) { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(pathToTemplate); } public DGSQueryProcessor(Mustache template) { if (template == null) { MustacheFactory mf = new DefaultMustacheFactory(); mustache = mf.compile(TEMPLATE_NAME); } else { mustache = template; } } @Override public String getDGSQueryWithLimit(int limit, ASTConstraint... contraints) throws DGSException { dgs.getRecommendationQuery().setLimit(limit); return this.getDGSQuery(contraints); } @Override public String getDGSQuery(ASTConstraint... contraints) throws DGSException { if (dgsQuery == null) { if (contraints != null && contraints.length != 0) { // TODO: add possible constraints to the query ast.getQuery().getWhereClause(); } writer.getBuffer().setLength(0); dgsQuery = mustache.execute(writer, dgs.getRecommendationQuery()).toString(); } return dgsQuery; } @Override public void load(String query) throws DGSException { try { dgsQuery = null; ast = SyntaxTreeBuilder.parseQuery(query); dgs.process(ast); } catch (ParseException e) { throw new DGSException(e); } catch (VisitorException e) { throw new DGSException(e); } catch (MalformedQueryException e) { throw new DGSException(e); } } @Override public POFMetadata getPofASTMetadata() { return dgs.getPOFMetadata(); } @Override public RecommendationType getRecommendationType() { return dgs.getRecommendationType(); } }
Update DGSQueryProcessor.java
recommendation-servlet/src/main/java/org/sindice/analytics/queryProcessor/DGSQueryProcessor.java
Update DGSQueryProcessor.java
<ide><path>ecommendation-servlet/src/main/java/org/sindice/analytics/queryProcessor/DGSQueryProcessor.java <ide> mustache = mf.compile(TEMPLATE_NAME); <ide> } <ide> <add> /** <add> * Create a new instance with a custom {@link Mustache} template <add> * @param pathToTemplate the path to the Mustache template for the SPARQL query translation <add> */ <ide> public DGSQueryProcessor(String pathToTemplate) { <ide> MustacheFactory mf = new DefaultMustacheFactory(); <ide> mustache = mf.compile(pathToTemplate); <ide> } <ide> <add> /** <add> * Create a new instance with the given {@link Mustache} instance <add> */ <ide> public DGSQueryProcessor(Mustache template) { <ide> if (template == null) { <ide> MustacheFactory mf = new DefaultMustacheFactory(); <ide> dgsQuery = null; <ide> ast = SyntaxTreeBuilder.parseQuery(query); <ide> dgs.process(ast); <del> } catch (ParseException e) { <del> throw new DGSException(e); <del> } catch (VisitorException e) { <del> throw new DGSException(e); <del> } catch (MalformedQueryException e) { <add> } catch (Exception e) { <ide> throw new DGSException(e); <ide> } <ide> }
Java
apache-2.0
eb9c83df4463de1502a7a4500bd69813c3240459
0
google/agi,google/agi,google/agi,google/agi,google/agi,google/agi,google/agi,google/agi
/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gapid.views; import static com.google.gapid.image.Images.noAlpha; import static com.google.gapid.models.ImagesModel.THUMB_SIZE; import static com.google.gapid.util.GeoUtils.right; import static com.google.gapid.util.GeoUtils.top; import static com.google.gapid.util.Loadable.MessageType.Error; import static com.google.gapid.util.Loadable.MessageType.Info; import static com.google.gapid.util.Logging.throttleLogRpcError; import static com.google.gapid.widgets.Widgets.createBaloonToolItem; import static com.google.gapid.widgets.Widgets.createComposite; import static com.google.gapid.widgets.Widgets.createLabel; import static com.google.gapid.widgets.Widgets.createSeparator; import static com.google.gapid.widgets.Widgets.createToggleToolItem; import static com.google.gapid.widgets.Widgets.createToolItem; import static com.google.gapid.widgets.Widgets.exclusiveSelection; import static com.google.gapid.widgets.Widgets.disposeAllChildren; import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed; import static com.google.gapid.widgets.Widgets.withLayoutData; import static java.util.Collections.emptyList; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.gapid.image.FetchedImage; import com.google.gapid.image.MultiLayerAndLevelImage; import com.google.gapid.models.Analytics.View; import com.google.gapid.models.Capture; import com.google.gapid.models.CommandStream; import com.google.gapid.models.CommandStream.CommandIndex; import com.google.gapid.models.Devices; import com.google.gapid.models.Follower; import com.google.gapid.models.Models; import com.google.gapid.models.Settings; import com.google.gapid.proto.device.Device; import com.google.gapid.proto.service.Service; import com.google.gapid.proto.service.Service.ClientAction; import com.google.gapid.proto.service.api.API; import com.google.gapid.proto.service.path.Path; import com.google.gapid.rpc.Rpc; import com.google.gapid.rpc.RpcException; import com.google.gapid.rpc.SingleInFlight; import com.google.gapid.rpc.UiErrorCallback; import com.google.gapid.server.Client.DataUnavailableException; import com.google.gapid.util.Experimental; import com.google.gapid.util.Loadable; import com.google.gapid.util.Messages; import com.google.gapid.util.MoreFutures; import com.google.gapid.util.Paths; import com.google.gapid.widgets.Balloon; import com.google.gapid.widgets.HorizontalList; import com.google.gapid.widgets.ImagePanel; import com.google.gapid.widgets.LoadableImage; import com.google.gapid.widgets.LoadingIndicator; import com.google.gapid.widgets.Theme; import com.google.gapid.widgets.Widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.internal.DPIUtil; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; import java.util.logging.Level; /** * View that displays the framebuffer at the current selection in an {@link ImagePanel}. */ public class FramebufferView extends Composite implements Tab, Capture.Listener, Devices.Listener, CommandStream.Listener, Follower.Listener { private static final Logger LOG = Logger.getLogger(FramebufferView.class.getName()); private static final int MAX_SIZE = 0xffff; private enum RenderSetting { RENDER_SHADED(MAX_SIZE, MAX_SIZE, Path.DrawMode.NORMAL), RENDER_OVERLAY(MAX_SIZE, MAX_SIZE, Path.DrawMode.WIREFRAME_OVERLAY), RENDER_WIREFRAME(MAX_SIZE, MAX_SIZE, Path.DrawMode.WIREFRAME_ALL), RENDER_OVERDRAW(MAX_SIZE, MAX_SIZE, Path.DrawMode.OVERDRAW), RENDER_THUMB(THUMB_SIZE, THUMB_SIZE, Path.DrawMode.NORMAL); public final int maxWidth; public final int maxHeight; public final Path.DrawMode drawMode; private RenderSetting(int maxWidth, int maxHeight, Path.DrawMode drawMode) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.drawMode = drawMode; } public Path.RenderSettings getRenderSettings(Settings settings) { return Paths.renderSettings(maxWidth, maxHeight, drawMode, settings.preferences().getDisableReplayOptimization()); } } private final Models models; private final Widgets widgets; private final SingleInFlight rpcController = new SingleInFlight(); protected final ImagePanel imagePanel; private RenderSetting renderSettings; private int target = 0; private final AttachmentPicker picker; private final Label pickerLabel; private final Composite splitter; private final GridData pickerGridData; private final Button pickerToggle; private boolean showAttachments; public FramebufferView(Composite parent, Models models, Widgets widgets) { super(parent, SWT.NONE); this.models = models; this.widgets = widgets; setLayout(new GridLayout(2, false)); ToolBar toolBar = createToolBar(widgets.theme); Composite header = createComposite(this, new GridLayout(2, false)); splitter = createComposite(this, new GridLayout(1, false)); picker = new AttachmentPicker(splitter); picker.addContentListener(SWT.MouseDown, e -> picker.selectAttachment(picker.getItemAt(e.x))); imagePanel = new ImagePanel(splitter, View.Framebuffer, models.analytics, widgets, true); pickerGridData = new GridData(SWT.FILL, SWT.FILL, true, false); showAttachments = models.settings.ui().getFramebufferPicker().getEnabled(); pickerGridData.exclude = true; picker.setVisible(false); splitter.addListener(SWT.Resize, e -> picker.resize()); toolBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 2)); header.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); splitter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); picker.setLayoutData(pickerGridData); imagePanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); pickerLabel = withLayoutData(createLabel(header, "Attachment:"), new GridData(SWT.FILL, SWT.CENTER, true, true)); pickerToggle = new Button(header, SWT.PUSH); pickerToggle.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false)); pickerToggle.setText(showAttachments ? "Hide Attachments" : "Show Attachments"); pickerToggle.addListener(SWT.Selection, e -> { showAttachments = !showAttachments; pickerGridData.exclude = !showAttachments; picker.setVisible(showAttachments); models.settings.writeUi().getFramebufferPickerBuilder().setEnabled(showAttachments); pickerToggle.setText(showAttachments ? "Hide Attachments" : "Show Attachments"); splitter.layout(); }); pickerToggle.setEnabled(false); imagePanel.createToolbar(toolBar, widgets.theme); // Work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=517480 Widgets.createSeparator(toolBar); renderSettings = RenderSetting.RENDER_SHADED; models.capture.addListener(this); models.devices.addListener(this); models.commands.addListener(this); models.follower.addListener(this); addListener(SWT.Dispose, e -> { models.capture.removeListener(this); models.devices.removeListener(this); models.commands.removeListener(this); models.follower.removeListener(this); }); } private ToolBar createToolBar(Theme theme) { ToolBar bar = new ToolBar(this, SWT.VERTICAL | SWT.FLAT); List<ToolItem> items = Lists.newArrayList( createToggleToolItem(bar, theme.wireframeNone(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Shaded); renderSettings = RenderSetting.RENDER_SHADED; updateBuffer(); }, "Render shaded geometry")); // The RENDER_OVERLAY feature leads to an error right now. // TODO(b/188417572): Investigate and fix this issue. if (Experimental.enableUnstableFeatures(models.settings)) { items.add(createToggleToolItem(bar, theme.wireframeOverlay(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.OverlayWireframe); renderSettings = RenderSetting.RENDER_OVERLAY; updateBuffer(); }, "Render shaded geometry and overlay wireframe of last draw call")); } items.add(createToggleToolItem(bar, theme.wireframeAll(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Wireframe); renderSettings = RenderSetting.RENDER_WIREFRAME; updateBuffer(); }, "Render wireframe geometry")); // The RENDER_OVERDRAW feature can cause crashes right now, disable by default. // TODO(b/188431629): Investigate and fix the overdraw issue. if (Experimental.enableUnstableFeatures(models.settings)) { items.add(createToggleToolItem(bar, theme.overdraw(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Overdraw); renderSettings = RenderSetting.RENDER_OVERDRAW; updateBuffer(); }, "Render overdraw")); } exclusiveSelection(items); createSeparator(bar); return bar; } @Override public Control getControl() { return this; } @Override public void reinitialize() { picker.setVisible(false); pickerGridData.exclude = true; pickerToggle.setEnabled(false); if (!models.capture.isLoaded()) { onCaptureLoadingStart(false); } else { loadBuffer(); } } @Override public void onCaptureLoadingStart(boolean maintainState) { picker.setVisible(false); pickerGridData.exclude = true; pickerToggle.setEnabled(false); imagePanel.setImage(null); imagePanel.showMessage(Info, Messages.LOADING_CAPTURE); target = 0; picker.reset(); } @Override public void onCaptureLoaded(Loadable.Message error) { if (error != null) { imagePanel.setImage(null); imagePanel.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE); } target = 0; picker.reset(); } @Override public void onCommandsLoaded() { loadBuffer(); } @Override public void onCommandsSelected(CommandIndex range) { loadBuffer(); } @Override public void onReplayDeviceChanged(Device.Instance dev) { loadBuffer(); } @Override public void onFramebufferAttachmentFollowed(Path.FramebufferAttachment path) { picker.selectAttachment(path.getIndex()); } private void updateRenderTarget(int attachment) { target = attachment; updateBuffer(); } private void loadBuffer() { imagePanel.startLoading(); if (models.commands.getSelectedCommands() == null) { imagePanel.showMessage(Info, Messages.SELECT_COMMAND); } else if (!models.devices.hasReplayDevice()) { imagePanel.showMessage(Error, Messages.NO_REPLAY_DEVICE); } else if (models.resources.isLoaded()) { Rpc.listen(models.resources.loadFramebufferAttachments(), new UiErrorCallback<Service.FramebufferAttachments, Service.FramebufferAttachments, Loadable.Message>(this, LOG) { @Override protected ResultOrError<Service.FramebufferAttachments, Loadable.Message> onRpcThread( Rpc.Result<Service.FramebufferAttachments> result) { try { return success(result.get()); } catch (DataUnavailableException e) { return error(Loadable.Message.error(e)); } catch (RpcException e) { models.analytics.reportException(e); return error(Loadable.Message.error(e)); } catch (ExecutionException e) { models.analytics.reportException(e); throttleLogRpcError(LOG, "Failed to load framebuffer attachments", e); return error(Loadable.Message.error(e.getCause().getMessage())); } } @Override protected void onUiThreadSuccess(Service.FramebufferAttachments fbaList) { pickerGridData.exclude = !showAttachments; picker.setVisible(showAttachments); pickerToggle.setEnabled(true); if (fbaList.getAttachmentsList().size() <= target) { target = 0; } List<Attachment> newAttachments = new ArrayList(); for (Service.FramebufferAttachment fba : fbaList.getAttachmentsList()) { newAttachments.add(new Attachment(fba.getIndex(), fba.getType(), fba.getLabel())); } picker.setData(newAttachments); picker.selectAttachment(target); } @Override protected void onUiThreadError(Loadable.Message message) { pickerGridData.exclude = true; picker.setVisible(false); pickerToggle.setEnabled(false); imagePanel.showMessage(message); } }); } } private void updateBuffer() { CommandIndex command = models.commands.getSelectedCommands(); if (command == null) { imagePanel.showMessage(Info, Messages.SELECT_COMMAND); } else if (!models.devices.hasReplayDevice()) { imagePanel.showMessage(Error, Messages.NO_REPLAY_DEVICE); } else { imagePanel.startLoading(); rpcController.start().listen(models.images.getFramebuffer(command, target, renderSettings.getRenderSettings(models.settings)), new UiErrorCallback<FetchedImage, MultiLayerAndLevelImage, Loadable.Message>(this, LOG) { @Override protected ResultOrError<MultiLayerAndLevelImage, Loadable.Message> onRpcThread( Rpc.Result<FetchedImage> result) throws RpcException, ExecutionException { try { return success(result.get()); } catch (DataUnavailableException e) { return error(Loadable.Message.info(e)); } catch (RpcException e) { return error(Loadable.Message.error(e)); } } @Override protected void onUiThreadSuccess(MultiLayerAndLevelImage result) { imagePanel.setImage(result); } @Override protected void onUiThreadError(Loadable.Message message) { imagePanel.showMessage(message); } }); } } private class Attachment { public final int index; public final API.FramebufferAttachmentType type; public final String label; public LoadableImage image; public int width, height; public Attachment(int index, API.FramebufferAttachmentType type, String label) { this.index = index; this.type = type; this.label = label; } public void paint(GC gc, Image toDraw, int x, int y, int w, int h, boolean selected) { if (selected) { gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.drawRectangle(x - 2, y - 2, w + 3, h + 3); gc.drawRectangle(x - 1, y - 1, w + 1, h + 1); } else { gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_BORDER)); gc.drawRectangle(x - 1, y - 1, w + 1, h + 1); } Rectangle size = toDraw.getBounds(); gc.drawImage(toDraw, 0, 0, size.width, size.height, Math.max(x, x + (w - size.width) / 2), Math.max(y, y + (h - size.height) / 2), Math.min(size.width, w), Math.min(size.height, h)); Point labelSize = gc.stringExtent(label); gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); gc.fillRoundRectangle(x + 4, y + 4, labelSize.x + 4, labelSize.y + 4, 6, 6); gc.drawRoundRectangle(x + 4, y + 4, labelSize.x + 4, labelSize.y + 4, 6, 6); gc.drawString(label, x + 6, y + 6); } public void dispose() { if (image != null) { image.dispose(); } } } private class AttachmentPicker extends HorizontalList implements LoadingIndicator.Repaintable { private static final int MIN_SIZE = 80; private List<Attachment> attachments = emptyList(); private int selectedIndex = -1; public AttachmentPicker(Composite parent) { super(parent, SWT.BORDER); } @Override protected void paint(GC gc, int index, int x, int y, int w, int h) { Attachment attachment = attachments.get(index); if (attachment.image == null) { load(attachment, index); } Image toDraw; if (attachment.image != null) { toDraw = attachment.image.getImage(); } else { toDraw = widgets.loading.getCurrentFrame(); widgets.loading.scheduleForRedraw(this); } attachment.paint(gc, toDraw, x, y, w, h, selectedIndex == index); } public void resize() { if (!attachments.isEmpty()) { int maxAttachmentHeight = 0; for (Attachment attachment : attachments) { if (attachment.height > maxAttachmentHeight) { maxAttachmentHeight = attachment.height; } } int pickerHeight = Math.min(maxAttachmentHeight, (int)(splitter.getBounds().height * 0.2)); // Note: we will delay repainting until the layout call for (int i = 0; i < attachments.size(); i++) { Attachment attachment = attachments.get(i); if (attachment.height > pickerHeight) { float aspectRatio = attachment.width / (float)attachment.height; int imageWidth = (int)(aspectRatio * pickerHeight); setItemSize(i, imageWidth, pickerHeight, false); } else { setItemSize(i, attachment.width, attachment.height, false); } } pickerGridData.heightHint = pickerHeight; splitter.layout(); } } public void load(Attachment attachment, int index) { CommandIndex command = models.commands.getSelectedCommands(); if (command == null) { return; } attachment.image = LoadableImage.newBuilder(widgets.loading) .forImageData(noAlpha(models.images.getThumbnail(command, attachment.index, THUMB_SIZE, info -> scheduleIfNotDisposed(this, () -> setItemSize(index, Math.max(MIN_SIZE, DPIUtil.autoScaleDown(info.getWidth())), Math.max(MIN_SIZE, DPIUtil.autoScaleDown(info.getHeight())), true))))) .onErrorShowErrorIcon(widgets.theme) .build(this, this); attachment.image.addListener(new LoadableImage.Listener() { @Override public void onLoaded(boolean success) { Rectangle bounds = attachment.image.getImage().getBounds(); attachment.width = Math.max(MIN_SIZE, bounds.width); attachment.height = Math.max(MIN_SIZE, bounds.height); setItemSize(index, attachment.width, attachment.height, false); resize(); } }); } public void setData(List<Attachment> newAttachments) { reset(); attachments = new ArrayList(newAttachments); setItemCount(attachments.size(), THUMB_SIZE, THUMB_SIZE); } public void reset() { for (Attachment attachment : attachments) { attachment.dispose(); } attachments = Collections.emptyList(); selectedIndex = -1; setItemCount(0, THUMB_SIZE, THUMB_SIZE); pickerLabel.setText("Attachment:"); resize(); } public void selectAttachment(int index) { if (index >= 0 && index < attachments.size()) { selectedIndex = index; Attachment a = attachments.get(index); switch(a.type) { case OutputColor: pickerLabel.setText("Attachment: Color (" + a.index + ")"); break; case OutputDepth: pickerLabel.setText("Attachment: Depth (" + a.index + ")"); break; case InputColor: pickerLabel.setText("Attachment: Input Color (" + a.index + ")"); break; case InputDepth: pickerLabel.setText("Attachment: InputDepth (" + a.index + ")"); break; } updateRenderTarget(a.index); repaint(); } } } }
gapic/src/main/com/google/gapid/views/FramebufferView.java
/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gapid.views; import static com.google.gapid.image.Images.noAlpha; import static com.google.gapid.models.ImagesModel.THUMB_SIZE; import static com.google.gapid.util.GeoUtils.right; import static com.google.gapid.util.GeoUtils.top; import static com.google.gapid.util.Loadable.MessageType.Error; import static com.google.gapid.util.Loadable.MessageType.Info; import static com.google.gapid.util.Logging.throttleLogRpcError; import static com.google.gapid.widgets.Widgets.createBaloonToolItem; import static com.google.gapid.widgets.Widgets.createComposite; import static com.google.gapid.widgets.Widgets.createLabel; import static com.google.gapid.widgets.Widgets.createSeparator; import static com.google.gapid.widgets.Widgets.createToggleToolItem; import static com.google.gapid.widgets.Widgets.createToolItem; import static com.google.gapid.widgets.Widgets.exclusiveSelection; import static com.google.gapid.widgets.Widgets.disposeAllChildren; import static com.google.gapid.widgets.Widgets.scheduleIfNotDisposed; import static com.google.gapid.widgets.Widgets.withLayoutData; import static java.util.Collections.emptyList; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.gapid.image.FetchedImage; import com.google.gapid.image.MultiLayerAndLevelImage; import com.google.gapid.models.Analytics.View; import com.google.gapid.models.Capture; import com.google.gapid.models.CommandStream; import com.google.gapid.models.CommandStream.CommandIndex; import com.google.gapid.models.Devices; import com.google.gapid.models.Follower; import com.google.gapid.models.Models; import com.google.gapid.models.Settings; import com.google.gapid.proto.device.Device; import com.google.gapid.proto.service.Service; import com.google.gapid.proto.service.Service.ClientAction; import com.google.gapid.proto.service.api.API; import com.google.gapid.proto.service.path.Path; import com.google.gapid.rpc.Rpc; import com.google.gapid.rpc.RpcException; import com.google.gapid.rpc.SingleInFlight; import com.google.gapid.rpc.UiErrorCallback; import com.google.gapid.server.Client.DataUnavailableException; import com.google.gapid.util.Experimental; import com.google.gapid.util.Loadable; import com.google.gapid.util.Messages; import com.google.gapid.util.MoreFutures; import com.google.gapid.util.Paths; import com.google.gapid.widgets.Balloon; import com.google.gapid.widgets.HorizontalList; import com.google.gapid.widgets.ImagePanel; import com.google.gapid.widgets.LoadableImage; import com.google.gapid.widgets.LoadingIndicator; import com.google.gapid.widgets.Theme; import com.google.gapid.widgets.Widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.internal.DPIUtil; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; import java.util.logging.Level; /** * View that displays the framebuffer at the current selection in an {@link ImagePanel}. */ public class FramebufferView extends Composite implements Tab, Capture.Listener, Devices.Listener, CommandStream.Listener, Follower.Listener { private static final Logger LOG = Logger.getLogger(FramebufferView.class.getName()); private static final int MAX_SIZE = 0xffff; private enum RenderSetting { RENDER_SHADED(MAX_SIZE, MAX_SIZE, Path.DrawMode.NORMAL), RENDER_OVERLAY(MAX_SIZE, MAX_SIZE, Path.DrawMode.WIREFRAME_OVERLAY), RENDER_WIREFRAME(MAX_SIZE, MAX_SIZE, Path.DrawMode.WIREFRAME_ALL), RENDER_OVERDRAW(MAX_SIZE, MAX_SIZE, Path.DrawMode.OVERDRAW), RENDER_THUMB(THUMB_SIZE, THUMB_SIZE, Path.DrawMode.NORMAL); public final int maxWidth; public final int maxHeight; public final Path.DrawMode drawMode; private RenderSetting(int maxWidth, int maxHeight, Path.DrawMode drawMode) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.drawMode = drawMode; } public Path.RenderSettings getRenderSettings(Settings settings) { return Paths.renderSettings(maxWidth, maxHeight, drawMode, settings.preferences().getDisableReplayOptimization()); } } private final Models models; private final Widgets widgets; private final SingleInFlight rpcController = new SingleInFlight(); protected final ImagePanel imagePanel; private RenderSetting renderSettings; private int target = 0; private final AttachmentPicker picker; private final Label pickerLabel; private final Composite splitter; private final GridData pickerGridData; private final Button pickerToggle; private boolean showAttachments; public FramebufferView(Composite parent, Models models, Widgets widgets) { super(parent, SWT.NONE); this.models = models; this.widgets = widgets; setLayout(new GridLayout(2, false)); ToolBar toolBar = createToolBar(widgets.theme); Composite header = createComposite(this, new GridLayout(2, false)); splitter = createComposite(this, new GridLayout(1, false)); picker = new AttachmentPicker(splitter); picker.addContentListener(SWT.MouseDown, e -> picker.selectAttachment(picker.getItemAt(e.x))); imagePanel = new ImagePanel(splitter, View.Framebuffer, models.analytics, widgets, true); pickerGridData = new GridData(SWT.FILL, SWT.FILL, true, false); showAttachments = models.settings.ui().getFramebufferPicker().getEnabled(); pickerGridData.exclude = true; picker.setVisible(false); splitter.addListener(SWT.Resize, e -> picker.resize()); toolBar.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 2)); header.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); splitter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); picker.setLayoutData(pickerGridData); imagePanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); pickerLabel = withLayoutData(createLabel(header, "Attachment:"), new GridData(SWT.FILL, SWT.CENTER, true, true)); pickerToggle = new Button(header, SWT.PUSH); pickerToggle.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false)); pickerToggle.setText(showAttachments ? "Hide Attachments" : "Show Attachments"); pickerToggle.addListener(SWT.Selection, e -> { showAttachments = !showAttachments; pickerGridData.exclude = !showAttachments; picker.setVisible(showAttachments); models.settings.writeUi().getFramebufferPickerBuilder().setEnabled(showAttachments); pickerToggle.setText(showAttachments ? "Hide Attachments" : "Show Attachments"); splitter.layout(); }); pickerToggle.setEnabled(false); imagePanel.createToolbar(toolBar, widgets.theme); // Work around for https://bugs.eclipse.org/bugs/show_bug.cgi?id=517480 Widgets.createSeparator(toolBar); renderSettings = RenderSetting.RENDER_SHADED; models.capture.addListener(this); models.devices.addListener(this); models.commands.addListener(this); models.follower.addListener(this); addListener(SWT.Dispose, e -> { models.capture.removeListener(this); models.devices.removeListener(this); models.commands.removeListener(this); models.follower.removeListener(this); }); } private ToolBar createToolBar(Theme theme) { ToolBar bar = new ToolBar(this, SWT.VERTICAL | SWT.FLAT); List<ToolItem> items = Lists.newArrayList( createToggleToolItem(bar, theme.wireframeNone(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Shaded); renderSettings = RenderSetting.RENDER_SHADED; updateBuffer(); }, "Render shaded geometry"), createToggleToolItem(bar, theme.wireframeOverlay(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.OverlayWireframe); renderSettings = RenderSetting.RENDER_OVERLAY; updateBuffer(); }, "Render shaded geometry and overlay wireframe of last draw call"), createToggleToolItem(bar, theme.wireframeAll(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Wireframe); renderSettings = RenderSetting.RENDER_WIREFRAME; updateBuffer(); }, "Render wireframe geometry")); // The RENDER_OVERDRAW feature can cause crashes right now, disable by default. // TODO(b/188431629): Investigate and fix the overdraw issue. if (Experimental.enableUnstableFeatures(models.settings)) { items.add(createToggleToolItem(bar, theme.overdraw(), e -> { models.analytics.postInteraction(View.Framebuffer, ClientAction.Overdraw); renderSettings = RenderSetting.RENDER_OVERDRAW; updateBuffer(); }, "Render overdraw")); } exclusiveSelection(items); createSeparator(bar); return bar; } @Override public Control getControl() { return this; } @Override public void reinitialize() { picker.setVisible(false); pickerGridData.exclude = true; pickerToggle.setEnabled(false); if (!models.capture.isLoaded()) { onCaptureLoadingStart(false); } else { loadBuffer(); } } @Override public void onCaptureLoadingStart(boolean maintainState) { picker.setVisible(false); pickerGridData.exclude = true; pickerToggle.setEnabled(false); imagePanel.setImage(null); imagePanel.showMessage(Info, Messages.LOADING_CAPTURE); target = 0; picker.reset(); } @Override public void onCaptureLoaded(Loadable.Message error) { if (error != null) { imagePanel.setImage(null); imagePanel.showMessage(Error, Messages.CAPTURE_LOAD_FAILURE); } target = 0; picker.reset(); } @Override public void onCommandsLoaded() { loadBuffer(); } @Override public void onCommandsSelected(CommandIndex range) { loadBuffer(); } @Override public void onReplayDeviceChanged(Device.Instance dev) { loadBuffer(); } @Override public void onFramebufferAttachmentFollowed(Path.FramebufferAttachment path) { picker.selectAttachment(path.getIndex()); } private void updateRenderTarget(int attachment) { target = attachment; updateBuffer(); } private void loadBuffer() { imagePanel.startLoading(); if (models.commands.getSelectedCommands() == null) { imagePanel.showMessage(Info, Messages.SELECT_COMMAND); } else if (!models.devices.hasReplayDevice()) { imagePanel.showMessage(Error, Messages.NO_REPLAY_DEVICE); } else if (models.resources.isLoaded()) { Rpc.listen(models.resources.loadFramebufferAttachments(), new UiErrorCallback<Service.FramebufferAttachments, Service.FramebufferAttachments, Loadable.Message>(this, LOG) { @Override protected ResultOrError<Service.FramebufferAttachments, Loadable.Message> onRpcThread( Rpc.Result<Service.FramebufferAttachments> result) { try { return success(result.get()); } catch (DataUnavailableException e) { return error(Loadable.Message.error(e)); } catch (RpcException e) { models.analytics.reportException(e); return error(Loadable.Message.error(e)); } catch (ExecutionException e) { models.analytics.reportException(e); throttleLogRpcError(LOG, "Failed to load framebuffer attachments", e); return error(Loadable.Message.error(e.getCause().getMessage())); } } @Override protected void onUiThreadSuccess(Service.FramebufferAttachments fbaList) { pickerGridData.exclude = !showAttachments; picker.setVisible(showAttachments); pickerToggle.setEnabled(true); if (fbaList.getAttachmentsList().size() <= target) { target = 0; } List<Attachment> newAttachments = new ArrayList(); for (Service.FramebufferAttachment fba : fbaList.getAttachmentsList()) { newAttachments.add(new Attachment(fba.getIndex(), fba.getType(), fba.getLabel())); } picker.setData(newAttachments); picker.selectAttachment(target); } @Override protected void onUiThreadError(Loadable.Message message) { pickerGridData.exclude = true; picker.setVisible(false); pickerToggle.setEnabled(false); imagePanel.showMessage(message); } }); } } private void updateBuffer() { CommandIndex command = models.commands.getSelectedCommands(); if (command == null) { imagePanel.showMessage(Info, Messages.SELECT_COMMAND); } else if (!models.devices.hasReplayDevice()) { imagePanel.showMessage(Error, Messages.NO_REPLAY_DEVICE); } else { imagePanel.startLoading(); rpcController.start().listen(models.images.getFramebuffer(command, target, renderSettings.getRenderSettings(models.settings)), new UiErrorCallback<FetchedImage, MultiLayerAndLevelImage, Loadable.Message>(this, LOG) { @Override protected ResultOrError<MultiLayerAndLevelImage, Loadable.Message> onRpcThread( Rpc.Result<FetchedImage> result) throws RpcException, ExecutionException { try { return success(result.get()); } catch (DataUnavailableException e) { return error(Loadable.Message.info(e)); } catch (RpcException e) { return error(Loadable.Message.error(e)); } } @Override protected void onUiThreadSuccess(MultiLayerAndLevelImage result) { imagePanel.setImage(result); } @Override protected void onUiThreadError(Loadable.Message message) { imagePanel.showMessage(message); } }); } } private class Attachment { public final int index; public final API.FramebufferAttachmentType type; public final String label; public LoadableImage image; public int width, height; public Attachment(int index, API.FramebufferAttachmentType type, String label) { this.index = index; this.type = type; this.label = label; } public void paint(GC gc, Image toDraw, int x, int y, int w, int h, boolean selected) { if (selected) { gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_SELECTION)); gc.drawRectangle(x - 2, y - 2, w + 3, h + 3); gc.drawRectangle(x - 1, y - 1, w + 1, h + 1); } else { gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_BORDER)); gc.drawRectangle(x - 1, y - 1, w + 1, h + 1); } Rectangle size = toDraw.getBounds(); gc.drawImage(toDraw, 0, 0, size.width, size.height, Math.max(x, x + (w - size.width) / 2), Math.max(y, y + (h - size.height) / 2), Math.min(size.width, w), Math.min(size.height, h)); Point labelSize = gc.stringExtent(label); gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_FOREGROUND)); gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_BACKGROUND)); gc.fillRoundRectangle(x + 4, y + 4, labelSize.x + 4, labelSize.y + 4, 6, 6); gc.drawRoundRectangle(x + 4, y + 4, labelSize.x + 4, labelSize.y + 4, 6, 6); gc.drawString(label, x + 6, y + 6); } public void dispose() { if (image != null) { image.dispose(); } } } private class AttachmentPicker extends HorizontalList implements LoadingIndicator.Repaintable { private static final int MIN_SIZE = 80; private List<Attachment> attachments = emptyList(); private int selectedIndex = -1; public AttachmentPicker(Composite parent) { super(parent, SWT.BORDER); } @Override protected void paint(GC gc, int index, int x, int y, int w, int h) { Attachment attachment = attachments.get(index); if (attachment.image == null) { load(attachment, index); } Image toDraw; if (attachment.image != null) { toDraw = attachment.image.getImage(); } else { toDraw = widgets.loading.getCurrentFrame(); widgets.loading.scheduleForRedraw(this); } attachment.paint(gc, toDraw, x, y, w, h, selectedIndex == index); } public void resize() { if (!attachments.isEmpty()) { int maxAttachmentHeight = 0; for (Attachment attachment : attachments) { if (attachment.height > maxAttachmentHeight) { maxAttachmentHeight = attachment.height; } } int pickerHeight = Math.min(maxAttachmentHeight, (int)(splitter.getBounds().height * 0.2)); // Note: we will delay repainting until the layout call for (int i = 0; i < attachments.size(); i++) { Attachment attachment = attachments.get(i); if (attachment.height > pickerHeight) { float aspectRatio = attachment.width / (float)attachment.height; int imageWidth = (int)(aspectRatio * pickerHeight); setItemSize(i, imageWidth, pickerHeight, false); } else { setItemSize(i, attachment.width, attachment.height, false); } } pickerGridData.heightHint = pickerHeight; splitter.layout(); } } public void load(Attachment attachment, int index) { CommandIndex command = models.commands.getSelectedCommands(); if (command == null) { return; } attachment.image = LoadableImage.newBuilder(widgets.loading) .forImageData(noAlpha(models.images.getThumbnail(command, attachment.index, THUMB_SIZE, info -> scheduleIfNotDisposed(this, () -> setItemSize(index, Math.max(MIN_SIZE, DPIUtil.autoScaleDown(info.getWidth())), Math.max(MIN_SIZE, DPIUtil.autoScaleDown(info.getHeight())), true))))) .onErrorShowErrorIcon(widgets.theme) .build(this, this); attachment.image.addListener(new LoadableImage.Listener() { @Override public void onLoaded(boolean success) { Rectangle bounds = attachment.image.getImage().getBounds(); attachment.width = Math.max(MIN_SIZE, bounds.width); attachment.height = Math.max(MIN_SIZE, bounds.height); setItemSize(index, attachment.width, attachment.height, false); resize(); } }); } public void setData(List<Attachment> newAttachments) { reset(); attachments = new ArrayList(newAttachments); setItemCount(attachments.size(), THUMB_SIZE, THUMB_SIZE); } public void reset() { for (Attachment attachment : attachments) { attachment.dispose(); } attachments = Collections.emptyList(); selectedIndex = -1; setItemCount(0, THUMB_SIZE, THUMB_SIZE); pickerLabel.setText("Attachment:"); resize(); } public void selectAttachment(int index) { if (index >= 0 && index < attachments.size()) { selectedIndex = index; Attachment a = attachments.get(index); switch(a.type) { case OutputColor: pickerLabel.setText("Attachment: Color (" + a.index + ")"); break; case OutputDepth: pickerLabel.setText("Attachment: Depth (" + a.index + ")"); break; case InputColor: pickerLabel.setText("Attachment: Input Color (" + a.index + ")"); break; case InputDepth: pickerLabel.setText("Attachment: InputDepth (" + a.index + ")"); break; } updateRenderTarget(a.index); repaint(); } } } }
Hide button to overlay wireframe (#824) The button leads to an error right now. Hide the button until the underlying issue is fixed. Bug: 188417572 Test: manual
gapic/src/main/com/google/gapid/views/FramebufferView.java
Hide button to overlay wireframe (#824)
<ide><path>apic/src/main/com/google/gapid/views/FramebufferView.java <ide> models.analytics.postInteraction(View.Framebuffer, ClientAction.Shaded); <ide> renderSettings = RenderSetting.RENDER_SHADED; <ide> updateBuffer(); <del> }, "Render shaded geometry"), <del> createToggleToolItem(bar, theme.wireframeOverlay(), e -> { <add> }, "Render shaded geometry")); <add> // The RENDER_OVERLAY feature leads to an error right now. <add> // TODO(b/188417572): Investigate and fix this issue. <add> if (Experimental.enableUnstableFeatures(models.settings)) { <add> items.add(createToggleToolItem(bar, theme.wireframeOverlay(), e -> { <ide> models.analytics.postInteraction(View.Framebuffer, ClientAction.OverlayWireframe); <ide> renderSettings = RenderSetting.RENDER_OVERLAY; <ide> updateBuffer(); <del> }, "Render shaded geometry and overlay wireframe of last draw call"), <del> createToggleToolItem(bar, theme.wireframeAll(), e -> { <del> models.analytics.postInteraction(View.Framebuffer, ClientAction.Wireframe); <del> renderSettings = RenderSetting.RENDER_WIREFRAME; <del> updateBuffer(); <del> }, "Render wireframe geometry")); <add> }, "Render shaded geometry and overlay wireframe of last draw call")); <add> } <add> items.add(createToggleToolItem(bar, theme.wireframeAll(), e -> { <add> models.analytics.postInteraction(View.Framebuffer, ClientAction.Wireframe); <add> renderSettings = RenderSetting.RENDER_WIREFRAME; <add> updateBuffer(); <add> }, "Render wireframe geometry")); <ide> // The RENDER_OVERDRAW feature can cause crashes right now, disable by default. <ide> // TODO(b/188431629): Investigate and fix the overdraw issue. <ide> if (Experimental.enableUnstableFeatures(models.settings)) {
Java
mit
f8e14bd0b701293b554b75020f56c02be2ea19d6
0
tylersuehr7/chips-input-layout
package com.tylersuehr.chips; import android.content.Context; import android.graphics.PorterDuff; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.TextView; /** * Copyright © 2017 Tyler Suehr * * This view displays the normal chip (specified in Material Design Guide). * * @author Tyler Suehr * @version 1.0 */ public class ChipView extends FrameLayout implements ChipComponent { private ChipImageRenderer mImageRenderer; private CircleImageView mAvatarView; private ImageButton mButtonDelete; private TextView mLabelView; private Chip mChip; ChipView(@NonNull Context context) { super(context); inflate(context, R.layout.chip_view, this); mAvatarView = findViewById(R.id.avatar); mLabelView = findViewById(R.id.label); mButtonDelete = findViewById(R.id.button_delete); } @Override public void setChipOptions(ChipOptions options) { // Options will permit showing/hiding avatar if (!options.mShowAvatar) { // Hide the avatar image mAvatarView.setVisibility(GONE); // Adjust left label margins according to the // Google Material Design Guide. ConstraintLayout.LayoutParams lp = (ConstraintLayout .LayoutParams)mLabelView.getLayoutParams(); lp.leftMargin = (int)(12f * getResources().getDisplayMetrics().density); } // Options will permit showing/hiding delete button if (!options.mShowDelete) { // Hide the delete button mButtonDelete.setVisibility(GONE); // Adjust right label margins according to the // Google Material Design Guide. ConstraintLayout.LayoutParams lp = (ConstraintLayout .LayoutParams)mLabelView.getLayoutParams(); lp.rightMargin = (int)(12f * getResources().getDisplayMetrics().density); } // Set other options if (options.mChipDeleteIcon != null) { mButtonDelete.setImageDrawable(options.mChipDeleteIcon); } if (options.mChipBackgroundColor != null) { setBackgroundColor(options.mChipBackgroundColor.getDefaultColor()); } if (options.mChipDeleteIconColor != null) { mButtonDelete.setColorFilter(options.mChipDeleteIconColor .getDefaultColor(), PorterDuff.Mode.SRC_ATOP); } if (options.mChipTextColor != null) { mLabelView.setTextColor(options.mChipTextColor); } mLabelView.setTypeface(options.mTypeface); mImageRenderer = options.mImageRenderer; } /** * Displays the information stored in the given chip object. * @param chip {@link Chip} */ public void inflateFromChip(Chip chip) { mChip = chip; mLabelView.setText(mChip.getTitle()); if (mImageRenderer == null) { throw new NullPointerException("Image renderer must be set!"); } mImageRenderer.renderAvatar(mAvatarView, chip); } public Chip getChip() { return mChip; } /** * Sets an OnClickListener on the ChipView itself. * @param listener {@link OnChipClickListener} */ public void setOnChipClicked(final OnChipClickListener listener) { final View child = getChildAt(0); if (listener == null) { child.setOnClickListener(null); } else { child.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onChipClicked(ChipView.this); } }); } } /** * Sets an OnClickListener on the delete button. * @param listener {@link OnChipDeleteListener} */ public void setOnDeleteClicked(final OnChipDeleteListener listener) { mButtonDelete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onChipDeleted(ChipView.this); } }); } /** * Defines callbacks for chip click events. */ public interface OnChipClickListener { void onChipClicked(ChipView v); } /** * Defines callbacks for chip delete events. */ public interface OnChipDeleteListener { void onChipDeleted(ChipView v); } }
library/src/main/java/com/tylersuehr/chips/ChipView.java
package com.tylersuehr.chips; import android.content.Context; import android.graphics.PorterDuff; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.TextView; /** * Copyright © 2017 Tyler Suehr * * This view displays the normal chip (specified in Material Design Guide). * * @author Tyler Suehr * @version 1.0 */ public class ChipView extends FrameLayout implements ChipComponent { private ChipImageRenderer mImageRenderer; private CircleImageView mAvatarView; private ImageButton mButtonDelete; private TextView mLabelView; private Chip mChip; ChipView(@NonNull Context context) { super(context); inflate(context, R.layout.chip_view, this); mAvatarView = findViewById(R.id.avatar); mLabelView = findViewById(R.id.label); mButtonDelete = findViewById(R.id.button_delete); } @Override public void setChipOptions(ChipOptions options) { // Options will permit showing/hiding avatar if (!options.mShowAvatar) { // Hide the avatar image mAvatarView.setVisibility(GONE); // Adjust left label margins according to the // Google Material Design Guide. ConstraintLayout.LayoutParams lp = (ConstraintLayout .LayoutParams)mLabelView.getLayoutParams(); lp.leftMargin = (int)(12f * getResources().getDisplayMetrics().density); } // Options will permit showing/hiding delete button if (!options.mShowDelete) { // Hide the delete button mButtonDelete.setVisibility(GONE); // Adjust right label margins according to the // Google Material Design Guide. ConstraintLayout.LayoutParams lp = (ConstraintLayout .LayoutParams)mLabelView.getLayoutParams(); lp.rightMargin = (int)(12f * getResources().getDisplayMetrics().density); } // Set other options if (options.mChipDeleteIcon != null) { mButtonDelete.setImageDrawable(options.mChipDeleteIcon); } if (options.mChipBackgroundColor != null) { setBackgroundColor(options.mChipBackgroundColor.getDefaultColor()); } if (options.mChipDeleteIconColor != null) { mButtonDelete.setColorFilter(options.mChipDeleteIconColor .getDefaultColor(), PorterDuff.Mode.SRC_ATOP); } if (options.mChipTextColor != null) { mLabelView.setTextColor(options.mChipTextColor); } mLabelView.setTypeface(options.mTypeface); mImageRenderer = options.mImageRenderer; } /** * Displays the information stored in the given chip object. * @param chip {@link Chip} */ public void inflateFromChip(Chip chip) { mChip = chip; mLabelView.setText(mChip.getTitle()); if (mImageRenderer == null) { throw new NullPointerException("Image renderer must be set!"); } mImageRenderer.renderAvatar(mAvatarView, chip); } public Chip getChip() { return mChip; } /** * Sets an OnClickListener on the ChipView itself. * @param listener {@link OnChipClickListener} */ public void setOnChipClicked(final OnChipClickListener listener) { getChildAt(0).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onChipClicked(ChipView.this); } }); } /** * Sets an OnClickListener on the delete button. * @param listener {@link OnChipDeleteListener} */ public void setOnDeleteClicked(final OnChipDeleteListener listener) { mButtonDelete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onChipDeleted(ChipView.this); } }); } /** * Defines callbacks for chip click events. */ public interface OnChipClickListener { void onChipClicked(ChipView v); } /** * Defines callbacks for chip delete events. */ public interface OnChipDeleteListener { void onChipDeleted(ChipView v); } }
Fixed bug where setting a null listener would cause a NullPointerException to be thrown because no check was there
library/src/main/java/com/tylersuehr/chips/ChipView.java
Fixed bug where setting a null listener would cause a NullPointerException to be thrown because no check was there
<ide><path>ibrary/src/main/java/com/tylersuehr/chips/ChipView.java <ide> * @param listener {@link OnChipClickListener} <ide> */ <ide> public void setOnChipClicked(final OnChipClickListener listener) { <del> getChildAt(0).setOnClickListener(new OnClickListener() { <del> @Override <del> public void onClick(View v) { <del> listener.onChipClicked(ChipView.this); <del> } <del> }); <add> final View child = getChildAt(0); <add> if (listener == null) { <add> child.setOnClickListener(null); <add> } else { <add> child.setOnClickListener(new OnClickListener() { <add> @Override <add> public void onClick(View v) { <add> listener.onChipClicked(ChipView.this); <add> } <add> }); <add> } <ide> } <ide> <ide> /**
Java
apache-2.0
89334351ce64be6515fc4160fddb7bc257b686c2
0
misterflud/aoleynikov,misterflud/aoleynikov,misterflud/aoleynikov
package ru.job4j; import java.util.HashMap; import java.util.List; /** * Created by Anton on 19.04.2017. */ public class UserConvert { /** * Adds User in map. * @param list of Users * @return Map of Users */ public HashMap<Integer, User> process(List<User> list) { HashMap<Integer, User> map = new HashMap<>(); for (User iter : list) { map.put(iter.getId(), iter); } return map; } }
chapter_005/generalization/src/main/java/ru/job4j/UserConvert.java
package ru.job4j; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; /** * Created by Anton on 19.04.2017. */ public class UserConvert { /** * Adds User in map. * @param list of Users * @return Map of Users */ public HashMap<Integer, User> process(List<User> list) { HashMap<Integer, User> map = new HashMap<>(); for (User iter : list) { map.put(iter.getId(), iter); } return map; } }
update
chapter_005/generalization/src/main/java/ru/job4j/UserConvert.java
update
<ide><path>hapter_005/generalization/src/main/java/ru/job4j/UserConvert.java <ide> package ru.job4j; <ide> <ide> import java.util.HashMap; <del>import java.util.LinkedHashMap; <del>import java.util.LinkedList; <ide> import java.util.List; <ide> <ide> /**
Java
apache-2.0
cfb078c78cc33cb1369a01252b2af9d2f5b5822f
0
monitorjbl/excel-streaming-reader
package com.monitorjbl.xlsx.impl; import com.monitorjbl.xlsx.exceptions.NotSupportedException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class StreamingRow implements Row { private int rowIndex; private boolean isHidden; private TreeMap<Integer, Cell> cellMap = new TreeMap<>(); public StreamingRow(int rowIndex, boolean isHidden) { this.rowIndex = rowIndex; this.isHidden = isHidden; } public Map<Integer, Cell> getCellMap() { return cellMap; } public void setCellMap(TreeMap<Integer, Cell> cellMap) { this.cellMap = cellMap; } /* Supported */ /** * Get row number this row represents * * @return the row number (0 based) */ @Override public int getRowNum() { return rowIndex; } /** * @return Cell iterator of the physically defined cells for this row. */ @Override public Iterator<Cell> cellIterator() { return cellMap.values().iterator(); } /** * @return Cell iterator of the physically defined cells for this row. */ @Override public Iterator<Cell> iterator() { return cellMap.values().iterator(); } /** * Get the cell representing a given column (logical cell) 0-based. If you * ask for a cell that is not defined, you get a null. * * @param cellnum 0 based column number * @return Cell representing that column or null if undefined. */ @Override public Cell getCell(int cellnum) { return cellMap.get(cellnum); } /** * Gets the index of the last cell contained in this row <b>PLUS ONE</b>. * * @return short representing the last logical cell in the row <b>PLUS ONE</b>, * or -1 if the row does not contain any cells. */ @Override public short getLastCellNum() { return (short) (cellMap.size() == 0 ? -1 : cellMap.lastEntry().getValue().getColumnIndex() + 1); } /** * Get whether or not to display this row with 0 height * * @return - zHeight height is zero or not. */ @Override public boolean getZeroHeight() { return isHidden; } /** * Gets the number of defined cells (NOT number of cells in the actual row!). * That is to say if only columns 0,4,5 have values then there would be 3. * * @return int representing the number of defined cells in the row. */ @Override public int getPhysicalNumberOfCells() { return cellMap.size(); } /** * {@inheritDoc} */ @Override public short getFirstCellNum() { if(cellMap.size() == 0) { return -1; } return cellMap.firstKey().shortValue(); } /** * {@inheritDoc} */ @Override public Cell getCell(int cellnum, MissingCellPolicy policy) { StreamingCell cell = (StreamingCell) cellMap.get(cellnum); if(policy == MissingCellPolicy.CREATE_NULL_AS_BLANK) { if(cell == null) { return new StreamingCell(cellnum, rowIndex, false); } } else if(policy == MissingCellPolicy.RETURN_BLANK_AS_NULL) { if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { return null; } } return cell; } /* Not supported */ /** * Not supported */ @Override public Cell createCell(int column) { throw new NotSupportedException(); } /** * Not supported */ @Override public Cell createCell(int column, int type) { throw new NotSupportedException(); } /** * Not supported */ @Override public Cell createCell(int i, CellType cellType) { throw new NotSupportedException(); } /** * Not supported */ @Override public void removeCell(Cell cell) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setRowNum(int rowNum) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setHeight(short height) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setZeroHeight(boolean zHeight) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setHeightInPoints(float height) { throw new NotSupportedException(); } /** * Not supported */ @Override public short getHeight() { throw new NotSupportedException(); } /** * Not supported */ @Override public float getHeightInPoints() { throw new NotSupportedException(); } /** * Not supported */ @Override public boolean isFormatted() { throw new NotSupportedException(); } /** * Not supported */ @Override public CellStyle getRowStyle() { throw new NotSupportedException(); } /** * Not supported */ @Override public void setRowStyle(CellStyle style) { throw new NotSupportedException(); } /** * Not supported */ @Override public Sheet getSheet() { throw new NotSupportedException(); } /** * Not supported */ @Override public int getOutlineLevel() { throw new NotSupportedException(); } }
src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java
package com.monitorjbl.xlsx.impl; import com.monitorjbl.xlsx.exceptions.NotSupportedException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class StreamingRow implements Row { private int rowIndex; private boolean isHidden; private TreeMap<Integer, Cell> cellMap = new TreeMap<>(); public StreamingRow(int rowIndex, boolean isHidden) { this.rowIndex = rowIndex; this.isHidden = isHidden; } public Map<Integer, Cell> getCellMap() { return cellMap; } public void setCellMap(TreeMap<Integer, Cell> cellMap) { this.cellMap = cellMap; } /* Supported */ /** * Get row number this row represents * * @return the row number (0 based) */ @Override public int getRowNum() { return rowIndex; } /** * @return Cell iterator of the physically defined cells for this row. */ @Override public Iterator<Cell> cellIterator() { return cellMap.values().iterator(); } /** * @return Cell iterator of the physically defined cells for this row. */ @Override public Iterator<Cell> iterator() { return cellMap.values().iterator(); } /** * Get the cell representing a given column (logical cell) 0-based. If you * ask for a cell that is not defined, you get a null. * * @param cellnum 0 based column number * @return Cell representing that column or null if undefined. */ @Override public Cell getCell(int cellnum) { return cellMap.get(cellnum); } /** * Gets the index of the last cell contained in this row <b>PLUS ONE</b>. * * @return short representing the last logical cell in the row <b>PLUS ONE</b>, * or -1 if the row does not contain any cells. */ @Override public short getLastCellNum() { return (short) (cellMap.size() == 0 ? -1 : cellMap.lastEntry().getValue().getColumnIndex() + 1); } /** * Get whether or not to display this row with 0 height * * @return - zHeight height is zero or not. */ @Override public boolean getZeroHeight() { return isHidden; } /** * Gets the number of defined cells (NOT number of cells in the actual row!). * That is to say if only columns 0,4,5 have values then there would be 3. * * @return int representing the number of defined cells in the row. */ @Override public int getPhysicalNumberOfCells() { return cellMap.size(); } /** * {@inheritDoc} */ @Override public short getFirstCellNum() { if(cellMap.size() == 0) { return -1; } return cellMap.firstKey().shortValue(); } /* Not supported */ /** * Not supported */ @Override public Cell createCell(int column) { throw new NotSupportedException(); } /** * Not supported */ @Override public Cell createCell(int column, int type) { throw new NotSupportedException(); } /** * Not supported */ @Override public Cell createCell(int i, CellType cellType) { throw new NotSupportedException(); } /** * Not supported */ @Override public void removeCell(Cell cell) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setRowNum(int rowNum) { throw new NotSupportedException(); } /** * Not supported */ @Override public Cell getCell(int cellnum, MissingCellPolicy policy) { StreamingCell cell = (StreamingCell) cellMap.get(cellnum); if (policy == Row.CREATE_NULL_AS_BLANK) { if (cell == null) return new StreamingCell(cellnum, rowIndex, false); } else if (policy == Row.RETURN_BLANK_AS_NULL) { if (cell.getCellType() == Cell.CELL_TYPE_BLANK) return null; } return cell; } /** * Not supported */ @Override public void setHeight(short height) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setZeroHeight(boolean zHeight) { throw new NotSupportedException(); } /** * Not supported */ @Override public void setHeightInPoints(float height) { throw new NotSupportedException(); } /** * Not supported */ @Override public short getHeight() { throw new NotSupportedException(); } /** * Not supported */ @Override public float getHeightInPoints() { throw new NotSupportedException(); } /** * Not supported */ @Override public boolean isFormatted() { throw new NotSupportedException(); } /** * Not supported */ @Override public CellStyle getRowStyle() { throw new NotSupportedException(); } /** * Not supported */ @Override public void setRowStyle(CellStyle style) { throw new NotSupportedException(); } /** * Not supported */ @Override public Sheet getSheet() { throw new NotSupportedException(); } /** * Not supported */ @Override public int getOutlineLevel() { throw new NotSupportedException(); } }
Fix for #85, adding null check for MissingCellPolicy
src/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java
Fix for #85, adding null check for MissingCellPolicy
<ide><path>rc/main/java/com/monitorjbl/xlsx/impl/StreamingRow.java <ide> return cellMap.firstKey().shortValue(); <ide> } <ide> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public Cell getCell(int cellnum, MissingCellPolicy policy) { <add> StreamingCell cell = (StreamingCell) cellMap.get(cellnum); <add> if(policy == MissingCellPolicy.CREATE_NULL_AS_BLANK) { <add> if(cell == null) { return new StreamingCell(cellnum, rowIndex, false); } <add> } else if(policy == MissingCellPolicy.RETURN_BLANK_AS_NULL) { <add> if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { return null; } <add> } <add> return cell; <add> } <add> <ide> /* Not supported */ <ide> <ide> /** <ide> * Not supported <ide> */ <ide> @Override <del> public Cell getCell(int cellnum, MissingCellPolicy policy) { <del> StreamingCell cell = (StreamingCell) cellMap.get(cellnum); <del> if (policy == Row.CREATE_NULL_AS_BLANK) { <del> if (cell == null) return new StreamingCell(cellnum, rowIndex, false); <del> <del> } else if (policy == Row.RETURN_BLANK_AS_NULL) { <del> if (cell.getCellType() == Cell.CELL_TYPE_BLANK) return null; <del> } <del> return cell; <del> } <del> <del> /** <del> * Not supported <del> */ <del> @Override <ide> public void setHeight(short height) { <ide> throw new NotSupportedException(); <ide> }
Java
mit
9769daa98ccc260d73c0b216929c98742c363ae2
0
yeelin/betweenus,yeelin/betweenus
package com.example.yeelin.projects.betweenus.fragment; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.yeelin.projects.betweenus.R; import com.example.yeelin.projects.betweenus.data.LocalBusiness; import com.example.yeelin.projects.betweenus.data.LocalConstants; import com.example.yeelin.projects.betweenus.data.fb.query.FbConstants; import com.example.yeelin.projects.betweenus.loader.LoaderId; import com.example.yeelin.projects.betweenus.loader.SingleSuggestionLoaderCallbacks; import com.example.yeelin.projects.betweenus.loader.callback.SingleSuggestionLoaderListener; import com.example.yeelin.projects.betweenus.utils.AnimationUtils; import com.example.yeelin.projects.betweenus.utils.FairnessScoringUtils; import com.example.yeelin.projects.betweenus.utils.ImageUtils; import com.example.yeelin.projects.betweenus.utils.MapColorUtils; import com.facebook.AccessToken; import com.facebook.shimmer.ShimmerFrameLayout; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.squareup.picasso.Target; /** * Created by ninjakiki on 7/15/15. */ public class SuggestionDetailFragment extends Fragment implements SingleSuggestionLoaderListener, View.OnClickListener, OnMapReadyCallback, GoogleMap.OnMapClickListener { //logcat private static final String TAG = SuggestionDetailFragment.class.getCanonicalName(); //bundle args private static final String ARG_ID = SuggestionDetailFragment.class.getSimpleName() + ".id"; private static final String ARG_NAME = SuggestionDetailFragment.class.getSimpleName() + ".name"; private static final String ARG_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".latLng"; private static final String ARG_POSITION = SuggestionDetailFragment.class.getSimpleName() + ".position"; private static final String ARG_TOGGLE_STATE = SuggestionDetailFragment.class.getSimpleName() + ".toggleState"; private static final String ARG_RATING = SuggestionDetailFragment.class.getSimpleName() + ".rating"; private static final String ARG_LIKES = SuggestionDetailFragment.class.getSimpleName() + ".likes"; private static final String ARG_NORMALIZED_LIKES = SuggestionDetailFragment.class.getSimpleName() + ".normalizedLikes"; private static final String ARG_USER_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".userLatLng"; private static final String ARG_FRIEND_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".friendLatLng"; private static final String ARG_MID_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".midLatLng"; //child fragment tags private static String FRAGMENT_TAG_LITEMAP = SupportMapFragment.class.getSimpleName(); //constants private static final int DEFAULT_ZOOM = 13; //member variables private String id; private String name; private LatLng latLng; private int position = 0; private boolean toggleState; private double rating; private int likes; private double normalizedLikes; private LatLng userLatLng; private LatLng friendLatLng; private LatLng midLatLng; private Marker marker; private LocalBusiness business; private SuggestionDetailFragmentListener listener; /** * Creates a new instance of this fragment * @param id * @param name * @param latLng * @param position * @param toggleState * @param rating * @param likes * @param normalizedLikes * @param userLatLng * @param friendLatLng * @param midLatLng midpoint between userLatLng and friendLatLng * @return */ public static SuggestionDetailFragment newInstance(String id, String name, LatLng latLng, int position, boolean toggleState, double rating, int likes, double normalizedLikes, LatLng userLatLng, LatLng friendLatLng, LatLng midLatLng) { Bundle args = new Bundle(); args.putString(ARG_ID, id); args.putString(ARG_NAME, name); args.putParcelable(ARG_LATLNG, latLng); args.putInt(ARG_POSITION, position); args.putBoolean(ARG_TOGGLE_STATE, toggleState); args.putDouble(ARG_RATING, rating); args.putInt(ARG_LIKES, likes); args.putDouble(ARG_NORMALIZED_LIKES, normalizedLikes); args.putParcelable(ARG_USER_LATLNG, userLatLng); args.putParcelable(ARG_FRIEND_LATLNG, friendLatLng); args.putParcelable(ARG_MID_LATLNG, midLatLng); SuggestionDetailFragment fragment = new SuggestionDetailFragment(); fragment.setArguments(args); return fragment; } /** * Interface for activities or parent fragments interested in events from this fragment */ public interface SuggestionDetailFragmentListener { void onOpenWebsite(String url); void onDialPhone(String phone); void onToggle(String id, int position, boolean toggleState); } /** * Required empty constructor */ public SuggestionDetailFragment() {} /** * Make sure activity or parent fragment is a listener * @param context */ @Override public void onAttach(Context context) { super.onAttach(context); Object objectToCast = getParentFragment() != null ? getParentFragment() : context; try { listener = (SuggestionDetailFragmentListener) objectToCast; } catch (ClassCastException e) { throw new ClassCastException(objectToCast.getClass().getSimpleName() + " must implement SuggestionDetailFragmentListener"); } } /** * Configure the fragment * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //read bundle args Bundle args = getArguments(); if (args != null) { //about the business id = args.getString(ARG_ID); name = args.getString(ARG_NAME); latLng = args.getParcelable(ARG_LATLNG); //about the view position = args.getInt(ARG_POSITION, position); FRAGMENT_TAG_LITEMAP = String.format("%s.%d", FRAGMENT_TAG_LITEMAP, position); toggleState = args.getBoolean(ARG_TOGGLE_STATE, false); rating = args.getDouble(ARG_RATING, LocalConstants.NO_DATA_DOUBLE); likes = args.getInt(ARG_LIKES, LocalConstants.NO_DATA_INTEGER); normalizedLikes = args.getDouble(ARG_NORMALIZED_LIKES, LocalConstants.NO_DATA_DOUBLE); //user and friend related info userLatLng = args.getParcelable(ARG_USER_LATLNG); friendLatLng = args.getParcelable(ARG_FRIEND_LATLNG); midLatLng = args.getParcelable(ARG_MID_LATLNG); } } /** * Inflate the view * @param inflater * @param container * @param savedInstanceState * @return */ @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_suggestion_detail, container, false); } /** * Configure the fragment's view */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //set view holder ViewHolder viewHolder = new ViewHolder(view); view.setTag(viewHolder); //set the name so that users with slow connections won't see a completely blank screen viewHolder.name.setText(name); //set up the state of the select button if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) viewHolder.selectButton.setCompoundDrawablesRelativeWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); else viewHolder.selectButton.setCompoundDrawablesWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); viewHolder.selectButton.setText(toggleState ? R.string.selected_button : R.string.select_button); //set up click listeners viewHolder.image.setOnClickListener(this); viewHolder.websiteButton.setOnClickListener(this); viewHolder.phoneButton.setOnClickListener(this); viewHolder.selectButton.setOnClickListener(this); //initially make the detail container gone and show the progress bar viewHolder.detailContainer.setVisibility(View.GONE); viewHolder.detailProgressBar.setVisibility(View.VISIBLE); //set up the map SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(FRAGMENT_TAG_LITEMAP); if (mapFragment == null) { Log.d(TAG, "onViewCreated: LiteMap fragment is null"); GoogleMapOptions googleMapOptions = new GoogleMapOptions() .camera(new CameraPosition(latLng, DEFAULT_ZOOM, 0, 0)) .compassEnabled(false) .liteMode(true) .mapToolbarEnabled(false) .mapType(GoogleMap.MAP_TYPE_NORMAL) .rotateGesturesEnabled(false) .scrollGesturesEnabled(false) .tiltGesturesEnabled(false) .zoomControlsEnabled(false) .zoomGesturesEnabled(false); mapFragment = SupportMapFragment.newInstance(googleMapOptions); getChildFragmentManager() .beginTransaction() .add(R.id.detail_mapContainer, mapFragment, FRAGMENT_TAG_LITEMAP) .commit(); } //load the map asynchronously mapFragment.getMapAsync(this); } /** * Init the loader * @param savedInstanceState */ @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); fetchPlaceDetails(); } /** * Helper method that initializes the loader to fetch details for a particular * id from either Yelp or Facebook */ private void fetchPlaceDetails() { int imageSizePx = getResources().getDimensionPixelSize(R.dimen.profile_image_size); if (FbConstants.USE_FB) { //check if user is currently logged into fb if (AccessToken.getCurrentAccessToken() != null) { Log.d(TAG, "onActivityCreated: User is logged in"); //initialize the loader to fetch details for this particular id from fb SingleSuggestionLoaderCallbacks.initLoader(getActivity(), getLoaderManager(), this, id, imageSizePx, imageSizePx, LocalConstants.FACEBOOK); } else { Log.d(TAG, "onActivityCreated: User is not logged in"); } } else { //initialize the loader to fetch details for this particular id from Yelp SingleSuggestionLoaderCallbacks.initLoader(getActivity(), getLoaderManager(), this, id, imageSizePx, imageSizePx, LocalConstants.YELP); } } /** * Do some shimmering in case we load slowly. */ @Override public void onResume() { super.onResume(); //shimmer while we are loading ViewHolder viewHolder = getViewHolder(); if (viewHolder != null) { viewHolder.shimmerContainer.setDuration(400); viewHolder.shimmerContainer.startShimmerAnimation(); } } /** * Nullify the open browser and dial phone listener */ @Override public void onDetach() { listener = null; super.onDetach(); } /** * SingleSuggestionLoaderCallbacks.SingleSuggestionLoaderListener callback * When the loader delivers the results, this method would be called. This method then calls updateView. * @param loaderId * @param business */ @Override public void onLoadComplete(LoaderId loaderId, @Nullable LocalBusiness business) { if (loaderId != LoaderId.SINGLE_PLACE) { Log.d(TAG, "onLoadComplete: Unknown loaderId:" + loaderId); return; } this.business = business; if (business == null) { Log.d(TAG, "onLoadComplete: Local business is null. Loader must be resetting"); //animate in the detail empty textview, and animate out the progress bar ViewHolder viewHolder = getViewHolder(); if (viewHolder != null && viewHolder.detailEmpty.getVisibility() != View.VISIBLE) { //stop shimmering viewHolder.shimmerContainer.stopShimmerAnimation(); viewHolder.detailContainer.setVisibility(View.GONE); //make sure container doesn't show AnimationUtils.crossFadeViews(getActivity(), viewHolder.detailEmpty, viewHolder.detailProgressBar); } return; } else { Log.d(TAG, "onLoadComplete: Local business is not null. Updating views"); //animate in the detail container, and animate out the progress bar ViewHolder viewHolder = getViewHolder(); if (viewHolder != null && viewHolder.detailContainer.getVisibility() != View.VISIBLE) { //stop shimmering viewHolder.shimmerContainer.stopShimmerAnimation(); viewHolder.detailEmpty.setVisibility(View.GONE); //make sure empty view doesn't show AnimationUtils.crossFadeViews(getActivity(), viewHolder.detailContainer, viewHolder.detailProgressBar); } updateView(); } } /** * Helper method to update all the text views that display business details */ private void updateView() { Log.d(TAG, "updateView"); //check if the view is ready final ViewHolder viewHolder = getViewHolder(); if (viewHolder == null) return; //image if (business.getImageUrl() != null) { ImageUtils.loadImage(getActivity(), business.getImageUrl(), viewHolder.image, R.drawable.ic_business_image_placeholder, R.drawable.ic_business_image_placeholder); } //name viewHolder.name.setText(name); //category list final String[] categoryList = business.getCategoryList(); if (categoryList == null) { viewHolder.categories.setVisibility(View.GONE); } else { viewHolder.categories.setVisibility(View.VISIBLE); StringBuilder builder = new StringBuilder(categoryList.length); for (int i=0; i<categoryList.length; i++) { builder.append(categoryList[i]); if (i < categoryList.length-1) builder.append(", "); } viewHolder.categories.setText(builder.toString()); } //compute who is closer final int fairness = FairnessScoringUtils.computeFairnessScore(userLatLng, friendLatLng, latLng); final double distanceDelta = FairnessScoringUtils.computeDistanceDelta(latLng, midLatLng, FairnessScoringUtils.IMPERIAL); final String displayString = FairnessScoringUtils.formatDistanceDeltaAndFairness(getActivity(), distanceDelta, fairness, FairnessScoringUtils.IMPERIAL, true); viewHolder.distanceFromMidPoint.setText(displayString); //address final String fullAddress = business.getLocalBusinessLocation() != null ? business.getLocalBusinessLocation().getLongDisplayAddress() : null; viewHolder.address.setText(fullAddress != null ? fullAddress : getString(R.string.not_available)); //cross streets final String crossStreets = business.getLocalBusinessLocation() != null ? business.getLocalBusinessLocation().getCrossStreets() : null; viewHolder.crossStreets.setText(getString(R.string.detail_crossStreets, crossStreets != null ? crossStreets : getString(R.string.not_available))); //phone viewHolder.phone.setText(business.getPhoneNumber() != null ? business.getPhoneNumber() : getString(R.string.not_available)); //web address and fbAddress viewHolder.webAddress.setText(business.getMobileUrl() != null ? business.getMobileUrl() : getString(R.string.not_available)); if (business.getFbLink() == null) viewHolder.fbAddress.setVisibility(View.GONE); else viewHolder.fbAddress.setText(business.getFbLink()); //price range viewHolder.priceRange.setText(business.getPriceRange() != null ? business.getPriceRange() : getString(R.string.not_available)); //ratings and reviews OR likes and checkins if (business.getReviewCount() != -1) { //we have yelp data viewHolder.reviews.setText(getString(R.string.review_count, business.getReviewCount())); //note: picasso only keeps a weak ref to the target so it may be gc-ed //use setTag so that target will be alive as long as the view is alive if (business.getRatingImageUrl() != null) { final Target target = ImageUtils.newTarget(getActivity(), viewHolder.reviews); viewHolder.reviews.setTag(target); ImageUtils.loadImage(getActivity(), business.getRatingImageUrl(), target); } viewHolder.checkins.setVisibility(View.GONE); } else { //we most likely have fb data viewHolder.checkins.setVisibility(View.VISIBLE); viewHolder.reviews.setText(getContext().getResources().getQuantityString( R.plurals.detail_like_count, business.getLikes(), business.getLikes())); viewHolder.checkins.setText(getContext().getResources().getQuantityString( R.plurals.detail_checkin_count, business.getCheckins(), business.getCheckins())); } //hours if (business.isAlwaysOpen()) { viewHolder.hoursRange.setText(R.string.always_open); } else { final String[] hoursArray = business.getHours(); if (hoursArray == null) { viewHolder.hoursRange.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(hoursArray.length); for (int i=0; i<hoursArray.length; i++) { builder.append(hoursArray[i]); if (i < hoursArray.length-1) builder.append("\n"); } viewHolder.hoursRange.setText(builder.toString()); } } //specialities final String[] specialitiesArray = business.getRestaurantSpecialities(); if (specialitiesArray == null) { viewHolder.specialities.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(specialitiesArray.length); for (int i=0; i<specialitiesArray.length; i++) { builder.append(specialitiesArray[i]); if (i < specialitiesArray.length-1) builder.append(", "); } viewHolder.specialities.setText(builder.toString()); } //services final String[] servicesArray = business.getRestaurantServices(); if (servicesArray == null) { viewHolder.services.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(servicesArray.length); for (int i=0; i<servicesArray.length; i++) { builder.append(servicesArray[i]); if (i < servicesArray.length-1) builder.append(", "); } viewHolder.services.setText(builder.toString()); } //parking final String[] parkingArray = business.getParking(); if (parkingArray == null) { viewHolder.parking.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(parkingArray.length); for (int i=0; i<parkingArray.length; i++) { builder.append(parkingArray[i]); if (i < parkingArray.length-1) builder.append(", "); } viewHolder.parking.setText(builder.toString()); } //payment options final String[] paymentOptionsArray = business.getPaymentOptions(); if (paymentOptionsArray == null) { viewHolder.paymentOptions.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(paymentOptionsArray.length); for (int i=0; i<paymentOptionsArray.length; i++) { builder.append(paymentOptionsArray[i]); if (i < paymentOptionsArray.length-1) builder.append(", "); } viewHolder.paymentOptions.setText(builder.toString()); } //culinary team viewHolder.culinaryTeam.setText(business.getCulinaryTeam() != null ? business.getCulinaryTeam() : getString(R.string.not_available)); //description (if description is null, use about. if both are null, then show "not available") final String description = business.getDescription() != null ? business.getDescription() : business.getAbout(); viewHolder.description.setText(description != null ? description : getString(R.string.not_available)); } /** * Handles the different button clicks * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.detail_image: Log.d(TAG, "onClick: Detail image clicked"); //TODO: Open picture pager break; case R.id.detail_website_button: listener.onOpenWebsite(business.getMobileUrl()); break; case R.id.detail_phone_button: listener.onDialPhone(business.getPhoneNumber()); break; case R.id.detail_select_button: toggleState = !toggleState; final ViewHolder viewHolder = getViewHolder(); if (viewHolder != null) { //update the select button icon and text if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) viewHolder.selectButton.setCompoundDrawablesRelativeWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); else viewHolder.selectButton.setCompoundDrawablesWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); viewHolder.selectButton.setText(toggleState ? R.string.selected_button : R.string.select_button); //update the marker color marker.setIcon(MapColorUtils.determineMarkerIcon(toggleState, rating != LocalConstants.NO_DATA_DOUBLE ? rating : normalizedLikes)); } listener.onToggle(id, position, toggleState); break; } } /** * OnMapReadyCallback callback * Add a single marker to the map * @param googleMap */ @Override public void onMapReady(GoogleMap googleMap) { Log.d(TAG, "onMapReady"); //intercept clicks on the map googleMap.setOnMapClickListener(this); //add marker MarkerOptions markerOptions = new MarkerOptions() .position(latLng) .icon(MapColorUtils.determineMarkerIcon(toggleState, rating != LocalConstants.NO_DATA_DOUBLE ? rating : normalizedLikes)); marker = googleMap.addMarker(markerOptions); } /** * GoogleMap.OnMapClickListener callback. * Override the default behavior of opening the google maps app. * TODO: Open an interactive map within the app. * @param latLng */ @Override public void onMapClick(LatLng latLng) { Log.d(TAG, "onMapClick: The map was clicked"); } /** * Returns the fragment view's view holder if it exists, or null. * @return */ @Nullable private ViewHolder getViewHolder() { View view = getView(); return view != null ? (ViewHolder) view.getTag() : null; } /** * View holder class */ private class ViewHolder { final ImageView image; final TextView name; final TextView categories;; final TextView distanceFromMidPoint; final TextView address; final TextView crossStreets; final TextView phone; final TextView webAddress; final TextView fbAddress; final TextView priceRange; final TextView reviews; final TextView checkins; final TextView hoursRange; final TextView specialities; final TextView services; final TextView parking; final TextView paymentOptions; final TextView culinaryTeam; final TextView description; final Button websiteButton; final Button phoneButton; final Button selectButton; final View detailContainer; final View detailProgressBar; final TextView detailEmpty; final ShimmerFrameLayout shimmerContainer; ViewHolder(View view) { //image view image = (ImageView) view.findViewById(R.id.detail_image); //text views name = (TextView) view.findViewById(R.id.detail_name); categories = (TextView) view.findViewById(R.id.detail_categories); distanceFromMidPoint = (TextView) view.findViewById(R.id.detail_distance_from_midpoint); address = (TextView) view.findViewById(R.id.detail_address); crossStreets = (TextView) view.findViewById(R.id.detail_crossStreets); phone = (TextView) view.findViewById(R.id.detail_phone); webAddress = (TextView) view.findViewById(R.id.detail_webAddress); fbAddress = (TextView) view.findViewById(R.id.detail_fbAddress); priceRange = (TextView) view.findViewById(R.id.detail_price_range); reviews = (TextView) view.findViewById(R.id.detail_reviews); checkins = (TextView) view.findViewById(R.id.detail_checkins); hoursRange = (TextView) view.findViewById(R.id.detail_hours_range); specialities = (TextView) view.findViewById(R.id.detail_specialities); services = (TextView) view.findViewById(R.id.detail_services); parking = (TextView) view.findViewById(R.id.detail_parking); paymentOptions = (TextView) view.findViewById(R.id.detail_payment_options); culinaryTeam = (TextView) view.findViewById(R.id.detail_culinary_team); description = (TextView) view.findViewById(R.id.detail_description); //buttons websiteButton = (Button) view.findViewById(R.id.detail_website_button); phoneButton = (Button) view.findViewById(R.id.detail_phone_button); selectButton = (Button) view.findViewById(R.id.detail_select_button); //for animation detailContainer = view.findViewById(R.id.detail_container); detailProgressBar = view.findViewById(R.id.detail_progressBar); detailEmpty = (TextView) view.findViewById(R.id.detail_empty); //shimmer shimmerContainer = (ShimmerFrameLayout) view.findViewById(R.id.shimmerContainer); } } }
app/src/main/java/com/example/yeelin/projects/betweenus/fragment/SuggestionDetailFragment.java
package com.example.yeelin.projects.betweenus.fragment; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.example.yeelin.projects.betweenus.R; import com.example.yeelin.projects.betweenus.data.LocalBusiness; import com.example.yeelin.projects.betweenus.data.LocalConstants; import com.example.yeelin.projects.betweenus.data.fb.query.FbConstants; import com.example.yeelin.projects.betweenus.loader.LoaderId; import com.example.yeelin.projects.betweenus.loader.SingleSuggestionLoaderCallbacks; import com.example.yeelin.projects.betweenus.loader.callback.SingleSuggestionLoaderListener; import com.example.yeelin.projects.betweenus.utils.AnimationUtils; import com.example.yeelin.projects.betweenus.utils.FairnessScoringUtils; import com.example.yeelin.projects.betweenus.utils.ImageUtils; import com.example.yeelin.projects.betweenus.utils.MapColorUtils; import com.facebook.AccessToken; import com.facebook.shimmer.ShimmerFrameLayout; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMapOptions; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.squareup.picasso.Target; /** * Created by ninjakiki on 7/15/15. */ public class SuggestionDetailFragment extends Fragment implements SingleSuggestionLoaderListener, View.OnClickListener, OnMapReadyCallback { //logcat private static final String TAG = SuggestionDetailFragment.class.getCanonicalName(); //bundle args private static final String ARG_ID = SuggestionDetailFragment.class.getSimpleName() + ".id"; private static final String ARG_NAME = SuggestionDetailFragment.class.getSimpleName() + ".name"; private static final String ARG_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".latLng"; private static final String ARG_POSITION = SuggestionDetailFragment.class.getSimpleName() + ".position"; private static final String ARG_TOGGLE_STATE = SuggestionDetailFragment.class.getSimpleName() + ".toggleState"; private static final String ARG_RATING = SuggestionDetailFragment.class.getSimpleName() + ".rating"; private static final String ARG_LIKES = SuggestionDetailFragment.class.getSimpleName() + ".likes"; private static final String ARG_NORMALIZED_LIKES = SuggestionDetailFragment.class.getSimpleName() + ".normalizedLikes"; private static final String ARG_USER_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".userLatLng"; private static final String ARG_FRIEND_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".friendLatLng"; private static final String ARG_MID_LATLNG = SuggestionDetailFragment.class.getSimpleName() + ".midLatLng"; //child fragment tags private static String FRAGMENT_TAG_LITEMAP = SupportMapFragment.class.getSimpleName(); //constants private static final int DEFAULT_ZOOM = 13; //member variables private String id; private String name; private LatLng latLng; private int position = 0; private boolean toggleState; private double rating; private int likes; private double normalizedLikes; private LatLng userLatLng; private LatLng friendLatLng; private LatLng midLatLng; private Marker marker; private LocalBusiness business; private SuggestionDetailFragmentListener listener; /** * Creates a new instance of this fragment * @param id * @param name * @param latLng * @param position * @param toggleState * @param rating * @param likes * @param normalizedLikes * @param userLatLng * @param friendLatLng * @param midLatLng midpoint between userLatLng and friendLatLng * @return */ public static SuggestionDetailFragment newInstance(String id, String name, LatLng latLng, int position, boolean toggleState, double rating, int likes, double normalizedLikes, LatLng userLatLng, LatLng friendLatLng, LatLng midLatLng) { Bundle args = new Bundle(); args.putString(ARG_ID, id); args.putString(ARG_NAME, name); args.putParcelable(ARG_LATLNG, latLng); args.putInt(ARG_POSITION, position); args.putBoolean(ARG_TOGGLE_STATE, toggleState); args.putDouble(ARG_RATING, rating); args.putInt(ARG_LIKES, likes); args.putDouble(ARG_NORMALIZED_LIKES, normalizedLikes); args.putParcelable(ARG_USER_LATLNG, userLatLng); args.putParcelable(ARG_FRIEND_LATLNG, friendLatLng); args.putParcelable(ARG_MID_LATLNG, midLatLng); SuggestionDetailFragment fragment = new SuggestionDetailFragment(); fragment.setArguments(args); return fragment; } /** * Interface for activities or parent fragments interested in events from this fragment */ public interface SuggestionDetailFragmentListener { void onOpenWebsite(String url); void onDialPhone(String phone); void onToggle(String id, int position, boolean toggleState); } /** * Required empty constructor */ public SuggestionDetailFragment() {} /** * Make sure activity or parent fragment is a listener * @param context */ @Override public void onAttach(Context context) { super.onAttach(context); Object objectToCast = getParentFragment() != null ? getParentFragment() : context; try { listener = (SuggestionDetailFragmentListener) objectToCast; } catch (ClassCastException e) { throw new ClassCastException(objectToCast.getClass().getSimpleName() + " must implement SuggestionDetailFragmentListener"); } } /** * Configure the fragment * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //read bundle args Bundle args = getArguments(); if (args != null) { //about the business id = args.getString(ARG_ID); name = args.getString(ARG_NAME); latLng = args.getParcelable(ARG_LATLNG); //about the view position = args.getInt(ARG_POSITION, position); FRAGMENT_TAG_LITEMAP = String.format("%s.%d", FRAGMENT_TAG_LITEMAP, position); toggleState = args.getBoolean(ARG_TOGGLE_STATE, false); rating = args.getDouble(ARG_RATING, LocalConstants.NO_DATA_DOUBLE); likes = args.getInt(ARG_LIKES, LocalConstants.NO_DATA_INTEGER); normalizedLikes = args.getDouble(ARG_NORMALIZED_LIKES, LocalConstants.NO_DATA_DOUBLE); //user and friend related info userLatLng = args.getParcelable(ARG_USER_LATLNG); friendLatLng = args.getParcelable(ARG_FRIEND_LATLNG); midLatLng = args.getParcelable(ARG_MID_LATLNG); } } /** * Inflate the view * @param inflater * @param container * @param savedInstanceState * @return */ @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_suggestion_detail, container, false); } /** * Configure the fragment's view */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //set view holder ViewHolder viewHolder = new ViewHolder(view); view.setTag(viewHolder); //set the name so that users with slow connections won't see a completely blank screen viewHolder.name.setText(name); //set up the state of the select button if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) viewHolder.selectButton.setCompoundDrawablesRelativeWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); else viewHolder.selectButton.setCompoundDrawablesWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); viewHolder.selectButton.setText(toggleState ? R.string.selected_button : R.string.select_button); //set up click listeners viewHolder.websiteButton.setOnClickListener(this); viewHolder.phoneButton.setOnClickListener(this); viewHolder.selectButton.setOnClickListener(this); //initially make the detail container gone and show the progress bar viewHolder.detailContainer.setVisibility(View.GONE); viewHolder.detailProgressBar.setVisibility(View.VISIBLE); //set up the map SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(FRAGMENT_TAG_LITEMAP); if (mapFragment == null) { Log.d(TAG, "onViewCreated: LiteMap fragment is null"); GoogleMapOptions googleMapOptions = new GoogleMapOptions() .camera(new CameraPosition(latLng, DEFAULT_ZOOM, 0, 0)) .compassEnabled(false) .liteMode(true) .mapToolbarEnabled(false) .mapType(GoogleMap.MAP_TYPE_NORMAL) .rotateGesturesEnabled(false) .scrollGesturesEnabled(false) .tiltGesturesEnabled(false) .zoomControlsEnabled(false) .zoomGesturesEnabled(false); mapFragment = SupportMapFragment.newInstance(googleMapOptions); getChildFragmentManager() .beginTransaction() .add(R.id.detail_mapContainer, mapFragment, FRAGMENT_TAG_LITEMAP) .commit(); } if (mapFragment != null && mapFragment.getView() != null) { Log.d(TAG, "onViewCreated: Disable map click"); mapFragment.getView().setClickable(false); } mapFragment.getMapAsync(this); } /** * Init the loader * @param savedInstanceState */ @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); fetchPlaceDetails(); } /** * Helper method that initializes the loader to fetch details for a particular * id from either Yelp or Facebook */ private void fetchPlaceDetails() { int imageSizePx = getResources().getDimensionPixelSize(R.dimen.profile_image_size); if (FbConstants.USE_FB) { //check if user is currently logged into fb if (AccessToken.getCurrentAccessToken() != null) { Log.d(TAG, "onActivityCreated: User is logged in"); //initialize the loader to fetch details for this particular id from fb SingleSuggestionLoaderCallbacks.initLoader(getActivity(), getLoaderManager(), this, id, imageSizePx, imageSizePx, LocalConstants.FACEBOOK); } else { Log.d(TAG, "onActivityCreated: User is not logged in"); } } else { //initialize the loader to fetch details for this particular id from Yelp SingleSuggestionLoaderCallbacks.initLoader(getActivity(), getLoaderManager(), this, id, imageSizePx, imageSizePx, LocalConstants.YELP); } } /** * Do some shimmering in case we load slowly. */ @Override public void onResume() { super.onResume(); //shimmer while we are loading ViewHolder viewHolder = getViewHolder(); if (viewHolder != null) { viewHolder.shimmerContainer.setDuration(400); viewHolder.shimmerContainer.startShimmerAnimation(); } } /** * Nullify the open browser and dial phone listener */ @Override public void onDetach() { listener = null; super.onDetach(); } /** * SingleSuggestionLoaderCallbacks.SingleSuggestionLoaderListener callback * When the loader delivers the results, this method would be called. This method then calls updateView. * @param loaderId * @param business */ @Override public void onLoadComplete(LoaderId loaderId, @Nullable LocalBusiness business) { if (loaderId != LoaderId.SINGLE_PLACE) { Log.d(TAG, "onLoadComplete: Unknown loaderId:" + loaderId); return; } this.business = business; if (business == null) { Log.d(TAG, "onLoadComplete: Local business is null. Loader must be resetting"); //animate in the detail empty textview, and animate out the progress bar ViewHolder viewHolder = getViewHolder(); if (viewHolder != null && viewHolder.detailEmpty.getVisibility() != View.VISIBLE) { //stop shimmering viewHolder.shimmerContainer.stopShimmerAnimation(); viewHolder.detailContainer.setVisibility(View.GONE); //make sure container doesn't show AnimationUtils.crossFadeViews(getActivity(), viewHolder.detailEmpty, viewHolder.detailProgressBar); } return; } else { Log.d(TAG, "onLoadComplete: Local business is not null. Updating views"); //animate in the detail container, and animate out the progress bar ViewHolder viewHolder = getViewHolder(); if (viewHolder != null && viewHolder.detailContainer.getVisibility() != View.VISIBLE) { //stop shimmering viewHolder.shimmerContainer.stopShimmerAnimation(); viewHolder.detailEmpty.setVisibility(View.GONE); //make sure empty view doesn't show AnimationUtils.crossFadeViews(getActivity(), viewHolder.detailContainer, viewHolder.detailProgressBar); } updateView(); } } /** * Helper method to update all the text views that display business details */ private void updateView() { Log.d(TAG, "updateView"); //check if the view is ready final ViewHolder viewHolder = getViewHolder(); if (viewHolder == null) return; //image if (business.getImageUrl() != null) { ImageUtils.loadImage(getActivity(), business.getImageUrl(), viewHolder.image, R.drawable.ic_business_image_placeholder, R.drawable.ic_business_image_placeholder); } //name viewHolder.name.setText(name); //category list final String[] categoryList = business.getCategoryList(); if (categoryList == null) { viewHolder.categories.setVisibility(View.GONE); } else { viewHolder.categories.setVisibility(View.VISIBLE); StringBuilder builder = new StringBuilder(categoryList.length); for (int i=0; i<categoryList.length; i++) { builder.append(categoryList[i]); if (i < categoryList.length-1) builder.append(", "); } viewHolder.categories.setText(builder.toString()); } //compute who is closer final int fairness = FairnessScoringUtils.computeFairnessScore(userLatLng, friendLatLng, latLng); final double distanceDelta = FairnessScoringUtils.computeDistanceDelta(latLng, midLatLng, FairnessScoringUtils.IMPERIAL); final String displayString = FairnessScoringUtils.formatDistanceDeltaAndFairness(getActivity(), distanceDelta, fairness, FairnessScoringUtils.IMPERIAL, true); viewHolder.distanceFromMidPoint.setText(displayString); //address final String fullAddress = business.getLocalBusinessLocation() != null ? business.getLocalBusinessLocation().getLongDisplayAddress() : null; viewHolder.address.setText(fullAddress != null ? fullAddress : getString(R.string.not_available)); //cross streets final String crossStreets = business.getLocalBusinessLocation() != null ? business.getLocalBusinessLocation().getCrossStreets() : null; viewHolder.crossStreets.setText(getString(R.string.detail_crossStreets, crossStreets != null ? crossStreets : getString(R.string.not_available))); //phone viewHolder.phone.setText(business.getPhoneNumber() != null ? business.getPhoneNumber() : getString(R.string.not_available)); //web address and fbAddress viewHolder.webAddress.setText(business.getMobileUrl() != null ? business.getMobileUrl() : getString(R.string.not_available)); if (business.getFbLink() == null) viewHolder.fbAddress.setVisibility(View.GONE); else viewHolder.fbAddress.setText(business.getFbLink()); //price range viewHolder.priceRange.setText(business.getPriceRange() != null ? business.getPriceRange() : getString(R.string.not_available)); //ratings and reviews OR likes and checkins if (business.getReviewCount() != -1) { //we have yelp data viewHolder.reviews.setText(getString(R.string.review_count, business.getReviewCount())); //note: picasso only keeps a weak ref to the target so it may be gc-ed //use setTag so that target will be alive as long as the view is alive if (business.getRatingImageUrl() != null) { final Target target = ImageUtils.newTarget(getActivity(), viewHolder.reviews); viewHolder.reviews.setTag(target); ImageUtils.loadImage(getActivity(), business.getRatingImageUrl(), target); } viewHolder.checkins.setVisibility(View.GONE); } else { //we most likely have fb data viewHolder.checkins.setVisibility(View.VISIBLE); viewHolder.reviews.setText(getContext().getResources().getQuantityString( R.plurals.detail_like_count, business.getLikes(), business.getLikes())); viewHolder.checkins.setText(getContext().getResources().getQuantityString( R.plurals.detail_checkin_count, business.getCheckins(), business.getCheckins())); } //hours if (business.isAlwaysOpen()) { viewHolder.hoursRange.setText(R.string.always_open); } else { final String[] hoursArray = business.getHours(); if (hoursArray == null) { viewHolder.hoursRange.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(hoursArray.length); for (int i=0; i<hoursArray.length; i++) { builder.append(hoursArray[i]); if (i < hoursArray.length-1) builder.append("\n"); } viewHolder.hoursRange.setText(builder.toString()); } } //specialities final String[] specialitiesArray = business.getRestaurantSpecialities(); if (specialitiesArray == null) { viewHolder.specialities.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(specialitiesArray.length); for (int i=0; i<specialitiesArray.length; i++) { builder.append(specialitiesArray[i]); if (i < specialitiesArray.length-1) builder.append(", "); } viewHolder.specialities.setText(builder.toString()); } //services final String[] servicesArray = business.getRestaurantServices(); if (servicesArray == null) { viewHolder.services.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(servicesArray.length); for (int i=0; i<servicesArray.length; i++) { builder.append(servicesArray[i]); if (i < servicesArray.length-1) builder.append(", "); } viewHolder.services.setText(builder.toString()); } //parking final String[] parkingArray = business.getParking(); if (parkingArray == null) { viewHolder.parking.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(parkingArray.length); for (int i=0; i<parkingArray.length; i++) { builder.append(parkingArray[i]); if (i < parkingArray.length-1) builder.append(", "); } viewHolder.parking.setText(builder.toString()); } //payment options final String[] paymentOptionsArray = business.getPaymentOptions(); if (paymentOptionsArray == null) { viewHolder.paymentOptions.setText(R.string.not_available); } else { StringBuilder builder = new StringBuilder(paymentOptionsArray.length); for (int i=0; i<paymentOptionsArray.length; i++) { builder.append(paymentOptionsArray[i]); if (i < paymentOptionsArray.length-1) builder.append(", "); } viewHolder.paymentOptions.setText(builder.toString()); } //culinary team viewHolder.culinaryTeam.setText(business.getCulinaryTeam() != null ? business.getCulinaryTeam() : getString(R.string.not_available)); //description (if description is null, use about. if both are null, then show "not available") final String description = business.getDescription() != null ? business.getDescription() : business.getAbout(); viewHolder.description.setText(description != null ? description : getString(R.string.not_available)); } /** * Handles the different button clicks * @param v */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.detail_website_button: listener.onOpenWebsite(business.getMobileUrl()); break; case R.id.detail_phone_button: listener.onDialPhone(business.getPhoneNumber()); break; case R.id.detail_select_button: toggleState = !toggleState; final ViewHolder viewHolder = getViewHolder(); if (viewHolder != null) { //update the select button icon and text if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) viewHolder.selectButton.setCompoundDrawablesRelativeWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); else viewHolder.selectButton.setCompoundDrawablesWithIntrinsicBounds(toggleState ? R.drawable.ic_action_detail_favorite_red300 : R.drawable.ic_action_detail_favorite, 0, 0, 0); viewHolder.selectButton.setText(toggleState ? R.string.selected_button : R.string.select_button); //update the marker color marker.setIcon(MapColorUtils.determineMarkerIcon(toggleState, rating != LocalConstants.NO_DATA_DOUBLE ? rating : normalizedLikes)); } listener.onToggle(id, position, toggleState); break; } } /** * OnMapReadyCallback callback * Add a single marker to the map * @param googleMap */ @Override public void onMapReady(GoogleMap googleMap) { Log.d(TAG, "onMapReady"); //disable click listener final SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(FRAGMENT_TAG_LITEMAP); if (mapFragment != null && mapFragment.getView() != null) { Log.d(TAG, "onMapReady: Disable map click"); mapFragment.getView().setClickable(false); } //add marker MarkerOptions markerOptions = new MarkerOptions() .position(latLng) .icon(MapColorUtils.determineMarkerIcon(toggleState, rating != LocalConstants.NO_DATA_DOUBLE ? rating : normalizedLikes)); marker = googleMap.addMarker(markerOptions); } /** * Returns the fragment view's view holder if it exists, or null. * @return */ @Nullable private ViewHolder getViewHolder() { View view = getView(); return view != null ? (ViewHolder) view.getTag() : null; } /** * View holder class */ private class ViewHolder { final ImageView image; final TextView name; final TextView categories;; final TextView distanceFromMidPoint; final TextView address; final TextView crossStreets; final TextView phone; final TextView webAddress; final TextView fbAddress; final TextView priceRange; final TextView reviews; final TextView checkins; final TextView hoursRange; final TextView specialities; final TextView services; final TextView parking; final TextView paymentOptions; final TextView culinaryTeam; final TextView description; final Button websiteButton; final Button phoneButton; final Button selectButton; final View detailContainer; final View detailProgressBar; final TextView detailEmpty; final ShimmerFrameLayout shimmerContainer; ViewHolder(View view) { //image view image = (ImageView) view.findViewById(R.id.detail_image); //text views name = (TextView) view.findViewById(R.id.detail_name); categories = (TextView) view.findViewById(R.id.detail_categories); distanceFromMidPoint = (TextView) view.findViewById(R.id.detail_distance_from_midpoint); address = (TextView) view.findViewById(R.id.detail_address); crossStreets = (TextView) view.findViewById(R.id.detail_crossStreets); phone = (TextView) view.findViewById(R.id.detail_phone); webAddress = (TextView) view.findViewById(R.id.detail_webAddress); fbAddress = (TextView) view.findViewById(R.id.detail_fbAddress); priceRange = (TextView) view.findViewById(R.id.detail_price_range); reviews = (TextView) view.findViewById(R.id.detail_reviews); checkins = (TextView) view.findViewById(R.id.detail_checkins); hoursRange = (TextView) view.findViewById(R.id.detail_hours_range); specialities = (TextView) view.findViewById(R.id.detail_specialities); services = (TextView) view.findViewById(R.id.detail_services); parking = (TextView) view.findViewById(R.id.detail_parking); paymentOptions = (TextView) view.findViewById(R.id.detail_payment_options); culinaryTeam = (TextView) view.findViewById(R.id.detail_culinary_team); description = (TextView) view.findViewById(R.id.detail_description); //buttons websiteButton = (Button) view.findViewById(R.id.detail_website_button); phoneButton = (Button) view.findViewById(R.id.detail_phone_button); selectButton = (Button) view.findViewById(R.id.detail_select_button); //for animation detailContainer = view.findViewById(R.id.detail_container); detailProgressBar = view.findViewById(R.id.detail_progressBar); detailEmpty = (TextView) view.findViewById(R.id.detail_empty); //shimmer shimmerContainer = (ShimmerFrameLayout) view.findViewById(R.id.shimmerContainer); } } }
Clicks on the lite map currently opens the google map app. Override the default behavior so that we can open an interactive map within the app instead. Also added a click listener for the imageview so that we can browse more pictures in the future.
app/src/main/java/com/example/yeelin/projects/betweenus/fragment/SuggestionDetailFragment.java
Clicks on the lite map currently opens the google map app. Override the default behavior so that we can open an interactive map within the app instead. Also added a click listener for the imageview so that we can browse more pictures in the future.
<ide><path>pp/src/main/java/com/example/yeelin/projects/betweenus/fragment/SuggestionDetailFragment.java <ide> implements <ide> SingleSuggestionLoaderListener, <ide> View.OnClickListener, <del> OnMapReadyCallback { <add> OnMapReadyCallback, <add> GoogleMap.OnMapClickListener { <ide> //logcat <ide> private static final String TAG = SuggestionDetailFragment.class.getCanonicalName(); <ide> //bundle args <ide> viewHolder.selectButton.setText(toggleState ? R.string.selected_button : R.string.select_button); <ide> <ide> //set up click listeners <add> viewHolder.image.setOnClickListener(this); <ide> viewHolder.websiteButton.setOnClickListener(this); <ide> viewHolder.phoneButton.setOnClickListener(this); <ide> viewHolder.selectButton.setOnClickListener(this); <ide> .commit(); <ide> } <ide> <del> if (mapFragment != null && mapFragment.getView() != null) { <del> Log.d(TAG, "onViewCreated: Disable map click"); <del> mapFragment.getView().setClickable(false); <del> } <del> <add> //load the map asynchronously <ide> mapFragment.getMapAsync(this); <ide> } <ide> <ide> @Override <ide> public void onClick(View v) { <ide> switch (v.getId()) { <add> case R.id.detail_image: <add> Log.d(TAG, "onClick: Detail image clicked"); //TODO: Open picture pager <add> break; <ide> case R.id.detail_website_button: <ide> listener.onOpenWebsite(business.getMobileUrl()); <ide> break; <ide> public void onMapReady(GoogleMap googleMap) { <ide> Log.d(TAG, "onMapReady"); <ide> <del> //disable click listener <del> final SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentByTag(FRAGMENT_TAG_LITEMAP); <del> if (mapFragment != null && mapFragment.getView() != null) { <del> Log.d(TAG, "onMapReady: Disable map click"); <del> mapFragment.getView().setClickable(false); <del> } <add> //intercept clicks on the map <add> googleMap.setOnMapClickListener(this); <ide> <ide> //add marker <ide> MarkerOptions markerOptions = new MarkerOptions() <ide> .position(latLng) <ide> .icon(MapColorUtils.determineMarkerIcon(toggleState, rating != LocalConstants.NO_DATA_DOUBLE ? rating : normalizedLikes)); <ide> marker = googleMap.addMarker(markerOptions); <add> } <add> <add> /** <add> * GoogleMap.OnMapClickListener callback. <add> * Override the default behavior of opening the google maps app. <add> * TODO: Open an interactive map within the app. <add> * @param latLng <add> */ <add> @Override <add> public void onMapClick(LatLng latLng) { <add> Log.d(TAG, "onMapClick: The map was clicked"); <ide> } <ide> <ide> /**
Java
apache-2.0
264313b481bcbdf7a112c1bd6a40b878ef3c71be
0
holmes/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fitermay/intellij-community,asedunov/intellij-community,petteyg/intellij-community,clumsy/intellij-community,diorcety/intellij-community,izonder/intellij-community,holmes/intellij-community,FHannes/intellij-community,dslomov/intellij-community,signed/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,semonte/intellij-community,apixandru/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,kool79/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,blademainer/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,caot/intellij-community,vvv1559/intellij-community,samthor/intellij-community,amith01994/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,retomerz/intellij-community,asedunov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,izonder/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,youdonghai/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,kdwink/intellij-community,retomerz/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,FHannes/intellij-community,holmes/intellij-community,clumsy/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,caot/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,allotria/intellij-community,samthor/intellij-community,diorcety/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,semonte/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ibinti/intellij-community,kool79/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,jagguli/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ernestp/consulo,vladmm/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ryano144/intellij-community,kool79/intellij-community,orekyuu/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,diorcety/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,slisson/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,clumsy/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,slisson/intellij-community,diorcety/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,izonder/intellij-community,xfournet/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,jagguli/intellij-community,slisson/intellij-community,fnouama/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,kool79/intellij-community,kool79/intellij-community,kdwink/intellij-community,supersven/intellij-community,vvv1559/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,retomerz/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,Lekanich/intellij-community,signed/intellij-community,Lekanich/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,caot/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,caot/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,Distrotech/intellij-community,caot/intellij-community,ernestp/consulo,lucafavatella/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,da1z/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,diorcety/intellij-community,semonte/intellij-community,petteyg/intellij-community,clumsy/intellij-community,hurricup/intellij-community,kool79/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ernestp/consulo,salguarnieri/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,consulo/consulo,muntasirsyed/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,izonder/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,fitermay/intellij-community,jagguli/intellij-community,xfournet/intellij-community,adedayo/intellij-community,retomerz/intellij-community,caot/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,joewalnes/idea-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,apixandru/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,youdonghai/intellij-community,orekyuu/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,fnouama/intellij-community,supersven/intellij-community,FHannes/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,slisson/intellij-community,hurricup/intellij-community,caot/intellij-community,da1z/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,holmes/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,semonte/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,xfournet/intellij-community,hurricup/intellij-community,kool79/intellij-community,kdwink/intellij-community,hurricup/intellij-community,signed/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,caot/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,apixandru/intellij-community,signed/intellij-community,signed/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,samthor/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,hurricup/intellij-community,consulo/consulo,muntasirsyed/intellij-community,semonte/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,ibinti/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,samthor/intellij-community,samthor/intellij-community,ibinti/intellij-community,fnouama/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,semonte/intellij-community,dslomov/intellij-community,apixandru/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,xfournet/intellij-community,adedayo/intellij-community,adedayo/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,retomerz/intellij-community,allotria/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,supersven/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,blademainer/intellij-community,supersven/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,fnouama/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,semonte/intellij-community,adedayo/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,joewalnes/idea-community,amith01994/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,allotria/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,kool79/intellij-community,consulo/consulo,lucafavatella/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,amith01994/intellij-community,consulo/consulo,lucafavatella/intellij-community,wreckJ/intellij-community,slisson/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,gnuhub/intellij-community,da1z/intellij-community,fnouama/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,ibinti/intellij-community,supersven/intellij-community,vladmm/intellij-community,jagguli/intellij-community,da1z/intellij-community,robovm/robovm-studio,adedayo/intellij-community,fitermay/intellij-community,dslomov/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,slisson/intellij-community,jagguli/intellij-community,adedayo/intellij-community,caot/intellij-community,kdwink/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,samthor/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,izonder/intellij-community,slisson/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,holmes/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,dslomov/intellij-community,robovm/robovm-studio,adedayo/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,holmes/intellij-community,amith01994/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,consulo/consulo,ol-loginov/intellij-community,dslomov/intellij-community,hurricup/intellij-community,allotria/intellij-community,gnuhub/intellij-community
/* * Copyright 2008 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.intentions.conversions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner; public class RemoveParenthesesFromMethodCallIntention extends Intention { @NotNull protected PsiElementPredicate getElementPredicate() { return new RemoveParenthesesFromMethodPredicate(); } @Override protected boolean isStopElement(PsiElement element) { return element instanceof GrStatementOwner; } protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { final GrMethodCallExpression expression = (GrMethodCallExpression) element; final StringBuilder newStatementText = new StringBuilder(); newStatementText.append(expression.getInvokedExpression().getText()).append(' '); final GrArgumentList argumentList = expression.getArgumentList(); if (argumentList != null) { final PsiElement leftParen = argumentList.getLeftParen(); final PsiElement rightParen = argumentList.getRightParen(); if (leftParen != null) leftParen.delete(); if (rightParen != null) rightParen.delete(); newStatementText.append(argumentList.getText()); } final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject()); final GrStatement newStatement = factory.createStatementFromText(newStatementText.toString()); expression.replaceWithStatement(newStatement); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/RemoveParenthesesFromMethodCallIntention.java
/* * Copyright 2008 Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.intentions.conversions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner; public class RemoveParenthesesFromMethodCallIntention extends Intention { @NotNull protected PsiElementPredicate getElementPredicate() { return new RemoveParenthesesFromMethodPredicate(); } @Override protected boolean isStopElement(PsiElement element) { return element instanceof GrStatementOwner; } protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { final GrMethodCallExpression expression = (GrMethodCallExpression) element; final StringBuilder newStatementText = new StringBuilder(); newStatementText.append(expression.getInvokedExpression().getText()); final GrArgumentList argumentList = expression.getArgumentList(); if (argumentList != null) { final PsiElement leftParen = argumentList.getLeftParen(); final PsiElement rightParen = argumentList.getRightParen(); if (leftParen != null) leftParen.delete(); if (rightParen != null) rightParen.delete(); newStatementText.append(argumentList.getText()); } final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject()); final GrStatement newStatement = factory.createStatementFromText(newStatementText.toString()); expression.replaceWithStatement(newStatement); } }
IDEA-59507 Groovy: "Remove Unnecessary Parentheses" intention doesn't insert space between method and argument IDEA-59508 Groovy: "Remove Unnecessary Parentheses" intention applied to methods with several arguments removes all arguments after the first one
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/RemoveParenthesesFromMethodCallIntention.java
IDEA-59507 Groovy: "Remove Unnecessary Parentheses" intention doesn't insert space between method and argument IDEA-59508 Groovy: "Remove Unnecessary Parentheses" intention applied to methods with several arguments removes all arguments after the first one
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/RemoveParenthesesFromMethodCallIntention.java <ide> protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException { <ide> final GrMethodCallExpression expression = (GrMethodCallExpression) element; <ide> final StringBuilder newStatementText = new StringBuilder(); <del> newStatementText.append(expression.getInvokedExpression().getText()); <add> newStatementText.append(expression.getInvokedExpression().getText()).append(' '); <ide> final GrArgumentList argumentList = expression.getArgumentList(); <ide> if (argumentList != null) { <ide> final PsiElement leftParen = argumentList.getLeftParen();
Java
agpl-3.0
7d42f3ebcf8f5e2095f16556e7a6eca4bb533bb4
0
denkbar/step,denkbar/step,denkbar/step,denkbar/step,denkbar/step
package step.core.plans.runner; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.junit.Test; import step.core.plans.builder.PlanBuilder; import step.core.plans.builder.PlanBuilderTest; public class DefaultPlanRunnerTest { @Test public void test() throws IOException { PlanBuilder builder = PlanBuilder.create().startBlock(PlanBuilderTest.artefact("Root")); for(int i=1;i<1000;i++) { builder.add(PlanBuilderTest.artefact("Child"+i)); } builder.endBlock(); DefaultPlanRunner runner = new DefaultPlanRunner(); StringWriter w = new StringWriter(); runner.run(builder.build()).printTree(w); //assertEquals(readResource(getClass(),"DefaultPlanRunnerTestExpected.txt"), w.toString()); assertEquals(readResource(new File("src/test/java/step/core/plans/runner/DefaultPlanRunnerTestExpected.txt")), w.toString()); } @Test public void testParallel() throws IOException, InterruptedException, ExecutionException { ExecutorService s = Executors.newFixedThreadPool(10); List<Future<?>> futures = new ArrayList<>(); for(int i=0;i<10;i++) { futures.add(s.submit(()->{ DefaultPlanRunnerTest test = new DefaultPlanRunnerTest(); try { for(int j=1;j<10;j++) { test.test(); } } catch (IOException e) { throw new RuntimeException(e); } })); } s.shutdown(); s.awaitTermination(1, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } } public static String readResource(Class<?> clazz, String resourceName) { return readStream(clazz.getResourceAsStream(resourceName)); } public static String readResource(File resource) { try(FileInputStream fis = new FileInputStream(resource)){ return readStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String readStream(InputStream is){ try(Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) { return scanner.useDelimiter("\\A").next().replaceAll("\r\n", "\n"); } } }
core/src/test/java/step/core/plans/runner/DefaultPlanRunnerTest.java
package step.core.plans.runner; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.junit.Test; import step.core.plans.builder.PlanBuilder; import step.core.plans.builder.PlanBuilderTest; public class DefaultPlanRunnerTest { @Test public void test() throws IOException { PlanBuilder builder = PlanBuilder.create().startBlock(PlanBuilderTest.artefact("Root")); for(int i=1;i<1000;i++) { builder.add(PlanBuilderTest.artefact("Child"+i)); } builder.endBlock(); DefaultPlanRunner runner = new DefaultPlanRunner(); StringWriter w = new StringWriter(); runner.run(builder.build()).printTree(w); //assertEquals(readResource(getClass(),"DefaultPlanRunnerTestExpected.txt"), w.toString()); assertEquals(readResource(new File("src/test/java/step/core/plans/runner/DefaultPlanRunnerTestExpected.txt")), w.toString()); } @Test public void testParallel() throws IOException, InterruptedException, ExecutionException { ExecutorService s = Executors.newFixedThreadPool(10); List<Future<?>> futures = new ArrayList<>(); for(int i=0;i<10;i++) { futures.add(s.submit(()->{ DefaultPlanRunnerTest test = new DefaultPlanRunnerTest(); try { for(int j=1;j<10;j++) { test.test(); } } catch (IOException e) { throw new RuntimeException(e); } })); } s.shutdown(); s.awaitTermination(1, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } } public static String readResource(Class<?> clazz, String resourceName) { return scan(clazz.getResourceAsStream(resourceName)); } public static String readResource(File resource) { try(FileInputStream fis = new FileInputStream(resource)){ return scan(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String scan(InputStream is){ try(Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) { return scanner.useDelimiter("\\A").next(); } } }
Fixing JUnit (crlf <> lf)
core/src/test/java/step/core/plans/runner/DefaultPlanRunnerTest.java
Fixing JUnit (crlf <> lf)
<ide><path>ore/src/test/java/step/core/plans/runner/DefaultPlanRunnerTest.java <ide> } <ide> <ide> public static String readResource(Class<?> clazz, String resourceName) { <del> return scan(clazz.getResourceAsStream(resourceName)); <add> return readStream(clazz.getResourceAsStream(resourceName)); <ide> } <ide> <ide> public static String readResource(File resource) { <ide> try(FileInputStream fis = new FileInputStream(resource)){ <del> return scan(fis); <add> return readStream(fis); <ide> } catch (FileNotFoundException e) { <ide> e.printStackTrace(); <ide> } catch (IOException e) { <ide> return null; <ide> } <ide> <del> public static String scan(InputStream is){ <add> public static String readStream(InputStream is){ <ide> try(Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) { <del> return scanner.useDelimiter("\\A").next(); <add> return scanner.useDelimiter("\\A").next().replaceAll("\r\n", "\n"); <ide> } <ide> } <ide> }
Java
apache-2.0
7034d47c8aedb3e5886e3c4eb052595daee83139
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.server; import com.intellij.build.events.MessageEvent; import com.intellij.ide.AppLifecycleListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.util.PathUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.xmlb.Converter; import com.intellij.util.xmlb.annotations.Attribute; import org.apache.lucene.search.Query; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.buildtool.MavenSyncConsole; import org.jetbrains.idea.maven.execution.MavenExecutionOptions; import org.jetbrains.idea.maven.execution.MavenRunnerSettings; import org.jetbrains.idea.maven.execution.RunnerBundle; import org.jetbrains.idea.maven.execution.SyncBundle; import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.project.MavenWorkspaceSettings; import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; import java.rmi.RemoteException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.jar.Attributes; @State( name = "MavenVersion", storages = @Storage(value = "mavenVersion.xml", deprecated = true) ) public class MavenServerManager implements PersistentStateComponent<MavenServerManager.State>, Disposable { public static final String BUNDLED_MAVEN_2 = "Bundled (Maven 2)"; public static final String BUNDLED_MAVEN_3 = "Bundled (Maven 3)"; private static final String DEFAULT_VM_OPTIONS = "-Xmx768m"; private final Map<Project, MavenServerConnector> myServerConnectors = new ConcurrentHashMap<>(); private File eventListenerJar; public boolean checkMavenSettings(Project project, MavenSyncConsole console) { MavenDistribution distribution = MavenDistribution.fromSettings(project); if (distribution == null) { console.showQuickFixBadMaven(SyncBundle.message("maven.sync.quickfixes.nomaven"), MessageEvent.Kind.ERROR); return false; } if (StringUtil.compareVersionNumbers(distribution.getVersion(), "3.6.0") == 0) { console.showQuickFixBadMaven(SyncBundle.message("maven.sync.quickfixes.maven360"), MessageEvent.Kind.WARNING); return false; } Sdk jdk = getJdk(project); if (!verifyMavenSdkRequirements(jdk, distribution.getVersion())) { console.showQuickFixJDK(distribution.getVersion()); return false; } return true; } public void unregisterConnector(MavenServerConnector serverConnector) { myServerConnectors.values().remove(serverConnector); } public void shutdownServer(Project project) { MavenServerConnector connector = myServerConnectors.get(project); if (connector != null) { connector.shutdown(true); } } public Collection<MavenServerConnector> getAllConnectors() { return Collections.unmodifiableCollection(myServerConnectors.values()); } static class State { @Deprecated @Attribute(value = "version", converter = UseMavenConverter.class) public boolean useMaven2; @Attribute public String vmOptions = DEFAULT_VM_OPTIONS; @Attribute public String embedderJdk = MavenRunnerSettings.USE_INTERNAL_JAVA; @Attribute(converter = MavenDistributionConverter.class) @Nullable public MavenDistribution mavenHome; @Attribute public MavenExecutionOptions.LoggingLevel loggingLevel = MavenExecutionOptions.LoggingLevel.INFO; } public static MavenServerManager getInstance() { return ServiceManager.getService(MavenServerManager.class); } public MavenServerManager() { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() { @Override public void appWillBeClosed(boolean isRestart) { ProgressManager.getInstance().run(new Task.Modal(null, RunnerBundle.message("maven.server.shutdown"), false) { @Override public void run(@NotNull ProgressIndicator indicator) { shutdown(true); } }); } }); } public MavenServerConnector getConnector(Project project) { MavenWorkspaceSettings settings = MavenWorkspaceSettingsComponent.getInstance(project).getSettings(); MavenDistribution distribution = new MavenDistributionConverter().fromString(settings.generalSettings.getMavenHome()); if (distribution == null) { throw new RuntimeException("Maven not found Version"); //TODO } Sdk jdk = getJdk(project); if (!verifyMavenSdkRequirements(jdk, distribution.getVersion())) { throw new RuntimeException("Wrong JDK Version"); //TODO } MavenServerConnector connector = myServerConnectors.get(project); if (connector == null) { connector = myServerConnectors.computeIfAbsent(project, p -> new MavenServerConnector(p, this, settings, jdk)); registerDisposable(project, connector); return connector; } if (!compatibleParameters(connector, jdk, settings.importingSettings.getVmOptionsForImporter())) { connector.shutdown(false); connector = new MavenServerConnector(project, this, settings, jdk); registerDisposable(project, connector); myServerConnectors.put(project, connector); } return connector; } @NotNull private Sdk getJdk(Project project) { Sdk jdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (jdk == null) { MavenLog.LOG.warn("cannot find JDK for project " + project); jdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } return jdk; } private void registerDisposable(Project project, MavenServerConnector connector) { if (project.isDefault()) { Disposer.register(this, connector); } else { Disposer.register(project, connector); } } private boolean compatibleParameters(MavenServerConnector connector, Sdk jdk, String vmOptions) { return StringUtil.equals(connector.getJdk().getName(), jdk.getName()) && StringUtil.equals(vmOptions, connector.getVMOptions()); } public MavenServerConnector getDefaultConnector() { return getConnector(ProjectManager.getInstance().getDefaultProject()); } @Override public void dispose() { } public synchronized void shutdown(boolean wait) { myServerConnectors.values().forEach(c -> c.shutdown(wait)); } public static boolean verifyMavenSdkRequirements(@NotNull Sdk jdk, String mavenVersion) { String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION); if (StringUtil.compareVersionNumbers(mavenVersion, "3.3.1") >= 0 && StringUtil.compareVersionNumbers(version, "1.7") < 0) { return false; } return true; } public static File getMavenEventListener() { return getInstance().getEventListenerJar(); } private File getEventListenerJar() { if (eventListenerJar != null) { return eventListenerJar; } final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); if (pluginFileOrDir.isDirectory()) { eventListenerJar = getEventSpyPathForLocalBuild(); } else { eventListenerJar = new File(root, "maven-event-listener.jar"); } if (!eventListenerJar.exists()) { if (ApplicationManager.getApplication().isInternal()) { MavenLog.LOG.warn("Event listener does not exist: Please run rebuild for maven modules:\n" + "community/plugins/maven/maven-event-listener\n" + "and all maven*-server* modules" ); } else { MavenLog.LOG.warn("Event listener does not exist " + eventListenerJar); } } return eventListenerJar; } private static File getEventSpyPathForLocalBuild() { final File root = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); return new File(root.getParent(), "intellij.maven.server.eventListener"); } @Nullable public String getMavenVersion(@Nullable String mavenHome) { return MavenUtil.getMavenVersion(getMavenHomeFile(mavenHome)); } @SuppressWarnings("unused") @Nullable public String getMavenVersion(@Nullable File mavenHome) { return MavenUtil.getMavenVersion(mavenHome); } @Nullable @Deprecated /** * @deprecated * use {@link MavenGeneralSettings.mavenHome} and {@link MavenUtil.getMavenVersion} */ public String getCurrentMavenVersion() { return null; } /* Made public for external systems integration */ public static List<File> collectClassPathAndLibsFolder(@NotNull String mavenVersion, @NotNull File mavenHome) { final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); final List<File> classpath = new ArrayList<>(); if (pluginFileOrDir.isDirectory()) { prepareClassPathForLocalRunAndUnitTests(mavenVersion, classpath, root); } else { prepareClassPathForProduction(mavenVersion, classpath, root); } addMavenLibs(classpath, mavenHome); MavenLog.LOG.debug("Collected classpath = ", classpath); return classpath; } private static void prepareClassPathForProduction(@NotNull String mavenVersion, List<File> classpath, String root) { classpath.add(new File(PathUtil.getJarPathForClass(MavenId.class))); classpath.add(new File(root, "maven-server-api.jar")); if (StringUtil.compareVersionNumbers(mavenVersion, "3") < 0) { classpath.add(new File(root, "maven2-server-impl.jar")); addDir(classpath, new File(root, "maven2-server-lib"), f -> true); } else { classpath.add(new File(root, "maven3-server-common.jar")); addDir(classpath, new File(root, "maven3-server-lib"), f -> true); if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") < 0) { classpath.add(new File(root, "maven30-server-impl.jar")); } else { classpath.add(new File(root, "maven3-server-impl.jar")); if (StringUtil.compareVersionNumbers(mavenVersion, "3.6") >= 0) { classpath.add(new File(root, "maven36-server-impl.jar")); } } } } private static void prepareClassPathForLocalRunAndUnitTests(@NotNull String mavenVersion, List<File> classpath, String root) { classpath.add(new File(PathUtil.getJarPathForClass(MavenId.class))); classpath.add(new File(root, "intellij.maven.server")); File parentFile = getMavenPluginParentFile(); if (StringUtil.compareVersionNumbers(mavenVersion, "3") < 0) { classpath.add(new File(root, "intellij.maven.server.m2.impl")); addDir(classpath, new File(parentFile, "maven2-server-impl/lib"), f -> true); } else { classpath.add(new File(root, "intellij.maven.server.m3.common")); addDir(classpath, new File(parentFile, "maven3-server-common/lib"), f -> true); if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") < 0) { classpath.add(new File(root, "intellij.maven.server.m30.impl")); } else { classpath.add(new File(root, "intellij.maven.server.m3.impl")); if (StringUtil.compareVersionNumbers(mavenVersion, "3.6") >= 0) { classpath.add(new File(root, "intellij.maven.server.m36.impl")); } } } } private static File getMavenPluginParentFile() { File luceneLib = new File(PathUtil.getJarPathForClass(Query.class)); return luceneLib.getParentFile().getParentFile().getParentFile(); } private static void addMavenLibs(List<File> classpath, File mavenHome) { addDir(classpath, new File(mavenHome, "lib"), f -> !f.getName().contains("maven-slf4j-provider")); File bootFolder = new File(mavenHome, "boot"); File[] classworldsJars = bootFolder.listFiles((dir, name) -> StringUtil.contains(name, "classworlds")); if (classworldsJars != null) { Collections.addAll(classpath, classworldsJars); } } private static void addDir(List<File> classpath, File dir, Predicate<File> filter) { File[] files = dir.listFiles(); if (files == null) return; for (File jar : files) { if (jar.isFile() && jar.getName().endsWith(".jar") && filter.test(jar)) { classpath.add(jar); } } } public MavenEmbedderWrapper createEmbedder(final Project project, final boolean alwaysOnline, @Nullable String workingDirectory, @Nullable String multiModuleProjectDirectory) { return new MavenEmbedderWrapper(null) { @NotNull @Override protected MavenServerEmbedder create() throws RemoteException { MavenServerSettings settings = convertSettings(MavenProjectsManager.getInstance(project).getGeneralSettings()); if (alwaysOnline && settings.isOffline()) { settings = settings.clone(); settings.setOffline(false); } settings.setProjectJdk(MavenUtil.getSdkPath(ProjectRootManager.getInstance(project).getProjectSdk())); return MavenServerManager.this.getConnector(project) .createEmbedder(new MavenEmbedderSettings(settings, workingDirectory, multiModuleProjectDirectory)); } }; } public MavenIndexerWrapper createIndexer() { return new MavenIndexerWrapper(null) { @NotNull @Override protected MavenServerIndexer create() throws RemoteException { return MavenServerManager.this.getDefaultConnector().createIndexer(); } }; } public void addDownloadListener(MavenServerDownloadListener listener) { myServerConnectors.values().forEach(l -> l.addDownloadListener(listener)); } public void removeDownloadListener(MavenServerDownloadListener listener) { myServerConnectors.values().forEach(l -> l.removeDownloadListener(listener)); } public static MavenServerSettings convertSettings(MavenGeneralSettings settings) { MavenServerSettings result = new MavenServerSettings(); result.setLoggingLevel(settings.getOutputLevel().getLevel()); result.setOffline(settings.isWorkOffline()); result.setMavenHome(settings.getEffectiveMavenHome()); result.setUserSettingsFile(settings.getEffectiveUserSettingsIoFile()); result.setGlobalSettingsFile(settings.getEffectiveGlobalSettingsIoFile()); result.setLocalRepository(settings.getEffectiveLocalRepository()); result.setPluginUpdatePolicy(settings.getPluginUpdatePolicy().getServerPolicy()); result.setSnapshotUpdatePolicy( settings.isAlwaysUpdateSnapshots() ? MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE : MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE); return result; } private static class UseMavenConverter extends Converter<Boolean> { @Nullable @Override public Boolean fromString(@NotNull String value) { return "2.x".equals(value); } @NotNull @Override public String toString(@NotNull Boolean value) { return value ? "2.x" : "3.x"; } } public boolean isUseMaven2() { final String version = getCurrentMavenVersion(); return version != null && StringUtil.compareVersionNumbers(version, "3") < 0 && StringUtil.compareVersionNumbers(version, "2") >= 0; } @Nullable public static File getMavenHomeFile(@Nullable String mavenHome) { if (mavenHome == null) return null; //will be removed after IDEA-205421 if (StringUtil.equals(BUNDLED_MAVEN_2, mavenHome) && ApplicationManager.getApplication().isUnitTestMode()) { return resolveEmbeddedMaven2HomeForTests().getMavenHome(); } if (StringUtil.equals(BUNDLED_MAVEN_3, mavenHome) || StringUtil.equals(MavenProjectBundle.message("maven.bundled.version.title"), mavenHome)) { return resolveEmbeddedMavenHome().getMavenHome(); } final File home = new File(mavenHome); return MavenUtil.isValidMavenHome(home) ? home : null; } @NotNull @Deprecated /** * @deprecated use MavenImportingSettings.setVmOptionsForImporter */ public String getMavenEmbedderVMOptions() { return ""; } @Deprecated /** * @deprecated use MavenImportingSettings.setVmOptionsForImporter */ public void setMavenEmbedderVMOptions(@NotNull String mavenEmbedderVMOptions) { } @Nullable @Override public State getState() { return null; } @Override public void loadState(@NotNull State state) { } @NotNull public static MavenDistribution resolveEmbeddedMavenHome() { final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); if (pluginFileOrDir.isDirectory()) { File parentFile = getMavenPluginParentFile(); return new MavenDistribution(new File(parentFile, "maven36-server-impl/lib/maven3"), BUNDLED_MAVEN_3); } else { return new MavenDistribution(new File(root, "maven3"), BUNDLED_MAVEN_3); } } @NotNull private static MavenDistribution resolveEmbeddedMaven2HomeForTests() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new IllegalStateException("Maven2 is for test purpose only"); } final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); if (pluginFileOrDir.isDirectory()) { File parentFile = getMavenPluginParentFile(); return new MavenDistribution(new File(parentFile, "maven2-server-impl/lib/maven2"), BUNDLED_MAVEN_2); } else { throw new IllegalStateException("Maven2 is not bundled anymore, please do not try to use it in tests"); } } }
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.server; import com.intellij.build.events.MessageEvent; import com.intellij.ide.AppLifecycleListener; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.projectRoots.JdkUtil; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.StringUtilRt; import com.intellij.util.PathUtil; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.xmlb.Converter; import com.intellij.util.xmlb.annotations.Attribute; import org.apache.lucene.search.Query; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.buildtool.MavenSyncConsole; import org.jetbrains.idea.maven.execution.MavenExecutionOptions; import org.jetbrains.idea.maven.execution.MavenRunnerSettings; import org.jetbrains.idea.maven.execution.RunnerBundle; import org.jetbrains.idea.maven.execution.SyncBundle; import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenGeneralSettings; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.project.MavenWorkspaceSettings; import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent; import org.jetbrains.idea.maven.utils.MavenLog; import org.jetbrains.idea.maven.utils.MavenUtil; import java.io.File; import java.rmi.RemoteException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.jar.Attributes; @State( name = "MavenVersion", storages = @Storage(value = "mavenVersion.xml", deprecated = true) ) public class MavenServerManager implements PersistentStateComponent<MavenServerManager.State>, Disposable { public static final String BUNDLED_MAVEN_2 = "Bundled (Maven 2)"; public static final String BUNDLED_MAVEN_3 = "Bundled (Maven 3)"; private static final String DEFAULT_VM_OPTIONS = "-Xmx768m"; private final Map<Project, MavenServerConnector> myServerConnectors = new ConcurrentHashMap<>(); private File eventListenerJar; public boolean checkMavenSettings(Project project, MavenSyncConsole console) { MavenDistribution distribution = MavenDistribution.fromSettings(project); if (distribution == null) { console.showQuickFixBadMaven(SyncBundle.message("maven.sync.quickfixes.nomaven"), MessageEvent.Kind.ERROR); return false; } if (StringUtil.compareVersionNumbers(distribution.getVersion(), "3.6.0") == 0) { console.showQuickFixBadMaven(SyncBundle.message("maven.sync.quickfixes.maven360"), MessageEvent.Kind.WARNING); return false; } Sdk jdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (!verifyMavenSdkRequirements(jdk, distribution.getVersion())) { console.showQuickFixJDK(distribution.getVersion()); return false; } return true; } public void unregisterConnector(MavenServerConnector serverConnector) { myServerConnectors.values().remove(serverConnector); } public void shutdownServer(Project project) { MavenServerConnector connector = myServerConnectors.get(project); if (connector != null) { connector.shutdown(true); } } public Collection<MavenServerConnector> getAllConnectors() { return Collections.unmodifiableCollection(myServerConnectors.values()); } static class State { @Deprecated @Attribute(value = "version", converter = UseMavenConverter.class) public boolean useMaven2; @Attribute public String vmOptions = DEFAULT_VM_OPTIONS; @Attribute public String embedderJdk = MavenRunnerSettings.USE_INTERNAL_JAVA; @Attribute(converter = MavenDistributionConverter.class) @Nullable public MavenDistribution mavenHome; @Attribute public MavenExecutionOptions.LoggingLevel loggingLevel = MavenExecutionOptions.LoggingLevel.INFO; } public static MavenServerManager getInstance() { return ServiceManager.getService(MavenServerManager.class); } public MavenServerManager() { MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() { @Override public void appWillBeClosed(boolean isRestart) { ProgressManager.getInstance().run(new Task.Modal(null, RunnerBundle.message("maven.server.shutdown"), false) { @Override public void run(@NotNull ProgressIndicator indicator) { shutdown(true); } }); } }); } public MavenServerConnector getConnector(Project project) { MavenWorkspaceSettings settings = MavenWorkspaceSettingsComponent.getInstance(project).getSettings(); MavenDistribution distribution = new MavenDistributionConverter().fromString(settings.generalSettings.getMavenHome()); if (distribution == null) { throw new RuntimeException("Maven not found Version"); //TODO } Sdk jdk = getJdk(project); if (!verifyMavenSdkRequirements(jdk, distribution.getVersion())) { throw new RuntimeException("Wrong JDK Version"); //TODO } MavenServerConnector connector = myServerConnectors.get(project); if (connector == null) { connector = myServerConnectors.computeIfAbsent(project, p -> new MavenServerConnector(p, this, settings, jdk)); registerDisposable(project, connector); return connector; } if (!compatibleParameters(connector, jdk, settings.importingSettings.getVmOptionsForImporter())) { connector.shutdown(false); connector = new MavenServerConnector(project, this, settings, jdk); registerDisposable(project, connector); myServerConnectors.put(project, connector); } return connector; } @NotNull private Sdk getJdk(Project project) { Sdk jdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (jdk == null) { MavenLog.LOG.warn("cannot find JDK for project " + project); jdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); } return jdk; } private void registerDisposable(Project project, MavenServerConnector connector) { if (project.isDefault()) { Disposer.register(this, connector); } else { Disposer.register(project, connector); } } private boolean compatibleParameters(MavenServerConnector connector, Sdk jdk, String vmOptions) { return StringUtil.equals(connector.getJdk().getName(), jdk.getName()) && StringUtil.equals(vmOptions, connector.getVMOptions()); } public MavenServerConnector getDefaultConnector() { return getConnector(ProjectManager.getInstance().getDefaultProject()); } @Override public void dispose() { } public synchronized void shutdown(boolean wait) { myServerConnectors.values().forEach(c -> c.shutdown(wait)); } public static boolean verifyMavenSdkRequirements(@NotNull Sdk jdk, String mavenVersion) { String version = JdkUtil.getJdkMainAttribute(jdk, Attributes.Name.IMPLEMENTATION_VERSION); if (StringUtil.compareVersionNumbers(mavenVersion, "3.3.1") >= 0 && StringUtil.compareVersionNumbers(version, "1.7") < 0) { return false; } return true; } public static File getMavenEventListener() { return getInstance().getEventListenerJar(); } private File getEventListenerJar() { if (eventListenerJar != null) { return eventListenerJar; } final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); if (pluginFileOrDir.isDirectory()) { eventListenerJar = getEventSpyPathForLocalBuild(); } else { eventListenerJar = new File(root, "maven-event-listener.jar"); } if (!eventListenerJar.exists()) { if (ApplicationManager.getApplication().isInternal()) { MavenLog.LOG.warn("Event listener does not exist: Please run rebuild for maven modules:\n" + "community/plugins/maven/maven-event-listener\n" + "and all maven*-server* modules" ); } else { MavenLog.LOG.warn("Event listener does not exist " + eventListenerJar); } } return eventListenerJar; } private static File getEventSpyPathForLocalBuild() { final File root = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); return new File(root.getParent(), "intellij.maven.server.eventListener"); } @Nullable public String getMavenVersion(@Nullable String mavenHome) { return MavenUtil.getMavenVersion(getMavenHomeFile(mavenHome)); } @SuppressWarnings("unused") @Nullable public String getMavenVersion(@Nullable File mavenHome) { return MavenUtil.getMavenVersion(mavenHome); } @Nullable @Deprecated /** * @deprecated * use {@link MavenGeneralSettings.mavenHome} and {@link MavenUtil.getMavenVersion} */ public String getCurrentMavenVersion() { return null; } /* Made public for external systems integration */ public static List<File> collectClassPathAndLibsFolder(@NotNull String mavenVersion, @NotNull File mavenHome) { final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); final List<File> classpath = new ArrayList<>(); if (pluginFileOrDir.isDirectory()) { prepareClassPathForLocalRunAndUnitTests(mavenVersion, classpath, root); } else { prepareClassPathForProduction(mavenVersion, classpath, root); } addMavenLibs(classpath, mavenHome); MavenLog.LOG.debug("Collected classpath = ", classpath); return classpath; } private static void prepareClassPathForProduction(@NotNull String mavenVersion, List<File> classpath, String root) { classpath.add(new File(PathUtil.getJarPathForClass(MavenId.class))); classpath.add(new File(root, "maven-server-api.jar")); if (StringUtil.compareVersionNumbers(mavenVersion, "3") < 0) { classpath.add(new File(root, "maven2-server-impl.jar")); addDir(classpath, new File(root, "maven2-server-lib"), f -> true); } else { classpath.add(new File(root, "maven3-server-common.jar")); addDir(classpath, new File(root, "maven3-server-lib"), f -> true); if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") < 0) { classpath.add(new File(root, "maven30-server-impl.jar")); } else { classpath.add(new File(root, "maven3-server-impl.jar")); if (StringUtil.compareVersionNumbers(mavenVersion, "3.6") >= 0) { classpath.add(new File(root, "maven36-server-impl.jar")); } } } } private static void prepareClassPathForLocalRunAndUnitTests(@NotNull String mavenVersion, List<File> classpath, String root) { classpath.add(new File(PathUtil.getJarPathForClass(MavenId.class))); classpath.add(new File(root, "intellij.maven.server")); File parentFile = getMavenPluginParentFile(); if (StringUtil.compareVersionNumbers(mavenVersion, "3") < 0) { classpath.add(new File(root, "intellij.maven.server.m2.impl")); addDir(classpath, new File(parentFile, "maven2-server-impl/lib"), f -> true); } else { classpath.add(new File(root, "intellij.maven.server.m3.common")); addDir(classpath, new File(parentFile, "maven3-server-common/lib"), f -> true); if (StringUtil.compareVersionNumbers(mavenVersion, "3.1") < 0) { classpath.add(new File(root, "intellij.maven.server.m30.impl")); } else { classpath.add(new File(root, "intellij.maven.server.m3.impl")); if (StringUtil.compareVersionNumbers(mavenVersion, "3.6") >= 0) { classpath.add(new File(root, "intellij.maven.server.m36.impl")); } } } } private static File getMavenPluginParentFile() { File luceneLib = new File(PathUtil.getJarPathForClass(Query.class)); return luceneLib.getParentFile().getParentFile().getParentFile(); } private static void addMavenLibs(List<File> classpath, File mavenHome) { addDir(classpath, new File(mavenHome, "lib"), f -> !f.getName().contains("maven-slf4j-provider")); File bootFolder = new File(mavenHome, "boot"); File[] classworldsJars = bootFolder.listFiles((dir, name) -> StringUtil.contains(name, "classworlds")); if (classworldsJars != null) { Collections.addAll(classpath, classworldsJars); } } private static void addDir(List<File> classpath, File dir, Predicate<File> filter) { File[] files = dir.listFiles(); if (files == null) return; for (File jar : files) { if (jar.isFile() && jar.getName().endsWith(".jar") && filter.test(jar)) { classpath.add(jar); } } } public MavenEmbedderWrapper createEmbedder(final Project project, final boolean alwaysOnline, @Nullable String workingDirectory, @Nullable String multiModuleProjectDirectory) { return new MavenEmbedderWrapper(null) { @NotNull @Override protected MavenServerEmbedder create() throws RemoteException { MavenServerSettings settings = convertSettings(MavenProjectsManager.getInstance(project).getGeneralSettings()); if (alwaysOnline && settings.isOffline()) { settings = settings.clone(); settings.setOffline(false); } settings.setProjectJdk(MavenUtil.getSdkPath(ProjectRootManager.getInstance(project).getProjectSdk())); return MavenServerManager.this.getConnector(project) .createEmbedder(new MavenEmbedderSettings(settings, workingDirectory, multiModuleProjectDirectory)); } }; } public MavenIndexerWrapper createIndexer() { return new MavenIndexerWrapper(null) { @NotNull @Override protected MavenServerIndexer create() throws RemoteException { return MavenServerManager.this.getDefaultConnector().createIndexer(); } }; } public void addDownloadListener(MavenServerDownloadListener listener) { myServerConnectors.values().forEach(l -> l.addDownloadListener(listener)); } public void removeDownloadListener(MavenServerDownloadListener listener) { myServerConnectors.values().forEach(l -> l.removeDownloadListener(listener)); } public static MavenServerSettings convertSettings(MavenGeneralSettings settings) { MavenServerSettings result = new MavenServerSettings(); result.setLoggingLevel(settings.getOutputLevel().getLevel()); result.setOffline(settings.isWorkOffline()); result.setMavenHome(settings.getEffectiveMavenHome()); result.setUserSettingsFile(settings.getEffectiveUserSettingsIoFile()); result.setGlobalSettingsFile(settings.getEffectiveGlobalSettingsIoFile()); result.setLocalRepository(settings.getEffectiveLocalRepository()); result.setPluginUpdatePolicy(settings.getPluginUpdatePolicy().getServerPolicy()); result.setSnapshotUpdatePolicy( settings.isAlwaysUpdateSnapshots() ? MavenServerSettings.UpdatePolicy.ALWAYS_UPDATE : MavenServerSettings.UpdatePolicy.DO_NOT_UPDATE); return result; } private static class UseMavenConverter extends Converter<Boolean> { @Nullable @Override public Boolean fromString(@NotNull String value) { return "2.x".equals(value); } @NotNull @Override public String toString(@NotNull Boolean value) { return value ? "2.x" : "3.x"; } } public boolean isUseMaven2() { final String version = getCurrentMavenVersion(); return version != null && StringUtil.compareVersionNumbers(version, "3") < 0 && StringUtil.compareVersionNumbers(version, "2") >= 0; } @Nullable public static File getMavenHomeFile(@Nullable String mavenHome) { if (mavenHome == null) return null; //will be removed after IDEA-205421 if (StringUtil.equals(BUNDLED_MAVEN_2, mavenHome) && ApplicationManager.getApplication().isUnitTestMode()) { return resolveEmbeddedMaven2HomeForTests().getMavenHome(); } if (StringUtil.equals(BUNDLED_MAVEN_3, mavenHome) || StringUtil.equals(MavenProjectBundle.message("maven.bundled.version.title"), mavenHome)) { return resolveEmbeddedMavenHome().getMavenHome(); } final File home = new File(mavenHome); return MavenUtil.isValidMavenHome(home) ? home : null; } @NotNull @Deprecated /** * @deprecated use MavenImportingSettings.setVmOptionsForImporter */ public String getMavenEmbedderVMOptions() { return ""; } @Deprecated /** * @deprecated use MavenImportingSettings.setVmOptionsForImporter */ public void setMavenEmbedderVMOptions(@NotNull String mavenEmbedderVMOptions) { } @Nullable @Override public State getState() { return null; } @Override public void loadState(@NotNull State state) { } @NotNull public static MavenDistribution resolveEmbeddedMavenHome() { final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); final String root = pluginFileOrDir.getParent(); if (pluginFileOrDir.isDirectory()) { File parentFile = getMavenPluginParentFile(); return new MavenDistribution(new File(parentFile, "maven36-server-impl/lib/maven3"), BUNDLED_MAVEN_3); } else { return new MavenDistribution(new File(root, "maven3"), BUNDLED_MAVEN_3); } } @NotNull private static MavenDistribution resolveEmbeddedMaven2HomeForTests() { if (!ApplicationManager.getApplication().isUnitTestMode()) { throw new IllegalStateException("Maven2 is for test purpose only"); } final File pluginFileOrDir = new File(PathUtil.getJarPathForClass(MavenServerManager.class)); if (pluginFileOrDir.isDirectory()) { File parentFile = getMavenPluginParentFile(); return new MavenDistribution(new File(parentFile, "maven2-server-impl/lib/maven2"), BUNDLED_MAVEN_2); } else { throw new IllegalStateException("Maven2 is not bundled anymore, please do not try to use it in tests"); } } }
mr-IDEA-1261 - IDEA-221517 - review fixes GitOrigin-RevId: 4ec56f95fb6f3808435d939e5642b592d85b431e
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java
mr-IDEA-1261 - IDEA-221517 - review fixes
<ide><path>lugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenServerManager.java <ide> return false; <ide> } <ide> <del> Sdk jdk = ProjectRootManager.getInstance(project).getProjectSdk(); <add> Sdk jdk = getJdk(project); <ide> if (!verifyMavenSdkRequirements(jdk, distribution.getVersion())) { <ide> console.showQuickFixJDK(distribution.getVersion()); <ide> return false;
Java
apache-2.0
a58ff04f8ca740d2b7180df3052e043d15c23400
0
seeburger-ag/commons-jxpath_RETIRED,seeburger-ag/commons-jxpath_RETIRED
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.model; import org.apache.commons.jxpath.AbstractFactory; import org.apache.commons.jxpath.IdentityManager; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathException; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Pointer; import org.apache.commons.jxpath.Variables; import org.apache.commons.jxpath.xml.DocumentContainer; /** * Abstract superclass for pure XPath 1.0. Subclasses * apply the same XPaths to contexts using different models: * DOM, JDOM etc. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public abstract class XMLModelTestCase extends JXPathTestCase { protected JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public XMLModelTestCase(String name) { super(name); } public void setUp() { if (context == null) { DocumentContainer docCtr = createDocumentContainer(); context = createContext(); Variables vars = context.getVariables(); vars.declareVariable("document", docCtr.getValue()); vars.declareVariable("container", docCtr); vars.declareVariable( "element", context.getPointer("vendor/location/address/street").getNode()); } } protected abstract String getModel(); protected DocumentContainer createDocumentContainer() { return new DocumentContainer( JXPathTestCase.class.getResource("Vendor.xml"), getModel()); } protected abstract AbstractFactory getAbstractFactory(); protected JXPathContext createContext() { JXPathContext context = JXPathContext.newContext(createDocumentContainer()); context.setFactory(getAbstractFactory()); context.registerNamespace("product", "productNS"); return context; } /** * An XML signature is used to determine if we have the right result * after a modification of XML by JXPath. It is basically a piece * of simplified XML. */ protected abstract String getXMLSignature( Object node, boolean elements, boolean attributes, boolean text, boolean pi); protected void assertXMLSignature( JXPathContext context, String path, String signature, boolean elements, boolean attributes, boolean text, boolean pi) { Object node = context.getPointer(path).getNode(); String sig = getXMLSignature(node, elements, attributes, text, pi); assertEquals("XML Signature mismatch: ", signature, sig); } // ------------------------------------------------ Individual Test Methods public void testDocumentOrder() { assertDocumentOrder( context, "vendor/location", "vendor/location/address/street", -1); assertDocumentOrder( context, "vendor/location[@id = '100']", "vendor/location[@id = '101']", -1); assertDocumentOrder( context, "vendor//price:amount", "vendor/location", 1); } public void testSetValue() { assertXPathSetValue( context, "vendor/location[@id = '100']", "New Text"); assertXMLSignature( context, "vendor/location[@id = '100']", "<E>New Text</E>", false, false, true, false); assertXPathSetValue( context, "vendor/location[@id = '101']", "Replacement Text"); assertXMLSignature( context, "vendor/location[@id = '101']", "<E>Replacement Text</E>", false, false, true, false); } /** * Test JXPathContext.createPath() with various arguments */ public void testCreatePath() { // Create a DOM element assertXPathCreatePath( context, "/vendor[1]/location[3]", "", "/vendor[1]/location[3]"); // Create a DOM element with contents assertXPathCreatePath( context, "/vendor[1]/location[3]/address/street", "", "/vendor[1]/location[3]/address[1]/street[1]"); // Create a DOM attribute assertXPathCreatePath( context, "/vendor[1]/location[2]/@manager", "", "/vendor[1]/location[2]/@manager"); assertXPathCreatePath( context, "/vendor[1]/location[1]/@name", "local", "/vendor[1]/location[1]/@name"); assertXPathCreatePathAndSetValue( context, "/vendor[1]/location[4]/@manager", "", "/vendor[1]/location[4]/@manager"); context.registerNamespace("price", "priceNS"); // Create a DOM element assertXPathCreatePath( context, "/vendor[1]/price:foo/price:bar", "", "/vendor[1]/price:foo[1]/price:bar[1]"); } /** * Test JXPath.createPathAndSetValue() with various arguments */ public void testCreatePathAndSetValue() { // Create a XML element assertXPathCreatePathAndSetValue( context, "vendor/location[3]", "", "/vendor[1]/location[3]"); // Create a DOM element with contents assertXPathCreatePathAndSetValue( context, "vendor/location[3]/address/street", "Lemon Circle", "/vendor[1]/location[3]/address[1]/street[1]"); // Create an attribute assertXPathCreatePathAndSetValue( context, "vendor/location[2]/@manager", "John Doe", "/vendor[1]/location[2]/@manager"); assertXPathCreatePathAndSetValue( context, "vendor/location[1]/@manager", "John Doe", "/vendor[1]/location[1]/@manager"); assertXPathCreatePathAndSetValue( context, "/vendor[1]/location[4]/@manager", "James Dow", "/vendor[1]/location[4]/@manager"); assertXPathCreatePathAndSetValue( context, "vendor/product/product:name/attribute::price:language", "English", "/vendor[1]/product[1]/product:name[1]/@price:language"); context.registerNamespace("price", "priceNS"); // Create a DOM element assertXPathCreatePathAndSetValue( context, "/vendor[1]/price:foo/price:bar", "123.20", "/vendor[1]/price:foo[1]/price:bar[1]"); } /** * Test JXPathContext.removePath() with various arguments */ public void testRemovePath() { // Remove XML nodes context.removePath("vendor/location[@id = '101']//street/text()"); assertEquals( "Remove DOM text", "", context.getValue("vendor/location[@id = '101']//street")); context.removePath("vendor/location[@id = '101']//street"); assertEquals( "Remove DOM element", new Double(0), context.getValue("count(vendor/location[@id = '101']//street)")); context.removePath("vendor/location[@id = '100']/@name"); assertEquals( "Remove DOM attribute", new Double(0), context.getValue("count(vendor/location[@id = '100']/@name)")); } public void testID() { context.setIdentityManager(new IdentityManager() { public Pointer getPointerByID(JXPathContext context, String id) { NodePointer ptr = (NodePointer) context.getPointer("/"); ptr = ptr.getValuePointer(); // Unwrap the container return ptr.getPointerByID(context, id); } }); assertXPathValueAndPointer( context, "id(101)//street", "Tangerine Drive", "id('101')/address[1]/street[1]"); assertXPathPointerLenient( context, "id(105)/address/street", "id(105)/address/street"); } public void testAxisChild() { assertXPathValue( context, "vendor/location/address/street", "Orchard Road"); // child:: - first child does not match, need to search assertXPathValue( context, "vendor/location/address/city", "Fruit Market"); // local-name(qualified) assertXPathValue( context, "local-name(vendor/product/price:amount)", "amount"); // local-name(non-qualified) assertXPathValue(context, "local-name(vendor/location)", "location"); // name (qualified) assertXPathValue( context, "name(vendor/product/price:amount)", "value:amount"); // name (non-qualified) assertXPathValue( context, "name(vendor/location)", "location"); // namespace-uri (qualified) assertXPathValue( context, "namespace-uri(vendor/product/price:amount)", "priceNS"); // default namespace does not affect search assertXPathValue(context, "vendor/product/prix", "934.99"); assertXPathValue(context, "/vendor/contact[@name='jim']", "Jim"); boolean nsv = false; try { context.setLenient(false); context.getValue("/vendor/contact[@name='jane']"); } catch (JXPathException ex) { nsv = true; } assertTrue("No such value: /vendor/contact[@name='jim']", nsv); nsv = false; try { context.setLenient(false); context.getValue("/vendor/contact[@name='jane']/*"); } catch (JXPathException ex) { nsv = true; } assertTrue("No such value: /vendor/contact[@name='jane']/*", nsv); // child:: with a wildcard assertXPathValue( context, "count(vendor/product/price:*)", new Double(2)); // child:: with the default namespace assertXPathValue(context, "count(vendor/product/*)", new Double(4)); // child:: with a qualified name assertXPathValue(context, "vendor/product/price:amount", "45.95"); // null default namespace context.registerNamespace("x", "temp"); assertXPathValue(context, "vendor/x:pos//number", "109"); } public void testAxisChildIndexPredicate() { assertXPathValue( context, "vendor/location[2]/address/street", "Tangerine Drive"); } public void testAxisDescendant() { // descendant:: assertXPathValue(context, "//street", "Orchard Road"); // descendent:: with a namespace and wildcard assertXPathValue(context, "count(//price:*)", new Double(2)); assertXPathValueIterator(context, "vendor//saleEnds", list("never")); assertXPathValueIterator(context, "vendor//promotion", list("")); assertXPathValueIterator( context, "vendor//saleEnds[../@stores = 'all']", list("never")); assertXPathValueIterator( context, "vendor//promotion[../@stores = 'all']", list("")); } // public void testAxisDescendantDocumentOrder() { // Iterator iter = context.iteratePointers("//*"); // while (iter.hasNext()) { // System.err.println(iter.next()); // } // } public void testAxisParent() { // parent:: assertXPathPointer( context, "//street/..", "/vendor[1]/location[1]/address[1]"); // parent:: (note reverse document order) assertXPathPointerIterator( context, "//street/..", list( "/vendor[1]/location[2]/address[1]", "/vendor[1]/location[1]/address[1]")); // parent:: with a namespace and wildcard assertXPathValue( context, "vendor/product/price:sale/saleEnds/parent::price:*" + "/saleEnds", "never"); } public void testAxisFollowingSibling() { // following-sibling:: assertXPathValue( context, "vendor/location[.//employeeCount = 10]/" + "following-sibling::location//street", "Tangerine Drive"); // following-sibling:: produces the correct pointer assertXPathPointer( context, "vendor/location[.//employeeCount = 10]/" + "following-sibling::location//street", "/vendor[1]/location[2]/address[1]/street[1]"); } public void testAxisPrecedingSibling() { // preceding-sibling:: produces the correct pointer assertXPathPointer( context, "//location[2]/preceding-sibling::location//street", "/vendor[1]/location[1]/address[1]/street[1]"); } public void testAxisAttribute() { // attribute:: assertXPathValue(context, "vendor/location/@id", "100"); // attribute:: produces the correct pointer assertXPathPointer( context, "vendor/location/@id", "/vendor[1]/location[1]/@id"); // iterate over attributes assertXPathValueIterator( context, "vendor/location/@id", list("100", "101")); // Using different prefixes for the same namespace assertXPathValue( context, "vendor/product/price:amount/@price:discount", "10%"); // namespace uri for an attribute assertXPathValue( context, "namespace-uri(vendor/product/price:amount/@price:discount)", "priceNS"); // local name of an attribute assertXPathValue( context, "local-name(vendor/product/price:amount/@price:discount)", "discount"); // name for an attribute assertXPathValue( context, "name(vendor/product/price:amount/@price:discount)", "price:discount"); // attribute:: with the default namespace assertXPathValue( context, "vendor/product/price:amount/@discount", "20%"); // namespace uri of an attribute with the default namespace assertXPathValue( context, "namespace-uri(vendor/product/price:amount/@discount)", ""); // local name of an attribute with the default namespace assertXPathValue( context, "local-name(vendor/product/price:amount/@discount)", "discount"); // name of an attribute with the default namespace assertXPathValue( context, "name(vendor/product/price:amount/@discount)", "discount"); // attribute:: with a namespace and wildcard assertXPathValueIterator( context, "vendor/product/price:amount/@price:*", list("10%")); // attribute:: with a wildcard assertXPathValueIterator( context, "vendor/location[1]/@*", set("100", "", "local")); // attribute:: with default namespace and wildcard assertXPathValueIterator( context, "vendor/product/price:amount/@*", list("20%")); // Empty attribute assertXPathValue(context, "vendor/location/@manager", ""); // Missing attribute assertXPathValueLenient(context, "vendor/location/@missing", null); // Missing attribute with namespace assertXPathValueLenient(context, "vendor/location/@miss:missing", null); // Using attribute in a predicate assertXPathValue( context, "vendor/location[@id='101']//street", "Tangerine Drive"); assertXPathValueIterator( context, "/vendor/location[1]/@*[name()!= 'manager']", list("100", "local")); } public void testAxisNamespace() { // namespace:: assertXPathValueAndPointer( context, "vendor/product/prix/namespace::price", "priceNS", "/vendor[1]/product[1]/prix[1]/namespace::price"); // namespace::* assertXPathValue( context, "count(vendor/product/namespace::*)", new Double(3)); // name of namespace assertXPathValue( context, "name(vendor/product/prix/namespace::price)", "price"); // local name of namespace assertXPathValue( context, "local-name(vendor/product/prix/namespace::price)", "price"); } public void testAxisAncestor() { // ancestor:: assertXPathValue( context, "vendor/product/price:sale/saleEnds/" + "ancestor::price:sale/saleEnds", "never"); // ancestor:: with a wildcard assertXPathValue( context, "vendor/product/price:sale/saleEnds/ancestor::price:*" + "/saleEnds", "never"); } public void testAxisAncestorOrSelf() { // ancestor-or-self:: assertXPathValue( context, "vendor/product/price:sale/" + "ancestor-or-self::price:sale/saleEnds", "never"); } public void testAxisFollowing() { assertXPathValueIterator( context, "vendor/contact/following::location//street", list("Orchard Road", "Tangerine Drive")); // following:: with a namespace assertXPathValue( context, "//location/following::price:sale/saleEnds", "never"); } public void testAxisSelf() { // self:: with a namespace assertXPathValue( context, "//price:sale/self::price:sale/saleEnds", "never"); // self:: with an unmatching name assertXPathValueLenient(context, "//price:sale/self::x/saleEnds", null); } public void testNodeTypeComment() { // comment() assertXPathValue( context, "//product/comment()", "We are not buying this product, ever"); } public void testNodeTypeText() { // text() //Note that this is questionable as the XPath spec tells us "." is short for self::node() and text() is by definition _not_ a node: assertXPathValue( context, "//product/text()[. != '']", "We love this product."); // text() pointer assertXPathPointer( context, "//product/text()", "/vendor[1]/product[1]/text()[1]"); } public void testNodeTypeProcessingInstruction() { // processing-instruction() without an argument assertXPathValue( context, "//product/processing-instruction()", "do not show anybody"); // processing-instruction() with an argument assertXPathValue( context, "//product/processing-instruction('report')", "average only"); // processing-instruction() pointer without an argument assertXPathPointer( context, "//product/processing-instruction('report')", "/vendor[1]/product[1]/processing-instruction('report')[1]"); // processing-instruction name assertXPathValue( context, "name(//product/processing-instruction()[1])", "security"); } public void testLang() { // xml:lang built-in attribute assertXPathValue(context, "//product/prix/@xml:lang", "fr"); // lang() used the built-in xml:lang attribute assertXPathValue(context, "//product/prix[lang('fr')]", "934.99"); // Default language assertXPathValue( context, "//product/price:sale[lang('en')]/saleEnds", "never"); } public void testDocument() { assertXPathValue( context, "$document/vendor/location[1]//street", "Orchard Road"); assertXPathPointer( context, "$document/vendor/location[1]//street", "$document/vendor[1]/location[1]/address[1]/street[1]"); assertXPathValue(context, "$document/vendor//street", "Orchard Road"); } public void testContainer() { assertXPathValue(context, "$container/vendor//street", "Orchard Road"); assertXPathValue(context, "$container//street", "Orchard Road"); assertXPathPointer( context, "$container//street", "$container/vendor[1]/location[1]/address[1]/street[1]"); // Conversion to number assertXPathValue( context, "number(vendor/location/employeeCount)", new Double(10)); } public void testElementInVariable() { assertXPathValue(context, "$element", "Orchard Road"); } public void testTypeConversions() { // Implicit conversion to number assertXPathValue( context, "vendor/location/employeeCount + 1", new Double(11)); // Implicit conversion to boolean assertXPathValue( context, "vendor/location/employeeCount and true()", Boolean.TRUE); } public void testBooleanFunction() { assertXPathValue( context, "boolean(vendor//saleEnds[../@stores = 'all'])", Boolean.TRUE); assertXPathValue( context, "boolean(vendor//promotion[../@stores = 'all'])", Boolean.TRUE); assertXPathValue( context, "boolean(vendor//promotion[../@stores = 'some'])", Boolean.FALSE); } public void testFunctionsLastAndPosition() { assertXPathPointer( context, "vendor//location[last()]", "/vendor[1]/location[2]"); } public void testNamespaceMapping() { context.registerNamespace("rate", "priceNS"); context.registerNamespace("goods", "productNS"); assertEquals("Context node namespace resolution", "priceNS", context.getNamespaceURI("price")); assertEquals("Registered namespace resolution", "priceNS", context.getNamespaceURI("rate")); // child:: with a namespace and wildcard assertXPathValue(context, "count(vendor/product/rate:*)", new Double(2)); assertXPathValue(context, "vendor[1]/product[1]/rate:amount[1]/@rate:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/rate:amount[1]/@price:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/price:amount[1]/@rate:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/price:amount[1]/@price:discount", "10%"); // Preference for externally registered namespace prefix assertXPathValueAndPointer(context, "//product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); // Same, but with a child context JXPathContext childCtx = JXPathContext.newContext(context, context.getContextBean()); assertXPathValueAndPointer(childCtx, "//product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); // Same, but with a relative context JXPathContext relativeCtx = context.getRelativeContext(context.getPointer("/vendor")); assertXPathValueAndPointer(relativeCtx, "product/product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); } public void testUnion() { assertXPathValue(context, "/vendor[1]/contact[1] | /vendor[1]/contact[4]", "John"); assertXPathValue(context, "/vendor[1]/contact[4] | /vendor[1]/contact[1]", "John"); } public void testNodes() { Pointer pointer = context.getPointer("/vendor[1]/contact[1]"); assertFalse(pointer.getNode().equals(pointer.getValue())); } }
src/test/org/apache/commons/jxpath/ri/model/XMLModelTestCase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.jxpath.ri.model; import org.apache.commons.jxpath.AbstractFactory; import org.apache.commons.jxpath.IdentityManager; import org.apache.commons.jxpath.JXPathContext; import org.apache.commons.jxpath.JXPathException; import org.apache.commons.jxpath.JXPathTestCase; import org.apache.commons.jxpath.Pointer; import org.apache.commons.jxpath.Variables; import org.apache.commons.jxpath.xml.DocumentContainer; /** * Abstract superclass for pure XPath 1.0. Subclasses * apply the same XPaths to contexts using different models: * DOM, JDOM etc. * * @author Dmitri Plotnikov * @version $Revision$ $Date$ */ public abstract class XMLModelTestCase extends JXPathTestCase { protected JXPathContext context; /** * Construct a new instance of this test case. * * @param name Name of the test case */ public XMLModelTestCase(String name) { super(name); } public void setUp() { if (context == null) { DocumentContainer docCtr = createDocumentContainer(); context = createContext(); Variables vars = context.getVariables(); vars.declareVariable("document", docCtr.getValue()); vars.declareVariable("container", docCtr); vars.declareVariable( "element", context.getPointer("vendor/location/address/street").getNode()); } } protected abstract String getModel(); protected DocumentContainer createDocumentContainer() { return new DocumentContainer( JXPathTestCase.class.getResource("Vendor.xml"), getModel()); } protected abstract AbstractFactory getAbstractFactory(); protected JXPathContext createContext() { JXPathContext context = JXPathContext.newContext(createDocumentContainer()); context.setFactory(getAbstractFactory()); context.registerNamespace("product", "productNS"); return context; } /** * An XML signature is used to determine if we have the right result * after a modification of XML by JXPath. It is basically a piece * of simplified XML. */ protected abstract String getXMLSignature( Object node, boolean elements, boolean attributes, boolean text, boolean pi); protected void assertXMLSignature( JXPathContext context, String path, String signature, boolean elements, boolean attributes, boolean text, boolean pi) { Object node = context.getPointer(path).getNode(); String sig = getXMLSignature(node, elements, attributes, text, pi); assertEquals("XML Signature mismatch: ", signature, sig); } // ------------------------------------------------ Individual Test Methods public void testDocumentOrder() { assertDocumentOrder( context, "vendor/location", "vendor/location/address/street", -1); assertDocumentOrder( context, "vendor/location[@id = '100']", "vendor/location[@id = '101']", -1); assertDocumentOrder( context, "vendor//price:amount", "vendor/location", 1); } public void testSetValue() { assertXPathSetValue( context, "vendor/location[@id = '100']", "New Text"); assertXMLSignature( context, "vendor/location[@id = '100']", "<E>New Text</E>", false, false, true, false); assertXPathSetValue( context, "vendor/location[@id = '101']", "Replacement Text"); assertXMLSignature( context, "vendor/location[@id = '101']", "<E>Replacement Text</E>", false, false, true, false); } /** * Test JXPathContext.createPath() with various arguments */ public void testCreatePath() { // Create a DOM element assertXPathCreatePath( context, "/vendor[1]/location[3]", "", "/vendor[1]/location[3]"); // Create a DOM element with contents assertXPathCreatePath( context, "/vendor[1]/location[3]/address/street", "", "/vendor[1]/location[3]/address[1]/street[1]"); // Create a DOM attribute assertXPathCreatePath( context, "/vendor[1]/location[2]/@manager", "", "/vendor[1]/location[2]/@manager"); assertXPathCreatePath( context, "/vendor[1]/location[1]/@name", "local", "/vendor[1]/location[1]/@name"); assertXPathCreatePathAndSetValue( context, "/vendor[1]/location[4]/@manager", "", "/vendor[1]/location[4]/@manager"); context.registerNamespace("price", "priceNS"); // Create a DOM element assertXPathCreatePath( context, "/vendor[1]/price:foo/price:bar", "", "/vendor[1]/price:foo[1]/price:bar[1]"); } /** * Test JXPath.createPathAndSetValue() with various arguments */ public void testCreatePathAndSetValue() { // Create a XML element assertXPathCreatePathAndSetValue( context, "vendor/location[3]", "", "/vendor[1]/location[3]"); // Create a DOM element with contents assertXPathCreatePathAndSetValue( context, "vendor/location[3]/address/street", "Lemon Circle", "/vendor[1]/location[3]/address[1]/street[1]"); // Create an attribute assertXPathCreatePathAndSetValue( context, "vendor/location[2]/@manager", "John Doe", "/vendor[1]/location[2]/@manager"); assertXPathCreatePathAndSetValue( context, "vendor/location[1]/@manager", "John Doe", "/vendor[1]/location[1]/@manager"); assertXPathCreatePathAndSetValue( context, "/vendor[1]/location[4]/@manager", "James Dow", "/vendor[1]/location[4]/@manager"); assertXPathCreatePathAndSetValue( context, "vendor/product/product:name/attribute::price:language", "English", "/vendor[1]/product[1]/product:name[1]/@price:language"); context.registerNamespace("price", "priceNS"); // Create a DOM element assertXPathCreatePathAndSetValue( context, "/vendor[1]/price:foo/price:bar", "123.20", "/vendor[1]/price:foo[1]/price:bar[1]"); } /** * Test JXPathContext.removePath() with various arguments */ public void testRemovePath() { // Remove XML nodes context.removePath("vendor/location[@id = '101']//street/text()"); assertEquals( "Remove DOM text", "", context.getValue("vendor/location[@id = '101']//street")); context.removePath("vendor/location[@id = '101']//street"); assertEquals( "Remove DOM element", new Double(0), context.getValue("count(vendor/location[@id = '101']//street)")); context.removePath("vendor/location[@id = '100']/@name"); assertEquals( "Remove DOM attribute", new Double(0), context.getValue("count(vendor/location[@id = '100']/@name)")); } public void testID() { context.setIdentityManager(new IdentityManager() { public Pointer getPointerByID(JXPathContext context, String id) { NodePointer ptr = (NodePointer) context.getPointer("/"); ptr = ptr.getValuePointer(); // Unwrap the container return ptr.getPointerByID(context, id); } }); assertXPathValueAndPointer( context, "id(101)//street", "Tangerine Drive", "id('101')/address[1]/street[1]"); assertXPathPointerLenient( context, "id(105)/address/street", "id(105)/address/street"); } public void testAxisChild() { assertXPathValue( context, "vendor/location/address/street", "Orchard Road"); // child:: - first child does not match, need to search assertXPathValue( context, "vendor/location/address/city", "Fruit Market"); // local-name(qualified) assertXPathValue( context, "local-name(vendor/product/price:amount)", "amount"); // local-name(non-qualified) assertXPathValue(context, "local-name(vendor/location)", "location"); // name (qualified) assertXPathValue( context, "name(vendor/product/price:amount)", "value:amount"); // name (non-qualified) assertXPathValue( context, "name(vendor/location)", "location"); // namespace-uri (qualified) assertXPathValue( context, "namespace-uri(vendor/product/price:amount)", "priceNS"); // default namespace does not affect search assertXPathValue(context, "vendor/product/prix", "934.99"); assertXPathValue(context, "/vendor/contact[@name='jim']", "Jim"); boolean nsv = false; try { context.setLenient(false); context.getValue("/vendor/contact[@name='jane']"); } catch (JXPathException ex) { nsv = true; } assertTrue("No such value: /vendor/contact[@name='jim']", nsv); nsv = false; try { context.setLenient(false); context.getValue("/vendor/contact[@name='jane']/*"); } catch (JXPathException ex) { nsv = true; } assertTrue("No such value: /vendor/contact[@name='jane']/*", nsv); // child:: with a wildcard assertXPathValue( context, "count(vendor/product/price:*)", new Double(2)); // child:: with the default namespace assertXPathValue(context, "count(vendor/product/*)", new Double(4)); // child:: with a qualified name assertXPathValue(context, "vendor/product/price:amount", "45.95"); // null default namespace context.registerNamespace("x", "temp"); assertXPathValue(context, "vendor/x:pos//number", "109"); } public void testAxisChildIndexPredicate() { assertXPathValue( context, "vendor/location[2]/address/street", "Tangerine Drive"); } public void testAxisDescendant() { // descendant:: assertXPathValue(context, "//street", "Orchard Road"); // descendent:: with a namespace and wildcard assertXPathValue(context, "count(//price:*)", new Double(2)); assertXPathValueIterator(context, "vendor//saleEnds", list("never")); assertXPathValueIterator(context, "vendor//promotion", list("")); assertXPathValueIterator( context, "vendor//saleEnds[../@stores = 'all']", list("never")); assertXPathValueIterator( context, "vendor//promotion[../@stores = 'all']", list("")); } // public void testAxisDescendantDocumentOrder() { // Iterator iter = context.iteratePointers("//*"); // while (iter.hasNext()) { // System.err.println(iter.next()); // } // } public void testAxisParent() { // parent:: assertXPathPointer( context, "//street/..", "/vendor[1]/location[1]/address[1]"); // parent:: (note reverse document order) assertXPathPointerIterator( context, "//street/..", list( "/vendor[1]/location[2]/address[1]", "/vendor[1]/location[1]/address[1]")); // parent:: with a namespace and wildcard assertXPathValue( context, "vendor/product/price:sale/saleEnds/parent::price:*" + "/saleEnds", "never"); } public void testAxisFollowingSibling() { // following-sibling:: assertXPathValue( context, "vendor/location[.//employeeCount = 10]/" + "following-sibling::location//street", "Tangerine Drive"); // following-sibling:: produces the correct pointer assertXPathPointer( context, "vendor/location[.//employeeCount = 10]/" + "following-sibling::location//street", "/vendor[1]/location[2]/address[1]/street[1]"); } public void testAxisPrecedingSibling() { // preceding-sibling:: produces the correct pointer assertXPathPointer( context, "//location[2]/preceding-sibling::location//street", "/vendor[1]/location[1]/address[1]/street[1]"); } public void testAxisAttribute() { // attribute:: assertXPathValue(context, "vendor/location/@id", "100"); // attribute:: produces the correct pointer assertXPathPointer( context, "vendor/location/@id", "/vendor[1]/location[1]/@id"); // iterate over attributes assertXPathValueIterator( context, "vendor/location/@id", list("100", "101")); // Using different prefixes for the same namespace assertXPathValue( context, "vendor/product/price:amount/@price:discount", "10%"); // namespace uri for an attribute assertXPathValue( context, "namespace-uri(vendor/product/price:amount/@price:discount)", "priceNS"); // local name of an attribute assertXPathValue( context, "local-name(vendor/product/price:amount/@price:discount)", "discount"); // name for an attribute assertXPathValue( context, "name(vendor/product/price:amount/@price:discount)", "price:discount"); // attribute:: with the default namespace assertXPathValue( context, "vendor/product/price:amount/@discount", "20%"); // namespace uri of an attribute with the default namespace assertXPathValue( context, "namespace-uri(vendor/product/price:amount/@discount)", ""); // local name of an attribute with the default namespace assertXPathValue( context, "local-name(vendor/product/price:amount/@discount)", "discount"); // name of an attribute with the default namespace assertXPathValue( context, "name(vendor/product/price:amount/@discount)", "discount"); // attribute:: with a namespace and wildcard assertXPathValueIterator( context, "vendor/product/price:amount/@price:*", list("10%")); // attribute:: with a wildcard assertXPathValueIterator( context, "vendor/location[1]/@*", set("100", "", "local")); // attribute:: with default namespace and wildcard assertXPathValueIterator( context, "vendor/product/price:amount/@*", list("20%")); // Empty attribute assertXPathValue(context, "vendor/location/@manager", ""); // Missing attribute assertXPathValueLenient(context, "vendor/location/@missing", null); // Missing attribute with namespace assertXPathValueLenient(context, "vendor/location/@miss:missing", null); // Using attribute in a predicate assertXPathValue( context, "vendor/location[@id='101']//street", "Tangerine Drive"); assertXPathValueIterator( context, "/vendor/location[1]/@*[name()!= 'manager']", list("100", "local")); } public void testAxisNamespace() { // namespace:: assertXPathValueAndPointer( context, "vendor/product/prix/namespace::price", "priceNS", "/vendor[1]/product[1]/prix[1]/namespace::price"); // namespace::* assertXPathValue( context, "count(vendor/product/namespace::*)", new Double(3)); // name of namespace assertXPathValue( context, "name(vendor/product/prix/namespace::price)", "price"); // local name of namespace assertXPathValue( context, "local-name(vendor/product/prix/namespace::price)", "price"); } public void testAxisAncestor() { // ancestor:: assertXPathValue( context, "vendor/product/price:sale/saleEnds/" + "ancestor::price:sale/saleEnds", "never"); // ancestor:: with a wildcard assertXPathValue( context, "vendor/product/price:sale/saleEnds/ancestor::price:*" + "/saleEnds", "never"); } public void testAxisAncestorOrSelf() { // ancestor-or-self:: assertXPathValue( context, "vendor/product/price:sale/" + "ancestor-or-self::price:sale/saleEnds", "never"); } public void testAxisFollowing() { assertXPathValueIterator( context, "vendor/contact/following::location//street", list("Orchard Road", "Tangerine Drive")); // following:: with a namespace assertXPathValue( context, "//location/following::price:sale/saleEnds", "never"); } public void testAxisSelf() { // self:: with a namespace assertXPathValue( context, "//price:sale/self::price:sale/saleEnds", "never"); // self:: with an unmatching name assertXPathValueLenient(context, "//price:sale/self::x/saleEnds", null); } public void testNodeTypeComment() { // comment() assertXPathValue( context, "//product/comment()", "We are not buying this product, ever"); } public void testNodeTypeText() { // text() //Note that this is questionable as the XPath spec tells us "." is short for self::node() and text() is by definition _not_ a node: assertXPathValue( context, "//product/text()[. != '']", "We love this product."); // text() pointer assertXPathPointer( context, "//product/text()", "/vendor[1]/product[1]/text()[1]"); } public void testNodeTypeProcessingInstruction() { // processing-instruction() without an argument assertXPathValue( context, "//product/processing-instruction()", "do not show anybody"); // processing-instruction() with an argument assertXPathValue( context, "//product/processing-instruction('report')", "average only"); // processing-instruction() pointer without an argument assertXPathPointer( context, "//product/processing-instruction('report')", "/vendor[1]/product[1]/processing-instruction('report')[1]"); // processing-instruction name assertXPathValue( context, "name(//product/processing-instruction()[1])", "security"); } public void testLang() { // xml:lang built-in attribute assertXPathValue(context, "//product/prix/@xml:lang", "fr"); // lang() used the built-in xml:lang attribute assertXPathValue(context, "//product/prix[lang('fr')]", "934.99"); // Default language assertXPathValue( context, "//product/price:sale[lang('en')]/saleEnds", "never"); } public void testDocument() { assertXPathValue( context, "$document/vendor/location[1]//street", "Orchard Road"); assertXPathPointer( context, "$document/vendor/location[1]//street", "$document/vendor[1]/location[1]/address[1]/street[1]"); assertXPathValue(context, "$document/vendor//street", "Orchard Road"); } public void testContainer() { assertXPathValue(context, "$container/vendor//street", "Orchard Road"); assertXPathValue(context, "$container//street", "Orchard Road"); assertXPathPointer( context, "$container//street", "$container/vendor[1]/location[1]/address[1]/street[1]"); // Conversion to number assertXPathValue( context, "number(vendor/location/employeeCount)", new Double(10)); } public void testElementInVariable() { assertXPathValue(context, "$element", "Orchard Road"); } public void testTypeConversions() { // Implicit conversion to number assertXPathValue( context, "vendor/location/employeeCount + 1", new Double(11)); // Implicit conversion to boolean assertXPathValue( context, "vendor/location/employeeCount and true()", Boolean.TRUE); } public void testBooleanFunction() { assertXPathValue( context, "boolean(vendor//saleEnds[../@stores = 'all'])", Boolean.TRUE); assertXPathValue( context, "boolean(vendor//promotion[../@stores = 'all'])", Boolean.TRUE); assertXPathValue( context, "boolean(vendor//promotion[../@stores = 'some'])", Boolean.FALSE); } public void testFunctionsLastAndPosition() { assertXPathPointer( context, "vendor//location[last()]", "/vendor[1]/location[2]"); } public void testNamespaceMapping() { context.registerNamespace("rate", "priceNS"); context.registerNamespace("goods", "productNS"); assertEquals("Context node namespace resolution", "priceNS", context.getNamespaceURI("price")); assertEquals("Registered namespace resolution", "priceNS", context.getNamespaceURI("rate")); // child:: with a namespace and wildcard assertXPathValue(context, "count(vendor/product/rate:*)", new Double(2)); assertXPathValue(context, "vendor[1]/product[1]/rate:amount[1]/@rate:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/rate:amount[1]/@price:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/price:amount[1]/@rate:discount", "10%"); assertXPathValue(context, "vendor[1]/product[1]/price:amount[1]/@price:discount", "10%"); // Preference for externally registered namespace prefix assertXPathValueAndPointer(context, "//product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); // Same, but with a child context JXPathContext childCtx = JXPathContext.newContext(context, context.getContextBean()); assertXPathValueAndPointer(childCtx, "//product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); // Same, but with a relative context JXPathContext relativeCtx = context.getRelativeContext(context.getPointer("/vendor")); assertXPathValueAndPointer(relativeCtx, "product/product:name", "Box of oranges", "/vendor[1]/product[1]/goods:name[1]"); } public void testUnion() { assertXPathValue(context, "/vendor[1]/contact[1] | /vendor[1]/contact[4]", "John"); assertXPathValue(context, "/vendor[1]/contact[4] | /vendor[1]/contact[1]", "John"); } }
add a node test
src/test/org/apache/commons/jxpath/ri/model/XMLModelTestCase.java
add a node test
<ide><path>rc/test/org/apache/commons/jxpath/ri/model/XMLModelTestCase.java <ide> assertXPathValue(context, "/vendor[1]/contact[1] | /vendor[1]/contact[4]", "John"); <ide> assertXPathValue(context, "/vendor[1]/contact[4] | /vendor[1]/contact[1]", "John"); <ide> } <add> <add> public void testNodes() { <add> Pointer pointer = context.getPointer("/vendor[1]/contact[1]"); <add> assertFalse(pointer.getNode().equals(pointer.getValue())); <add> } <ide> }
Java
apache-2.0
2ccf821414be51520ec030d2ebb830b4b8f8c057
0
marcjansen/shogun2,annarieger/shogun2,terrestris/shogun2,ahennr/shogun2,dnlkoch/shogun2,buehner/shogun2,terrestris/shogun2,terrestris/shogun2,ahennr/shogun2,marcjansen/shogun2,buehner/shogun2,dnlkoch/shogun2,ahennr/shogun2,annarieger/shogun2,dnlkoch/shogun2,marcjansen/shogun2,buehner/shogun2,annarieger/shogun2
/** * */ package de.terrestris.shogun2.security.access.entity; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Test; import de.terrestris.shogun2.model.User; import de.terrestris.shogun2.model.security.Permission; import de.terrestris.shogun2.util.test.TestUtil; /** * @author Nils Bühner * */ public class UserPermissionEvaluatorTest extends AbstractSecuredObjectPermissionEvaluatorTest<User> { public UserPermissionEvaluatorTest() { super(User.class, new UserPermissionEvaluator<>(), new User()); } @Test public void hasPermission_shouldAlwaysGrantReadOnOwnUserObject() throws NoSuchFieldException, IllegalAccessException { Permission readPermission = Permission.READ; // prepare a user that User user = new User(); final int userId = 42; TestUtil.setIdOnPersistentObject(user, userId); // we do not add any permissions to the user, but expect that he is allowed to READ himself // call method to test boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(userId , user, readPermission); assertThat(permissionResult, equalTo(true)); } @Test public void hasPermission_shouldNeverGrantAdminDeleteOrWriteOnOwnUserObject() throws NoSuchFieldException, IllegalAccessException { // prepare a user that User user = new User(); final int userId = 42; TestUtil.setIdOnPersistentObject(user, userId); Set<Permission> permissions = new HashSet<Permission>(Arrays.asList(Permission.values())); permissions.remove(Permission.READ); // everything but READ for (Permission permission : permissions) { // call method to test boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(userId , user, permission); assertThat(permissionResult, equalTo(false)); } } }
src/shogun2-security/src/test/java/de/terrestris/shogun2/security/access/entity/UserPermissionEvaluatorTest.java
/** * */ package de.terrestris.shogun2.security.access.entity; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.junit.Test; import de.terrestris.shogun2.model.User; import de.terrestris.shogun2.model.security.Permission; import de.terrestris.shogun2.util.test.TestUtil; /** * @author Nils Bühner * */ public class UserPermissionEvaluatorTest extends AbstractPersistentObjectPermissionEvaluatorTest<User> { public UserPermissionEvaluatorTest() { super(User.class, new UserPermissionEvaluator<>(), new User()); } @Test public void hasPermission_shouldAlwaysGrantReadOnOwnUserObject() throws NoSuchFieldException, IllegalAccessException { Permission readPermission = Permission.READ; // prepare a user that User user = new User(); final int userId = 42; TestUtil.setIdOnPersistentObject(user, userId); // we do not add any permissions to the user, but expect that he is allowed to READ himself // call method to test boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(userId , user, readPermission); assertThat(permissionResult, equalTo(true)); } @Test public void hasPermission_shouldNeverGrantAdminDeleteOrWriteOnOwnUserObject() throws NoSuchFieldException, IllegalAccessException { // prepare a user that User user = new User(); final int userId = 42; TestUtil.setIdOnPersistentObject(user, userId); Set<Permission> permissions = new HashSet<Permission>(Arrays.asList(Permission.values())); permissions.remove(Permission.READ); // everything but READ for (Permission permission : permissions) { // call method to test boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(userId , user, permission); assertThat(permissionResult, equalTo(false)); } } }
Extend from correct parent class
src/shogun2-security/src/test/java/de/terrestris/shogun2/security/access/entity/UserPermissionEvaluatorTest.java
Extend from correct parent class
<ide><path>rc/shogun2-security/src/test/java/de/terrestris/shogun2/security/access/entity/UserPermissionEvaluatorTest.java <ide> * <ide> */ <ide> public class UserPermissionEvaluatorTest extends <del> AbstractPersistentObjectPermissionEvaluatorTest<User> { <add> AbstractSecuredObjectPermissionEvaluatorTest<User> { <ide> <ide> public UserPermissionEvaluatorTest() { <ide> super(User.class, new UserPermissionEvaluator<>(), new User());
Java
lgpl-2.1
57b0fad3e9e4046b29203128a319897aa02bb4d7
0
xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.web; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Locale; import java.util.Map; import javax.portlet.PortletMode; import javax.portlet.PortletModeException; import javax.portlet.PortletURL; import javax.portlet.WindowState; import javax.portlet.WindowStateException; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; public class XWikiServletResponse implements XWikiResponse { private HttpServletResponse response; public XWikiServletResponse(HttpServletResponse response) { this.response = response; } public HttpServletResponse getHttpServletResponse() { return this.response; } public void sendRedirect(String redirect) throws IOException { this.response.sendRedirect(redirect); } public void setContentType(String type) { this.response.setContentType(type); } public void setBufferSize(int i) { this.response.setBufferSize(i); } public int getBufferSize() { return this.response.getBufferSize(); } public void flushBuffer() throws IOException { this.response.flushBuffer(); } public void resetBuffer() { this.response.resetBuffer(); } public boolean isCommitted() { return this.response.isCommitted(); } public void reset() { this.response.reset(); } public void setContentLength(int length) { this.response.setContentLength(length); } public String getCharacterEncoding() { return this.response.getCharacterEncoding(); } public ServletOutputStream getOutputStream() throws IOException { return this.response.getOutputStream(); } public PrintWriter getWriter() throws IOException { return this.response.getWriter(); } public void setCharacterEncoding(String s) { this.response.setCharacterEncoding(s); } public void addCookie(Cookie cookie) { this.response.addCookie(cookie); } public void addCookie(String cookieName, String cookieValue, int age) { Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setVersion(1); cookie.setMaxAge(age); this.response.addCookie(cookie); } /** * Remove a cookie. * * @param request The servlet request needed to find the cookie to remove * @param cookieName The name of the cookie that must be removed. */ public void removeCookie(String cookieName, XWikiRequest request) { Cookie cookie = request.getCookie(cookieName); if (cookie != null) { cookie.setMaxAge(0); cookie.setPath(cookie.getPath()); addCookie(cookie); } } public void setLocale(Locale locale) { this.response.setLocale(locale); } public Locale getLocale() { return this.response.getLocale(); } public void setDateHeader(String name, long value) { this.response.setDateHeader(name, value); } public void setIntHeader(String name, int value) { this.response.setIntHeader(name, value); } public void setHeader(String name, String value) { this.response.addHeader(name, value); } public void addHeader(String name, String value) { this.response.addHeader(name, value); } public void addDateHeader(String name, long value) { this.response.addDateHeader(name, value); } public void addIntHeader(String name, int value) { this.response.addIntHeader(name, value); } public void setStatus(int i) { this.response.setStatus(i); } /** * @deprecated */ @Deprecated public void setStatus(int i, String s) { this.response.setStatus(i, s); } public boolean containsHeader(String name) { return this.response.containsHeader(name); } public String encodeURL(String s) { return this.response.encodeURL(s); } public String encodeRedirectURL(String s) { return this.response.encodeRedirectURL(s); } /** * @deprecated */ @Deprecated public String encodeUrl(String s) { return this.response.encodeUrl(s); } /** * @deprecated */ @Deprecated public String encodeRedirectUrl(String s) { return this.response.encodeRedirectUrl(s); } public void sendError(int i, String s) throws IOException { this.response.sendError(i, s); } public void sendError(int i) throws IOException { this.response.sendError(i); } /* * Portlet Functions */ public void addProperty(String s, String s1) { } public void setProperty(String s, String s1) { } public String getContentType() { return null; } public OutputStream getPortletOutputStream() throws IOException { return null; } public PortletURL createRenderURL() { return null; } public PortletURL createActionURL() { return null; } public String getNamespace() { return null; } public void setTitle(String s) { } public void setWindowState(WindowState windowState) throws WindowStateException { } public void setPortletMode(PortletMode portletMode) throws PortletModeException { } public void setRenderParameters(Map map) { } public void setRenderParameter(String s, String s1) { } public void setRenderParameter(String s, String[] strings) { } }
xwiki-core/src/main/java/com/xpn/xwiki/web/XWikiServletResponse.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.web; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Locale; import java.util.Map; import javax.portlet.PortletMode; import javax.portlet.PortletModeException; import javax.portlet.PortletURL; import javax.portlet.WindowState; import javax.portlet.WindowStateException; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; public class XWikiServletResponse implements XWikiResponse { private HttpServletResponse response; public XWikiServletResponse(HttpServletResponse response) { this.response = response; } public HttpServletResponse getHttpServletResponse () { return response; } public void sendRedirect(String redirect) throws IOException { response.sendRedirect(redirect); } public void setContentType(String type) { response.setContentType(type); } public void setBufferSize(int i) { response.setBufferSize(i); } public int getBufferSize() { return response.getBufferSize(); } public void flushBuffer() throws IOException { response.flushBuffer(); } public void resetBuffer() { response.resetBuffer(); } public boolean isCommitted() { return response.isCommitted(); } public void reset() { response.reset(); } public void setContentLength(int length) { response.setContentLength(length); } public String getCharacterEncoding() { return response.getCharacterEncoding(); } public ServletOutputStream getOutputStream() throws IOException { return response.getOutputStream(); } public PrintWriter getWriter() throws IOException { return response.getWriter(); } public void setCharacterEncoding(String s) { response.setCharacterEncoding(s); } public void addCookie(Cookie cookie) { response.addCookie(cookie); } public void addCookie(String cookieName, String cookieValue, int age) { Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setVersion(1); cookie.setMaxAge(age); response.addCookie(cookie); } /** * Remove a cookie. * * @param request The servlet request needed to find the cookie to remove * @param cookieName The name of the cookie that must be removed. */ public void removeCookie(String cookieName, XWikiRequest request) { Cookie cookie = request.getCookie(cookieName); if (cookie != null) { cookie.setMaxAge(0); cookie.setPath(cookie.getPath()); addCookie(cookie); } } public void setLocale(Locale locale) { response.setLocale(locale); } public Locale getLocale() { return response.getLocale(); } public void setDateHeader(String name, long value) { response.setDateHeader(name, value); } public void setIntHeader(String name, int value) { response.setIntHeader(name, value); } public void setHeader(String name, String value) { response.addHeader(name, value); } public void addHeader(String name, String value) { response.addHeader(name, value); } public void addDateHeader(String name, long value) { response.addDateHeader(name, value); } public void addIntHeader(String name, int value) { response.addIntHeader(name, value); } public void setStatus(int i) { response.setStatus(i); } /** * @deprecated */ public void setStatus(int i, String s) { response.setStatus(i, s); } public boolean containsHeader(String name) { return response.containsHeader(name); } public String encodeURL(String s) { return response.encodeURL(s); } public String encodeRedirectURL(String s) { return response.encodeRedirectURL(s); } /** * @deprecated */ public String encodeUrl(String s) { return response.encodeUrl(s); } /** * @deprecated */ public String encodeRedirectUrl(String s) { return response.encodeRedirectUrl(s); } public void sendError(int i, String s) throws IOException { response.sendError(i, s); } public void sendError(int i) throws IOException { response.sendError(i); } /* * Portlet Functions */ public void addProperty(String s, String s1) { } public void setProperty(String s, String s1) { } public String getContentType() { return null; } public OutputStream getPortletOutputStream() throws IOException { return null; } public PortletURL createRenderURL() { return null; } public PortletURL createActionURL() { return null; } public String getNamespace() { return null; } public void setTitle(String s) { } public void setWindowState(WindowState windowState) throws WindowStateException { } public void setPortletMode(PortletMode portletMode) throws PortletModeException { } public void setRenderParameters(Map map) { } public void setRenderParameter(String s, String s1) { } public void setRenderParameter(String s, String[] strings) { } }
[cleanup] Apply codestyle git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@14416 f329d543-caf0-0310-9063-dda96c69346f
xwiki-core/src/main/java/com/xpn/xwiki/web/XWikiServletResponse.java
[cleanup] Apply codestyle
<ide><path>wiki-core/src/main/java/com/xpn/xwiki/web/XWikiServletResponse.java <ide> import javax.servlet.http.Cookie; <ide> import javax.servlet.http.HttpServletResponse; <ide> <del>public class XWikiServletResponse implements XWikiResponse { <add>public class XWikiServletResponse implements XWikiResponse <add>{ <ide> private HttpServletResponse response; <ide> <del> public XWikiServletResponse(HttpServletResponse response) { <add> public XWikiServletResponse(HttpServletResponse response) <add> { <ide> this.response = response; <ide> } <ide> <del> public HttpServletResponse getHttpServletResponse () { <del> return response; <del> } <del> <del> <del> public void sendRedirect(String redirect) throws IOException { <del> response.sendRedirect(redirect); <del> } <del> <del> public void setContentType(String type) { <del> response.setContentType(type); <del> } <del> <del> public void setBufferSize(int i) { <del> response.setBufferSize(i); <del> } <del> <del> public int getBufferSize() { <del> return response.getBufferSize(); <del> } <del> <del> public void flushBuffer() throws IOException { <del> response.flushBuffer(); <del> } <del> <del> public void resetBuffer() { <del> response.resetBuffer(); <del> } <del> <del> public boolean isCommitted() { <del> return response.isCommitted(); <del> } <del> <del> public void reset() { <del> response.reset(); <del> } <del> <del> public void setContentLength(int length) { <del> response.setContentLength(length); <del> } <del> <del> public String getCharacterEncoding() { <del> return response.getCharacterEncoding(); <del> } <del> <del> public ServletOutputStream getOutputStream() throws IOException { <del> return response.getOutputStream(); <del> } <del> <del> public PrintWriter getWriter() throws IOException { <del> return response.getWriter(); <del> } <del> <del> public void setCharacterEncoding(String s) { <del> response.setCharacterEncoding(s); <del> } <del> <del> public void addCookie(Cookie cookie) { <del> response.addCookie(cookie); <del> } <del> <del> public void addCookie(String cookieName, String cookieValue, int age) { <add> public HttpServletResponse getHttpServletResponse() <add> { <add> return this.response; <add> } <add> <add> public void sendRedirect(String redirect) throws IOException <add> { <add> this.response.sendRedirect(redirect); <add> } <add> <add> public void setContentType(String type) <add> { <add> this.response.setContentType(type); <add> } <add> <add> public void setBufferSize(int i) <add> { <add> this.response.setBufferSize(i); <add> } <add> <add> public int getBufferSize() <add> { <add> return this.response.getBufferSize(); <add> } <add> <add> public void flushBuffer() throws IOException <add> { <add> this.response.flushBuffer(); <add> } <add> <add> public void resetBuffer() <add> { <add> this.response.resetBuffer(); <add> } <add> <add> public boolean isCommitted() <add> { <add> return this.response.isCommitted(); <add> } <add> <add> public void reset() <add> { <add> this.response.reset(); <add> } <add> <add> public void setContentLength(int length) <add> { <add> this.response.setContentLength(length); <add> } <add> <add> public String getCharacterEncoding() <add> { <add> return this.response.getCharacterEncoding(); <add> } <add> <add> public ServletOutputStream getOutputStream() throws IOException <add> { <add> return this.response.getOutputStream(); <add> } <add> <add> public PrintWriter getWriter() throws IOException <add> { <add> return this.response.getWriter(); <add> } <add> <add> public void setCharacterEncoding(String s) <add> { <add> this.response.setCharacterEncoding(s); <add> } <add> <add> public void addCookie(Cookie cookie) <add> { <add> this.response.addCookie(cookie); <add> } <add> <add> public void addCookie(String cookieName, String cookieValue, int age) <add> { <ide> Cookie cookie = new Cookie(cookieName, cookieValue); <ide> cookie.setVersion(1); <ide> cookie.setMaxAge(age); <del> response.addCookie(cookie); <add> this.response.addCookie(cookie); <ide> } <ide> <ide> /** <ide> * Remove a cookie. <del> * <add> * <ide> * @param request The servlet request needed to find the cookie to remove <ide> * @param cookieName The name of the cookie that must be removed. <ide> */ <ide> } <ide> } <ide> <del> <del> public void setLocale(Locale locale) { <del> response.setLocale(locale); <del> } <del> <del> public Locale getLocale() { <del> return response.getLocale(); <del> } <del> <del> public void setDateHeader(String name, long value) { <del> response.setDateHeader(name, value); <del> } <del> <del> public void setIntHeader(String name, int value) { <del> response.setIntHeader(name, value); <del> } <del> <del> public void setHeader(String name, String value) { <del> response.addHeader(name, value); <del> } <del> <del> public void addHeader(String name, String value) { <del> response.addHeader(name, value); <del> } <del> <del> public void addDateHeader(String name, long value) { <del> response.addDateHeader(name, value); <del> } <del> <del> public void addIntHeader(String name, int value) { <del> response.addIntHeader(name, value); <del> } <del> <del> public void setStatus(int i) { <del> response.setStatus(i); <add> public void setLocale(Locale locale) <add> { <add> this.response.setLocale(locale); <add> } <add> <add> public Locale getLocale() <add> { <add> return this.response.getLocale(); <add> } <add> <add> public void setDateHeader(String name, long value) <add> { <add> this.response.setDateHeader(name, value); <add> } <add> <add> public void setIntHeader(String name, int value) <add> { <add> this.response.setIntHeader(name, value); <add> } <add> <add> public void setHeader(String name, String value) <add> { <add> this.response.addHeader(name, value); <add> } <add> <add> public void addHeader(String name, String value) <add> { <add> this.response.addHeader(name, value); <add> } <add> <add> public void addDateHeader(String name, long value) <add> { <add> this.response.addDateHeader(name, value); <add> } <add> <add> public void addIntHeader(String name, int value) <add> { <add> this.response.addIntHeader(name, value); <add> } <add> <add> public void setStatus(int i) <add> { <add> this.response.setStatus(i); <ide> } <ide> <ide> /** <ide> * @deprecated <ide> */ <del> public void setStatus(int i, String s) { <del> response.setStatus(i, s); <del> } <del> <del> public boolean containsHeader(String name) { <del> return response.containsHeader(name); <del> } <del> <del> public String encodeURL(String s) { <del> return response.encodeURL(s); <del> } <del> <del> public String encodeRedirectURL(String s) { <del> return response.encodeRedirectURL(s); <add> @Deprecated <add> public void setStatus(int i, String s) <add> { <add> this.response.setStatus(i, s); <add> } <add> <add> public boolean containsHeader(String name) <add> { <add> return this.response.containsHeader(name); <add> } <add> <add> public String encodeURL(String s) <add> { <add> return this.response.encodeURL(s); <add> } <add> <add> public String encodeRedirectURL(String s) <add> { <add> return this.response.encodeRedirectURL(s); <ide> } <ide> <ide> /** <ide> * @deprecated <ide> */ <del> public String encodeUrl(String s) { <del> return response.encodeUrl(s); <add> @Deprecated <add> public String encodeUrl(String s) <add> { <add> return this.response.encodeUrl(s); <ide> } <ide> <ide> /** <ide> * @deprecated <ide> */ <del> public String encodeRedirectUrl(String s) { <del> return response.encodeRedirectUrl(s); <del> } <del> <del> public void sendError(int i, String s) throws IOException { <del> response.sendError(i, s); <del> } <del> <del> public void sendError(int i) throws IOException { <del> response.sendError(i); <add> @Deprecated <add> public String encodeRedirectUrl(String s) <add> { <add> return this.response.encodeRedirectUrl(s); <add> } <add> <add> public void sendError(int i, String s) throws IOException <add> { <add> this.response.sendError(i, s); <add> } <add> <add> public void sendError(int i) throws IOException <add> { <add> this.response.sendError(i); <ide> } <ide> <ide> /* <del> * Portlet Functions <del> */ <del> public void addProperty(String s, String s1) { <del> } <del> <del> public void setProperty(String s, String s1) { <del> } <del> <del> public String getContentType() { <del> return null; <del> } <del> <del> public OutputStream getPortletOutputStream() throws IOException { <del> return null; <del> } <del> <del> public PortletURL createRenderURL() { <del> return null; <del> } <del> <del> public PortletURL createActionURL() { <del> return null; <del> } <del> <del> public String getNamespace() { <del> return null; <del> } <del> <del> public void setTitle(String s) { <del> } <del> <del> public void setWindowState(WindowState windowState) throws WindowStateException { <del> } <del> <del> public void setPortletMode(PortletMode portletMode) throws PortletModeException { <del> } <del> <del> public void setRenderParameters(Map map) { <del> } <del> <del> public void setRenderParameter(String s, String s1) { <del> } <del> <del> public void setRenderParameter(String s, String[] strings) { <add> * Portlet Functions <add> */ <add> public void addProperty(String s, String s1) <add> { <add> } <add> <add> public void setProperty(String s, String s1) <add> { <add> } <add> <add> public String getContentType() <add> { <add> return null; <add> } <add> <add> public OutputStream getPortletOutputStream() throws IOException <add> { <add> return null; <add> } <add> <add> public PortletURL createRenderURL() <add> { <add> return null; <add> } <add> <add> public PortletURL createActionURL() <add> { <add> return null; <add> } <add> <add> public String getNamespace() <add> { <add> return null; <add> } <add> <add> public void setTitle(String s) <add> { <add> } <add> <add> public void setWindowState(WindowState windowState) throws WindowStateException <add> { <add> } <add> <add> public void setPortletMode(PortletMode portletMode) throws PortletModeException <add> { <add> } <add> <add> public void setRenderParameters(Map map) <add> { <add> } <add> <add> public void setRenderParameter(String s, String s1) <add> { <add> } <add> <add> public void setRenderParameter(String s, String[] strings) <add> { <ide> } <ide> <ide> }
Java
apache-2.0
4a9c06e9f3a93f547b2a7aa57ce64ea0a08b0036
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.persistence; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.HostName; import com.yahoo.slime.ArrayTraverser; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.ObjectTraverser; import com.yahoo.slime.Slime; import com.yahoo.vespa.config.SlimeUtils; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.api.integration.metrics.MetricsService.ApplicationMetrics; import com.yahoo.vespa.hosted.controller.api.integration.certificates.ApplicationCertificate; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.api.integration.organization.IssueId; import com.yahoo.vespa.hosted.controller.api.integration.organization.User; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.vespa.hosted.controller.application.AssignedRotation; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.ClusterInfo; import com.yahoo.vespa.hosted.controller.application.ClusterUtilization; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.DeploymentActivity; import com.yahoo.vespa.hosted.controller.application.DeploymentJobs; import com.yahoo.vespa.hosted.controller.application.DeploymentJobs.JobError; import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics; import com.yahoo.vespa.hosted.controller.application.EndpointId; import com.yahoo.vespa.hosted.controller.application.JobStatus; import com.yahoo.vespa.hosted.controller.application.RotationStatus; import com.yahoo.vespa.hosted.controller.rotation.RotationId; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.TreeMap; import java.util.stream.Collectors; /** * Serializes {@link Application} to/from slime. * This class is multithread safe. * * @author bratseth */ public class ApplicationSerializer { // WARNING: Since there are multiple servers in a ZooKeeper cluster and they upgrade one by one // (and rewrite all nodes on startup), changes to the serialized format must be made // such that what is serialized on version N+1 can be read by version N: // - ADDING FIELDS: Always ok // - REMOVING FIELDS: Stop reading the field first. Stop writing it on a later version. // - CHANGING THE FORMAT OF A FIELD: Don't do it bro. // Application fields private final String idField = "id"; private final String createdAtField = "createdAt"; private final String deploymentSpecField = "deploymentSpecField"; private final String validationOverridesField = "validationOverrides"; private final String deploymentsField = "deployments"; private final String deploymentJobsField = "deploymentJobs"; private final String deployingField = "deployingField"; private final String pinnedField = "pinned"; private final String outstandingChangeField = "outstandingChangeField"; private final String ownershipIssueIdField = "ownershipIssueId"; private final String ownerField = "confirmedOwner"; private final String majorVersionField = "majorVersion"; private final String writeQualityField = "writeQuality"; private final String queryQualityField = "queryQuality"; private final String pemDeployKeyField = "pemDeployKey"; private final String assignedRotationsField = "assignedRotations"; private final String assignedRotationEndpointField = "endpointId"; private final String assignedRotationClusterField = "clusterId"; private final String assignedRotationRotationField = "rotationId"; private final String rotationsField = "endpoints"; private final String deprecatedRotationField = "rotation"; private final String rotationStatusField = "rotationStatus"; private final String applicationCertificateField = "applicationCertificate"; // Deployment fields private final String zoneField = "zone"; private final String environmentField = "environment"; private final String regionField = "region"; private final String deployTimeField = "deployTime"; private final String applicationBuildNumberField = "applicationBuildNumber"; private final String applicationPackageRevisionField = "applicationPackageRevision"; private final String sourceRevisionField = "sourceRevision"; private final String repositoryField = "repositoryField"; private final String branchField = "branchField"; private final String commitField = "commitField"; private final String authorEmailField = "authorEmailField"; private final String compileVersionField = "compileVersion"; private final String buildTimeField = "buildTime"; private final String lastQueriedField = "lastQueried"; private final String lastWrittenField = "lastWritten"; private final String lastQueriesPerSecondField = "lastQueriesPerSecond"; private final String lastWritesPerSecondField = "lastWritesPerSecond"; // DeploymentJobs fields private final String projectIdField = "projectId"; private final String jobStatusField = "jobStatus"; private final String issueIdField = "jiraIssueId"; private final String builtInternallyField = "builtInternally"; // JobStatus field private final String jobTypeField = "jobType"; private final String errorField = "jobError"; private final String lastTriggeredField = "lastTriggered"; private final String lastCompletedField = "lastCompleted"; private final String firstFailingField = "firstFailing"; private final String lastSuccessField = "lastSuccess"; private final String pausedUntilField = "pausedUntil"; // JobRun fields private final String jobRunIdField = "id"; private final String versionField = "version"; private final String revisionField = "revision"; private final String sourceVersionField = "sourceVersion"; private final String sourceApplicationField = "sourceRevision"; private final String reasonField = "reason"; private final String atField = "at"; // ClusterInfo fields private final String clusterInfoField = "clusterInfo"; private final String clusterInfoFlavorField = "flavor"; private final String clusterInfoCostField = "cost"; private final String clusterInfoCpuField = "flavorCpu"; private final String clusterInfoMemField = "flavorMem"; private final String clusterInfoDiskField = "flavorDisk"; private final String clusterInfoTypeField = "clusterType"; private final String clusterInfoHostnamesField = "hostnames"; // ClusterUtils fields private final String clusterUtilsField = "clusterUtils"; private final String clusterUtilsCpuField = "cpu"; private final String clusterUtilsMemField = "mem"; private final String clusterUtilsDiskField = "disk"; private final String clusterUtilsDiskBusyField = "diskbusy"; // Deployment metrics fields private final String deploymentMetricsField = "metrics"; private final String deploymentMetricsQPSField = "queriesPerSecond"; private final String deploymentMetricsWPSField = "writesPerSecond"; private final String deploymentMetricsDocsField = "documentCount"; private final String deploymentMetricsQueryLatencyField = "queryLatencyMillis"; private final String deploymentMetricsWriteLatencyField = "writeLatencyMillis"; private final String deploymentMetricsUpdateTime = "lastUpdated"; private final String deploymentMetricsWarningsField = "warnings"; // ------------------ Serialization public Slime toSlime(Application application) { Slime slime = new Slime(); Cursor root = slime.setObject(); root.setString(idField, application.id().serializedForm()); root.setLong(createdAtField, application.createdAt().toEpochMilli()); root.setString(deploymentSpecField, application.deploymentSpec().xmlForm()); root.setString(validationOverridesField, application.validationOverrides().xmlForm()); deploymentsToSlime(application.deployments().values(), root.setArray(deploymentsField)); toSlime(application.deploymentJobs(), root.setObject(deploymentJobsField)); toSlime(application.change(), root, deployingField); toSlime(application.outstandingChange(), root, outstandingChangeField); application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value())); application.owner().ifPresent(owner -> root.setString(ownerField, owner.username())); application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion)); root.setDouble(queryQualityField, application.metrics().queryServiceQuality()); root.setDouble(writeQualityField, application.metrics().writeServiceQuality()); application.pemDeployKey().ifPresent(pemDeployKey -> root.setString(pemDeployKeyField, pemDeployKey)); application.legacyRotation().ifPresent(rotation -> root.setString(deprecatedRotationField, rotation.asString())); rotationsToSlime(application.assignedRotations(), root, rotationsField); assignedRotationsToSlime(application.assignedRotations(), root, assignedRotationsField); toSlime(application.rotationStatus(), root.setArray(rotationStatusField)); application.applicationCertificate().ifPresent(cert -> root.setString(applicationCertificateField, cert.secretsKeyNamePrefix())); return slime; } private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) { for (Deployment deployment : deployments) deploymentToSlime(deployment, array.addObject()); } private void deploymentToSlime(Deployment deployment, Cursor object) { zoneIdToSlime(deployment.zone(), object.setObject(zoneField)); object.setString(versionField, deployment.version().toString()); object.setLong(deployTimeField, deployment.at().toEpochMilli()); toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField)); clusterInfoToSlime(deployment.clusterInfo(), object); clusterUtilsToSlime(deployment.clusterUtils(), object); deploymentMetricsToSlime(deployment.metrics(), object); deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli())); deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli())); deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value)); deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value)); } private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) { Cursor root = object.setObject(deploymentMetricsField); root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond()); root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond()); root.setDouble(deploymentMetricsDocsField, metrics.documentCount()); root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis()); root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis()); metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli())); if (!metrics.warnings().isEmpty()) { Cursor warningsObject = root.setObject(deploymentMetricsWarningsField); metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count)); } } private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) { Cursor root = object.setObject(clusterInfoField); for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) { toSlime(entry.getValue(), root.setObject(entry.getKey().value())); } } private void toSlime(ClusterInfo info, Cursor object) { object.setString(clusterInfoFlavorField, info.getFlavor()); object.setLong(clusterInfoCostField, info.getFlavorCost()); object.setDouble(clusterInfoCpuField, info.getFlavorCPU()); object.setDouble(clusterInfoMemField, info.getFlavorMem()); object.setDouble(clusterInfoDiskField, info.getFlavorDisk()); object.setString(clusterInfoTypeField, info.getClusterType().name()); Cursor array = object.setArray(clusterInfoHostnamesField); for (String host : info.getHostnames()) { array.addString(host); } } private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) { Cursor root = object.setObject(clusterUtilsField); for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) { toSlime(entry.getValue(), root.setObject(entry.getKey().value())); } } private void toSlime(ClusterUtilization utils, Cursor object) { object.setDouble(clusterUtilsCpuField, utils.getCpu()); object.setDouble(clusterUtilsMemField, utils.getMemory()); object.setDouble(clusterUtilsDiskField, utils.getDisk()); object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy()); } private void zoneIdToSlime(ZoneId zone, Cursor object) { object.setString(environmentField, zone.environment().value()); object.setString(regionField, zone.region().value()); } private void toSlime(ApplicationVersion applicationVersion, Cursor object) { if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) { object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong()); toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField)); applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email)); applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString())); applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli())); } } private void toSlime(SourceRevision sourceRevision, Cursor object) { object.setString(repositoryField, sourceRevision.repository()); object.setString(branchField, sourceRevision.branch()); object.setString(commitField, sourceRevision.commit()); } private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) { deploymentJobs.projectId().ifPresent(projectId -> cursor.setLong(projectIdField, projectId)); jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField)); deploymentJobs.issueId().ifPresent(jiraIssueId -> cursor.setString(issueIdField, jiraIssueId.value())); cursor.setBool(builtInternallyField, deploymentJobs.deployedInternally()); } private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) { for (JobStatus jobStatus : jobStatuses) toSlime(jobStatus, jobStatusArray.addObject()); } private void toSlime(JobStatus jobStatus, Cursor object) { object.setString(jobTypeField, jobStatus.type().jobName()); if (jobStatus.jobError().isPresent()) object.setString(errorField, jobStatus.jobError().get().name()); jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField)); jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField)); jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField)); jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField)); jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until)); } private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) { Cursor object = parent.setObject(jobRunObjectName); object.setLong(jobRunIdField, jobRun.id()); object.setString(versionField, jobRun.platform().toString()); toSlime(jobRun.application(), object.setObject(revisionField)); jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString())); jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField))); object.setString(reasonField, jobRun.reason()); object.setLong(atField, jobRun.at().toEpochMilli()); } private void toSlime(Change deploying, Cursor parentObject, String fieldName) { if (deploying.isEmpty()) return; Cursor object = parentObject.setObject(fieldName); if (deploying.platform().isPresent()) object.setString(versionField, deploying.platform().get().toString()); if (deploying.application().isPresent()) toSlime(deploying.application().get(), object); if (deploying.isPinned()) object.setBool(pinnedField, true); } private void toSlime(Map<HostName, RotationStatus> rotationStatus, Cursor array) { rotationStatus.forEach((hostname, status) -> { Cursor object = array.addObject(); object.setString("hostname", hostname.value()); object.setString("status", status.name()); }); } private void rotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { var rotationsArray = parent.setArray(fieldName); rotations.forEach(rot -> rotationsArray.addString(rot.rotationId().asString())); } private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { var rotationsArray = parent.setArray(fieldName); for (var rotation : rotations) { var object = rotationsArray.addObject(); object.setString(assignedRotationEndpointField, rotation.endpointId().id()); object.setString(assignedRotationRotationField, rotation.rotationId().asString()); object.setString(assignedRotationClusterField, rotation.clusterId().value()); } } // ------------------ Deserialization public Application fromSlime(Slime slime) { Inspector root = slime.get(); ApplicationId id = ApplicationId.fromSerializedForm(root.field(idField).asString()); Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong()); DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false); ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString()); List<Deployment> deployments = deploymentsFromSlime(root.field(deploymentsField)); DeploymentJobs deploymentJobs = deploymentJobsFromSlime(root.field(deploymentJobsField)); Change deploying = changeFromSlime(root.field(deployingField)); Change outstandingChange = changeFromSlime(root.field(outstandingChangeField)); Optional<IssueId> ownershipIssueId = optionalString(root.field(ownershipIssueIdField)).map(IssueId::from); Optional<User> owner = optionalString(root.field(ownerField)).map(User::from); OptionalInt majorVersion = optionalInteger(root.field(majorVersionField)); ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(), root.field(writeQualityField).asDouble()); Optional<String> pemDeployKey = optionalString(root.field(pemDeployKeyField)); List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, root); Map<HostName, RotationStatus> rotationStatus = rotationStatusFromSlime(root.field(rotationStatusField)); Optional<ApplicationCertificate> applicationCertificate = optionalString(root.field(applicationCertificateField)).map(ApplicationCertificate::new); return new Application(id, createdAt, deploymentSpec, validationOverrides, deployments, deploymentJobs, deploying, outstandingChange, ownershipIssueId, owner, majorVersion, metrics, pemDeployKey, assignedRotations, rotationStatus, applicationCertificate); } private List<Deployment> deploymentsFromSlime(Inspector array) { List<Deployment> deployments = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item))); return deployments; } private Deployment deploymentFromSlime(Inspector deploymentObject) { return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)), applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)), Version.fromString(deploymentObject.field(versionField).asString()), Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()), clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)), clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)), deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)), DeploymentActivity.create(optionalInstant(deploymentObject.field(lastQueriedField)), optionalInstant(deploymentObject.field(lastWrittenField)), optionalDouble(deploymentObject.field(lastQueriesPerSecondField)), optionalDouble(deploymentObject.field(lastWritesPerSecondField)))); } private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) { Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ? Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) : Optional.empty(); return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(), object.field(deploymentMetricsWPSField).asDouble(), object.field(deploymentMetricsDocsField).asDouble(), object.field(deploymentMetricsQueryLatencyField).asDouble(), object.field(deploymentMetricsWriteLatencyField).asDouble(), instant, deploymentWarningsFrom(object.field(deploymentMetricsWarningsField))); } private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) { Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>(); object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name), (int) value.asLong())); return Collections.unmodifiableMap(warnings); } private Map<HostName, RotationStatus> rotationStatusFromSlime(Inspector object) { if (!object.valid()) { return Collections.emptyMap(); } Map<HostName, RotationStatus> rotationStatus = new TreeMap<>(); object.traverse((ArrayTraverser) (idx, inspect) -> { HostName hostname = HostName.from(inspect.field("hostname").asString()); RotationStatus status = RotationStatus.valueOf(inspect.field("status").asString()); rotationStatus.put(hostname, status); }); return Collections.unmodifiableMap(rotationStatus); } private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) { Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>(); object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value))); return map; } private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) { Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>(); object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value))); return map; } private ClusterUtilization clusterUtililzationFromSlime(Inspector object) { double cpu = object.field(clusterUtilsCpuField).asDouble(); double mem = object.field(clusterUtilsMemField).asDouble(); double disk = object.field(clusterUtilsDiskField).asDouble(); double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble(); return new ClusterUtilization(mem, cpu, disk, diskBusy); } private ClusterInfo clusterInfoFromSlime(Inspector inspector) { String flavor = inspector.field(clusterInfoFlavorField).asString(); int cost = (int)inspector.field(clusterInfoCostField).asLong(); String type = inspector.field(clusterInfoTypeField).asString(); double flavorCpu = inspector.field(clusterInfoCpuField).asDouble(); double flavorMem = inspector.field(clusterInfoMemField).asDouble(); double flavorDisk = inspector.field(clusterInfoDiskField).asDouble(); List<String> hostnames = new ArrayList<>(); inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString())); return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames); } private ZoneId zoneIdFromSlime(Inspector object) { return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString()); } private ApplicationVersion applicationVersionFromSlime(Inspector object) { if ( ! object.valid()) return ApplicationVersion.unknown; OptionalLong applicationBuildNumber = optionalLong(object.field(applicationBuildNumberField)); Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField)); if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) { return ApplicationVersion.unknown; } Optional<String> authorEmail = optionalString(object.field(authorEmailField)); Optional<Version> compileVersion = optionalString(object.field(compileVersionField)).map(Version::fromString); Optional<Instant> buildTime = optionalInstant(object.field(buildTimeField)); if (authorEmail.isEmpty()) return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong()); if (compileVersion.isEmpty() || buildTime.isEmpty()) return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get()); return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(), compileVersion.get(), buildTime.get()); } private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new SourceRevision(object.field(repositoryField).asString(), object.field(branchField).asString(), object.field(commitField).asString())); } private DeploymentJobs deploymentJobsFromSlime(Inspector object) { OptionalLong projectId = optionalLong(object.field(projectIdField)); List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField)); Optional<IssueId> issueId = optionalString(object.field(issueIdField)).map(IssueId::from); boolean builtInternally = object.field(builtInternallyField).asBool(); return new DeploymentJobs(projectId, jobStatusList, issueId, builtInternally); } private Change changeFromSlime(Inspector object) { if ( ! object.valid()) return Change.empty(); Inspector versionFieldValue = object.field(versionField); Change change = Change.empty(); if (versionFieldValue.valid()) change = Change.of(Version.fromString(versionFieldValue.asString())); if (object.field(applicationBuildNumberField).valid()) change = change.with(applicationVersionFromSlime(object)); if (object.field(pinnedField).asBool()) change = change.withPin(); return change; } private List<JobStatus> jobStatusListFromSlime(Inspector array) { List<JobStatus> jobStatusList = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add)); return jobStatusList; } private Optional<JobStatus> jobStatusFromSlime(Inspector object) { // if the job type has since been removed, ignore it Optional<JobType> jobType = JobType.fromOptionalJobName(object.field(jobTypeField).asString()); if (jobType.isEmpty()) return Optional.empty(); Optional<JobError> jobError = Optional.empty(); if (object.field(errorField).valid()) jobError = Optional.of(JobError.valueOf(object.field(errorField).asString())); return Optional.of(new JobStatus(jobType.get(), jobError, jobRunFromSlime(object.field(lastTriggeredField)), jobRunFromSlime(object.field(lastCompletedField)), jobRunFromSlime(object.field(firstFailingField)), jobRunFromSlime(object.field(lastSuccessField)), optionalLong(object.field(pausedUntilField)))); } private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(), new Version(object.field(versionField).asString()), applicationVersionFromSlime(object.field(revisionField)), optionalString(object.field(sourceVersionField)).map(Version::fromString), Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime), object.field(reasonField).asString(), Instant.ofEpochMilli(object.field(atField).asLong()))); } private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) { var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>(); root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> { var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString()); var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString()); var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString()); var regions = deploymentSpec.endpoints().stream() .filter(endpoint -> endpoint.endpointId().equals(endpointId.id())) .flatMap(endpoint -> endpoint.regions().stream()) .collect(Collectors.toSet()); assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions)); }); return List.copyOf(assignedRotations.values()); } private OptionalLong optionalLong(Inspector field) { return field.valid() ? OptionalLong.of(field.asLong()) : OptionalLong.empty(); } private OptionalInt optionalInteger(Inspector field) { return field.valid() ? OptionalInt.of((int) field.asLong()) : OptionalInt.empty(); } private OptionalDouble optionalDouble(Inspector field) { return field.valid() ? OptionalDouble.of(field.asDouble()) : OptionalDouble.empty(); } private Optional<String> optionalString(Inspector field) { return SlimeUtils.optionalString(field); } private Optional<Instant> optionalInstant(Inspector field) { OptionalLong value = optionalLong(field); return value.isPresent() ? Optional.of(Instant.ofEpochMilli(value.getAsLong())) : Optional.empty(); } }
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializer.java
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.persistence; import com.yahoo.component.Version; import com.yahoo.config.application.api.DeploymentSpec; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.HostName; import com.yahoo.slime.ArrayTraverser; import com.yahoo.slime.Cursor; import com.yahoo.slime.Inspector; import com.yahoo.slime.ObjectTraverser; import com.yahoo.slime.Slime; import com.yahoo.vespa.config.SlimeUtils; import com.yahoo.vespa.hosted.controller.Application; import com.yahoo.vespa.hosted.controller.api.integration.metrics.MetricsService.ApplicationMetrics; import com.yahoo.vespa.hosted.controller.api.integration.certificates.ApplicationCertificate; import com.yahoo.vespa.hosted.controller.api.integration.deployment.ApplicationVersion; import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType; import com.yahoo.vespa.hosted.controller.api.integration.deployment.SourceRevision; import com.yahoo.vespa.hosted.controller.api.integration.organization.IssueId; import com.yahoo.vespa.hosted.controller.api.integration.organization.User; import com.yahoo.config.provision.zone.ZoneId; import com.yahoo.vespa.hosted.controller.application.AssignedRotation; import com.yahoo.vespa.hosted.controller.application.Change; import com.yahoo.vespa.hosted.controller.application.ClusterInfo; import com.yahoo.vespa.hosted.controller.application.ClusterUtilization; import com.yahoo.vespa.hosted.controller.application.Deployment; import com.yahoo.vespa.hosted.controller.application.DeploymentActivity; import com.yahoo.vespa.hosted.controller.application.DeploymentJobs; import com.yahoo.vespa.hosted.controller.application.DeploymentJobs.JobError; import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics; import com.yahoo.vespa.hosted.controller.application.EndpointId; import com.yahoo.vespa.hosted.controller.application.JobStatus; import com.yahoo.vespa.hosted.controller.application.RotationStatus; import com.yahoo.vespa.hosted.controller.rotation.RotationId; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.TreeMap; import java.util.stream.Collectors; /** * Serializes {@link Application} to/from slime. * This class is multithread safe. * * @author bratseth */ public class ApplicationSerializer { // WARNING: Since there are multiple servers in a ZooKeeper cluster and they upgrade one by one // (and rewrite all nodes on startup), changes to the serialized format must be made // such that what is serialized on version N+1 can be read by version N: // - ADDING FIELDS: Always ok // - REMOVING FIELDS: Stop reading the field first. Stop writing it on a later version. // - CHANGING THE FORMAT OF A FIELD: Don't do it bro. // Application fields private final String idField = "id"; private final String createdAtField = "createdAt"; private final String deploymentSpecField = "deploymentSpecField"; private final String validationOverridesField = "validationOverrides"; private final String deploymentsField = "deployments"; private final String deploymentJobsField = "deploymentJobs"; private final String deployingField = "deployingField"; private final String pinnedField = "pinned"; private final String outstandingChangeField = "outstandingChangeField"; private final String ownershipIssueIdField = "ownershipIssueId"; private final String ownerField = "confirmedOwner"; private final String majorVersionField = "majorVersion"; private final String writeQualityField = "writeQuality"; private final String queryQualityField = "queryQuality"; private final String pemDeployKeyField = "pemDeployKey"; private final String assignedRotationsField = "assignedRotations"; private final String assignedRotationEndpointField = "endpointId"; private final String assignedRotationClusterField = "clusterId"; private final String assignedRotationRotationField = "rotationId"; private final String rotationsField = "endpoints"; private final String deprecatedRotationField = "rotation"; private final String rotationStatusField = "rotationStatus"; private final String applicationCertificateField = "applicationCertificate"; // Deployment fields private final String zoneField = "zone"; private final String environmentField = "environment"; private final String regionField = "region"; private final String deployTimeField = "deployTime"; private final String applicationBuildNumberField = "applicationBuildNumber"; private final String applicationPackageRevisionField = "applicationPackageRevision"; private final String sourceRevisionField = "sourceRevision"; private final String repositoryField = "repositoryField"; private final String branchField = "branchField"; private final String commitField = "commitField"; private final String authorEmailField = "authorEmailField"; private final String compileVersionField = "compileVersion"; private final String buildTimeField = "buildTime"; private final String lastQueriedField = "lastQueried"; private final String lastWrittenField = "lastWritten"; private final String lastQueriesPerSecondField = "lastQueriesPerSecond"; private final String lastWritesPerSecondField = "lastWritesPerSecond"; // DeploymentJobs fields private final String projectIdField = "projectId"; private final String jobStatusField = "jobStatus"; private final String issueIdField = "jiraIssueId"; private final String builtInternallyField = "builtInternally"; // JobStatus field private final String jobTypeField = "jobType"; private final String errorField = "jobError"; private final String lastTriggeredField = "lastTriggered"; private final String lastCompletedField = "lastCompleted"; private final String firstFailingField = "firstFailing"; private final String lastSuccessField = "lastSuccess"; private final String pausedUntilField = "pausedUntil"; // JobRun fields private final String jobRunIdField = "id"; private final String versionField = "version"; private final String revisionField = "revision"; private final String sourceVersionField = "sourceVersion"; private final String sourceApplicationField = "sourceRevision"; private final String reasonField = "reason"; private final String atField = "at"; // ClusterInfo fields private final String clusterInfoField = "clusterInfo"; private final String clusterInfoFlavorField = "flavor"; private final String clusterInfoCostField = "cost"; private final String clusterInfoCpuField = "flavorCpu"; private final String clusterInfoMemField = "flavorMem"; private final String clusterInfoDiskField = "flavorDisk"; private final String clusterInfoTypeField = "clusterType"; private final String clusterInfoHostnamesField = "hostnames"; // ClusterUtils fields private final String clusterUtilsField = "clusterUtils"; private final String clusterUtilsCpuField = "cpu"; private final String clusterUtilsMemField = "mem"; private final String clusterUtilsDiskField = "disk"; private final String clusterUtilsDiskBusyField = "diskbusy"; // Deployment metrics fields private final String deploymentMetricsField = "metrics"; private final String deploymentMetricsQPSField = "queriesPerSecond"; private final String deploymentMetricsWPSField = "writesPerSecond"; private final String deploymentMetricsDocsField = "documentCount"; private final String deploymentMetricsQueryLatencyField = "queryLatencyMillis"; private final String deploymentMetricsWriteLatencyField = "writeLatencyMillis"; private final String deploymentMetricsUpdateTime = "lastUpdated"; private final String deploymentMetricsWarningsField = "warnings"; // ------------------ Serialization public Slime toSlime(Application application) { Slime slime = new Slime(); Cursor root = slime.setObject(); root.setString(idField, application.id().serializedForm()); root.setLong(createdAtField, application.createdAt().toEpochMilli()); root.setString(deploymentSpecField, application.deploymentSpec().xmlForm()); root.setString(validationOverridesField, application.validationOverrides().xmlForm()); deploymentsToSlime(application.deployments().values(), root.setArray(deploymentsField)); toSlime(application.deploymentJobs(), root.setObject(deploymentJobsField)); toSlime(application.change(), root, deployingField); toSlime(application.outstandingChange(), root, outstandingChangeField); application.ownershipIssueId().ifPresent(issueId -> root.setString(ownershipIssueIdField, issueId.value())); application.owner().ifPresent(owner -> root.setString(ownerField, owner.username())); application.majorVersion().ifPresent(majorVersion -> root.setLong(majorVersionField, majorVersion)); root.setDouble(queryQualityField, application.metrics().queryServiceQuality()); root.setDouble(writeQualityField, application.metrics().writeServiceQuality()); application.pemDeployKey().ifPresent(pemDeployKey -> root.setString(pemDeployKeyField, pemDeployKey)); application.legacyRotation().ifPresent(rotation -> root.setString(deprecatedRotationField, rotation.asString())); rotationsToSlime(application.assignedRotations(), root, rotationsField); assignedRotationsToSlime(application.assignedRotations(), root, assignedRotationsField); toSlime(application.rotationStatus(), root.setArray(rotationStatusField)); application.applicationCertificate().ifPresent(cert -> root.setString(applicationCertificateField, cert.secretsKeyNamePrefix())); return slime; } private void deploymentsToSlime(Collection<Deployment> deployments, Cursor array) { for (Deployment deployment : deployments) deploymentToSlime(deployment, array.addObject()); } private void deploymentToSlime(Deployment deployment, Cursor object) { zoneIdToSlime(deployment.zone(), object.setObject(zoneField)); object.setString(versionField, deployment.version().toString()); object.setLong(deployTimeField, deployment.at().toEpochMilli()); toSlime(deployment.applicationVersion(), object.setObject(applicationPackageRevisionField)); clusterInfoToSlime(deployment.clusterInfo(), object); clusterUtilsToSlime(deployment.clusterUtils(), object); deploymentMetricsToSlime(deployment.metrics(), object); deployment.activity().lastQueried().ifPresent(instant -> object.setLong(lastQueriedField, instant.toEpochMilli())); deployment.activity().lastWritten().ifPresent(instant -> object.setLong(lastWrittenField, instant.toEpochMilli())); deployment.activity().lastQueriesPerSecond().ifPresent(value -> object.setDouble(lastQueriesPerSecondField, value)); deployment.activity().lastWritesPerSecond().ifPresent(value -> object.setDouble(lastWritesPerSecondField, value)); } private void deploymentMetricsToSlime(DeploymentMetrics metrics, Cursor object) { Cursor root = object.setObject(deploymentMetricsField); root.setDouble(deploymentMetricsQPSField, metrics.queriesPerSecond()); root.setDouble(deploymentMetricsWPSField, metrics.writesPerSecond()); root.setDouble(deploymentMetricsDocsField, metrics.documentCount()); root.setDouble(deploymentMetricsQueryLatencyField, metrics.queryLatencyMillis()); root.setDouble(deploymentMetricsWriteLatencyField, metrics.writeLatencyMillis()); metrics.instant().ifPresent(instant -> root.setLong(deploymentMetricsUpdateTime, instant.toEpochMilli())); if (!metrics.warnings().isEmpty()) { Cursor warningsObject = root.setObject(deploymentMetricsWarningsField); metrics.warnings().forEach((warning, count) -> warningsObject.setLong(warning.name(), count)); } } private void clusterInfoToSlime(Map<ClusterSpec.Id, ClusterInfo> clusters, Cursor object) { Cursor root = object.setObject(clusterInfoField); for (Map.Entry<ClusterSpec.Id, ClusterInfo> entry : clusters.entrySet()) { toSlime(entry.getValue(), root.setObject(entry.getKey().value())); } } private void toSlime(ClusterInfo info, Cursor object) { object.setString(clusterInfoFlavorField, info.getFlavor()); object.setLong(clusterInfoCostField, info.getFlavorCost()); object.setDouble(clusterInfoCpuField, info.getFlavorCPU()); object.setDouble(clusterInfoMemField, info.getFlavorMem()); object.setDouble(clusterInfoDiskField, info.getFlavorDisk()); object.setString(clusterInfoTypeField, info.getClusterType().name()); Cursor array = object.setArray(clusterInfoHostnamesField); for (String host : info.getHostnames()) { array.addString(host); } } private void clusterUtilsToSlime(Map<ClusterSpec.Id, ClusterUtilization> clusters, Cursor object) { Cursor root = object.setObject(clusterUtilsField); for (Map.Entry<ClusterSpec.Id, ClusterUtilization> entry : clusters.entrySet()) { toSlime(entry.getValue(), root.setObject(entry.getKey().value())); } } private void toSlime(ClusterUtilization utils, Cursor object) { object.setDouble(clusterUtilsCpuField, utils.getCpu()); object.setDouble(clusterUtilsMemField, utils.getMemory()); object.setDouble(clusterUtilsDiskField, utils.getDisk()); object.setDouble(clusterUtilsDiskBusyField, utils.getDiskBusy()); } private void zoneIdToSlime(ZoneId zone, Cursor object) { object.setString(environmentField, zone.environment().value()); object.setString(regionField, zone.region().value()); } private void toSlime(ApplicationVersion applicationVersion, Cursor object) { if (applicationVersion.buildNumber().isPresent() && applicationVersion.source().isPresent()) { object.setLong(applicationBuildNumberField, applicationVersion.buildNumber().getAsLong()); toSlime(applicationVersion.source().get(), object.setObject(sourceRevisionField)); applicationVersion.authorEmail().ifPresent(email -> object.setString(authorEmailField, email)); applicationVersion.compileVersion().ifPresent(version -> object.setString(compileVersionField, version.toString())); applicationVersion.buildTime().ifPresent(time -> object.setLong(buildTimeField, time.toEpochMilli())); } } private void toSlime(SourceRevision sourceRevision, Cursor object) { object.setString(repositoryField, sourceRevision.repository()); object.setString(branchField, sourceRevision.branch()); object.setString(commitField, sourceRevision.commit()); } private void toSlime(DeploymentJobs deploymentJobs, Cursor cursor) { deploymentJobs.projectId().ifPresent(projectId -> cursor.setLong(projectIdField, projectId)); jobStatusToSlime(deploymentJobs.jobStatus().values(), cursor.setArray(jobStatusField)); deploymentJobs.issueId().ifPresent(jiraIssueId -> cursor.setString(issueIdField, jiraIssueId.value())); cursor.setBool(builtInternallyField, deploymentJobs.deployedInternally()); } private void jobStatusToSlime(Collection<JobStatus> jobStatuses, Cursor jobStatusArray) { for (JobStatus jobStatus : jobStatuses) toSlime(jobStatus, jobStatusArray.addObject()); } private void toSlime(JobStatus jobStatus, Cursor object) { object.setString(jobTypeField, jobStatus.type().jobName()); if (jobStatus.jobError().isPresent()) object.setString(errorField, jobStatus.jobError().get().name()); jobStatus.lastTriggered().ifPresent(run -> jobRunToSlime(run, object, lastTriggeredField)); jobStatus.lastCompleted().ifPresent(run -> jobRunToSlime(run, object, lastCompletedField)); jobStatus.lastSuccess().ifPresent(run -> jobRunToSlime(run, object, lastSuccessField)); jobStatus.firstFailing().ifPresent(run -> jobRunToSlime(run, object, firstFailingField)); jobStatus.pausedUntil().ifPresent(until -> object.setLong(pausedUntilField, until)); } private void jobRunToSlime(JobStatus.JobRun jobRun, Cursor parent, String jobRunObjectName) { Cursor object = parent.setObject(jobRunObjectName); object.setLong(jobRunIdField, jobRun.id()); object.setString(versionField, jobRun.platform().toString()); toSlime(jobRun.application(), object.setObject(revisionField)); jobRun.sourcePlatform().ifPresent(version -> object.setString(sourceVersionField, version.toString())); jobRun.sourceApplication().ifPresent(version -> toSlime(version, object.setObject(sourceApplicationField))); object.setString(reasonField, jobRun.reason()); object.setLong(atField, jobRun.at().toEpochMilli()); } private void toSlime(Change deploying, Cursor parentObject, String fieldName) { if (deploying.isEmpty()) return; Cursor object = parentObject.setObject(fieldName); if (deploying.platform().isPresent()) object.setString(versionField, deploying.platform().get().toString()); if (deploying.application().isPresent()) toSlime(deploying.application().get(), object); if (deploying.isPinned()) object.setBool(pinnedField, true); } private void toSlime(Map<HostName, RotationStatus> rotationStatus, Cursor array) { rotationStatus.forEach((hostname, status) -> { Cursor object = array.addObject(); object.setString("hostname", hostname.value()); object.setString("status", status.name()); }); } private void rotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { final var rotationsArray = parent.setArray(fieldName); rotations.forEach(rot -> rotationsArray.addString(rot.rotationId().asString())); } private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { final var rotationsArray = parent.setArray(fieldName); for (var rotation : rotations) { final var object = rotationsArray.addObject(); object.setString(assignedRotationEndpointField, rotation.endpointId().id()); object.setString(assignedRotationRotationField, rotation.rotationId().asString()); object.setString(assignedRotationClusterField, rotation.clusterId().value()); } } // ------------------ Deserialization public Application fromSlime(Slime slime) { Inspector root = slime.get(); ApplicationId id = ApplicationId.fromSerializedForm(root.field(idField).asString()); Instant createdAt = Instant.ofEpochMilli(root.field(createdAtField).asLong()); DeploymentSpec deploymentSpec = DeploymentSpec.fromXml(root.field(deploymentSpecField).asString(), false); ValidationOverrides validationOverrides = ValidationOverrides.fromXml(root.field(validationOverridesField).asString()); List<Deployment> deployments = deploymentsFromSlime(root.field(deploymentsField)); DeploymentJobs deploymentJobs = deploymentJobsFromSlime(root.field(deploymentJobsField)); Change deploying = changeFromSlime(root.field(deployingField)); Change outstandingChange = changeFromSlime(root.field(outstandingChangeField)); Optional<IssueId> ownershipIssueId = optionalString(root.field(ownershipIssueIdField)).map(IssueId::from); Optional<User> owner = optionalString(root.field(ownerField)).map(User::from); OptionalInt majorVersion = optionalInteger(root.field(majorVersionField)); ApplicationMetrics metrics = new ApplicationMetrics(root.field(queryQualityField).asDouble(), root.field(writeQualityField).asDouble()); Optional<String> pemDeployKey = optionalString(root.field(pemDeployKeyField)); List<AssignedRotation> assignedRotations = assignedRotationsFromSlime(deploymentSpec, root); Map<HostName, RotationStatus> rotationStatus = rotationStatusFromSlime(root.field(rotationStatusField)); Optional<ApplicationCertificate> applicationCertificate = optionalString(root.field(applicationCertificateField)).map(ApplicationCertificate::new); return new Application(id, createdAt, deploymentSpec, validationOverrides, deployments, deploymentJobs, deploying, outstandingChange, ownershipIssueId, owner, majorVersion, metrics, pemDeployKey, assignedRotations, rotationStatus, applicationCertificate); } private List<Deployment> deploymentsFromSlime(Inspector array) { List<Deployment> deployments = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> deployments.add(deploymentFromSlime(item))); return deployments; } private Deployment deploymentFromSlime(Inspector deploymentObject) { return new Deployment(zoneIdFromSlime(deploymentObject.field(zoneField)), applicationVersionFromSlime(deploymentObject.field(applicationPackageRevisionField)), Version.fromString(deploymentObject.field(versionField).asString()), Instant.ofEpochMilli(deploymentObject.field(deployTimeField).asLong()), clusterUtilsMapFromSlime(deploymentObject.field(clusterUtilsField)), clusterInfoMapFromSlime(deploymentObject.field(clusterInfoField)), deploymentMetricsFromSlime(deploymentObject.field(deploymentMetricsField)), DeploymentActivity.create(optionalInstant(deploymentObject.field(lastQueriedField)), optionalInstant(deploymentObject.field(lastWrittenField)), optionalDouble(deploymentObject.field(lastQueriesPerSecondField)), optionalDouble(deploymentObject.field(lastWritesPerSecondField)))); } private DeploymentMetrics deploymentMetricsFromSlime(Inspector object) { Optional<Instant> instant = object.field(deploymentMetricsUpdateTime).valid() ? Optional.of(Instant.ofEpochMilli(object.field(deploymentMetricsUpdateTime).asLong())) : Optional.empty(); return new DeploymentMetrics(object.field(deploymentMetricsQPSField).asDouble(), object.field(deploymentMetricsWPSField).asDouble(), object.field(deploymentMetricsDocsField).asDouble(), object.field(deploymentMetricsQueryLatencyField).asDouble(), object.field(deploymentMetricsWriteLatencyField).asDouble(), instant, deploymentWarningsFrom(object.field(deploymentMetricsWarningsField))); } private Map<DeploymentMetrics.Warning, Integer> deploymentWarningsFrom(Inspector object) { Map<DeploymentMetrics.Warning, Integer> warnings = new HashMap<>(); object.traverse((ObjectTraverser) (name, value) -> warnings.put(DeploymentMetrics.Warning.valueOf(name), (int) value.asLong())); return Collections.unmodifiableMap(warnings); } private Map<HostName, RotationStatus> rotationStatusFromSlime(Inspector object) { if (!object.valid()) { return Collections.emptyMap(); } Map<HostName, RotationStatus> rotationStatus = new TreeMap<>(); object.traverse((ArrayTraverser) (idx, inspect) -> { HostName hostname = HostName.from(inspect.field("hostname").asString()); RotationStatus status = RotationStatus.valueOf(inspect.field("status").asString()); rotationStatus.put(hostname, status); }); return Collections.unmodifiableMap(rotationStatus); } private Map<ClusterSpec.Id, ClusterInfo> clusterInfoMapFromSlime (Inspector object) { Map<ClusterSpec.Id, ClusterInfo> map = new HashMap<>(); object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterInfoFromSlime(value))); return map; } private Map<ClusterSpec.Id, ClusterUtilization> clusterUtilsMapFromSlime(Inspector object) { Map<ClusterSpec.Id, ClusterUtilization> map = new HashMap<>(); object.traverse((String name, Inspector value) -> map.put(new ClusterSpec.Id(name), clusterUtililzationFromSlime(value))); return map; } private ClusterUtilization clusterUtililzationFromSlime(Inspector object) { double cpu = object.field(clusterUtilsCpuField).asDouble(); double mem = object.field(clusterUtilsMemField).asDouble(); double disk = object.field(clusterUtilsDiskField).asDouble(); double diskBusy = object.field(clusterUtilsDiskBusyField).asDouble(); return new ClusterUtilization(mem, cpu, disk, diskBusy); } private ClusterInfo clusterInfoFromSlime(Inspector inspector) { String flavor = inspector.field(clusterInfoFlavorField).asString(); int cost = (int)inspector.field(clusterInfoCostField).asLong(); String type = inspector.field(clusterInfoTypeField).asString(); double flavorCpu = inspector.field(clusterInfoCpuField).asDouble(); double flavorMem = inspector.field(clusterInfoMemField).asDouble(); double flavorDisk = inspector.field(clusterInfoDiskField).asDouble(); List<String> hostnames = new ArrayList<>(); inspector.field(clusterInfoHostnamesField).traverse((ArrayTraverser)(int index, Inspector value) -> hostnames.add(value.asString())); return new ClusterInfo(flavor, cost, flavorCpu, flavorMem, flavorDisk, ClusterSpec.Type.from(type), hostnames); } private ZoneId zoneIdFromSlime(Inspector object) { return ZoneId.from(object.field(environmentField).asString(), object.field(regionField).asString()); } private ApplicationVersion applicationVersionFromSlime(Inspector object) { if ( ! object.valid()) return ApplicationVersion.unknown; OptionalLong applicationBuildNumber = optionalLong(object.field(applicationBuildNumberField)); Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField)); if ( ! sourceRevision.isPresent() || ! applicationBuildNumber.isPresent()) { return ApplicationVersion.unknown; } Optional<String> authorEmail = optionalString(object.field(authorEmailField)); Optional<Version> compileVersion = optionalString(object.field(compileVersionField)).map(Version::fromString); Optional<Instant> buildTime = optionalInstant(object.field(buildTimeField)); if ( ! authorEmail.isPresent()) return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong()); if ( ! compileVersion.isPresent() || ! buildTime.isPresent()) return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get()); return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(), compileVersion.get(), buildTime.get()); } private Optional<SourceRevision> sourceRevisionFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new SourceRevision(object.field(repositoryField).asString(), object.field(branchField).asString(), object.field(commitField).asString())); } private DeploymentJobs deploymentJobsFromSlime(Inspector object) { OptionalLong projectId = optionalLong(object.field(projectIdField)); List<JobStatus> jobStatusList = jobStatusListFromSlime(object.field(jobStatusField)); Optional<IssueId> issueId = optionalString(object.field(issueIdField)).map(IssueId::from); boolean builtInternally = object.field(builtInternallyField).asBool(); return new DeploymentJobs(projectId, jobStatusList, issueId, builtInternally); } private Change changeFromSlime(Inspector object) { if ( ! object.valid()) return Change.empty(); Inspector versionFieldValue = object.field(versionField); Change change = Change.empty(); if (versionFieldValue.valid()) change = Change.of(Version.fromString(versionFieldValue.asString())); if (object.field(applicationBuildNumberField).valid()) change = change.with(applicationVersionFromSlime(object)); if (object.field(pinnedField).asBool()) change = change.withPin(); return change; } private List<JobStatus> jobStatusListFromSlime(Inspector array) { List<JobStatus> jobStatusList = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> jobStatusFromSlime(item).ifPresent(jobStatusList::add)); return jobStatusList; } private Optional<JobStatus> jobStatusFromSlime(Inspector object) { // if the job type has since been removed, ignore it Optional<JobType> jobType = JobType.fromOptionalJobName(object.field(jobTypeField).asString()); if (! jobType.isPresent()) return Optional.empty(); Optional<JobError> jobError = Optional.empty(); if (object.field(errorField).valid()) jobError = Optional.of(JobError.valueOf(object.field(errorField).asString())); return Optional.of(new JobStatus(jobType.get(), jobError, jobRunFromSlime(object.field(lastTriggeredField)), jobRunFromSlime(object.field(lastCompletedField)), jobRunFromSlime(object.field(firstFailingField)), jobRunFromSlime(object.field(lastSuccessField)), optionalLong(object.field(pausedUntilField)))); } private Optional<JobStatus.JobRun> jobRunFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new JobStatus.JobRun(object.field(jobRunIdField).asLong(), new Version(object.field(versionField).asString()), applicationVersionFromSlime(object.field(revisionField)), optionalString(object.field(sourceVersionField)).map(Version::fromString), Optional.of(object.field(sourceApplicationField)).filter(Inspector::valid).map(this::applicationVersionFromSlime), object.field(reasonField).asString(), Instant.ofEpochMilli(object.field(atField).asLong()))); } private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) { final var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>(); root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> { final var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString()); final var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString()); final var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString()); final var regions = deploymentSpec.endpoints().stream() .filter(endpoint -> endpoint.endpointId().equals(endpointId.id())) .flatMap(endpoint -> endpoint.regions().stream()) .collect(Collectors.toSet()); assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions)); }); return List.copyOf(assignedRotations.values()); } private OptionalLong optionalLong(Inspector field) { return field.valid() ? OptionalLong.of(field.asLong()) : OptionalLong.empty(); } private OptionalInt optionalInteger(Inspector field) { return field.valid() ? OptionalInt.of((int) field.asLong()) : OptionalInt.empty(); } private OptionalDouble optionalDouble(Inspector field) { return field.valid() ? OptionalDouble.of(field.asDouble()) : OptionalDouble.empty(); } private Optional<String> optionalString(Inspector field) { return SlimeUtils.optionalString(field); } private Optional<Instant> optionalInstant(Inspector field) { OptionalLong value = optionalLong(field); return value.isPresent() ? Optional.of(Instant.ofEpochMilli(value.getAsLong())) : Optional.empty(); } }
Simplify
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializer.java
Simplify
<ide><path>ontroller-server/src/main/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializer.java <ide> } <ide> <ide> private void rotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { <del> final var rotationsArray = parent.setArray(fieldName); <add> var rotationsArray = parent.setArray(fieldName); <ide> rotations.forEach(rot -> rotationsArray.addString(rot.rotationId().asString())); <ide> } <ide> <ide> private void assignedRotationsToSlime(List<AssignedRotation> rotations, Cursor parent, String fieldName) { <del> final var rotationsArray = parent.setArray(fieldName); <add> var rotationsArray = parent.setArray(fieldName); <ide> for (var rotation : rotations) { <del> final var object = rotationsArray.addObject(); <add> var object = rotationsArray.addObject(); <ide> object.setString(assignedRotationEndpointField, rotation.endpointId().id()); <ide> object.setString(assignedRotationRotationField, rotation.rotationId().asString()); <ide> object.setString(assignedRotationClusterField, rotation.clusterId().value()); <ide> if ( ! object.valid()) return ApplicationVersion.unknown; <ide> OptionalLong applicationBuildNumber = optionalLong(object.field(applicationBuildNumberField)); <ide> Optional<SourceRevision> sourceRevision = sourceRevisionFromSlime(object.field(sourceRevisionField)); <del> if ( ! sourceRevision.isPresent() || ! applicationBuildNumber.isPresent()) { <add> if (sourceRevision.isEmpty() || applicationBuildNumber.isEmpty()) { <ide> return ApplicationVersion.unknown; <ide> } <ide> Optional<String> authorEmail = optionalString(object.field(authorEmailField)); <ide> Optional<Version> compileVersion = optionalString(object.field(compileVersionField)).map(Version::fromString); <ide> Optional<Instant> buildTime = optionalInstant(object.field(buildTimeField)); <ide> <del> if ( ! authorEmail.isPresent()) <add> if (authorEmail.isEmpty()) <ide> return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong()); <ide> <del> if ( ! compileVersion.isPresent() || ! buildTime.isPresent()) <add> if (compileVersion.isEmpty() || buildTime.isEmpty()) <ide> return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get()); <ide> <ide> return ApplicationVersion.from(sourceRevision.get(), applicationBuildNumber.getAsLong(), authorEmail.get(), <ide> // if the job type has since been removed, ignore it <ide> Optional<JobType> jobType = <ide> JobType.fromOptionalJobName(object.field(jobTypeField).asString()); <del> if (! jobType.isPresent()) return Optional.empty(); <add> if (jobType.isEmpty()) return Optional.empty(); <ide> <ide> Optional<JobError> jobError = Optional.empty(); <ide> if (object.field(errorField).valid()) <ide> } <ide> <ide> private List<AssignedRotation> assignedRotationsFromSlime(DeploymentSpec deploymentSpec, Inspector root) { <del> final var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>(); <add> var assignedRotations = new LinkedHashMap<EndpointId, AssignedRotation>(); <ide> <ide> root.field(assignedRotationsField).traverse((ArrayTraverser) (idx, inspector) -> { <del> final var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString()); <del> final var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString()); <del> final var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString()); <del> final var regions = deploymentSpec.endpoints().stream() <del> .filter(endpoint -> endpoint.endpointId().equals(endpointId.id())) <del> .flatMap(endpoint -> endpoint.regions().stream()) <del> .collect(Collectors.toSet()); <add> var clusterId = new ClusterSpec.Id(inspector.field(assignedRotationClusterField).asString()); <add> var endpointId = EndpointId.of(inspector.field(assignedRotationEndpointField).asString()); <add> var rotationId = new RotationId(inspector.field(assignedRotationRotationField).asString()); <add> var regions = deploymentSpec.endpoints().stream() <add> .filter(endpoint -> endpoint.endpointId().equals(endpointId.id())) <add> .flatMap(endpoint -> endpoint.regions().stream()) <add> .collect(Collectors.toSet()); <ide> assignedRotations.putIfAbsent(endpointId, new AssignedRotation(clusterId, endpointId, rotationId, regions)); <ide> }); <ide>
Java
apache-2.0
4e7f837e24c39df46d8d2227d5ceda3bb84108f8
0
ios-driver/ios-driver,darraghgrace/ios-driver,azaytsev/ios-driver,seem-sky/ios-driver,masbog/ios-driver,adataylor/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,seem-sky/ios-driver,masbog/ios-driver,seem-sky/ios-driver,ios-driver/ios-driver,seem-sky/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,darraghgrace/ios-driver,adataylor/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,adataylor/ios-driver,adataylor/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,masbog/ios-driver,masbog/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,adataylor/ios-driver,ios-driver/ios-driver
/* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.uiautomation.ios; import com.beust.jcommander.JCommander; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.ServletContextHandler; import org.libimobiledevice.ios.driver.binding.raw.JNAInit; import org.openqa.selenium.WebDriverException; import org.uiautomation.ios.application.APPIOSApplication; import org.uiautomation.ios.application.MobileSafariLocator; import org.uiautomation.ios.command.configuration.Configuration; import org.uiautomation.ios.grid.SelfRegisteringRemote; import org.uiautomation.ios.inspector.IDEServlet; import org.uiautomation.ios.instruments.commandExecutor.CURLIAutomationCommandExecutor; import org.uiautomation.ios.servlet.ApplicationsServlet; import org.uiautomation.ios.servlet.ArchiveServlet; import org.uiautomation.ios.servlet.CapabilitiesServlet; import org.uiautomation.ios.servlet.DeviceServlet; import org.uiautomation.ios.servlet.IOSServlet; import org.uiautomation.ios.servlet.InstrumentsLogServlet; import org.uiautomation.ios.servlet.ResourceServlet; import org.uiautomation.ios.servlet.StaticResourceServlet; import org.uiautomation.ios.utils.BuildInfo; import org.uiautomation.ios.utils.FolderMonitor; import org.uiautomation.ios.utils.IOSVersion; import org.uiautomation.ios.utils.ZipUtils; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; public class IOSServer { public static final String DRIVER = IOSServerManager.class.getName(); private static final Logger log = Logger.getLogger(IOSServer.class.getName()); private final IOSServerConfiguration options; private boolean initialized = false; private Server server; private IOSServerManager driver; private FolderMonitor folderMonitor; private SelfRegisteringRemote selfRegisteringRemote; public IOSServer(IOSServerConfiguration options) { this.options = options; } public IOSServer(String[] args) { IOSServerConfiguration options = new IOSServerConfiguration(); new JCommander(options, args); this.options = options; } public static void main(String[] args) throws Exception { final IOSServer server = new IOSServer(args); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { server.stop(); } catch (Exception e) { e.printStackTrace(); } } }); try { server.start(); } catch (Exception e) { log.log(Level.SEVERE, "cannot start ios-driver server: " + e, e); Runtime.getRuntime().exit(1); } } private void init() { initialized = true; Configuration.BETA_FEATURE = options.isBeta(); Configuration.SIMULATORS_ENABLED = options.hasSimulators(); initDriver(); initServer(); } private void initDriver() { driver = new IOSServerManager(options); for (String app : this.options.getSupportedApps()) { File appFile = new File(app); if (Configuration.BETA_FEATURE && !appFile.exists()) { // if an url download and extract it try { URL u = new URL(app); appFile = ZipUtils.extractAppFromURL(u); } catch (IOException ignore) { log.fine("url: " + app + ": " + ignore); } } if (appFile == null || !appFile.exists()) { throw new WebDriverException(app + " isn't an IOS app."); } driver.addSupportedApplication(APPIOSApplication.createFrom(appFile)); } StringBuilder b = new StringBuilder(); b.append(String.format("\nBeta features enabled (enabled by -beta flag): %b", Configuration.BETA_FEATURE)); b.append(String.format("\nSimulator enabled : %b", Configuration.SIMULATORS_ENABLED)); b.append(String.format("\nInspector: http://0.0.0.0:%d/inspector/", options.getPort())); b.append(String.format("\nTests can access the server at http://0.0.0.0:%d/wd/hub", options.getPort())); b.append(String.format("\nServer status: http://0.0.0.0:%d/wd/hub/status", options.getPort())); b.append(String.format("\nConnected devices: http://0.0.0.0:%d/wd/hub/devices/all", options.getPort())); b.append(String.format("\nApplications: http://0.0.0.0:%d/wd/hub/applications/all", options.getPort())); b.append(String.format("\nCapabilities: http://0.0.0.0:%d/wd/hub/capabilities/all", options.getPort())); b.append( String.format("\nMonitoring '%s' for new applications", options.getAppFolderToMonitor())); b.append(String.format("\nArchived apps: %s", driver.getApplicationStore().getFolder().getAbsolutePath())); b.append("\nBuild info: " + BuildInfo.toBuildInfoString()); b.append("\nRunning on: " + driver.getHostInfo().getOSInfo()); b.append("\nUsing java: " + driver.getHostInfo().getJavaVersion()); if (Configuration.SIMULATORS_ENABLED) { addSimulatorDetails(b); } b.append("\n\nApplications :\n--------------- \n"); for (APPIOSApplication app : driver.getSupportedApplications()) { b.append("\t" + app + "\n"); } log.info(b.toString()); } private void addSimulatorDetails(StringBuilder b) { File xcodeInstall = driver.getHostInfo().getXCodeInstall(); String hostSDK = driver.getHostInfo().getSDK(); b.append(String.format("\nUsing Xcode install: %s", driver.getHostInfo().getXCodeInstall().getPath())); b.append( String.format("\nUsing instruments: %s", driver.getHostInfo().getInstrumentsVersion())); b.append(String.format("\nUsing iOS version %s", hostSDK)); boolean safari = false; // automatically add safari for host SDK and above as instruments starts simulator on host SDK version for (String s : driver.getHostInfo().getInstalledSDKs()) { IOSVersion version = new IOSVersion(s); if (version.isGreaterOrEqualTo("6.0")) { safari = true; driver.addSupportedApplication(MobileSafariLocator.locateSafariInstall(s)); } } if (safari) { b.append("\niOS >= 6.0. Safari and hybrid apps are supported."); } else { b.append("\niOS < 6.0. Safari and hybrid apps are NOT supported."); } } private void initServer() { String host = System.getProperty("ios-driver.host"); if (host == null) { host = "0.0.0.0"; } server = new Server(new InetSocketAddress(host, options.getPort())); ServletContextHandler wd = new ServletContextHandler(server, "/wd/hub", true, false); wd.addServlet(CURLIAutomationCommandExecutor.UIAScriptServlet.class, "/uiascriptproxy/*"); wd.addServlet(InstrumentsLogServlet.class, "/log/*"); wd.addServlet(IOSServlet.class, "/*"); wd.addServlet(ResourceServlet.class, "/resources/*"); wd.addServlet(DeviceServlet.class, "/devices/*"); wd.addServlet(ApplicationsServlet.class, "/applications/*"); wd.addServlet(CapabilitiesServlet.class, "/capabilities/*"); wd.addServlet(ArchiveServlet.class, "/archive/*"); wd.getServletContext().getContextHandler().setMaxFormContentSize(500000); wd.setAttribute(DRIVER, driver); ServletContextHandler statics = new ServletContextHandler(server, "/static", true, false); statics.addServlet(StaticResourceServlet.class, "/*"); ServletContextHandler extra = new ServletContextHandler(server, "/", true, false); extra.addServlet(IDEServlet.class, "/inspector/*"); for (String clazz : options.getServlets()) { try { Class c = Class.forName(clazz); String path = "/extra/" + c.getSimpleName() + "/*"; extra.addServlet(c, "/extra/" + c.getSimpleName() + "/*"); log.info("Servlet " + c + " visible @ " + path); } catch (ClassNotFoundException e) { throw new WebDriverException( "cannot plug servlet " + clazz + ". Cause : " + e.getMessage()); } } extra.setAttribute(DRIVER, driver); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{wd, statics, extra}); server.setHandler(handlers); } public static File getTmpIOSFolder() { File f = new File(System.getProperty("user.home") + "/.ios-driver/"); f.mkdirs(); return f; } public void start() throws Exception { if (!initialized) { JNAInit.init(); initialized = true; init(); } if (!server.isRunning()) { server.start(); } startFolderMonitor(); startHubRegistration(); } private void startFolderMonitor() { if (options.getAppFolderToMonitor() != null) { try { folderMonitor = new FolderMonitor(options, driver); folderMonitor.start(); } catch (IOException e) { log.warning("Couldn't monitor the given folder: " + options.getAppFolderToMonitor()); } } } private void startHubRegistration() { if (options.getRegistrationURL() != null) { selfRegisteringRemote = new SelfRegisteringRemote(options, driver); selfRegisteringRemote.start(); } } public void stop() throws Exception { if (!initialized) { return; } if (selfRegisteringRemote != null) { try { selfRegisteringRemote.stop(); selfRegisteringRemote = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (folderMonitor != null) { try { folderMonitor.stop(); folderMonitor = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (driver != null) { try { driver.stop(); driver = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (server != null) { try { server.stop(); server = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } } }
server/src/main/java/org/uiautomation/ios/IOSServer.java
/* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.uiautomation.ios; import com.beust.jcommander.JCommander; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.ServletContextHandler; import org.libimobiledevice.ios.driver.binding.raw.JNAInit; import org.openqa.selenium.WebDriverException; import org.uiautomation.ios.application.APPIOSApplication; import org.uiautomation.ios.application.MobileSafariLocator; import org.uiautomation.ios.command.configuration.Configuration; import org.uiautomation.ios.grid.SelfRegisteringRemote; import org.uiautomation.ios.inspector.IDEServlet; import org.uiautomation.ios.instruments.commandExecutor.CURLIAutomationCommandExecutor; import org.uiautomation.ios.servlet.ApplicationsServlet; import org.uiautomation.ios.servlet.ArchiveServlet; import org.uiautomation.ios.servlet.CapabilitiesServlet; import org.uiautomation.ios.servlet.DeviceServlet; import org.uiautomation.ios.servlet.IOSServlet; import org.uiautomation.ios.servlet.InstrumentsLogServlet; import org.uiautomation.ios.servlet.ResourceServlet; import org.uiautomation.ios.servlet.StaticResourceServlet; import org.uiautomation.ios.utils.BuildInfo; import org.uiautomation.ios.utils.FolderMonitor; import org.uiautomation.ios.utils.IOSVersion; import org.uiautomation.ios.utils.ZipUtils; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.logging.Level; import java.util.logging.Logger; public class IOSServer { public static final String DRIVER = IOSServerManager.class.getName(); private static final Logger log = Logger.getLogger(IOSServer.class.getName()); private final IOSServerConfiguration options; private boolean initialized = false; private Server server; private IOSServerManager driver; private FolderMonitor folderMonitor; private SelfRegisteringRemote selfRegisteringRemote; public IOSServer(IOSServerConfiguration options) { this.options = options; } public IOSServer(String[] args) { IOSServerConfiguration options = new IOSServerConfiguration(); new JCommander(options, args); this.options = options; } public static void main(String[] args) throws Exception { final IOSServer server = new IOSServer(args); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { server.stop(); } catch (Exception e) { e.printStackTrace(); } } }); try { server.start(); } catch (Exception e) { log.log(Level.SEVERE, "cannot start ios-driver server: " + e, e); Runtime.getRuntime().exit(1); } } private void init() { initialized = true; Configuration.BETA_FEATURE = options.isBeta(); Configuration.SIMULATORS_ENABLED = options.hasSimulators(); initDriver(); initServer(); } private void initDriver() { driver = new IOSServerManager(options); for (String app : this.options.getSupportedApps()) { File appFile = new File(app); if (Configuration.BETA_FEATURE && !appFile.exists()) { // if an url download and extract it try { // TODO freynaud ? appFile = ZipUtils.extractAppFromURL(null); } catch (IOException ignore) { log.fine("url: " + app + ": " + ignore); } } if (appFile == null || !appFile.exists()) { throw new WebDriverException(app + " isn't an IOS app."); } driver.addSupportedApplication(APPIOSApplication.createFrom(appFile)); } StringBuilder b = new StringBuilder(); b.append(String.format("\nBeta features enabled (enabled by -beta flag): %b", Configuration.BETA_FEATURE)); b.append(String.format("\nSimulator enabled : %b", Configuration.SIMULATORS_ENABLED)); b.append(String.format("\nInspector: http://0.0.0.0:%d/inspector/", options.getPort())); b.append(String.format("\nTests can access the server at http://0.0.0.0:%d/wd/hub", options.getPort())); b.append(String.format("\nServer status: http://0.0.0.0:%d/wd/hub/status", options.getPort())); b.append(String.format("\nConnected devices: http://0.0.0.0:%d/wd/hub/devices/all", options.getPort())); b.append(String.format("\nApplications: http://0.0.0.0:%d/wd/hub/applications/all", options.getPort())); b.append(String.format("\nCapabilities: http://0.0.0.0:%d/wd/hub/capabilities/all", options.getPort())); b.append( String.format("\nMonitoring '%s' for new applications", options.getAppFolderToMonitor())); b.append(String.format("\nArchived apps: %s", driver.getApplicationStore().getFolder().getAbsolutePath())); b.append("\nBuild info: " + BuildInfo.toBuildInfoString()); b.append("\nRunning on: " + driver.getHostInfo().getOSInfo()); b.append("\nUsing java: " + driver.getHostInfo().getJavaVersion()); if (Configuration.SIMULATORS_ENABLED) { addSimulatorDetails(b); } b.append("\n\nApplications :\n--------------- \n"); for (APPIOSApplication app : driver.getSupportedApplications()) { b.append("\t" + app + "\n"); } log.info(b.toString()); } private void addSimulatorDetails(StringBuilder b) { File xcodeInstall = driver.getHostInfo().getXCodeInstall(); String hostSDK = driver.getHostInfo().getSDK(); b.append(String.format("\nUsing Xcode install: %s", driver.getHostInfo().getXCodeInstall().getPath())); b.append( String.format("\nUsing instruments: %s", driver.getHostInfo().getInstrumentsVersion())); b.append(String.format("\nUsing iOS version %s", hostSDK)); boolean safari = false; // automatically add safari for host SDK and above as instruments starts simulator on host SDK version for (String s : driver.getHostInfo().getInstalledSDKs()) { IOSVersion version = new IOSVersion(s); if (version.isGreaterOrEqualTo("6.0")) { safari = true; driver.addSupportedApplication(MobileSafariLocator.locateSafariInstall(s)); } } if (safari) { b.append("\niOS >= 6.0. Safari and hybrid apps are supported."); } else { b.append("\niOS < 6.0. Safari and hybrid apps are NOT supported."); } } private void initServer() { String host = System.getProperty("ios-driver.host"); if (host == null) { host = "0.0.0.0"; } server = new Server(new InetSocketAddress(host, options.getPort())); ServletContextHandler wd = new ServletContextHandler(server, "/wd/hub", true, false); wd.addServlet(CURLIAutomationCommandExecutor.UIAScriptServlet.class, "/uiascriptproxy/*"); wd.addServlet(InstrumentsLogServlet.class, "/log/*"); wd.addServlet(IOSServlet.class, "/*"); wd.addServlet(ResourceServlet.class, "/resources/*"); wd.addServlet(DeviceServlet.class, "/devices/*"); wd.addServlet(ApplicationsServlet.class, "/applications/*"); wd.addServlet(CapabilitiesServlet.class, "/capabilities/*"); wd.addServlet(ArchiveServlet.class, "/archive/*"); wd.getServletContext().getContextHandler().setMaxFormContentSize(500000); wd.setAttribute(DRIVER, driver); ServletContextHandler statics = new ServletContextHandler(server, "/static", true, false); statics.addServlet(StaticResourceServlet.class, "/*"); ServletContextHandler extra = new ServletContextHandler(server, "/", true, false); extra.addServlet(IDEServlet.class, "/inspector/*"); for (String clazz : options.getServlets()) { try { Class c = Class.forName(clazz); String path = "/extra/" + c.getSimpleName() + "/*"; extra.addServlet(c, "/extra/" + c.getSimpleName() + "/*"); log.info("Servlet " + c + " visible @ " + path); } catch (ClassNotFoundException e) { throw new WebDriverException( "cannot plug servlet " + clazz + ". Cause : " + e.getMessage()); } } extra.setAttribute(DRIVER, driver); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{wd, statics, extra}); server.setHandler(handlers); } public static File getTmpIOSFolder() { File f = new File(System.getProperty("user.home") + "/.ios-driver/"); f.mkdirs(); return f; } public void start() throws Exception { if (!initialized) { JNAInit.init(); initialized = true; init(); } if (!server.isRunning()) { server.start(); } startFolderMonitor(); startHubRegistration(); } private void startFolderMonitor() { if (options.getAppFolderToMonitor() != null) { try { folderMonitor = new FolderMonitor(options, driver); folderMonitor.start(); } catch (IOException e) { log.warning("Couldn't monitor the given folder: " + options.getAppFolderToMonitor()); } } } private void startHubRegistration() { if (options.getRegistrationURL() != null) { selfRegisteringRemote = new SelfRegisteringRemote(options, driver); selfRegisteringRemote.start(); } } public void stop() throws Exception { if (!initialized) { return; } if (selfRegisteringRemote != null) { try { selfRegisteringRemote.stop(); selfRegisteringRemote = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (folderMonitor != null) { try { folderMonitor.stop(); folderMonitor = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (driver != null) { try { driver.stop(); driver = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } if (server != null) { try { server.stop(); server = null; } catch (Exception e) { log.warning("exception stopping: " + e); } } } }
A URL can be passed for apps
server/src/main/java/org/uiautomation/ios/IOSServer.java
A URL can be passed for apps
<ide><path>erver/src/main/java/org/uiautomation/ios/IOSServer.java <ide> import java.io.File; <ide> import java.io.IOException; <ide> import java.net.InetSocketAddress; <add>import java.net.URL; <ide> import java.util.logging.Level; <ide> import java.util.logging.Logger; <ide> <ide> if (Configuration.BETA_FEATURE && !appFile.exists()) { <ide> // if an url download and extract it <ide> try { <del> // TODO freynaud ? <del> appFile = ZipUtils.extractAppFromURL(null); <add> URL u = new URL(app); <add> appFile = ZipUtils.extractAppFromURL(u); <ide> } catch (IOException ignore) { <ide> log.fine("url: " + app + ": " + ignore); <ide> }
JavaScript
mit
1a681ec1d7e5341786e74eb6d3b700ffe373cf17
0
France-ioi/bebras-modules,France-ioi/bebras-modules
//"use strict"; var buzzerSound = { context: null, default_freq: 200, channels: {}, muted: {}, getContext: function() { if(!this.context) { this.context = ('AudioContext' in window) || ('webkitAudioContext' in window) ? new(window.AudioContext || window.webkitAudioContext)() : null; } return this.context; }, startOscillator: function(freq) { var o = this.context.createOscillator(); o.type = 'sine'; o.frequency.value = freq; o.connect(this.context.destination); o.start(); return o; }, start: function(channel, freq=this.default_freq) { if(!this.channels[channel]) { this.channels[channel] = { muted: false } } if(this.channels[channel].freq === freq) { return; } var context = this.getContext(); if(!context) { return; } this.stop(channel); if (freq == 0 || this.channels[channel].muted) { return; } this.channels[channel].oscillator = this.startOscillator(freq); this.channels[channel].freq = freq; }, stop: function(channel) { if(this.channels[channel]) { this.channels[channel].oscillator && this.channels[channel].oscillator.stop(); delete this.channels[channel].oscillator; delete this.channels[channel].freq; } }, mute: function(channel) { if(!this.channels[channel]) { this.channels[channel] = { muted: true } return; } this.channels[channel].muted = true; this.channels[channel].oscillator && this.channels[channel].oscillator.stop(); delete this.channels[channel].oscillator; }, unmute: function(channel) { if(!this.channels[channel]) { this.channels[channel] = { muted: false } return; } this.channels[channel].muted = false; if(this.channels[channel].freq) { this.channels[channel].oscillator = this.startOscillator(this.channels[channel].freq); } }, isMuted: function(channel) { if(this.channels[channel]) { return this.channels[channel].muted; } return false; }, stopAll: function() { for(var channel in this.channels) { if(this.channels.hasOwnProperty(channel)) { this.stop(channel); } } } } var gyroscope3D = (function() { var instance; function createInstance(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; // debug code start /* canvas.style.zIndex = 99999; canvas.style.position = 'fixed'; canvas.style.top = '0'; canvas.style.left = '0'; document.body.appendChild(canvas); */ // debug code end try { var renderer = new zen3d.Renderer(canvas, { antialias: true, alpha: true }); } catch(e) { return false; } renderer.glCore.state.colorBuffer.setClear(0, 0, 0, 0); var scene = new zen3d.Scene(); var lambert = new zen3d.LambertMaterial(); lambert.diffuse.setHex(0x468DDF); var cube_geometry = new zen3d.CubeGeometry(10, 2, 10); var cube = new zen3d.Mesh(cube_geometry, lambert); cube.position.x = 0; cube.position.y = 0; cube.position.z = 0; scene.add(cube); var ambientLight = new zen3d.AmbientLight(0xffffff, 2); scene.add(ambientLight); var pointLight = new zen3d.PointLight(0xffffff, 1, 100); pointLight.position.set(-20, 40, 10); scene.add(pointLight); var camera = new zen3d.Camera(); camera.position.set(0, 13, 13); camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0)); camera.setPerspective(45 / 180 * Math.PI, width / height, 1, 1000); scene.add(camera); return { resize: function(width, height) { camera.setPerspective( 45 / 180 * Math.PI, width / height, 1, 1000 ); }, render: function(ax, ay, az) { cube.euler.x = Math.PI * ax / 360; cube.euler.y = Math.PI * ay / 360; cube.euler.z = Math.PI * az / 360; renderer.render(scene, camera); return canvas; } } } return { getInstance: function(width, height) { if(!instance) { instance = createInstance(width, height); } else { instance.resize(width, height) } return instance; } } })(); function QuickStore(rwidentifier, rwpassword) { var url = 'http://cloud.quick-pi.org'; var connected = (rwidentifier === undefined); function post(path, data, callback) { $.ajax({ type: 'POST', url: url + path, crossDomain: true, data: data, dataType: 'json', success: callback }); } return { connected: rwpassword, read: function(identifier, key, callback) { var data = { prefix: identifier, key: key }; post('/api/data/read', data, callback); }, write: function(identifier, key, value, callback) { if (identifier != rwidentifier) { callback({ sucess: false, message: "Tried to write to read/only identifier", }); } else { var data = { prefix: identifier, password: rwpassword, key: key, value: JSON.stringify(value) }; post('/api/data/write', data, callback); } } } } // This is a template of library for use with quickAlgo. var getContext = function (display, infos, curLevel) { window.quickAlgoInterface.stepDelayMin = 0.0001; // Local language strings for each language var introControls = null; var localLanguageStrings = { fr: { // French strings label: { // Labels for the blocks sleep: "attendre %1 millisecondes", currentTime: "temps écoulé en millisecondes", turnLedOn: "allumer la LED", turnLedOff: "éteindre la LED", setLedState: "passer la LED %1 à %2 ", toggleLedState: "inverser la LED %1", isLedOn: "LED allumée", isLedOnWithName: "LED %1 allumée", setLedBrightness: "mettre la luminosité de %1 à %2", getLedBrightness: "lire la luminosité de %1", turnBuzzerOn: "allumer le buzzer", turnBuzzerOff: "éteindre le buzzer", setBuzzerState: "mettre le buzzer %1 à %2", isBuzzerOn: "buzzer allumé", isBuzzerOnWithName: "buzzer %1 allumé", setBuzzerNote: "jouer la fréquence %2Hz sur %1", getBuzzerNote: "fréquence du buzzer %1", isButtonPressed: "bouton enfoncé", isButtonPressedWithName: "bouton %1 enfoncé", waitForButton: "attendre une pression sur le bouton", buttonWasPressed: "le bouton a été enfoncé", displayText: "afficher %1", displayText2Lines: "afficher Ligne 1: %1 Ligne 2: %2", readTemperature: "température ambiante", getTemperature: "temperature de %1", readRotaryAngle: "état du potentiomètre %1", readDistance: "distance mesurée par %1", readLightIntensity: "intensité lumineuse", readHumidity: "humidité ambiante", setServoAngle: "mettre le servo %1 à l'angle %2", getServoAngle: "angle du servo %1", drawPoint: "draw pixel", isPointSet: "is pixel set in screen", drawLine: "ligne x₀: %1 y₀: %2 x₁: %3 y₁: %4", drawRectangle: "rectangle x₀: %1 y₀: %2 largeur₀: %3 hauteur₀: %4", drawCircle: "cercle x₀: %1 y₀: %2 diamètre₀: %3", clearScreen: "effacer tout l'écran", updateScreen: "mettre à jour l'écran", autoUpdate: "mode de mise à jour automatique de l'écran", fill: "mettre la couleur de fond à %1", noFill: "ne pas remplir les formes", stroke: "mettre la couleur de tracé à %1", noStroke: "ne pas dessiner les contours", readAcceleration: "accélération en (m/s²) dans l'axe %1", computeRotation: "compute rotation from accelerometer (°) %1", readSoundLevel: "volume sonore", readMagneticForce: "read Magnetic Force (µT) %1", computeCompassHeading: "compute Compass Heading (°)", readInfraredState: "read Infrared Receiver State %1", setInfraredState: "set Infrared transmiter State %1", // Gyroscope readAngularVelocity: "read angular velocity (°/s) %1", setGyroZeroAngle: "set the gyroscope zero point", computeRotationGyro: "compute rotation in the gyroscope %1", //Internet store connectToCloudStore: "Se connecter au cloud. Identifiant %1 Mot de passe %2", writeToCloudStore: "Écrire dans le cloud. Identifiant %1 Clé %2 Valeur %3", readFromCloudStore: "Lire dans le cloud. Identifiant %1 Clé %2", }, code: { // Names of the functions in Python, or Blockly translated in JavaScript turnLedOn: "turnLedOn", turnLedOff: "turnLedOff", setLedState: "setLedState", isButtonPressed: "isButtonPressed", isButtonPressedWithName : "isButtonPressed", waitForButton: "waitForButton", buttonWasPressed: "buttonWasPressed", toggleLedState: "toggleLedState", displayText: "displayText", displayText2Lines: "displayText", readTemperature: "readTemperature", sleep: "sleep", setServoAngle: "setServoAngle", readRotaryAngle: "readRotaryAngle", readDistance: "readDistance", readLightIntensity: "readLightIntensity", readHumidity: "readHumidity", currentTime: "currentTime", getTemperature: "getTemperature", isLedOn: "isLedOn", isLedOnWithName: "isLedOn", setBuzzerNote: "setBuzzerNote", getBuzzerNote: "getBuzzerNote", setLedBrightness: "setLedBrightness", getLedBrightness: "getLedBrightness", getServoAngle: "getServoAngle", setBuzzerState: "setBuzzerState", setBuzzerNote: "setBuzzerNote", turnBuzzerOn: "turnBuzzerOn", turnBuzzerOff: "turnBuzzerOff", isBuzzerOn: "isBuzzerOn", isBuzzerOnWithName: "isBuzzerOn", drawPoint: "drawPoint", isPointSet: "isPointSet", drawLine: "drawLine", drawRectangle: "drawRectangle", drawCircle: "drawCircle", clearScreen: "clearScreen", updateScreen: "updateScreen", autoUpdate: "autoUpdate", fill: "fill", noFill: "noFill", stroke: "stroke", noStroke: "noStroke", readAcceleration: "readAcceleration", computeRotation: "computeRotation", readSoundLevel: "readSoundLevel", readMagneticForce: "readMagneticForce", computeCompassHeading: "computeCompassHeading", readInfraredState: "readInfraredState", setInfraredState: "setInfraredState", // Gyroscope readAngularVelocity: "readAngularVelocity", setGyroZeroAngle: "setGyroZeroAngle", computeRotationGyro: "computeRotationGyro", //Internet store connectToCloudStore: "connectToCloudStore", writeToCloudStore: "writeToCloudStore", readFromCloudStore: "readFromCloudStore", }, description: { // Descriptions of the functions in Python (optional) turnLedOn: "turnLedOn() allume la LED", turnLedOff: "turnLedOff() éteint la LED", isButtonPressed: "isButtonPressed() retourne True si le bouton est enfoncé, False sinon", isButtonPressedWithName: "isButtonPressed(button) retourne True si le bouton est enfoncé, False sinon", waitForButton: "waitForButton(button) met en pause l'exécution jusqu'à ce que le bouton soit appuyé", buttonWasPressed: "buttonWasPressed(button) indique si le bouton a été appuyé depuis le dernier appel à cette fonction", setLedState: "setLedState(led, state) modifie l'état de la LED : True pour l'allumer, False pour l'éteindre", toggleLedState: "toggleLedState(led) inverse l'état de la LED", displayText: "displayText(line1, line2) affiche une ou deux lignes de texte. line2 est optionnel", displayText2Lines: "displayText(line1, line2) affiche une ou deux lignes de texte. line2 est optionnel", readTemperature: "readTemperature(thermometer) retourne la température ambiante", sleep: "sleep(milliseconds) met en pause l'exécution pendant une durée en ms", setServoAngle: "setServoAngle(servo, angle) change l'angle du servomoteur", readRotaryAngle: "readRotaryAngle(potentiometer) retourne la position potentiomètre", readDistance: "readDistance(distanceSensor) retourne la distance mesurée", readLightIntensity: "readLightIntensity(lightSensor) retourne l'intensité lumineuse", readHumidity: "readHumidity(hygrometer) retourne l'humidité ambiante", currentTime: "currentTime(milliseconds) temps en millisecondes depuis le début du programme", setLedBrightness: "setLedBrightness(led, brightness) règle l'intensité lumineuse de la LED", getLedBrightness: "getLedBrightness(led) retourne l'intensité lumineuse de la LED", getServoAngle: "getServoAngle(servo) retourne l'angle du servomoteur", isLedOn: "isLedOn() retourne True si la LED est allumée, False si elle est éteinte", isLedOnWithName: "isLedOn(led) retourne True si la LED est allumée, False sinon", turnBuzzerOn: "turnBuzzerOn() allume le buzzer", turnBuzzerOff: "turnBuzzerOff() éteint le buzzer", isBuzzerOn: "isBuzzerOn() retourne True si le buzzer est allumé, False sinon", isBuzzerOnWithName: "isBuzzerOn(buzzer) retourne True si le buzzer est allumé, False sinon", setBuzzerState: "setBuzzerState(buzzer, state) modifie l'état du buzzer: True pour allumé, False sinon", setBuzzerNote: "setBuzzerNote(buzzer, frequency) fait sonner le buzzer à la fréquence indiquée", getBuzzerNote: "getBuzzerNote(buzzer) retourne la fréquence actuelle du buzzer", getTemperature: "getTemperature(thermometer) ", drawPoint: "drawPoint(x, y)", isPointSet: "isPointSet(x, y)", drawLine: "drawLine(x0, y0, x1, y1)", drawRectangle: "drawRectangle(x0, y0, width, height)", drawCircle: "drawCircle(x0, y0, diameter)", clearScreen: "clearScreen()", updateScreen: "updateScreen()", autoUpdate: "autoUpdate(auto)", fill: "fill(color)", noFill: "noFill()", stroke: "stroke(color)", noStroke: "noStroke()", readAcceleration: "readAcceleration(axis)", computeRotation: "computeRotation()", readSoundLevel: "readSoundLevel(port)", readMagneticForce: "readMagneticForce(axis)", computeCompassHeading: "computeCompassHeading()", readInfraredState: "readInfraredState()", setInfraredState: "setInfraredState()", // Gyroscope readAngularVelocity: "readAngularVelocity()", setGyroZeroAngle: "setGyroZeroAngle()", computeRotationGyro: "computeRotationGyro()", //Internet store connectToCloudStore: "connectToCloudStore(identifier, password)", writeToCloudStore: "writeToCloudStore(identifier, key, value)", readFromCloudStore: "readFromCloudStore(identifier, key)", }, constant: { }, startingBlockName: "Programme", // Name for the starting block messages: { sensorNotFound: "Accès à un capteur ou actuateur inexistant : {0}.", manualTestSuccess: "Test automatique validé.", testSuccess: "Bravo ! La sortie est correcte", wrongState: "Test échoué : {0} a été dans l'état {1} au lieu de {2} à t={3}ms.", wrongStateDrawing: "Test échoué : {0} diffère de {1} pixels par rapport à l'affichage attendu à t={2}ms.", wrongStateSensor: "Test échoué : votre programme n'a pas lu l'état de {0} après t={1}ms.", programEnded: "programme terminé.", piPlocked: "L'appareil est verrouillé. Déverrouillez ou redémarrez.", cantConnect: "Impossible de se connecter à l'appareil.", wrongVersion: "Votre Raspberry Pi a une version trop ancienne, mettez le à jour.", sensorInOnlineMode: "Vous ne pouvez pas agir sur les capteurs en mode connecté.", actuatorsWhenRunning: "Impossible de modifier les actionneurs lors de l'exécution d'un programme", cantConnectoToUSB: 'Tentative de connexion par USB en cours, veuillez brancher votre Raspberry sur le port USB <i class="fas fa-circle-notch fa-spin"></i>', cantConnectoToBT: 'Tentative de connection par Bluetooth, veuillez connecter votre appareil au Raspberry par Bluetooth <i class="fas fa-circle-notch fa-spin"></i>', canConnectoToUSB: "Connecté en USB.", canConnectoToBT: "Connecté en Bluetooth.", noPortsAvailable: "Aucun port compatible avec ce {0} n'est disponible (type {1})", sensor: "capteur", actuator: "actionneur", removeConfirmation: "Êtes-vous certain de vouloir retirer ce capteur ou actuateur?", remove: "Retirer", keep: "Garder", minutesago: "Last seen {0} minutes ago", hoursago: "Last seen more than one hour ago", drawing: "dessin", connectionHTML: ` <div id="piui"> <button type="button" id="piconnect" class="btn"> <span class="fa fa-wifi"></span><span id="piconnecttext" class="btnText">Connecter</span> <span id="piconnectprogress" class="fas fa-spinner fa-spin"></span> </button> <span id="piinstallui"> <span class="fa fa-exchange-alt"></span> <button type="button" id="piinstall" class="btn"> <span class="fa fa-upload"></span><span>Installer</span><span id=piinstallprogresss class="fas fa-spinner fa-spin"></span><span id="piinstallcheck" class="fa fa-check"></span> </button> </span> <span id="pichangehatui"> <button type="button" id="pichangehat" class="btn"> <span class="fas fa-hat-wizard"></span><span>Changer de carte</span></span></span> </button> <button type="button" id="pihatsetup" class="btn"> <span class="fas fa-cog"></span><span>Config</span></span></span> </button> </span> </div>`, connectionDialogHTML: ` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Configuration du Raspberry Pi </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div id="piconnectionmainui"> <div class="switchRadio btn-group" id="piconsel"> <button type="button" class="btn active" id="piconwifi"><i class="fa fa-wifi icon"></i>WiFi</button> <button type="button" class="btn" id="piconusb"><i class="fab fa-usb icon"></i>USB</button> <button type="button" class="btn" id="piconbt"><i class="fab fa-bluetooth-b icon"></i>Bluetooth</button> </div> <div id="pischoolcon"> <div class="form-group"> <label id="pischoolkeylabel">Indiquez un identifiant d'école</label> <div class="input-group"> <div class="input-group-prepend">Aa</div> <input type="text" id="schoolkey" class="form-control"> </div> </div> <div class="form-group"> <label id="pilistlabel">Sélectionnez un appareil à connecter dans la liste suivante</label> <div class="input-group"> <button class="input-group-prepend" id=pigetlist disabled>Obtenir la liste</button> <select id="pilist" class="custom-select" disabled> </select> </div> </div> <div class="form-group"> <label id="piiplabel">ou entrez son adesse IP</label> <div class="input-group"> <div class="input-group-prepend">123</div> <input id=piaddress type="text" class="form-control"> </div> </div> <div> <input id="piusetunnel" disabled type="checkbox">Connecter à travers le France-ioi tunnel </div> </div> <div panel-body-usbbt> <label id="piconnectionlabel"></label> </div> </div> <div class="inlineButtons"> <button id="piconnectok" class="btn"><i class="fa fa-wifi icon"></i>Connecter l'appareil</button> <button id="pirelease" class="btn"><i class="fa fa-times icon"></i>Déconnecter</button> </div> </div> </div> `, stickPortsDialog: ` <div class="content qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Stick names and port </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div id="sensorPicker" class="panel-body"> <label></label> <div class="flex-container"> <table style="display:table-header-group;"> <tr> <th>Name</th> <th>Port</th> <th>State</th> <th>Direction</th> </tr> <tr> <td><label id="stickupname"></td><td><label id="stickupport"></td><td><label id="stickupstate"></td><td><label id="stickupdirection"><i class="fas fa-arrow-up"></i></td> </tr> <tr> <td><label id="stickdownname"></td><td><label id="stickdownport"></td><td><label id="stickdownstate"></td><td><label id="stickdowndirection"><i class="fas fa-arrow-down"></i></td> </tr> <tr> <td><label id="stickleftname"></td><td><label id="stickleftport"></td><td><label id="stickleftstate"></td><td><label id="stickleftdirection"><i class="fas fa-arrow-left"></i></td> </tr> <tr> <td><label id="stickrightname"></td><td><label id="stickrightport"></td><td><label id="stickrightstate"></td><td><label id="stickrightdirection"><i class="fas fa-arrow-right"></i></td> </tr> <tr> <td><label id="stickcentername"></td><td><label id="stickcenterport"></td><td><label id="stickcenterstate"></td><td><label id="stickcenterdirection"><i class="fas fa-circle"></i></td> </tr> </table> </div> </div> <div class="singleButton"> <button id="picancel2" class="btn btn-centered"><i class="icon fa fa-check"></i>Fermer</button> </div> </div> `, } }, none: { comment: { // Comments for each block, used in the auto-generated documentation for task writers turnLedOn: "Turns on a light connected to Raspberry", turnLedOff: "Turns off a light connected to Raspberry", isButtonPressed: "Returns the state of a button, Pressed means True and not pressed means False", waitForButton: "Stops program execution until a button is pressed", buttonWasPressed: "Returns true if the button has been pressed and will clear the value", setLedState: "Change led state in the given port", toggleLedState: "If led is on, turns it off, if it's off turns it on", isButtonPressedWithName: "Returns the state of a button, Pressed means True and not pressed means False", displayText: "Display text in LCD screen", displayText2Lines: "Display text in LCD screen (two lines)", readTemperature: "Read Ambient temperature", sleep: "pause program execute for a number of seconds", setServoAngle: "Set servo motor to an specified angle", readRotaryAngle: "Read state of potentiometer", readDistance: "Read distance using ultrasonic sensor", readLightIntensity: "Read light intensity", readHumidity: "lire l'humidité ambiante", currentTime: "returns current time", setBuzzerState: "sonnerie", setBuzzerNote: "sonnerie note", getTemperature: "Get temperature", setBuzzerNote: "Set buzzer note", getBuzzerNote: "Get buzzer note", setLedBrightness: "Set Led Brightness", getLedBrightness: "Get Led Brightness", getServoAngle: "Get Servo Angle", isLedOn: "Get led state", isLedOnWithName: "Get led state", turnBuzzerOn: "Turn Buzzer on", turnBuzzerOff: "Turn Buzzer off", isBuzzerOn: "Is Buzzer On", isBuzzerOnWithName: "get buzzer state", drawPoint: "drawPoint", isPointSet: "isPointSet", drawLine: "drawLine", drawRectangle: "drawRectangle", drawCircle: "drawCircle", clearScreen: "clearScreen", updateScreen: "updateScreen", autoUpdate: "autoUpdate", fill: "fill", noFill: "noFill", stroke: "stroke", noStroke: "noStroke", readAcceleration: "readAcceleration", computeRotation: "computeRotation", readSoundLevel: "readSoundLevel", readMagneticForce: "readMagneticForce", computeCompassHeading: "computeCompassHeading", readInfraredState: "readInfraredState", setInfraredState: "setInfraredState", // Gyroscope readAngularVelocity: "readAngularVelocity", setGyroZeroAngle: "setGyroZeroAngle", computeRotationGyro: "computeRotationGyro", //Internet store connectToCloudStore: "connectToCloudStore", writeToCloudStore: "writeToCloudStore", readFromCloudStore: "readFromCloudStore", } } } // Create a base context var context = quickAlgoContext(display, infos); // Import our localLanguageStrings into the global scope var strings = context.setLocalLanguageStrings(localLanguageStrings); // Some data can be made accessible by the library through the context object context.quickpi = {}; // List of concepts to be included by conceptViewer context.conceptList = [ {id: 'language', ignore: true}, { id: 'quickpi_start', name: 'Créer un programme', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_start', language: 'all', isBase: true, order: 1, python: [] }, { id: 'quickpi_validation', name: 'Valider son programme', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_validation', language: 'all', isBase: true, order: 2, python: [] }, { id: 'quickpi_buzzer', name: 'Buzzer', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_buzzer', language: 'all', order: 200, python: ['setBuzzerState', 'setBuzzerNote','turnBuzzerOn','turnBuzzerOff'] }, { id: 'quickpi_led', name: 'LEDs', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_led', language: 'all', order: 201, python: ['setLedState','toggleLedState','turnLedOn','turnLedOff'] }, { id: 'quickpi_button', name: 'Boutons et manette', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_button', language: 'all', order: 202, python: ['isButtonPressed', 'isButtonPressedWithName'] }, { id: 'quickpi_screen', name: 'Écran', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_screen', language: 'all', order: 203, python: ['displayText'] }, { id: 'quickpi_range', name: 'Capteur de distance', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_range', language: 'all', order: 204, python: ['readDistance'] }, { id: 'quickpi_servo', name: 'Servomoteur', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_servo', language: 'all', order: 205, python: ['setServoAngle', 'getServoAngle'] }, { id: 'quickpi_thermometer', name: 'Thermomètre', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_thermometer', language: 'all', order: 206, python: ['readTemperature'] }, { id: 'quickpi_microphone', name: 'Microphone', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_microphone', language: 'all', order: 207, python: ['readSoundLevel'] }, { id: 'quickpi_light_sensor', name: 'Capteur de luminosité', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_light_sensor', language: 'all', order: 208, python: ['readLightIntensity'] }, { id: 'quickpi_accelerometer', name: 'Accéléromètre', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_accelerometer', language: 'all', order: 209, python: ['readAcceleration'] }, { id: 'quickpi_wait', name: 'Gestion du temps', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_wait', language: 'all', order: 250, python: ['sleep'] }, { id: 'quickpi_cloud', name: 'Stockage dans le cloud', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_cloud', language: 'all', order: 250, python: ['writeToCloudStore','connectToCloudStore','readFromCloudStore'] } ]; var boardDefinitions = [ { name: "grovepi", friendlyName: "Grove Base Hat for Raspberry Pi", image: "grovepihat.png", adc: "grovepi", portTypes: { "D": [5, 16, 18, 22, 24, 26], "A": [0, 2, 4, 6], "i2c": ["i2c"], }, default: [ { type: "screen", suggestedName: "screen1", port: "i2c", subType: "16x2lcd" }, { type: "led", suggestedName: "led1", port: 'D5', subType: "blue" }, { type: "servo", suggestedName: "servo1", port: "D16" }, { type: "range", suggestedName: "range1", port :"D18", subType: "ultrasonic"}, { type: "button", suggestedName: "button1", port: "D22" }, { type: "humidity", suggestedName: "humidity1", port: "D24"}, { type: "buzzer", suggestedName: "buzzer1", port: "D26", subType: "active"}, { type: "temperature", suggestedName: "temperature1", port: 'A0', subType: "groveanalog" }, { type: "potentiometer", suggestedName: "potentiometer1", port :"A4"}, { type: "light", suggestedName: "light1", port :"A6"}, ] }, { name: "quickpi", friendlyName: "France IOI QuickPi Hat", image: "quickpihat.png", adc: "ads1015", portTypes: { "D": [5, 16, 24], "A": [0], }, builtinSensors: [ { type: "screen", subType: "oled128x32", port: "i2c", suggestedName: "screen1", }, { type: "led", subType: "red", port: "D4", suggestedName: "led1", }, { type: "led", subType: "green", port: "D17", suggestedName: "led2", }, { type: "led", subType: "blue", port: "D27", suggestedName: "led3", }, { type: "irtrans", port: "D22", suggestedName: "infraredtransmiter1", }, { type: "irrecv", port: "D23", suggestedName: "infraredreceiver1", }, { type: "sound", port: "A1", suggestedName: "microphone1", }, { type: "buzzer", subType: "passive", port: "D12", suggestedName: "buzzer1", }, { type: "accelerometer", subType: "BMI160", port: "i2c", suggestedName: "accelerometer1", }, { type: "gyroscope", subType: "BMI160", port: "i2c", suggestedName: "gryscope1", }, { type: "magnetometer", subType: "LSM303C", port: "i2c", suggestedName: "magnetometer1", }, { type: "temperature", subType: "BMI160", port: "i2c", suggestedName: "temperature1", }, { type: "range", subType: "vl53l0x", port: "i2c", suggestedName: "distance1", }, { type: "button", port: "D26", suggestedName: "button1", }, { type: "light", port: "A2", suggestedName: "light1", }, { type: "stick", port: "D7", suggestedName: "stick1", } ], }, { name: "pinohat", image: "pinohat.png", friendlyName: "Raspberry Pi without hat", adc: ["ads1015", "none"], portTypes: { "D": [5, 16, 24], "A": [0], "i2c": ["i2c"], }, } ] var sensorDefinitions = [ /******************************** */ /* Actuators */ /**********************************/ { name: "led", description: "LED", isAnalog: false, isSensor: false, portType: "D", getInitialState: function (sensor) { return false; }, selectorImages: ["ledon-red.png"], valueType: "boolean", pluggable: true, getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setLedState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { return state ? "ON" : "OFF"; }, subTypes: [{ subType: "blue", description: "LED bleue", selectorImages: ["ledon-blue.png"], suggestedName: "blueled", }, { subType: "green", description: "LED verte", selectorImages: ["ledon-green.png"], suggestedName: "greenled", }, { subType: "orange", description: "LED orange", selectorImages: ["ledon-orange.png"], suggestedName: "orangeled", }, { subType: "red", description: "LED rouge", selectorImages: ["ledon-red.png"], suggestedName: "redled", } ], }, { name: "buzzer", description: "Buzzer", isAnalog: false, isSensor: false, getInitialState: function(sensor) { return false; }, portType: "D", selectorImages: ["buzzer-ringing.png"], valueType: "boolean", getPercentageFromState: function (state, sensor) { if (sensor.showAsAnalog) { return (state - sensor.minAnalog) / (sensor.maxAnalog - sensor.minAnalog); } else { if (state) return 1; else return 0; } }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setBuzzerState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { if(typeof state == 'number' && state != 1 && state != 0) { return state.toString() + "Hz"; } return state ? "ON" : "OFF"; }, subTypes: [{ subType: "active", description: "Grove Buzzer", pluggable: true, }, { subType: "passive", description: "Quick Pi Passive Buzzer", }], }, { name: "servo", description: "Servo motor", isAnalog: true, isSensor: false, getInitialState: function(sensor) { return 0; }, portType: "D", valueType: "number", pluggable: true, valueMin: 0, valueMax: 180, selectorImages: ["servo.png", "servo-pale.png", "servo-center.png"], getPercentageFromState: function (state) { return state / 180; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 180); }, setLiveState: function (sensor, state, callback) { var command = "setServoAngle(\"" + sensor.name + "\"," + state + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { return "" + state + "°"; } }, { name: "screen", description: "Screen", isAnalog: false, isSensor: false, getInitialState: function(sensor) { if (sensor.isDrawingScreen) return null; else return {line1: "", line2: ""}; }, cellsAmount: function(paper) { if(context.board == 'grovepi') { return 2; } if(paper.width < 250) { return 4; } else if(paper.width < 350) { return 3; } return 2; }, portType: "i2c", valueType: "object", selectorImages: ["screen.png"], compareState: function (state1, state2) { // Both are null are equal if (state1 == null && state2 == null) return true; // If only one is null they are different if ((state1 == null && state2) || (state1 && state2 == null)) return false; if (state1.isDrawingData != state2.isDrawingData) return false; if (state1 && state1.isDrawingData) { // They are ImageData objects // The image data is RGBA so there are 4 bits per pixel var data1 = state1.getData(1).data; var data2 = state2.getData(1).data; for (var i = 0; i < data1.length; i+=4) { if (data1[i] != data2[i] || data1[i + 1] != data2[i + 1] || data1[i + 2] != data2[i + 2] || data1[i + 3] != data2[i + 3]) return false; } return true; } else { // Otherwise compare the strings return (state1.line1 == state2.line1) && ((state1.line2 == state2.line2) || (!state1.line2 && !state2.line2)); } }, setLiveState: function (sensor, state, callback) { var line2 = state.line2; if (!line2) line2 = ""; var command = "displayText(\"" + sensor.name + "\"," + state.line1 + "\", \"" + line2 + "\")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { if(!state) { return '""'; } if (state.isDrawingData) return strings.messages.drawing; else return '"' + state.line1 + (state.line2 ? " / " + state.line2 : "") + '"'; }, getWrongStateString: function(failInfo) { if(!failInfo.expected || !failInfo.expected.isDrawingData || !failInfo.actual || !failInfo.actual.isDrawingData) { return null; // Use default message } var data1 = failInfo.expected.getData(1).data; var data2 = failInfo.actual.getData(1).data; var nbDiff = 0; for (var i = 0; i < data1.length; i+=4) { if(data1[i] != data2[i]) { nbDiff += 1; } } return strings.messages.wrongStateDrawing.format(failInfo.name, nbDiff, failInfo.time); }, subTypes: [{ subType: "16x2lcd", description: "Grove 16x2 LCD", pluggable: true, }, { subType: "oled128x32", description: "128x32 Oled Screen", }], }, { name: "irtrans", description: "IR Transmiter", isAnalog: true, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["irtranson.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setInfraredState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, }, /******************************** */ /* sensors */ /**********************************/ { name: "button", description: "Button", isAnalog: false, isSensor: true, portType: "D", valueType: "boolean", pluggable: true, selectorImages: ["buttonoff.png"], getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("buttonStateInPort(\"" + sensor.name + "\")", function (retVal) { var intVal = parseInt(retVal, 10); callback(intVal != 0); }); }, }, { name: "stick", description: "5 way button", isAnalog: false, isSensor: true, portType: "D", valueType: "boolean", selectorImages: ["stick.png"], gpiosNames: ["up", "down", "left", "right", "center"], gpios: [10, 9, 11, 8, 7], getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, compareState: function (state1, state2) { if (state1 == null && state2 == null) return true; return state1[0] == state2[0] && state1[1] == state2[1] && state1[2] == state2[2] && state1[3] == state2[3] && state1[4] == state2[4]; }, getLiveState: function (sensor, callback) { var cmd = "readStick(" + this.gpios.join() + ")"; context.quickPiConnection.sendCommand("readStick(" + this.gpios.join() + ")", function (retVal) { var array = JSON.parse(retVal); callback(array); }); }, getButtonState: function(buttonname, state) { if (state) { var buttonparts = buttonname.split("."); var actualbuttonmame = buttonname; if (buttonparts.length == 2) { actualbuttonmame = buttonparts[1]; } var index = this.gpiosNames.indexOf(actualbuttonmame); if (index >= 0) { return state[index]; } } return false; } }, { name: "temperature", description: "Temperature sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["temperature-hot.png", "temperature-overlay.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readTemperature(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, subTypes: [{ subType: "groveanalog", description: "Grove Analog tempeature sensor", portType: "A", pluggable: true, }, { subType: "BMI160", description: "Quick Pi Accelerometer+Gyroscope temperature sensor", portType: "i2c", }, { subType: "DHT11", description: "DHT11 Tempeature Sensor", portType: "D", pluggable: true, }], }, { name: "potentiometer", description: "Potentiometer", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["potentiometer.png", "potentiometer-pale.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readRotaryAngle(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "light", description: "Light sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["light.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readLightIntensity(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "range", description: "Capteur de distance", isAnalog: true, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 5000, selectorImages: ["range.png"], getPercentageFromState: function (state) { return state / 500; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 500); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readDistance(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, subTypes: [{ subType: "vl53l0x", description: "Time of flight distance sensor", portType: "i2c", }, { subType: "ultrasonic", description: "Capteur de distance à ultrason", portType: "D", pluggable: true, }], }, { name: "humidity", description: "Humidity sensor", isAnalog: true, isSensor: true, portType: "D", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["humidity.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readHumidity(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "sound", description: "Sound sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["sound.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readSoundLevel(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "accelerometer", description: "Accelerometer sensor (BMI160)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, step: 0.1, selectorImages: ["accel.png"], getStateString: function (state) { if (state == null) return "0m/s²"; if (Array.isArray(state)) { return "X: " + state[0] + "m/s² Y: " + state[1] + "m/s² Z: " + state[2] + "m/s²"; } else { return state.toString() + "m/s²"; } }, getPercentageFromState: function (state) { return ((state + 78.48) / 156.96); }, getStateFromPercentage: function (percentage) { var value = ((percentage * 156.96) - 78.48); return parseFloat(value.toFixed(1)); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readAccelBMI160()", function(val) { var array = JSON.parse(val); callback(array); }); }, }, { name: "gyroscope", description: "Gyropscope sensor (BMI160)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, selectorImages: ["gyro.png"], getPercentageFromState: function (state) { return (state + 125) / 250; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 250) - 125; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readGyroBMI160()", function(val) { var array = JSON.parse(val); array[0] = Math.round(array[0]); array[1] = Math.round(array[1]); array[2] = Math.round(array[2]); callback(array); }); }, }, { name: "magnetometer", description: "Magnetometer sensor (LSM303C)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, selectorImages: ["mag.png"], getPercentageFromState: function (state) { return (state + 1600) / 3200; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 3200) - 1600; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readMagnetometerLSM303C(False)", function(val) { var array = JSON.parse(val); array[0] = Math.round(array[0]); array[1] = Math.round(array[1]); array[2] = Math.round(array[2]); callback(array); }); }, }, { name: "irrecv", description: "IR Receiver", isAnalog: false, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["irrecvon.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("buttonStateInPort(\"" + sensor.name + "\")", function (retVal) { var intVal = parseInt(retVal, 10); callback(intVal == 0); }); }, }, /******************************** */ /* dummy sensors */ /**********************************/ { name: "cloudstore", description: "Cloud store", isAnalog: false, isSensor: false, portType: "none", valueType: "object", selectorImages: ["cloudstore.png"], /*getInitialState: function(sensor) { return {}; },*/ compareState: function (state1, state2) { return quickPiStore.compareState(state1, state2); }, }, { name: "clock", description: "Cloud store", isAnalog: false, isSensor: false, portType: "none", valueType: "object", selectorImages: ["clock.png"], }, ]; function findSensorDefinition(sensor) { var sensorDef = null; for (var iType = 0; iType < sensorDefinitions.length; iType++) { var type = sensorDefinitions[iType]; if (sensor.type == type.name) { if (sensor.subType && type.subTypes) { for (var iSubType = 0; iSubType < type.subTypes.length; iSubType++) { var subType = type.subTypes[iSubType]; if (subType.subType == sensor.subType) { sensorDef = $.extend({}, type, subType); } } } else { sensorDef = type; } } } if(sensorDef && !sensorDef.compareState) { sensorDef.compareState = function(state1, state2) { return state1 == state2; }; } return sensorDef; } var defaultQuickPiOptions = { disableConnection: false, increaseTimeAfterCalls: 5 }; function getQuickPiOption(name) { if(name == 'disableConnection') { // TODO :: Legacy, remove when all tasks will have been updated return (context.infos && (context.infos.quickPiDisableConnection || (context.infos.quickPi && context.infos.quickPi.disableConnection))); } if(context.infos && context.infos.quickPi && typeof context.infos.quickPi[name] != 'undefined') { return context.infos.quickPi[name]; } else { return defaultQuickPiOptions[name]; } } function getWrongStateText(failInfo) { var actualStateStr = "" + failInfo.actual; var expectedStateStr = "" + failInfo.expected; var sensorDef = findSensorDefinition(failInfo.sensor); if(sensorDef) { if(sensorDef.isSensor) { return strings.messages.wrongStateSensor.format(failInfo.name, failInfo.time); } if(sensorDef.getWrongStateString) { var sensorWrongStr = sensorDef.getWrongStateString(failInfo); if(sensorWrongStr) { return sensorWrongStr; } } if(sensorDef.getStateString) { actualStateStr = sensorDef.getStateString(failInfo.actual); expectedStateStr = sensorDef.getStateString(failInfo.expected); } } return strings.messages.wrongState.format(failInfo.name, actualStateStr, expectedStateStr, failInfo.time); } function getCurrentBoard() { var found = boardDefinitions.find(function (element) { if (context.board == element.name) return element; }); return found; } function getSessionStorage(name) { // Use a try in case it gets blocked try { return sessionStorage[name]; } catch(e) { return null; } } function setSessionStorage(name, value) { // Use a try in case it gets blocked try { sessionStorage[name] = value; } catch(e) {} } if(window.getQuickPiConnection) { var lockstring = getSessionStorage('lockstring'); if(!lockstring) { lockstring = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); setSessionStorage('lockstring', lockstring); } context.quickPiConnection = getQuickPiConnection(lockstring, raspberryPiConnected, raspberryPiDisconnected, raspberryPiChangeBoard); } var paper; context.offLineMode = true; context.onExecutionEnd = function () { if (context.autoGrading) { buzzerSound.stopAll(); } }; infos.checkEndEveryTurn = true; infos.checkEndCondition = function (context, lastTurn) { if (!context.display && !context.autoGrading) { context.success = true; throw (strings.messages.manualTestSuccess); } if (context.failImmediately) { context.success = false; throw (context.failImmediately); } var testEnded = lastTurn || context.currentTime > context.maxTime; if (context.autoGrading) { if (!testEnded) { return; } if (lastTurn && context.display && !context.loopsForever) { context.currentTime = Math.floor(context.maxTime * 1.05); drawNewStateChanges(); drawCurrentTime(); } var failInfo = null; for(var sensorName in context.gradingStatesBySensor) { // Cycle through each sensor from the grading states var sensor = findSensorByName(sensorName); var sensorDef = findSensorDefinition(sensor); var expectedStates = context.gradingStatesBySensor[sensorName]; if(!expectedStates.length) { continue;} var actualStates = context.actualStatesBySensor[sensorName]; var actualIdx = 0; // Check that we went through all expected states for (var i = 0; i < context.gradingStatesBySensor[sensorName].length; i++) { var expectedState = context.gradingStatesBySensor[sensorName][i]; if(expectedState.hit) { continue; } // Was hit, valid var newFailInfo = null; if(actualStates) { // Scroll through actual states until we get the state at this time while(actualIdx + 1 < actualStates.length && actualStates[actualIdx+1].time <= expectedState.time) { actualIdx += 1; } if(!sensorDef.compareState(actualStates[actualIdx].state, expectedState.state)) { newFailInfo = { sensor: sensor, name: sensorName, time: expectedState.time, expected: expectedState.state, actual: actualStates[actualIdx].state }; } } else { // No actual states to compare to newFailInfo = { sensor: sensor, name: sensorName, time: expectedState.time, expected: expectedState.state, actual: null }; } if(newFailInfo) { // Only update failInfo if we found an error earlier failInfo = failInfo && failInfo.time < newFailInfo.time ? failInfo : newFailInfo; } } // Check that no actual state conflicts an expected state if(!actualStates) { continue; } var expectedIdx = 0; for(var i = 0; i < actualStates.length ; i++) { var actualState = actualStates[i]; while(expectedIdx + 1 < expectedStates.length && expectedStates[expectedIdx+1].time <= actualState.time) { expectedIdx += 1; } if(!sensorDef.compareState(actualState.state, expectedStates[expectedIdx].state)) { // Got an unexpected state change var newFailInfo = { sensor: sensor, name: sensorName, time: actualState.time, expected: expectedStates[expectedIdx].state, actual: actualState.state }; failInfo = failInfo && failInfo.time < newFailInfo.time ? failInfo : newFailInfo; } } } if(failInfo) { // Missed expected state context.success = false; throw (getWrongStateText(failInfo)); } else { // Success context.success = true; throw (strings.messages.programEnded); } } else { if (!context.offLineMode) { $('#piinstallcheck').hide(); } if (lastTurn) { context.success = true; throw (strings.messages.programEnded); } } }; context.generatePythonSensorTable = function() { var pythonSensorTable = "sensorTable = ["; var first = true; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; if (first) { first = false; } else { pythonSensorTable += ","; } if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); var firststick = true; for (var iStick = 0; iStick < stickDefinition.gpiosNames.length; iStick++) { var name = sensor.name + "." + stickDefinition.gpiosNames[iStick]; var port = "D" + stickDefinition.gpios[iStick]; if (firststick) { firststick = false; } else { pythonSensorTable += ","; } pythonSensorTable += "{\"type\":\"button\""; pythonSensorTable += ",\"name\":\"" + name + "\""; pythonSensorTable += ",\"port\":\"" + port + "\"}"; } } else { pythonSensorTable += "{\"type\":\"" + sensor.type + "\""; pythonSensorTable += ",\"name\":\"" + sensor.name + "\""; pythonSensorTable += ",\"port\":\"" + sensor.port + "\""; if (sensor.subType) pythonSensorTable += ",\"subType\":\"" + sensor.subType + "\""; pythonSensorTable += "}"; } } var board = getCurrentBoard(); pythonSensorTable += "]; currentADC = \"" + board.adc + "\""; return pythonSensorTable; } context.resetSensorTable = function() { var pythonSensorTable = context.generatePythonSensorTable(); context.quickPiConnection.sendCommand(pythonSensorTable, function(x) {}); } context.findSensor = function findSensor(type, port, error=true) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == type && sensor.port == port) return sensor; } if (error) { context.success = false; throw (strings.messages.sensorNotFound.format('type ' + type + ', port ' + port)); } return null; } function sensorAssignPort(sensor) { var board = getCurrentBoard(); var sensorDefinition = findSensorDefinition(sensor); sensor.port = null; // first try with built ins if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; // Search for the specified subtype if (builtinsensor.type == sensor.type && builtinsensor.subType == sensor.subType && !context.findSensor(builtinsensor.type, builtinsensor.port, false)) { sensor.port = builtinsensor.port; return; } } // Search without subtype for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; // Search for the specified subtype if (builtinsensor.type == sensor.type && !context.findSensor(builtinsensor.type, builtinsensor.port, false)) { sensor.port = builtinsensor.port; sensor.subType = builtinsensor.subType; return; } } // If this is a button try to set it to a stick if (!sensor.port && sensor.type == "button") { for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; if (builtinsensor.type == "stick") { sensor.port = builtinsensor.port; return; } } } } // Second try assign it a grove port if (!sensor.port) { var sensorDefinition = findSensorDefinition(sensor); var pluggable = sensorDefinition.pluggable; if (sensorDefinition.subTypes) { for (var iSubTypes = 0; iSubTypes < sensorDefinition.subTypes.length; iSubTypes++) { var subTypeDefinition = sensorDefinition.subTypes[iSubTypes]; if (pluggable || subTypeDefinition.pluggable) { var ports = board.portTypes[sensorDefinition.portType]; for (var iPorts = 0; iPorts < ports.length; iPorts++) { var port = sensorDefinition.portType; if (sensorDefinition.portType != "i2c") port = sensorDefinition.portType + ports[iPorts]; if (!findSensorByPort(port)) { sensor.port = port; if (!sensor.subType) sensor.subType = subTypeDefinition.subType; return; } } } } } else { if (pluggable) { var ports = board.portTypes[sensorDefinition.portType]; for (var iPorts = 0; iPorts < ports.length; iPorts++) { var port = sensorDefinition.portType + ports[iPorts]; if (!findSensorByPort(port)) { sensor.port = port; return; } } } } } } context.reset = function (taskInfos) { buzzerSound.stopAll(); context.failImmediately = null; if (!context.offLineMode) { $('#piinstallcheck').hide(); context.quickPiConnection.startNewSession(); context.resetSensorTable(); } context.currentTime = 0; if (taskInfos != undefined) { context.actualStatesBySensor = {}; context.tickIncrease = 100; context.autoGrading = taskInfos.autoGrading; context.loopsForever = taskInfos.loopsForever; context.allowInfiniteLoop = !context.autoGrading; if (context.autoGrading) { context.maxTime = 0; if (taskInfos.input) { for (var i = 0; i < taskInfos.input.length; i++) { taskInfos.input[i].input = true; } context.gradingStatesByTime = taskInfos.input.concat(taskInfos.output); } else { context.gradingStatesByTime = taskInfos.output; } // Copy states to avoid modifying the taskInfos states context.gradingStatesByTime = context.gradingStatesByTime.map( function(val) { return Object.assign({}, val); }); context.gradingStatesByTime.sort(function (a, b) { return a.time - b.time; }); context.gradingStatesBySensor = {}; for (var i = 0; i < context.gradingStatesByTime.length; i++) { var state = context.gradingStatesByTime[i]; if (!context.gradingStatesBySensor.hasOwnProperty(state.name)) context.gradingStatesBySensor[state.name] = []; context.gradingStatesBySensor[state.name].push(state); // state.hit = false; // state.badonce = false; if (state.time > context.maxTime) context.maxTime = state.time; } for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; if (sensor.type == "buzzer") { var states = context.gradingStatesBySensor[sensor.name]; if (states) { for (var iState = 0; iState < states.length; iState++) { var state = states[iState].state; if (typeof state == 'number' && state != 0 && state != 1) { sensor.showAsAnalog = true; break; } } } } var isAnalog = findSensorDefinition(sensor).isAnalog || sensor.showAsAnalog; if (isAnalog) { sensor.maxAnalog = Number.MIN_VALUE; sensor.minAnalog = Number.MAX_VALUE; if (context.gradingStatesBySensor.hasOwnProperty(sensor.name)) { var states = context.gradingStatesBySensor[sensor.name]; for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; if (state.state > sensor.maxAnalog) sensor.maxAnalog = state.state; if (state.state < sensor.minAnalog) sensor.minAnalog = state.state; } } } if (sensor.type == "screen") { var states = context.gradingStatesBySensor[sensor.name]; if (states) { for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; if (state.state.isDrawingData) sensor.isDrawingScreen = true; } } } } } if (infos.quickPiSensors == "default") { infos.quickPiSensors = []; addDefaultBoardSensors(); } } context.success = false; if (context.autoGrading) context.doNotStartGrade = false; else context.doNotStartGrade = true; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; sensor.state = null; sensor.screenDrawing = null; sensor.lastDrawnTime = 0; sensor.lastDrawnState = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; sensor.removed = false; sensor.quickStore = null; // If the sensor has no port assign one if (!sensor.port) { sensorAssignPort(sensor); } // Set initial state var sensorDef = findSensorDefinition(sensor); if(sensorDef && !sensorDef.isSensor && sensorDef.getInitialState) { var initialState = sensorDef.getInitialState(sensor); if (initialState != null) context.registerQuickPiEvent(sensor.name, initialState, true, true); } } if (context.display) { context.resetDisplay(); } else { context.success = false; } context.timeLineStates = []; startSensorPollInterval(); }; function clearSensorPollInterval() { if(context.sensorPollInterval) { clearInterval(context.sensorPollInterval); context.sensorPollInterval = null; } }; function startSensorPollInterval() { // Start polling the sensors on the raspberry if the raspberry is connected clearSensorPollInterval(); context.liveUpdateCount = 0; if(!context.quickPiConnection.isConnected()) { return; } context.sensorPollInterval = setInterval(function () { if((context.runner && context.runner.isRunning()) || context.offLineMode || context.liveUpdateCount != 0) { return; } context.quickPiConnection.startTransaction(); for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; updateLiveSensor(sensor); } context.quickPiConnection.endTransaction(); }, 200); }; function updateLiveSensor(sensor) { if (findSensorDefinition(sensor).isSensor && findSensorDefinition(sensor).getLiveState) { context.liveUpdateCount++; //console.log("updateLiveSensor " + sensor.name, context.liveUpdateCount); findSensorDefinition(sensor).getLiveState(sensor, function (returnVal) { context.liveUpdateCount--; //console.log("updateLiveSensor callback" + sensor.name, context.liveUpdateCount); if (!sensor.removed) { sensor.state = returnVal; drawSensor(sensor); } }); } } context.changeBoard = function(newboardname) { if (context.board == newboardname) return; var board = null; for (var i = 0; i < boardDefinitions.length; i++) { board = boardDefinitions[i]; if (board.name == newboardname) break; } if (board == null) return; context.board = newboardname; setSessionStorage('board', newboardname); if (infos.customSensors) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } infos.quickPiSensors = []; if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var sensor = board.builtinSensors[i]; var newSensor = { "type": sensor.type, "port": sensor.port, "builtin": true, }; if (sensor.subType) { newSensor.subType = sensor.subType; } newSensor.name = getSensorSuggestedName(sensor.type, sensor.suggestedName); sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(newSensor); } } } else { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensorAssignPort(sensor); } } context.resetSensorTable(); context.resetDisplay(); }; context.board = "quickpi"; if (getSessionStorage('board')) context.changeBoard(getSessionStorage('board')) context.savePrograms = function(xml) { if (context.infos.customSensors) { var node = goog.dom.createElement("quickpi"); xml.appendChild(node); for (var i = 0; i < infos.quickPiSensors.length; i++) { var currentSensor = infos.quickPiSensors[i]; var node = goog.dom.createElement("sensor"); node.setAttribute("type", currentSensor.type); node.setAttribute("port", currentSensor.port); node.setAttribute("name", currentSensor.name); if (currentSensor.subType) node.setAttribute("subtype", currentSensor.subType); var elements = xml.getElementsByTagName("quickpi"); elements[0].appendChild(node); } } } context.loadPrograms = function(xml) { if (context.infos.customSensors) { var elements = xml.getElementsByTagName("sensor"); if (elements.length > 0) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } infos.quickPiSensors = []; for (var i = 0; i < elements.length; i++) { var sensornode = elements[i]; var sensor = { "type" : sensornode.getAttribute("type"), "port" : sensornode.getAttribute("port"), "name" : sensornode.getAttribute("name"), }; if (sensornode.getAttribute("subtype")) { sensor.subType = sensornode.getAttribute("subtype"); } sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(sensor); } this.resetDisplay(); } } } // Reset the context's display context.resetDisplay = function () { // Do something here //$('#grid').html('Display for the library goes here.'); // Ask the parent to update sizes //context.blocklyHelper.updateSize(); //context.updateScale(); if (!context.display || !this.raphaelFactory) return; var piUi = getQuickPiOption('disableConnection') ? '' : strings.messages.connectionHTML; var hasIntroControls = $('#taskIntro').find('#introControls').length; if (!hasIntroControls) { $('#taskIntro').append(`<div id="introControls"></div>`); } if (introControls === null) { introControls = piUi + $('#introControls').html(); } $('#introControls').html(introControls) $('#taskIntro').addClass('piui'); $('#grid').html(` <div id="virtualSensors" style="height: 90%; width: 90%; padding: 5px;"> </div> ` ); this.raphaelFactory.destroyAll(); paper = this.raphaelFactory.create( "paperMain", "virtualSensors", $('#virtualSensors').width(), $('#virtualSensors').height() ); if (infos.quickPiSensors == "default") { infos.quickPiSensors = []; addDefaultBoardSensors(); } if (context.timeLineCurrent) { context.timeLineCurrent.remove(); context.timeLineCurrent = null; } if (context.timeLineCircle) { context.timeLineCircle.remove(); context.timeLineCircle = null; } if (context.timeLineTriangle) { context.timeLineTriangle.remove(); context.timeLineTriangle = null; } if (context.autoGrading) { var numSensors = infos.quickPiSensors.length; var sensorSize = Math.min(paper.height / numSensors * 0.80, paper.width / 10); context.sensorSize = sensorSize * .90; context.timelineStartx = context.sensorSize * 3; var maxTime = context.maxTime; if (maxTime == 0) maxTime = 1000; if (!context.loopsForever) maxTime = Math.floor(maxTime * 1.05); context.pixelsPerTime = (paper.width - context.timelineStartx - 30) / maxTime; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; sensor.drawInfo = { x: 0, y: 10 + (sensorSize * iSensor), width: sensorSize * .90, height: sensorSize * .90 } drawSensor(sensor); sensor.timelinelastxlabel = 0; if (context.gradingStatesBySensor.hasOwnProperty(sensor.name)) { var states = context.gradingStatesBySensor[sensor.name]; var startTime = 0; var lastState = null; sensor.lastAnalogState = null; for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; drawSensorTimeLineState(sensor, lastState, startTime, state.time, "expected", true); startTime = state.time; lastState = state.state; } drawSensorTimeLineState(sensor, lastState, state.time, context.maxTime, "expected", true); if (!context.loopsForever) drawSensorTimeLineState(sensor, lastState, startTime, maxTime, "finnish", false); sensor.lastAnalogState = null; } } context.timeLineY = 10 + (sensorSize * (iSensor + 1)); drawTimeLine(); for (var iState = 0; iState < context.timeLineStates.length; iState++) { var timelinestate = context.timeLineStates[iState]; drawSensorTimeLineState(timelinestate.sensor, timelinestate.state, timelinestate.startTime, timelinestate.endTime, timelinestate.type, true); } } else { var nSensors = infos.quickPiSensors.length; infos.quickPiSensors.forEach(function (sensor) { var cellsAmount = findSensorDefinition(sensor).cellsAmount; if (cellsAmount) { nSensors += cellsAmount(paper) - 1; } }); if (infos.customSensors) { nSensors++; } if (nSensors < 4) nSensors = 4; var geometry = squareSize(paper.width, paper.height, nSensors); context.sensorSize = geometry.size * .10; var iSensor = 0; for (var col = 0; col < geometry.cols; col++) { var y = geometry.size * col; var line = paper.path(["M", 0, y, "L", paper.width, y]); line.attr({ "stroke-width": 1, "stroke": "lightgrey", "stroke-linecapstring": "round" }); for (var row = 0; row < geometry.rows; row++) { var x = paper.width / geometry.rows * row; var y1 = y + geometry.size / 4; var y2 = y + geometry.size * 3 / 4; line = paper.path(["M", x, y1, "L", x, y2]); line.attr({ "stroke-width": 1, "stroke": "lightgrey", "stroke-linecapstring": "round" }); if (iSensor == infos.quickPiSensors.length && infos.customSensors) { drawCustomSensorAdder(x, y, geometry.size); } else if (infos.quickPiSensors[iSensor]) { var sensor = infos.quickPiSensors[iSensor]; var cellsAmount = findSensorDefinition(sensor).cellsAmount; if (cellsAmount) { row += cellsAmount(paper) - 1; sensor.drawInfo = { x: x, y: y, width: geometry.size * cellsAmount(paper), height: geometry.size } } else { sensor.drawInfo = { x: x, y: y, width: geometry.size, height: geometry.size } } drawSensor(sensor); } iSensor++; } } } context.blocklyHelper.updateSize(); context.inUSBConnection = false; context.inBTConnection = false; context.releasing = false; context.offLineMode = true; showasReleased(); if (context.quickPiConnection.isConnecting()) { showasConnecting(); } if (context.quickPiConnection.isConnected()) { showasConnected(); context.offLineMode = false; } $('#piconnect').click(function () { window.displayHelper.showPopupDialog(strings.messages.connectionDialogHTML); if (context.offLineMode) { $('#pirelease').attr('disabled', true); } else { $('#pirelease').attr('disabled', false); } $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').hide(); if (context.quickPiConnection.isConnected()) { if (getSessionStorage('connectionMethod') == "USB") { $('#piconwifi').removeClass('active'); $('#piconusb').addClass('active'); $('#pischoolcon').hide(); $('#piaddress').val("192.168.233.1"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').text(strings.messages.canConnectoToUSB) context.inUSBConnection = true; context.inBTConnection = false; } else if (getSessionStorage('connectionMethod') == "BT") { $('#piconwifi').removeClass('active'); $('#piconbt').addClass('active'); $('#pischoolcon').hide(); $('#piaddress').val("192.168.233.2"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').text(strings.messages.canConnectoToBT) context.inUSBConnection = false; context.inBTConnection = true; } } else { setSessionStorage('connectionMethod', "WIFI"); } $('#piaddress').on('input', function (e) { if (context.offLineMode) { var content = $('#piaddress').val(); if (content) $('#piconnectok').attr('disabled', false); else $('#piconnectok').attr('disabled', true); } }); if (infos.runningOnQuickPi) { $('#piconnectionmainui').hide(); $('#piaddress').val(window.location.hostname); $('#piaddress').trigger("input"); } if (getSessionStorage('pilist')) { populatePiList(JSON.parse(getSessionStorage('pilist'))); } if (getSessionStorage('raspberryPiIpAddress')) { $('#piaddress').val(getSessionStorage('raspberryPiIpAddress')); $('#piaddress').trigger("input"); } if (getSessionStorage('schoolkey')) { $('#schoolkey').val(getSessionStorage('schoolkey')); $('#pigetlist').attr("disabled", false); } $('#piconnectok').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; if ($('#piusetunnel').is(":checked")) { var piname = $("#pilist option:selected").text().split("-")[0].trim(); var url = "ws://api.quick-pi.org/client/" + $('#schoolkey').val() + "-" + piname + "/api/v1/commands"; setSessionStorage('quickPiUrl', url); context.quickPiConnection.connect(url); } else { var ipaddress = $('#piaddress').val(); setSessionStorage('raspberryPiIpAddress', ipaddress); showasConnecting(); var url = "ws://" + ipaddress + ":5000/api/v1/commands"; setSessionStorage('quickPiUrl', url); context.quickPiConnection.connect(url); } }); $('#pirelease').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; // IF connected release lock context.releasing = true; context.quickPiConnection.releaseLock(); }); $('#picancel').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#schoolkey').on('input', function (e) { var schoolkey = $('#schoolkey').val(); setSessionStorage('schoolkey', schoolkey); if (schoolkey) $('#pigetlist').attr("disabled", false); else $('#pigetlist').attr("disabled", true); }); $('#pigetlist').click(function () { var schoolkey = $('#schoolkey').val(); fetch('http://www.france-ioi.org/QuickPi/list.php?school=' + schoolkey) .then(function (response) { return response.json(); }) .then(function (jsonlist) { populatePiList(jsonlist); }); }); // Select device connexion methods $('#piconsel .btn').click(function () { if (!context.quickPiConnection.isConnected()) { if (!$(this).hasClass('active')) { $('#piconsel .btn').removeClass('active'); $(this).addClass('active'); } } }); $('#piconwifi').click(function () { if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "WIFI"); $(this).addClass('active'); $('#pischoolcon').show("slow"); $('#piconnectionlabel').hide(); } context.inUSBConnection = false; context.inBTConnection = false; }); $('#piconusb').click(function () { if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "USB"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').html(strings.messages.cantConnectoToUSB) $(this).addClass('active'); $('#pischoolcon').hide("slow"); $('#piaddress').val("192.168.233.1"); context.inUSBConnection = true; context.inBTConnection = false; function updateUSBAvailability(available) { if (context.inUSBConnection && context.offLineMode) { if (available) { $('#piconnectok').attr('disabled', false); $('#piconnectionlabel').text(strings.messages.canConnectoToUSB) } else { $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').html(strings.messages.cantConnectoToUSB) } context.quickPiConnection.isAvailable("192.168.233.1", updateUSBAvailability); } } updateUSBAvailability(false); } }); $('#piconbt').click(function () { $('#piconnectionlabel').show(); if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "BT"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').html(strings.messages.cantConnectoToBT) $(this).addClass('active'); $('#pischoolcon').hide("slow"); $('#piaddress').val("192.168.233.2"); context.inUSBConnection = false; context.inBTConnection = true; function updateBTAvailability(available) { if (context.inUSBConnection && context.offLineMode) { if (available) { $('#piconnectok').attr('disabled', false); $('#piconnectionlabel').text(strings.messages.canConnectoToBT) } else { $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').html(strings.messages.cantConnectoToBT) } context.quickPiConnection.isAvailable("192.168.233.2", updateUSBAvailability); } } updateBTAvailability(false); } }); function populatePiList(jsonlist) { setSessionStorage('pilist', JSON.stringify(jsonlist)); var select = document.getElementById("pilist"); var first = true; $('#pilist').empty(); $('#piusetunnel').attr('disabled', true); for (var i = 0; i < jsonlist.length; i++) { var pi = jsonlist[i]; var el = document.createElement("option"); var minutes = Math.round(jsonlist[i].seconds_since_ping / 60); var timeago = ""; if (minutes < 60) timeago = strings.messages.minutesago.format(minutes); else timeago = strings.messages.hoursago; el.textContent = jsonlist[i].name + " - " + timeago; el.value = jsonlist[i].ip; select.appendChild(el); if (first) { $('#piaddress').val(jsonlist[i].ip); $('#piaddress').trigger("input"); first = false; $('#pilist').prop('disabled', false); $('#piusetunnel').attr('disabled', false); } } } $('#pilist').on('change', function () { $("#piaddress").val(this.value); }); }); $('#pichangehat').click(function () { window.displayHelper.showPopupDialog(` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Choisissez votre carte </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div id=boardlist> </div> <div panel-body-usbbt> <label id="piconnectionlabel"></label> </div> </div> </div>`); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); for (var i = 0; i < boardDefinitions.length; i++) { var board = boardDefinitions[i]; var image = document.createElement('img'); image.src = getImg(board.image); $('#boardlist').append(image).append("&nbsp;&nbsp;"); image.onclick = function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; context.changeBoard(board.name); } } }); $('#pihatsetup').click(function () { var command = "getBuzzerAudioOutput()"; context.quickPiConnection.sendCommand(command, function(val) { var buzzerstate = parseInt(val); window.displayHelper.showPopupDialog(` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> QuickPi Hat Settings </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div> <input type="checkbox" id="buzzeraudio" value="buzzeron"> Output audio trought audio buzzer<br> </div> <div class="inlineButtons"> <button id="pisetupok" class="btn"><i class="fas fa-cog icon"></i>Set</button> </div> </div> </div>`); $('#buzzeraudio').prop('checked', buzzerstate ? true : false); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#pisetupok').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; var radioValue = $('#buzzeraudio').is(":checked"); var command = "setBuzzerAudioOutput(" + (radioValue ? "True" : "False") + ")"; context.quickPiConnection.sendCommand(command, function(x) {}); }); }); }); $('#piinstall').click(function () { context.blocklyHelper.reportValues = false; python_code = context.generatePythonSensorTable(); python_code += "\n\n"; python_code += window.task.displayedSubTask.blocklyHelper.getCode('python'); python_code = python_code.replace("from quickpi import *", ""); if (context.runner) context.runner.stop(); context.installing = true; $('#piinstallprogresss').show(); $('#piinstallcheck').hide(); context.quickPiConnection.installProgram(python_code, function () { context.justinstalled = true; $('#piinstallprogresss').hide(); $('#piinstallcheck').show(); }); }); if (parseInt(getSessionStorage('autoConnect'))) { if (!context.quickPiConnection.isConnected() && !context.quickPiConnection.isConnecting()) { $('#piconnect').attr("disabled", true); context.quickPiConnection.connect(getSessionStorage('quickPiUrl')); } } }; function addDefaultBoardSensors() { var board = getCurrentBoard(); var boardDefaultSensors = board.default; if (!boardDefaultSensors) boardDefaultSensors = board.builtinSensors; if (boardDefaultSensors) { for (var i = 0; i < boardDefaultSensors.length; i++) { var sensor = boardDefaultSensors[i]; var newSensor = { "type": sensor.type, "port": sensor.port, "builtin": true, }; if (sensor.subType) { newSensor.subType = sensor.subType; } newSensor.name = getSensorSuggestedName(sensor.type, sensor.suggestedName); sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(newSensor); } } }; function getNewSensorSuggestedName(name) { var maxvalue = 0; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; var firstdigit = sensor.name.search(/\d/); if (firstdigit > 0) { var namepart = sensor.name.substring(0, firstdigit); var numberpart = parseInt(sensor.name.substring(firstdigit), 10); if (name == namepart && numberpart > maxvalue) { maxvalue = numberpart; } } } return name + (maxvalue + 1); } function drawCustomSensorAdder(x, y, size) { if (context.sensorAdder) { context.sensorAdder.remove(); } var centerx = x + size / 2; var centery = y + size / 2; var fontsize = size * .70; context.sensorAdder = paper.text(centerx, centery, "+"); context.sensorAdder.attr({ "font-size": fontsize + "px", fill: "lightgray" }); context.sensorAdder.node.style = "-moz-user-select: none; -webkit-user-select: none;"; context.sensorAdder.click(function () { window.displayHelper.showPopupDialog(` <div class="content qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Ajouter un composant </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div id="sensorPicker" class="panel-body"> <label>Sélectionnez un composant à ajouter à votre Raspberry Pi et attachez-le à un port.</label> <div class="flex-container"> <div id="selector-image-container" class="flex-col half"> <img id="selector-sensor-image"> </div> <div class="flex-col half"> <div class="form-group"> <div class="input-group"> <select id="selector-sensor-list" class="custom-select"></select> </div> </div> <div class="form-group"> <div class="input-group"> <select id="selector-sensor-port" class="custom-select"></select> </div> <label id="selector-label"></label> </div> </div> </div> </div> <div class="singleButton"> <button id="selector-add-button" class="btn btn-centered"><i class="icon fa fa-check"></i>Ajouter</button> </div> </div> `); var select = document.getElementById("selector-sensor-list"); for (var iSensorDef = 0; iSensorDef < sensorDefinitions.length; iSensorDef++) { var sensorDefinition = sensorDefinitions[iSensorDef]; if (sensorDefinition.subTypes) { for (var iSubType = 0; iSubType < sensorDefinition.subTypes.length; iSubType++) { if (!sensorDefinition.pluggable && !sensorDefinition.subTypes[iSubType].pluggable) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description; if (sensorDefinition.subTypes[iSubType].description) el.textContent = sensorDefinition.subTypes[iSubType].description; el.value = sensorDefinition.name; el.value += "-" + sensorDefinition.subTypes[iSubType].subType; select.appendChild(el); } } else { if (!sensorDefinition.pluggable) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description; el.value = sensorDefinition.name; select.appendChild(el); } } var board = getCurrentBoard(); if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var sensor = board.builtinSensors[i]; var sensorDefinition = findSensorDefinition(sensor); if (context.findSensor(sensor.type, sensor.port, false)) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description + "(builtin)"; el.value = sensorDefinition.name + "-"; if (sensor.subType) el.value += sensor.subType; el.value += "-" + sensor.port; select.appendChild(el); } } $('#selector-sensor-list').on('change', function () { var values = this.value.split("-"); var builtinport = false; var dummysensor = { type: values[0] }; if (values.length >= 2) if (values[1]) dummysensor.subType = values[1]; if (values.length >= 3) builtinport = values[2]; var sensorDefinition = findSensorDefinition(dummysensor); var imageContainer = document.getElementById("selector-image-container"); while (imageContainer.firstChild) { imageContainer.removeChild(imageContainer.firstChild); } for (var i = 0; i < sensorDefinition.selectorImages.length; i++) { var image = document.createElement('img'); image.src = getImg(sensorDefinition.selectorImages[i]); imageContainer.appendChild(image); //$('#selector-sensor-image').attr("src", getImg(sensorDefinition.selectorImages[0])); } var portSelect = document.getElementById("selector-sensor-port"); $('#selector-sensor-port').empty(); var hasPorts = false; if (builtinport) { var option = document.createElement('option'); option.innerText = builtinport; option.value = builtinport; portSelect.appendChild(option); hasPorts = true; } else { var ports = getCurrentBoard().portTypes[sensorDefinition.portType]; if (sensorDefinition.portType == "i2c") { ports = ["i2c"]; } for (var iPort = 0; iPort < ports.length; iPort++) { var port = sensorDefinition.portType + ports[iPort]; if (sensorDefinition.portType == "i2c") port = "i2c"; if (!isPortUsed(sensorDefinition.name, port)) { var option = document.createElement('option'); option.innerText = port; option.value = port; portSelect.appendChild(option); hasPorts = true; } } } if (!hasPorts) { $('#selector-add-button').attr("disabled", true); var object_function = strings.messages.actuator; if (sensorDefinition.isSensor) object_function = strings.messages.sensor; $('#selector-label').text(strings.messages.noPortsAvailable.format(object_function, sensorDefinition.portType)); $('#selector-label').show(); } else { $('#selector-add-button').attr("disabled", false); $('#selector-label').hide(); } }); $('#selector-add-button').click(function () { var sensorType = $("#selector-sensor-list option:selected").val(); var values = sensorType.split("-"); var dummysensor = { type: values[0] }; if (values.length == 2) dummysensor.subType = values[1]; var sensorDefinition = findSensorDefinition(dummysensor); var port = $("#selector-sensor-port option:selected").text(); var name = getNewSensorSuggestedName(sensorDefinition.name); if(name == 'screen1') { // prepend screen because squareSize func can't handle cells wrap infos.quickPiSensors.unshift({ type: sensorDefinition.name, subType: sensorDefinition.subType, port: port, name: name }); } else { infos.quickPiSensors.push({ type: sensorDefinition.name, subType: sensorDefinition.subType, port: port, name: name }); } $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; context.resetSensorTable(); context.resetDisplay(); }); $("#selector-sensor-list").trigger("change"); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); }); }; function isPortUsed(type, port) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (port == "i2c") { if (sensor.type == type) return true; } else { if (sensor.port == port) return true; } } return false; }; // Straight from stack overflow :) function squareSize(x, y, n) { // Compute number of rows and columns, and cell size var ratio = x / y; var ncols_float = Math.sqrt(n * ratio); var nrows_float = n / ncols_float; // Find best option filling the whole height var nrows1 = Math.ceil(nrows_float); var ncols1 = Math.ceil(n / nrows1); while (nrows1 * ratio < ncols1) { nrows1++; ncols1 = Math.ceil(n / nrows1); } var cell_size1 = y / nrows1; // Find best option filling the whole width var ncols2 = Math.ceil(ncols_float); var nrows2 = Math.ceil(n / ncols2); while (ncols2 < nrows2 * ratio) { ncols2++; nrows2 = Math.ceil(n / ncols2); } var cell_size2 = x / ncols2; // Find the best values var nrows, ncols, cell_size; if (cell_size1 < cell_size2) { nrows = nrows2; ncols = ncols2; cell_size = cell_size2; } else { nrows = nrows1; ncols = ncols1; cell_size = cell_size1; } return { rows: ncols, cols: nrows, size: cell_size }; } function showasConnected() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstallui').show(); if (context.board == "quickpi") $('#pihatsetup').show(); else $('#pihatsetup').hide(); $('#piconnect').css('background-color', '#F9A423'); $('#piinstall').css('background-color', "#488FE1"); $('#piconnecttext').hide(); } function showasConnecting() { $('#piconnectprogress').show(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); } function showasReleased() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstallui').hide(); $('#pihatsetup').hide(); $('#piconnect').css('background-color', '#F9A423'); $('#piconnecttext').show(); } function showasDisconnected() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstall').css('background-color', 'gray'); $('#piconnect').css('background-color', 'gray'); $('#piconnecttext').hide(); } function raspberryPiConnected() { showasConnected(); context.resetSensorTable(); context.quickPiConnection.startNewSession(); context.liveUpdateCount = 0; context.offLineMode = false; setSessionStorage('autoConnect', "1"); context.resetDisplay(); startSensorPollInterval(); } function raspberryPiDisconnected(wasConnected, wrongversion) { if (context.releasing || !wasConnected) showasReleased(); else showasDisconnected(); window.task.displayedSubTask.context.offLineMode = true; if (context.quickPiConnection.wasLocked()) { window.displayHelper.showPopupMessage(strings.messages.piPlocked, 'blanket'); } else if (wrongversion) { window.displayHelper.showPopupMessage(strings.messages.wrongVersion, 'blanket'); } else if (!context.releasing && !wasConnected) { window.displayHelper.showPopupMessage(strings.messages.cantConnect, 'blanket'); } clearSensorPollInterval(); if (wasConnected && !context.releasing && !context.quickPiConnection.wasLocked() && !wrongversion) { context.quickPiConnection.connect(getSessionStorage('quickPiUrl')); } else { // If I was never connected don't attempt to autoconnect again setSessionStorage('autoConnect', "0"); window.task.displayedSubTask.context.resetDisplay(); } } function raspberryPiChangeBoard(board) { window.task.displayedSubTask.context.changeBoard(board); window.task.displayedSubTask.context.resetSensorTable(); } // Update the context's display to the new scale (after a window resize for instance) context.updateScale = function () { if (!context.display) { return; } var width = $('#virtualSensors').width(); var height = $('#virtualSensors').height(); if (!context.oldwidth || !context.oldheight || context.oldwidth != width || context.oldheight != height) { context.oldwidth = width; context.oldheight = height; context.resetDisplay(); } }; // When the context is unloaded, this function is called to clean up // anything the context may have created context.unload = function () { // Do something here clearSensorPollInterval(); if (context.display) { // Do something here } for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } }; function drawTimeLine() { if (paper == undefined || !context.display) return; if (context.timelineText) for (var i = 0; i < context.timelineText.length; i++) { context.timelineText[i].remove(); } context.timelineText = []; var step = 1000; if (context.maxTime <= 1000) step = 100; else if (context.maxTime <= 3000) step = 500; else step = 1000; var i = 0; for (; i <= context.maxTime; i += step) { var x = context.timelineStartx + (i * context.pixelsPerTime); var timelabel = paper.text(x, context.timeLineY, (i / 1000).toString() + "s"); var fontsize = context.pixelsPerTime * step * 0.4; if (fontsize > 15) fontsize = 15; timelabel.attr({ "font-size": fontsize.toString() + "px", 'text-anchor': 'center', 'font-weight': 'bold', fill: "gray" }); context.timelineText.push(timelabel); } context.timeLineHoverPath = paper.path(["M", context.timelineStartx, context.timeLineY, "L", context.timelineStartx + (context.maxTime * context.pixelsPerTime), (context.timeLineY)]); context.timeLineHoverPath.attr({ "stroke-width": 40, "opacity": 0, "stroke-linecap": "square", "stroke-linejoin": "round", }); context.timeLineHoverPath.mousemove(function(event){ $('#screentooltip').remove(); var ms = (event.clientX - context.timelineStartx) / context.pixelsPerTime; ms = Math.round(ms); if (ms < -4) return; if (ms < 0) ms = 0; $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); $('#screentooltip').css("left", event.clientX + 2).css("top", event.clientY + 2); $('#screentooltip').text(ms.toString() + "ms"); if (context.timeLineHoverLine) context.timeLineHoverLine.remove(); context.timeLineHoverLine = paper.path(["M", event.clientX, 0, "L", event.clientX, context.timeLineY]); context.timeLineHoverLine.attr({ "stroke-width": 4, "stroke": "blue", "opacity": 0.2, "stroke-linecap": "square", "stroke-linejoin": "round", }); }); context.timeLineHoverPath.mouseout(function() { if (context.timeLineHoverLine) context.timeLineHoverLine.remove(); $('#screentooltip').remove(); }); if (!context.loopsForever) { var endx = context.timelineStartx + (context.maxTime * context.pixelsPerTime); var x = context.timelineStartx + (i * context.pixelsPerTime); var timelabel = paper.text(x, context.timeLineY, '\uf11e'); timelabel.node.style.fontFamily = '"Font Awesome 5 Free"'; timelabel.node.style.fontWeight = "bold"; timelabel.attr({ "font-size": "20" + "px", 'text-anchor': 'middle', 'font-weight': 'bold', fill: "gray" }); context.timelineText.push(timelabel); if (context.timeLineEndLine) context.timeLineEndLine.remove(); context.timeLineEndLine = paper.path(["M", endx, 0, "L", endx, context.timeLineY]); if (context.endFlagEnd) context.endFlagEnd.remove(); context.endFlagEnd = paper.rect(endx, 0, x, context.timeLineY + 10); context.endFlagEnd.attr({ "fill": "lightgray", "stroke": "none", "opacity": 0.2, }); } /* paper.path(["M", context.timelineStartx, paper.height - context.sensorSize * 3 / 4, "L", paper.width, paper.height - context.sensorSize * 3 / 4]); */ } function drawCurrentTime() { if (!paper || !context.display || isNaN(context.currentTime)) return; /* if (context.currentTimeText) context.currentTimeText.remove(); context.currentTimeText = paper.text(0, paper.height - 40, context.currentTime.toString() + "ms"); context.currentTimeText.attr({ "font-size": "10px", 'text-anchor': 'start' }); */ if (!context.autoGrading) return; var animationSpeed = 200; // ms var startx = context.timelineStartx + (context.currentTime * context.pixelsPerTime); var targetpath = ["M", startx, 0, "L", startx, context.timeLineY]; if (context.timeLineCurrent) { context.timeLineCurrent.animate({path: targetpath}, animationSpeed); } else { context.timeLineCurrent = paper.path(targetpath); context.timeLineCurrent.attr({ "stroke-width": 5, "stroke": "#678AB4", "stroke-linecap": "round" }); } if (context.timeLineCircle) { context.timeLineCircle.animate({cx: startx}, animationSpeed); } else { var circleradius = 10; context.timeLineCircle = paper.circle(startx, context.timeLineY, 10); context.timeLineCircle.attr({ "fill": "white", "stroke": "#678AB4" }); } var trianglew = 10; var targetpath = ["M", startx, 0, "L", startx + trianglew, 0, "L", startx, trianglew, "L", startx - trianglew, 0, "L", startx, 0 ]; if (context.timeLineTriangle) { context.timeLineTriangle.animate({path: targetpath}, animationSpeed); } else { context.timeLineTriangle = paper.path(targetpath); context.timeLineTriangle.attr({ "fill": "#678AB4", "stroke": "#678AB4" }); } } function storeTimeLineState(sensor, state, startTime, endTime, type) { var found = false; var timelinestate = { sensor: sensor, state: state, startTime: startTime, endTime: endTime, type: type }; for (var i = 0; i < context.timeLineStates.length; i++) { var currenttlstate = context.timeLineStates[i]; if (currenttlstate.sensor == sensor && currenttlstate.startTime == startTime && currenttlstate.endTime == endTime && currenttlstate.type == type) { context.timeLineStates[i] = timelinestate; found = true; break; } } if (!found) { context.timeLineStates.push(timelinestate); } } function drawSensorTimeLineState(sensor, state, startTime, endTime, type, skipsave = false, expectedState = null) { if (paper == undefined || !context.display || !context.autoGrading) return; if (!skipsave) { storeTimeLineState(sensor, state, startTime, endTime, type); } var startx = context.timelineStartx + (startTime * context.pixelsPerTime); var stateLenght = (endTime - startTime) * context.pixelsPerTime; var ypositionmiddle = ((sensor.drawInfo.y + (sensor.drawInfo.height * .5)) + (sensor.drawInfo.height * .20)); var ypositiontop = sensor.drawInfo.y var ypositionbottom = sensor.drawInfo.y + sensor.drawInfo.height; var color = "green"; var strokewidth = 4; if (type == "expected" || type == "finnish") { color = "lightgrey"; strokewidth = 8; } else if (type == "wrong") { color = "red"; strokewidth = 4; } else if (type == "actual") { color = "yellow"; strokewidth = 4; } var isAnalog = findSensorDefinition(sensor).isAnalog; var percentage = + state; var drawnElements = []; var deleteLastDrawnElements = true; if (sensor.type == "accelerometer" || sensor.type == "gyroscope" || sensor.type == "magnetometer") { if (state != null) { for (var i = 0; i < 3; i++) { var startx = context.timelineStartx + (startTime * context.pixelsPerTime); var stateLenght = (endTime - startTime) * context.pixelsPerTime; var yspace = sensor.drawInfo.height / 3; var ypositiontop = sensor.drawInfo.y + (yspace * i) var ypositionbottom = ypositiontop + yspace; var offset = (ypositionbottom - ypositiontop) * findSensorDefinition(sensor).getPercentageFromState(state[i], sensor); if (type == "expected" || type == "finnish") { color = "lightgrey"; strokewidth = 4; } else if (type == "wrong") { color = "red"; strokewidth = 2; } else if (type == "actual") { color = "yellow"; strokewidth = 2; } if (sensor.lastAnalogState != null && sensor.lastAnalogState[i] != state[i]) { var oldStatePercentage = findSensorDefinition(sensor).getPercentageFromState(sensor.lastAnalogState[i], sensor); var previousOffset = (ypositionbottom - ypositiontop) * oldStatePercentage; var joinline = paper.path(["M", startx, ypositiontop + offset, "L", startx, ypositiontop + previousOffset]); joinline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); if (sensor.timelinelastxlabel == null) sensor.timelinelastxlabel = [0, 0, 0]; if ((startx) - sensor.timelinelastxlabel[i] > 40) { var sensorDef = findSensorDefinition(sensor); var stateText = state.toString(); if(sensorDef && sensorDef.getStateString) { stateText = sensorDef.getStateString(state[i]); } var paperText = paper.text(startx, ypositiontop + offset - 10, stateText); drawnElements.push(paperText); sensor.timelinelastxlabel[i] = startx; } } var stateline = paper.path(["M", startx, ypositiontop + offset, "L", startx + stateLenght, ypositiontop + offset]); stateline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); } sensor.lastAnalogState = state == null ? [0, 0, 0] : state; } } else if (isAnalog || sensor.showAsAnalog) { var offset = (ypositionbottom - ypositiontop) * findSensorDefinition(sensor).getPercentageFromState(state, sensor); if (type == "wrong") { color = "red"; ypositionmiddle += 4; } else if (type == "actual") { color = "yellow"; ypositionmiddle += 4; } if (sensor.lastAnalogState != null && sensor.lastAnalogState != state) { var oldStatePercentage = findSensorDefinition(sensor).getPercentageFromState(sensor.lastAnalogState, sensor); var previousOffset = (ypositionbottom - ypositiontop) * oldStatePercentage; var joinline = paper.path(["M", startx, ypositiontop + offset, "L", startx, ypositiontop + previousOffset]); joinline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); if (!sensor.timelinelastxlabel) sensor.timelinelastxlabel = 0; if (!sensor.timelinelastxlabel) sensor.timelinelastxlabel = 0; if ((startx) - sensor.timelinelastxlabel > 5) { var sensorDef = findSensorDefinition(sensor); var stateText = state.toString(); if(sensorDef && sensorDef.getStateString) { stateText = sensorDef.getStateString(state); } if (sensor.timelinestateup) { var paperText = paper.text(startx, ypositiontop + offset - 10, stateText); sensor.timelinestateup = false; } else { var paperText = paper.text(startx, ypositiontop + offset + 20, stateText); sensor.timelinestateup = true; } drawnElements.push(paperText); sensor.timelinelastxlabel = startx; } } sensor.lastAnalogState = state == null ? 0 : state; var stateline = paper.path(["M", startx, ypositiontop + offset, "L", startx + stateLenght, ypositiontop + offset]); stateline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); } else if (sensor.type == "stick") { var stateToFA = [ "\uf062", "\uf063", "\uf060", "\uf061", "\uf111", ] var spacing = sensor.drawInfo.height / 5; for (var i = 0; i < 5; i++) { if (state && state[i]) { var ypos = sensor.drawInfo.y + (i * spacing); var startingpath = ["M", startx, ypos, "L", startx, ypos]; var targetpath = ["M", startx, ypos, "L", startx + stateLenght, ypos]; if (type == "expected") { var stateline = paper.path(targetpath); } else { var stateline = paper.path(startingpath); stateline.animate({path: targetpath}, 200); } stateline.attr({ "stroke-width": 2, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); if (type == "expected") { sensor.stateArrow = paper.text(startx, ypos, stateToFA[i]); sensor.stateArrow.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (strokewidth * 2) + "px" }); sensor.stateArrow.node.style.fontFamily = '"Font Awesome 5 Free"'; sensor.stateArrow.node.style.fontWeight = "bold"; } } } } else if (sensor.type == "screen" && state) { var sensorDef = findSensorDefinition(sensor); if (type != "actual" || !sensor.lastScreenState || !sensorDef.compareState(sensor.lastScreenState, state)) { sensor.lastScreenState = state; if (state.isDrawingData) { var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf303'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (4 * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup(event) { if (!sensor.showingTooltip) { $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); $('#screentooltip').css("width", "262px"); $('#screentooltip').css("height", "70px"); $('#screentooltip').css("left", event.clientX+2).css("top", event.clientY+2); var canvas = document.createElement("canvas"); canvas.id = "tooltipcanvas"; canvas.width = 128 * 2; canvas.height = 32 * 2; $('#screentooltip').append(canvas); $(canvas).css("position", "absolute"); $(canvas).css("z-index", "1500"); $(canvas).css("left", 3).css("top", 3); var ctx = canvas.getContext('2d'); if (expectedState && type == "wrong") { screenDrawing.renderDifferences(expectedState, state, canvas, 2); } else { screenDrawing.renderToCanvas(state, canvas, 2); } sensor.showingTooltip = true; } }; $(stateBubble.node).mouseenter(showPopup); $(stateBubble.node).click(showPopup); $(stateBubble.node).mouseleave(function(event) { sensor.showingTooltip = false; $('#screentooltip').remove(); }); } else { var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf27a'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (strokewidth * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup() { if (!sensor.tooltip) { sensor.tooltipText = paper.text(startx, ypositionmiddle + 50, state.line1 + "\n" + (state.line2 ? state.line2 : "")); var textDimensions = sensor.tooltipText.getBBox(); sensor.tooltip = paper.rect(textDimensions.x - 15, textDimensions.y - 15, textDimensions.width + 30, textDimensions.height + 30); sensor.tooltip.attr({ "stroke": "black", "stroke-width": 2, "fill": "white", }); sensor.tooltipText.toFront(); } }; stateBubble.click(showPopup); stateBubble.hover(showPopup, function () { if (sensor.tooltip) { sensor.tooltip.remove(); sensor.tooltip = null; } if (sensor.tooltipText) { sensor.tooltipText.remove(); sensor.tooltipText = null; } }); } drawnElements.push(stateBubble); } else { deleteLastDrawnElements = false; } } else if (sensor.type == "cloudstore") { var sensorDef = findSensorDefinition(sensor); if (type != "actual" || !sensor.lastScreenState || !sensorDef.compareState(sensor.lastScreenState, state)) { sensor.lastScreenState = state; var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf044'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (4 * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup(event) { if (!sensor.showingTooltip) { $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); /* $('#screentooltip').css("width", "262px"); $('#screentooltip').css("height", "70px");*/ $('#screentooltip').css("left", event.clientX+2).css("top", event.clientY+2); if (expectedState && type == "wrong") { var div = quickPiStore.renderDifferences(expectedState, state); $('#screentooltip').append(div); } else { for (var property in state) { var div = document.createElement("div"); $(div).text(property + " = " + state[property]); $('#screentooltip').append(div); } } sensor.showingTooltip = true; } }; $(stateBubble.node).mouseenter(showPopup); $(stateBubble.node).click(showPopup); $(stateBubble.node).mouseleave(function(event) { sensor.showingTooltip = false; $('#screentooltip').remove(); }); drawnElements.push(stateBubble); } else { deleteLastDrawnElements = false; } } else if (percentage != 0) { if (type == "wrong" || type == "actual") { ypositionmiddle += 2; } if (type == "expected") { var c = paper.rect(startx, ypositionmiddle, stateLenght, strokewidth); c.attr({ "stroke": "none", "fill": color, }); } else { var c = paper.rect(startx, ypositionmiddle, 0, strokewidth); c.attr({ "stroke": "none", "fill": color, }); c.animate({ width: stateLenght }, 200); } drawnElements.push(c); } if (type == "wrong") { /* wrongindicator = paper.path(["M", startx, sensor.drawInfo.y, "L", startx + stateLenght, sensor.drawInfo.y + sensor.drawInfo.height, "M", startx, sensor.drawInfo.y + sensor.drawInfo.height, "L", startx + stateLenght, sensor.drawInfo.y ]); wrongindicator.attr({ "stroke-width": 5, "stroke" : "red", "stroke-linecap": "round" });*/ } if(type == 'actual' || type == 'wrong') { if(!sensor.drawnGradingElements) { sensor.drawnGradingElements = []; } else if(deleteLastDrawnElements) { for(var i = 0; i < sensor.drawnGradingElements.length; i++) { var dge = sensor.drawnGradingElements[i]; if(dge.time >= startTime) { for(var j = 0; j < dge.elements.length; j++) { dge.elements[j].remove(); } sensor.drawnGradingElements.splice(i, 1); i -= 1; } } } if(drawnElements.length) { sensor.drawnGradingElements.push({time: startTime, elements: drawnElements}); } } // Make sure the current time bar is always on top of states drawCurrentTime(); } function getImg(filename) { // Get the path to an image stored in bebras-modules return (window.modulesPath ? window.modulesPath : '../../modules/') + 'img/quickpi/' + filename; } function createSlider(sensor, max, min, x, y, w, h, index) { var sliderobj = {}; sliderobj.sliderdata = {}; sliderobj.index = index; sliderobj.min = min; sliderobj.max = max; var outsiderectx = x; var outsiderecty = y; var outsidewidth = w / 6; var outsideheight = h; var insidewidth = outsidewidth / 6; sliderobj.sliderdata.insideheight = h * 0.60; var insiderectx = outsiderectx + (outsidewidth / 2) - (insidewidth / 2); sliderobj.sliderdata.insiderecty = outsiderecty + (outsideheight / 2) - (sliderobj.sliderdata.insideheight / 2); var circleradius = (outsidewidth / 2) - 1; var pluscirclex = outsiderectx + (outsidewidth / 2); var pluscircley = outsiderecty + circleradius + 1; var minuscirclex = pluscirclex; var minuscircley = outsiderecty + outsideheight - circleradius - 1; paper.setStart(); sliderobj.sliderrect = paper.rect(outsiderectx, outsiderecty, outsidewidth, outsideheight, outsidewidth / 2); sliderobj.sliderrect.attr("fill", "#468DDF"); sliderobj.sliderrect.attr("stroke", "#468DDF"); sliderobj.sliderrect = paper.rect(insiderectx, sliderobj.sliderdata.insiderecty, insidewidth, sliderobj.sliderdata.insideheight, 2); sliderobj.sliderrect.attr("fill", "#2E5D94"); sliderobj.sliderrect.attr("stroke", "#2E5D94"); sliderobj.plusset = paper.set(); sliderobj.pluscircle = paper.circle(pluscirclex, pluscircley, circleradius); sliderobj.pluscircle.attr("fill", "#F5A621"); sliderobj.pluscircle.attr("stroke", "#F5A621"); sliderobj.plus = paper.text(pluscirclex, pluscircley, "+"); sliderobj.plus.attr({ fill: "white" }); sliderobj.plus.node.style = "-moz-user-select: none; -webkit-user-select: none;"; sliderobj.plusset.push(sliderobj.pluscircle, sliderobj.plus); sliderobj.plusset.click(function () { var step = 1; var sensorDef = findSensorDefinition(sensor); if (sensorDef.step) step = sensorDef.step; if (Array.isArray(sensor.state)) { if (sensor.state[sliderobj.index] < sliderobj.max) sensor.state[sliderobj.index] += step; } else { if (sensor.state < sliderobj.max) sensor.state += step; } drawSensor(sensor, true); }); sliderobj.minusset = paper.set(); sliderobj.minuscircle = paper.circle(minuscirclex, minuscircley, circleradius); sliderobj.minuscircle.attr("fill", "#F5A621"); sliderobj.minuscircle.attr("stroke", "#F5A621"); sliderobj.minus = paper.text(minuscirclex, minuscircley, "-"); sliderobj.minus.attr({ fill: "white" }); sliderobj.minus.node.style = "-moz-user-select: none; -webkit-user-select: none;"; sliderobj.minusset.push(sliderobj.minuscircle, sliderobj.minus); sliderobj.minusset.click(function () { var step = 1; var sensorDef = findSensorDefinition(sensor); if (sensorDef.step) step = sensorDef.step; if (Array.isArray(sensor.state)) { if (sensor.state[sliderobj.index] > sliderobj.min) sensor.state[sliderobj.index] -= step; } else { if (sensor.state > sliderobj.min) sensor.state -= step; } drawSensor(sensor, true); }); var thumbwidth = outsidewidth * .80; sliderobj.sliderdata.thumbheight = outsidewidth * 1.4; sliderobj.sliderdata.scale = (sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight); if (Array.isArray(sensor.state)) { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state[index], sensor); } else { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state, sensor); } var thumby = sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight - (percentage * sliderobj.sliderdata.scale); var thumbx = insiderectx + (insidewidth / 2) - (thumbwidth / 2); sliderobj.thumb = paper.rect(thumbx, thumby, thumbwidth, sliderobj.sliderdata.thumbheight, outsidewidth / 2); sliderobj.thumb.attr("fill", "#F5A621"); sliderobj.thumb.attr("stroke", "#F5A621"); sliderobj.slider = paper.setFinish(); sliderobj.thumb.drag( function (dx, dy, x, y, event) { var newy = sliderobj.sliderdata.zero + dy; if (newy < sliderobj.sliderdata.insiderecty) newy = sliderobj.sliderdata.insiderecty; if (newy > sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight) newy = sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight; sliderobj.thumb.attr('y', newy); var percentage = 1 - ((newy - sliderobj.sliderdata.insiderecty) / sliderobj.sliderdata.scale); if (Array.isArray(sensor.state)) { sensor.state[sliderobj.index] = findSensorDefinition(sensor).getStateFromPercentage(percentage); } else { sensor.state = findSensorDefinition(sensor).getStateFromPercentage(percentage); } drawSensor(sensor, true); }, function (x, y, event) { sliderobj.sliderdata.zero = sliderobj.thumb.attr('y'); }, function (event) { } ); return sliderobj; } function setSlider(sensor, juststate, imgx, imgy, imgw, imgh, min, max, triaxial) { if (juststate) { if (Array.isArray(sensor.state)) { for (var i = 0; i < sensor.state.length; i++) { if (sensor.sliders[i] == undefined) continue; var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state[i], sensor); thumby = sensor.sliders[i].sliderdata.insiderecty + sensor.sliders[i].sliderdata.insideheight - sensor.sliders[i].sliderdata.thumbheight - (percentage * sensor.sliders[i].sliderdata.scale); sensor.sliders[i].thumb.attr('y', thumby); } } else { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state, sensor); thumby = sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight - (percentage * sensor.sliders[0].sliderdata.scale); sensor.sliders[0].thumb.attr('y', thumby); } return; } removeSlider(sensor); sensor.sliders = []; var actuallydragged; sensor.hasslider = true; sensor.focusrect.drag( function (dx, dy, x, y, event) { if (sensor.sliders.length != 1) return; var newy = sensor.sliders[0].sliderdata.zero + dy; if (newy < sensor.sliders[0].sliderdata.insiderecty) newy = sensor.sliders[0].sliderdata.insiderecty; if (newy > sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight) newy = sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight; sensor.sliders[0].thumb.attr('y', newy); var percentage = 1 - ((newy - sensor.sliders[0].sliderdata.insiderecty) / sensor.sliders[0].sliderdata.scale); sensor.state = findSensorDefinition(sensor).getStateFromPercentage(percentage); drawSensor(sensor, true); actuallydragged++; }, function (x, y, event) { showSlider(); actuallydragged = 0; if (sensor.sliders.length == 1) sensor.sliders[0].sliderdata.zero = sensor.sliders[0].thumb.attr('y'); }, function (event) { if (actuallydragged > 4) { hideSlider(sensor); } } ); function showSlider() { hideSlider(sensorWithSlider); sensorWithSlider = sensor; if (Array.isArray(sensor.state)) { var offset = 0; var sign = -1; if (sensor.drawInfo.x - ((sensor.state.length - 1) * sensor.drawInfo.width / 5) < 0) { sign = 1; offset = sensor.drawInfo.width; } for (var i = 0; i < sensor.state.length; i++) { sliderobj = createSlider(sensor, max, min, sensor.drawInfo.x + offset + (sign * i * sensor.drawInfo.width / 5) , sensor.drawInfo.y, sensor.drawInfo.width, sensor.drawInfo.height, i); sensor.sliders.push(sliderobj); } } else { sliderobj = createSlider(sensor, max, min, sensor.drawInfo.x, sensor.drawInfo.y, sensor.drawInfo.width, sensor.drawInfo.height, 0); sensor.sliders.push(sliderobj); } } } function removeSlider(sensor) { if (sensor.hasslider && sensor.focusrect) { sensor.focusrect.undrag(); sensor.hasslider = false; } if (sensor.sliders) { for (var i = 0; i < sensor.sliders.length; i++) { sensor.sliders[i].slider.remove(); } sensor.sliders = []; } } function sensorInConnectedModeError() { window.displayHelper.showPopupMessage(strings.messages.sensorInOnlineMode, 'blanket'); } function actuatorsInRunningModeError() { window.displayHelper.showPopupMessage(strings.messages.actuatorsWhenRunning, 'blanket'); } function drawSensor(sensor, juststate = false, donotmovefocusrect = false) { if (paper == undefined || !context.display || !sensor.drawInfo) return; var imgw = sensor.drawInfo.width / 2; var imgh = sensor.drawInfo.height / 2; var imgx = sensor.drawInfo.x + imgw / 6; var imgy = sensor.drawInfo.y + (sensor.drawInfo.height / 2) - (imgh / 2); var state1x = (imgx + imgw) + 3; var state1y = imgy + imgh / 3; var portx = state1x; var porty = imgy; var namex = sensor.drawInfo.x + (sensor.drawInfo.height / 2); var namey = sensor.drawInfo.y + (imgh * 0.20); var nameanchor = "middle"; var portsize = sensor.drawInfo.height * 0.10; var statesize = sensor.drawInfo.height * 0.09; var namesize = sensor.drawInfo.height * 0.10; var drawPortText = true; var drawName = true; if (!sensor.focusrect || !sensor.focusrect.paper.canvas) sensor.focusrect = paper.rect(imgx, imgy, imgw, imgh); sensor.focusrect.attr({ "fill": "468DDF", "fill-opacity": 0, "opacity": 0, "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (context.autoGrading) { imgw = sensor.drawInfo.width * .80; imgh = sensor.drawInfo.height * .80; imgx = sensor.drawInfo.x + imgw * 0.75; imgy = sensor.drawInfo.y + (sensor.drawInfo.height / 2) - (imgh / 2); state1x = imgx + imgw * 1.2; state1y = imgy + (imgh / 2); portx = sensor.drawInfo.x; porty = imgy + (imgh / 2); portsize = imgh / 3; statesize = sensor.drawInfo.height * 0.2; namex = portx; namesize = portsize; nameanchor = "start"; } if (sensor.type == "led") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 0; if (!sensor.ledoff || !sensor.ledoff.paper.canvas) { sensor.ledoff = paper.image(getImg('ledoff.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } if (!sensor.ledon || !sensor.ledon.paper.canvas) { var imagename = "ledon-"; if (sensor.subType) imagename += sensor.subType; else imagename += "red"; imagename += ".png"; sensor.ledon = paper.image(getImg(imagename), imgx, imgy, imgw, imgh); } sensor.ledon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.ledoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.showAsAnalog) { sensor.stateText = paper.text(state1x, state1y, sensor.state); } else { if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.stateText = paper.text(state1x, state1y, "OFF"); } } if (sensor.state) { sensor.ledon.attr({ "opacity": 1 }); sensor.ledoff.attr({ "opacity": 0 }); } else { sensor.ledon.attr({ "opacity": 0 }); sensor.ledoff.attr({ "opacity": 1 }); } var x = typeof sensor.state; if(typeof sensor.state == 'number' ) { sensor.ledon.attr({ "opacity": sensor.state }); sensor.ledoff.attr({ "opacity": 1 }); } if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); } } else if (sensor.type == "buzzer") { if(typeof sensor.state == 'number' && sensor.state != 0 && sensor.state != 1) { buzzerSound.start(sensor.name, sensor.state); } else if (sensor.state) { buzzerSound.start(sensor.name); } else { buzzerSound.stop(sensor.name); } if(!juststate) { if(sensor.muteBtn) { sensor.muteBtn.remove(); } var muteBtnSize = sensor.drawInfo.width * 0.15; sensor.muteBtn = paper.text( state1x, state1y + imgh / 2, buzzerSound.isMuted(sensor.name) ? "\uf6a9" : "\uf028" ); sensor.muteBtn.node.style.fontWeight = "bold"; sensor.muteBtn.node.style.cursor = "default"; sensor.muteBtn.node.style.MozUserSelect = "none"; sensor.muteBtn.node.style.WebkitUserSelect = "none"; sensor.muteBtn.attr({ "font-size": muteBtnSize + "px", fill: buzzerSound.isMuted(sensor.name) ? "lightgray" : "#468DDF", "font-family": '"Font Awesome 5 Free"', 'text-anchor': 'start' }); sensor.muteBtn.click(function () { if(buzzerSound.isMuted(sensor.name)) { buzzerSound.unmute(sensor.name) } else { buzzerSound.mute(sensor.name) } drawSensor(sensor); }); } if (!sensor.buzzeron || !sensor.buzzeron.paper.canvas) sensor.buzzeron = paper.image(getImg('buzzer-ringing.png'), imgx, imgy, imgw, imgh); if (!sensor.buzzeroff || !sensor.buzzeroff.paper.canvas) { sensor.buzzeroff = paper.image(getImg('buzzer.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } if (sensor.state) { if (!sensor.buzzerInterval) { sensor.buzzerInterval = setInterval(function () { if (!sensor.removed) { sensor.ringingState = !sensor.ringingState; drawSensor(sensor, true, true); } else { clearInterval(sensor.buzzerInterval); } }, 100); } } else { if (sensor.buzzerInterval) { clearInterval(sensor.buzzerInterval); sensor.buzzerInterval = null; sensor.ringingState = null; } } sensor.buzzeron.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buzzeroff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); var drawState = sensor.state; if (sensor.ringingState != null) drawState = sensor.ringingState; if (drawState) { sensor.buzzeron.attr({ "opacity": 1 }); sensor.buzzeroff.attr({ "opacity": 0 }); } else { sensor.buzzeron.attr({ "opacity": 0 }); sensor.buzzeroff.attr({ "opacity": 1 }); } if (sensor.stateText) sensor.stateText.remove(); var stateText = findSensorDefinition(sensor).getStateString(sensor.state); sensor.stateText = paper.text(state1x, state1y, stateText); if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { var setLiveState = findSensorDefinition(sensor).setLiveState; if (setLiveState) { setLiveState(sensor, sensor.state, function(x) {}); } } } else if (sensor.type == "button") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.buttonon || !sensor.buttonon.paper.canvas) sensor.buttonon = paper.image(getImg('buttonon.png'), imgx, imgy, imgw, imgh); if (!sensor.buttonoff || !sensor.buttonoff.paper.canvas) sensor.buttonoff = paper.image(getImg('buttonoff.png'), imgx, imgy, imgw, imgh); if (sensor.state == null) sensor.state = false; sensor.buttonon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buttonoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.buttonon.attr({ "opacity": 1 }); sensor.buttonoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.buttonon.attr({ "opacity": 0 }); sensor.buttonoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if (!context.autoGrading && !sensor.buttonon.node.onmousedown) { sensor.focusrect.node.onmousedown = function () { if (context.offLineMode) { sensor.state = true; drawSensor(sensor); } else sensorInConnectedModeError(); }; sensor.focusrect.node.onmouseup = function () { if (context.offLineMode) { sensor.state = false; sensor.wasPressed = true; drawSensor(sensor); if (sensor.onPressed) sensor.onPressed(); } else sensorInConnectedModeError(); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } } else if (sensor.type == "screen") { if (sensor.stateText) { sensor.stateText.remove(); sensor.stateText = null; } var borderSize = 5; var screenScale = 2; if(sensor.drawInfo.width < 300) { screenScale = 1; } if(sensor.drawInfo.width < 150) { screenScale = 0.5; } var screenScalerSize = { width: 128 * screenScale, height: 32 * screenScale } borderSize = borderSize * screenScale; imgw = screenScalerSize.width + borderSize * 2; imgh = screenScalerSize.height + borderSize * 2; imgx = sensor.drawInfo.x + Math.max(0, (sensor.drawInfo.width - imgw) * 0.5); imgy = sensor.drawInfo.y + Math.max(0, (sensor.drawInfo.height - imgh) * 0.5); portx = imgx + imgw + borderSize; porty = imgy + imgh / 3; /* if (context.autoGrading) { state1x = imgx + imgw; state1y = imgy + (imgh / 2); portsize = imgh / 4; statesize = imgh / 6; } */ statesize = imgh / 3.5; if (!sensor.img || !sensor.img.paper.canvas) { sensor.img = paper.image(getImg('screen.png'), imgx, imgy, imgw, imgh); } sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { if (sensor.state.isDrawingData) { if (!sensor.screenrect || !sensor.screenrect.paper.canvas || !sensor.canvasNode) { sensor.screenrect = paper.rect(imgx, imgy, screenScalerSize.width, screenScalerSize.height); sensor.canvasNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignObject'); sensor.canvasNode.setAttribute("x",imgx + borderSize); //Set rect data sensor.canvasNode.setAttribute("y",imgy + borderSize); //Set rect data sensor.canvasNode.setAttribute("width", screenScalerSize.width); //Set rect data sensor.canvasNode.setAttribute("height", screenScalerSize.height); //Set rect data paper.canvas.appendChild(sensor.canvasNode); sensor.canvas = document.createElement("canvas"); sensor.canvas.id = "screencanvas"; sensor.canvas.width = screenScalerSize.width; sensor.canvas.height = screenScalerSize.height; sensor.canvasNode.appendChild(sensor.canvas); } sensor.canvasNode.setAttribute("x", imgx + borderSize); //Set rect data sensor.canvasNode.setAttribute("y", imgy + borderSize); //Set rect data sensor.canvasNode.setAttribute("width", screenScalerSize.width); //Set rect data sensor.canvasNode.setAttribute("height", screenScalerSize.height); //Set rect data sensor.screenrect.attr({ "x": imgx + borderSize, "y": imgy + borderSize, "width": 128, "height": 32, }); sensor.screenrect.attr({ "opacity": 0 }); sensor.screenDrawing.copyToCanvas(sensor.canvas, screenScale); } else { var statex = imgx + (imgw * .05); var statey = imgy + (imgh * .2); if (sensor.state.line1.length > 16) sensor.state.line1 = sensor.state.line1.substring(0, 16); if (sensor.state.line2 && sensor.state.line2.length > 16) sensor.state.line2 = sensor.state.line2.substring(0, 16); if (sensor.canvasNode) { $(sensor.canvasNode).remove(); sensor.canvasNode = null; } sensor.stateText = paper.text(statex, statey, sensor.state.line1 + "\n" + (sensor.state.line2 ? sensor.state.line2 : "")); sensor.stateText.attr("") } } } else if (sensor.type == "temperature") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 25; // FIXME if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('temperature-cold.png'), imgx, imgy, imgw, imgh); if (!sensor.img2 || !sensor.img2.paper.canvas) sensor.img2 = paper.image(getImg('temperature-hot.png'), imgx, imgy, imgw, imgh); if (!sensor.img3 || !sensor.img3.paper.canvas) sensor.img3 = paper.image(getImg('temperature-overlay.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.img2.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.img3.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); var scale = imgh / 60; var cliph = scale * sensor.state; sensor.img2.attr({ "clip-rect": imgx + "," + (imgy + imgh - cliph) + "," + (imgw) + "," + cliph }); sensor.stateText = paper.text(state1x, state1y, sensor.state + "C"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 60); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "servo") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('servo.png'), imgx, imgy, imgw, imgh); if (!sensor.pale || !sensor.pale.paper.canvas) sensor.pale = paper.image(getImg('servo-pale.png'), imgx, imgy, imgw, imgh); if (!sensor.center || !sensor.center.paper.canvas) sensor.center = paper.image(getImg('servo-center.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); sensor.center.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.rotate(sensor.state); if (sensor.state == null) sensor.state = 0; sensor.state = Math.round(sensor.state); sensor.stateText = paper.text(state1x, state1y, sensor.state + "°"); if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { if (!sensor.updatetimeout) { sensor.updatetimeout = setTimeout(function () { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); sensor.updatetimeout = null; }, 100); } } if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 180); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "potentiometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('potentiometer.png'), imgx, imgy, imgw, imgh); if (!sensor.pale || !sensor.pale.paper.canvas) sensor.pale = paper.image(getImg('potentiometer-pale.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); if (sensor.state == null) sensor.state = 0; sensor.pale.rotate(sensor.state * 3.6); sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "range") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('range.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 500; if (sensor.rangedistance) sensor.rangedistance.remove(); if (sensor.rangedistancestart) sensor.rangedistancestart.remove(); if (sensor.rangedistanceend) sensor.rangedistanceend.remove(); var rangew; if (sensor.state < 30) { rangew = imgw * sensor.state / 100; } else { var firstpart = imgw * 30 / 100; var remaining = imgw - firstpart; rangew = firstpart + (remaining * (sensor.state) * 0.0015); } var centerx = imgx + (imgw / 2); sensor.rangedistance = paper.path(["M", centerx - (rangew / 2), imgy + imgw, "L", centerx + (rangew / 2), imgy + imgw]); var markh = 16; sensor.rangedistancestart = paper.path(["M", centerx - (rangew / 2), imgy + imgw - (markh / 2), "L", centerx - (rangew / 2), imgy + imgw + (markh / 2)]); sensor.rangedistanceend = paper.path(["M", centerx + (rangew / 2), imgy + imgw - (markh / 2), "L", centerx + (rangew / 2), imgy + imgw + (markh / 2)]); sensor.rangedistance.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); sensor.rangedistancestart.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); sensor.rangedistanceend.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); if (sensor.state >= 10) sensor.state = Math.round(sensor.state); sensor.stateText = paper.text(state1x, state1y, sensor.state + "cm"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 500); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "light") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('light.png'), imgx, imgy, imgw, imgh); if (!sensor.moon || !sensor.moon.paper.canvas) sensor.moon = paper.image(getImg('light-moon.png'), imgx, imgy, imgw, imgh); if (!sensor.sun || !sensor.sun.paper.canvas) sensor.sun = paper.image(getImg('light-sun.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 0; if (sensor.state > 50) { var opacity = (sensor.state - 50) * 0.02; sensor.sun.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": opacity * .80 }); sensor.moon.attr({ "opacity": 0 }); } else { var opacity = (50 - sensor.state) * 0.02; sensor.moon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": opacity * .80 }); sensor.sun.attr({ "opacity": 0 }); } sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "humidity") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('humidity.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 0; sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "accelerometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('accel.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.stateText) sensor.stateText.remove(); if (!sensor.state) { sensor.state = [0, 0, 1]; } if (sensor.state) { try { sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "m/s²\nY: " + sensor.state[1] + "m/s²\nZ: " + sensor.state[2] + "m/s²"); } catch (Err) { var a = 1; } } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -8 * 9.81, 8 * 9.81); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "gyroscope") { if (!sensor.state) { sensor.state = [0, 0, 0]; } if (sensor.stateText) { sensor.stateText.remove(); } sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "°/s\nY: " + sensor.state[1] + "°/s\nZ: " + sensor.state[2] + "°/s"); if (!context.autoGrading && context.offLineMode) { var img3d = gyroscope3D.getInstance(imgw, imgh); } if(img3d) { if (!sensor.screenrect || !sensor.screenrect.paper.canvas) { sensor.screenrect = paper.rect(imgx, imgy, imgw, imgh); sensor.screenrect.attr({ "opacity": 0 }); sensor.canvasNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignObject'); sensor.canvasNode.setAttribute("x", imgx); sensor.canvasNode.setAttribute("y", imgy); sensor.canvasNode.setAttribute("width", imgw); sensor.canvasNode.setAttribute("height", imgh); paper.canvas.appendChild(sensor.canvasNode); sensor.canvas = document.createElement("canvas"); sensor.canvas.width = imgw; sensor.canvas.height = imgh; sensor.canvasNode.appendChild(sensor.canvas); } var sensorCtx = sensor.canvas.getContext('2d'); sensorCtx.clearRect(0, 0, imgw, imgh); sensorCtx.drawImage(img3d.render( sensor.state[0], sensor.state[2], sensor.state[1] ), 0, 0); if(!juststate) { sensor.focusrect.drag( function(dx, dy, x, y, event) { sensor.state[0] = Math.max(-125, Math.min(125, sensor.old_state[0] + dy)); sensor.state[1] = Math.max(-125, Math.min(125, sensor.old_state[1] - dx)); drawSensor(sensor, true) }, function() { sensor.old_state = sensor.state.slice(); } ); } } else { if (!sensor.img || !sensor.img.paper.canvas) { sensor.img = paper.image(getImg('gyro.png'), imgx, imgy, imgw, imgh); } sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -125, 125); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } } else if (sensor.type == "magnetometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('mag.png'), imgx, imgy, imgw, imgh); if (!sensor.needle || !sensor.needle.paper.canvas) sensor.needle = paper.image(getImg('mag-needle.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.needle.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); if (!sensor.state) { sensor.state = [0, 0, 0]; } if (sensor.state) { var heading = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; sensor.needle.rotate(heading); } if (sensor.stateText) sensor.stateText.remove(); if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "μT\nY: " + sensor.state[1] + "μT\nZ: " + sensor.state[2] + "μT"); } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -1600, 1600); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "sound") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 25; // FIXME if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('sound.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.stateText) sensor.stateText.remove(); if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, sensor.state); } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 60); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "irtrans") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.ledon || !sensor.ledon.paper.canvas) { sensor.ledon = paper.image(getImg("irtranson.png"), imgx, imgy, imgw, imgh); } if (!sensor.ledoff || !sensor.ledoff.paper.canvas) { sensor.ledoff = paper.image(getImg('irtransoff.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } sensor.ledon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.ledoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.ledon.attr({ "opacity": 1 }); sensor.ledoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.ledon.attr({ "opacity": 0 }); sensor.ledoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); } } else if (sensor.type == "irrecv") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.buttonon || !sensor.buttonon.paper.canvas) sensor.buttonon = paper.image(getImg('irrecvon.png'), imgx, imgy, imgw, imgh); if (!sensor.buttonoff || !sensor.buttonoff.paper.canvas) sensor.buttonoff = paper.image(getImg('irrecvoff.png'), imgx, imgy, imgw, imgh); sensor.buttonon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buttonoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.buttonon.attr({ "opacity": 1 }); sensor.buttonoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.buttonon.attr({ "opacity": 0 }); sensor.buttonoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if (!context.autoGrading && !sensor.buttonon.node.onmousedown) { sensor.focusrect.node.onmousedown = function () { if (context.offLineMode) { sensor.state = true; drawSensor(sensor); } else sensorInConnectedModeError(); }; sensor.focusrect.node.onmouseup = function () { if (context.offLineMode) { sensor.state = false; drawSensor(sensor); if (sensor.onPressed) sensor.onPressed(); } else sensorInConnectedModeError(); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } } else if (sensor.type == "stick") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('stick.png'), imgx, imgy, imgw, imgh); if (!sensor.imgup || !sensor.imgup.paper.canvas) sensor.imgup = paper.image(getImg('stickup.png'), imgx, imgy, imgw, imgh); if (!sensor.imgdown || !sensor.imgdown.paper.canvas) sensor.imgdown = paper.image(getImg('stickdown.png'), imgx, imgy, imgw, imgh); if (!sensor.imgleft || !sensor.imgleft.paper.canvas) sensor.imgleft = paper.image(getImg('stickleft.png'), imgx, imgy, imgw, imgh); if (!sensor.imgright || !sensor.imgright.paper.canvas) sensor.imgright = paper.image(getImg('stickright.png'), imgx, imgy, imgw, imgh); if (!sensor.imgcenter || !sensor.imgcenter.paper.canvas) sensor.imgcenter = paper.image(getImg('stickcenter.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.imgup.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgdown.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgleft.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgright.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgcenter.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); if (sensor.stateText) sensor.stateText.remove(); if (!sensor.state) sensor.state = [false, false, false, false, false]; var stateString = ""; if (sensor.state[0]) { stateString += "UP\n" sensor.imgup.attr({ "opacity": 1 }); } if (sensor.state[1]) { stateString += "DOWN\n" sensor.imgdown.attr({ "opacity": 1 }); } if (sensor.state[2]) { stateString += "LEFT\n" sensor.imgleft.attr({ "opacity": 1 }); } if (sensor.state[3]) { stateString += "RIGHT\n" sensor.imgright.attr({ "opacity": 1 }); } if (sensor.state[4]) { stateString += "CENTER\n" sensor.imgcenter.attr({ "opacity": 1 }); } sensor.stateText = paper.text(state1x, state1y, stateString); if (sensor.portText) sensor.portText.remove(); drawPortText = false; if (sensor.portText) sensor.portText.remove(); if (!context.autoGrading) { var gpios = findSensorDefinition(sensor).gpios; var min = 255; var max = 0; for (var i = 0; i < gpios.length; i++) { if (gpios[i] > max) max = gpios[i]; if (gpios[i] < min) min = gpios[i]; } sensor.portText = paper.text(portx, porty, "D" + min.toString() + "-D" + max.toString() + "?"); sensor.portText.attr({ "font-size": portsize + "px", 'text-anchor': 'start', fill: "blue" }); sensor.portText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; var b = sensor.portText._getBBox(); sensor.portText.translate(0, b.height / 2); $('#stickupstate').text(sensor.state[0] ? "ON" : "OFF"); $('#stickdownstate').text(sensor.state[1] ? "ON" : "OFF"); $('#stickleftstate').text(sensor.state[2] ? "ON" : "OFF"); $('#stickrightstate').text(sensor.state[3] ? "ON" : "OFF"); $('#stickcenterstate').text(sensor.state[4] ? "ON" : "OFF"); sensor.portText.click(function () { window.displayHelper.showPopupDialog(strings.messages.stickPortsDialog); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#picancel2').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#stickupname').text(sensor.name + ".up"); $('#stickdownname').text(sensor.name + ".down"); $('#stickleftname').text(sensor.name + ".left"); $('#stickrightname').text(sensor.name + ".right"); $('#stickcentername').text(sensor.name + ".center"); $('#stickupport').text("D" + gpios[0]); $('#stickdownport').text("D" + gpios[1]); $('#stickleftport').text("D" + gpios[2]); $('#stickrightport').text("D" + gpios[3]); $('#stickcenterport').text("D" + gpios[4]); $('#stickupstate').text(sensor.state[0] ? "ON" : "OFF"); $('#stickdownstate').text(sensor.state[1] ? "ON" : "OFF"); $('#stickleftstate').text(sensor.state[2] ? "ON" : "OFF"); $('#stickrightstate').text(sensor.state[3] ? "ON" : "OFF"); $('#stickcenterstate').text(sensor.state[4] ? "ON" : "OFF"); }); } function poinInRect(rect, x, y) { if (x > rect.left && x < rect.right && y > rect.top && y < rect.bottom) return true; return false; } function moveRect(rect, x, y) { rect.left += x; rect.right += x; rect.top += y; rect.bottom += y; } sensor.focusrect.node.onmousedown = function(evt) { if (!context.offLineMode) { sensorInConnectedModeError(); return; } var e = evt.target; var dim = e.getBoundingClientRect(); var rectsize = dim.width * .30; var rect = { left: dim.left, right: dim.left + rectsize, top: dim.top, bottom: dim.top + rectsize, } // Up left if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; sensor.state[2] = true; } // Up moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; } // Up right moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; sensor.state[3] = true; } // Right moveRect(rect, 0, rectsize); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[3] = true; } // Center moveRect(rect, -rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[4] = true; } // Left moveRect(rect, -rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[2] = true; } // Down left moveRect(rect, 0, rectsize); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; sensor.state[2] = true; } // Down moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; } // Down right moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; sensor.state[3] = true; } drawSensor(sensor); } sensor.focusrect.node.onmouseup = function(evt) { if (!context.offLineMode) { sensorInConnectedModeError(); return; } sensor.state = [false, false, false, false, false]; drawSensor(sensor); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } else if (sensor.type == "cloudstore") { if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('cloudstore.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); drawPortText = false; drawName = false; } else if (sensor.type == "clock") { if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('clock.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.stateText = paper.text(state1x, state1y, context.currentTime.toString() + "ms"); drawPortText = false; drawName = false; } sensor.focusrect.mousedown(function () { if (infos.customSensors && !context.autoGrading) { if (context.removerect) { context.removerect.remove(); } if (!context.runner || !context.runner.isRunning()) { context.removerect = paper.text(portx, imgy, "\uf00d"); // fa-times char removeRect = context.removerect; sensorWithRemoveRect = sensor; context.removerect.attr({ "font-size": "30" + "px", fill: "lightgray", "font-family": "Font Awesome 5 Free", 'text-anchor': 'start', "x": portx, "y": imgy, }); context.removerect.node.style = "-moz-user-select: none; -webkit-user-select: none;"; context.removerect.node.style.fontFamily = '"Font Awesome 5 Free"'; context.removerect.node.style.fontWeight = "bold"; context.removerect.click(function (element) { window.displayHelper.showPopupMessage(strings.messages.removeConfirmation, 'blanket', strings.messages.remove, function () { for (var i = 0; i < infos.quickPiSensors.length; i++) { if (infos.quickPiSensors[i] === sensor) { sensor.removed = true; infos.quickPiSensors.splice(i, 1); } } context.resetDisplay(); }, strings.messages.keep); }); } } }); if (sensor.stateText) { try { sensor.stateText.attr({ "font-size": statesize + "px", 'text-anchor': 'start', 'font-weight': 'bold', fill: "gray" }); var b = sensor.stateText._getBBox(); sensor.stateText.translate(0, b.height/2); sensor.stateText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; } catch (err) { } } if (drawPortText) { if (sensor.portText) sensor.portText.remove(); sensor.portText = paper.text(portx, porty, sensor.port); sensor.portText.attr({ "font-size": portsize + "px", 'text-anchor': 'start', fill: "gray" }); sensor.portText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; var b = sensor.portText._getBBox(); sensor.portText.translate(0,b.height/2); } if (sensor.nameText) { sensor.nameText.remove(); } if (drawName) { if (sensor.name) { sensor.nameText = paper.text(namex, namey, sensor.name ); sensor.nameText.attr({ "font-size": namesize + "px", 'text-anchor': nameanchor, fill: "#7B7B7B" }); sensor.nameText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; } } if (!donotmovefocusrect) { // This needs to be in front of everything sensor.focusrect.toFront(); } } context.registerQuickPiEvent = function (name, newState, setInSensor = true, allowFail = false) { var sensor = findSensorByName(name); if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } if (setInSensor) { sensor.state = newState; drawSensor(sensor); } if (context.autoGrading && context.gradingStatesBySensor != undefined) { var fail = false; var type = "actual"; if(!context.actualStatesBySensor[name]) { context.actualStatesBySensor[name] = []; } var actualStates = context.actualStatesBySensor[name]; var lastRealState = actualStates.length > 0 ? actualStates[actualStates.length-1] : null; if(lastRealState) { if(lastRealState.time == context.currentTime) { lastRealState.state = newState; } else { actualStates.push({time: context.currentTime, state: newState}); } } else { actualStates.push({time: context.currentTime, state: newState}); } drawNewStateChangesSensor(name, newState); context.increaseTime(sensor); } } function drawNewStateChangesSensor(name, newState=null) { var sensor = findSensorByName(name); if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } var sensorDef = findSensorDefinition(sensor); if(sensor.lastDrawnState !== null) { // Get all states between the last drawn time and now var expectedStates = context.getSensorExpectedState(name, sensor.lastDrawnTime, context.currentTime); for(var i = 0; expectedStates && i < expectedStates.length; i++) { // Draw the line up to the next expected state var expectedState = expectedStates[i]; var nextTime = i+1 < expectedStates.length ? expectedStates[i+1].time : context.currentTime; var type = "actual"; // Check the previous state if(!sensorDef.compareState(sensor.lastDrawnState, expectedState.state)) { type = "wrong"; } drawSensorTimeLineState(sensor, sensor.lastDrawnState, sensor.lastDrawnTime, nextTime, type, false, expectedState.state); sensor.lastDrawnTime = nextTime; } } sensor.lastDrawnTime = context.currentTime; if(newState !== null && sensor.lastDrawnState != newState) { // Draw the new state change if(sensor.lastDrawnState === null) { sensor.lastDrawnState = newState; } var type = "actual"; // Check the new state var expectedState = context.getSensorExpectedState(name, context.currentTime); if (expectedState !== null && !sensorDef.compareState(expectedState.state, newState)) { type = "wrong"; } drawSensorTimeLineState(sensor, newState, context.currentTime, context.currentTime, type, false, expectedState && expectedState.state); sensor.lastDrawnState = newState; } } function drawNewStateChanges() { // Draw all sensors if(!context.gradingStatesBySensor) { return; } for(var sensorName in context.gradingStatesBySensor) { drawNewStateChangesSensor(sensorName); } } context.increaseTime = function (sensor) { if (!sensor.lastTimeIncrease) { sensor.lastTimeIncrease = 0; } if (sensor.callsInTimeSlot == undefined) sensor.callsInTimeSlot = 0; if (sensor.lastTimeIncrease == context.currentTime) { sensor.callsInTimeSlot += 1; } else { sensor.lastTimeIncrease = context.currentTime; sensor.callsInTimeSlot = 1; } if (sensor.callsInTimeSlot > getQuickPiOption('increaseTimeAfterCalls')) { context.currentTime += context.tickIncrease; sensor.lastTimeIncrease = context.currentTime; sensor.callsInTimeSlot = 0; } drawCurrentTime(); if(context.autoGrading) { drawNewStateChanges(); } if(context.runner) { // Tell the runner an "action" happened context.runner.signalAction(); } } context.increaseTimeBy = function (time) { var iStates = 0; var newTime = context.currentTime + time; if (context.gradingStatesByTime) { // Advance until current time, ignore everything in the past. while (iStates < context.gradingStatesByTime.length && context.gradingStatesByTime[iStates].time < context.currentTime) iStates++; for (; iStates < context.gradingStatesByTime.length; iStates++) { var sensorState = context.gradingStatesByTime[iStates]; // Until the new time if (sensorState.time >= newTime) break; // Mark all inputs as hit if (sensorState.input) { sensorState.hit = true; // context.currentTime = sensorState.time; context.getSensorState(sensorState.name); } } } if(context.runner) { // Tell the runner an "action" happened context.runner.signalAction(); } context.currentTime = newTime; drawCurrentTime(); if (context.autoGrading) { drawNewStateChanges(); } } context.getSensorExpectedState = function (name, targetTime = null, upToTime = null) { var state = null; if(targetTime === null) { targetTime = context.currentTime; } if (!context.gradingStatesBySensor) { return null; } var actualname = name; var parts = name.split("."); if (parts.length == 2) { actualname = parts[0]; } var sensorStates = context.gradingStatesBySensor[actualname]; if (!sensorStates) return null; // Fail?? var lastState; var startTime = -1; for (var idx = 0; idx < sensorStates.length; idx++) { if (startTime >= 0 && targetTime >= startTime && targetTime < sensorStates[idx].time) { state = lastState; break; } startTime = sensorStates[idx].time; lastState = sensorStates[idx]; } // This is the end state if(state === null && targetTime >= startTime) { state = lastState; } if(state && upToTime !== null) { // If upToTime is given, return an array of states instead var states = [state]; for(var idx2 = idx+1; idx2 < sensorStates.length; idx2++) { if(sensorStates[idx2].time < upToTime) { states.push(sensorStates[idx2]); } else { break; } } return states; } else { return state; } } context.getSensorState = function (name) { var state = null; var sensor = findSensorByName(name); if (!context.display || context.autoGrading) { var stateTime = context.getSensorExpectedState(name); if (stateTime != null) { stateTime.hit = true; state = stateTime.state; if(sensor) { // Redraw from the beginning of this state sensor.lastDrawnTime = Math.min(sensor.lastDrawnTime, stateTime.time); } } else { state = 0; } } if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } if (state == null) { state = sensor.state; } else { sensor.state = state; drawSensor(sensor); } drawNewStateChangesSensor(sensor.name, sensor.state); context.increaseTime(sensor); return state; } // This will advance grading time to the next button release for waitForButton // will return false if the next event wasn't a button press context.advanceToNextRelease = function (sensorType, port) { var retval = false; var iStates = 0; // Advance until current time, ignore everything in the past. while (context.gradingStatesByTime[iStates].time <= context.currentTime) iStates++; for (; iStates < context.gradingStatesByTime.length; iStates++) { sensorState = context.gradingStatesByTime[iStates]; if (sensorState.type == sensorType && sensorState.port == port) { sensorState.hit = true; if (!sensorState.state) { context.currentTime = sensorState.time; retval = true; break; } } else { retval = false; break; } } return retval; }; /***** Functions *****/ /* Here we define each function of the library. Blocks will generally use context.group.blockName as their handler function, hence we generally use this name for the functions. */ context.quickpi.turnLedOn = function (callback) { context.registerQuickPiEvent("led1", true); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnLedOn()", cb); } }; context.quickpi.turnLedOff = function (callback) { context.registerQuickPiEvent("led1", false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnLedOff()", cb); } }; context.quickpi.turnBuzzerOn = function (callback) { context.registerQuickPiEvent("buzzer1", true); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnBuzzerOn()", cb); } }; context.quickpi.turnBuzzerOff = function (callback) { context.registerQuickPiEvent("buzzer1", false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnBuzzerOff()", cb); } }; context.quickpi.waitForButton = function (name, callback) { // context.registerQuickPiEvent("button", "D22", "wait", false); var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading) { context.advanceToNextRelease("button", sensor.port); context.waitDelay(callback); } else if (context.offLineMode) { if (sensor) { var cb = context.runner.waitCallback(callback); sensor.onPressed = function () { cb(); } } else { context.waitDelay(callback); } } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("waitForButton(\"" + name + "\")", cb); } }; context.quickpi.isButtonPressed = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("button"); var name = sensor.name; } else { var callback = arg2; var sensor = findSensorByName(arg1, true); var name = arg1; } if (!context.display || context.autoGrading || context.offLineMode) { if (sensor.type == "stick") { var state = context.getSensorState(name); var stickDefinition = findSensorDefinition(sensor); var buttonstate = stickDefinition.getButtonState(name, sensor.state); context.runner.noDelay(callback, buttonstate); } else { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } } else { var cb = context.runner.waitCallback(callback); if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); stickDefinition.getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); var buttonstate = stickDefinition.getButtonState(name, sensor.state); cb(buttonstate); }); } else { findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal != "0"; drawSensor(sensor); cb(returnVal != "0"); }); } } }; context.quickpi.isButtonPressedWithName = context.quickpi.isButtonPressed; context.quickpi.buttonWasPressed = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("buttonWasPressed(\"" + name + "\")", function (returnVal) { cb(returnVal != "0"); }); } }; context.quickpi.setLedState = function (name, state, callback) { var sensor = findSensorByName(name, true); var command = "setLedState(\"" + sensor.port + "\"," + (state ? "True" : "False") + ")"; context.registerQuickPiEvent(name, state ? true : false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.setBuzzerState = function (name, state, callback) { var sensor = findSensorByName(name, true); var command = "setBuzzerState(\"" + name + "\"," + (state ? "True" : "False") + ")"; context.registerQuickPiEvent(name, state ? true : false); if(context.display) { state ? buzzerSound.start(name) : buzzerSound.stop(name); } if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.isBuzzerOn = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("buzzer"); } else { var callback = arg2; var sensor = findSensorByName(arg1, true); } var command = "isBuzzerOn(\"" + sensor.name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState("buzzer1"); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isBuzzerOnWithName = context.quickpi.isBuzzerOn; context.quickpi.setBuzzerNote = function (name, frequency, callback) { var sensor = findSensorByName(name, true); var command = "setBuzzerNote(\"" + name + "\"," + frequency + ")"; context.registerQuickPiEvent(name, frequency); if(context.display && context.offLineMode) { buzzerSound.start(name, frequency); } if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.getBuzzerNote = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getBuzzerNote(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.setLedBrightness = function (name, level, callback) { var sensor = findSensorByName(name, true); if (typeof level == "object") { level = level.valueOf(); } var command = "setLedBrightness(\"" + name + "\"," + level + ")"; context.registerQuickPiEvent(name, level); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.getLedBrightness = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getLedBrightness(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isLedOn = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("led"); } else { var callback = arg2; var sensor = findSensorByName(arg1, true); } var command = "getLedState(\"" + sensor.name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isLedOnWithName = context.quickpi.isLedOn; context.quickpi.toggleLedState = function (name, callback) { var sensor = findSensorByName(name, true); var command = "toggleLedState(\"" + name + "\")"; var state = sensor.state; context.registerQuickPiEvent(name, !state); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { return returnVal != "0"; }); } }; context.quickpi.displayText = function (line1, arg2, arg3) { if(typeof arg3 == "undefined") { // Only one argument var line2 = null; var callback = arg2; } else { var line2 = arg2; var callback = arg3; } var sensor = findSensorByType("screen"); var command = "displayText(\"" + line1 + "\", \"\")"; context.registerQuickPiEvent(sensor.name, { line1: line1, line2: line2 } ); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function (retval) { cb(); }); } }; context.quickpi.displayText2Lines = context.quickpi.displayText; context.quickpi.readTemperature = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.sleep = function (time, callback) { context.increaseTimeBy(time); if (!context.display || context.autoGrading) { context.runner.noDelay(callback); } else { context.runner.waitDelay(callback, null, time); } }; context.quickpi.setServoAngle = function (name, angle, callback) { var sensor = findSensorByName(name, true); if (angle > 180) angle = 180; else if (angle < 0) angle = 0; context.registerQuickPiEvent(name, angle); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var command = "setServoAngle(\"" + name + "\"," + angle + ")"; cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.getServoAngle = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getServoAngle(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.readRotaryAngle = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readDistance = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readLightIntensity = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readHumidity = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.currentTime = function (callback) { var millis = new Date().getTime(); if (context.autoGrading) { millis = context.currentTime; } context.runner.waitDelay(callback, millis); }; context.quickpi.getTemperature = function(location, callback) { var retVal = 25; context.waitDelay(callback, retVal); }; context.initScreenDrawing = function(sensor) { if (!sensor.screenDrawing) sensor.screenDrawing = new screenDrawing(sensor.canvas); } context.quickpi.drawPoint = function(x, y, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawPoint(x, y); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawPoint(" + x + "," + y + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.isPointSet = function(x, y, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); var value = sensor.screenDrawing.isPointSet(x, y); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, value); } else { var cb = context.runner.waitCallback(callback); var command = "drawPoint(" + x + "," + y + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawLine = function(x0, y0, x1, y1, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawLine(x0, y0, x1, y1); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawLine(" + x0 + "," + y0 + "," + x1 + "," + y1 + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawRectangle = function(x0, y0, width, height, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawRectangle(x0, y0, width, height); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawRectangle(" + x0 + "," + y0 + "," + width + "," + height + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawCircle = function(x0, y0, diameter, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawCircle(x0, y0, diameter, diameter); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawCircle(" + x0 + "," + y0 + "," + diameter + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.clearScreen = function(callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.clearScreen(); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "clearScreen()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.updateScreen = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "updateScreen()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.autoUpdate = function(autoupdate, callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "autoUpdate(\"" + (autoupdate ? "True" : "False") + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.fill = function(color, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("screen"); if (sensor && sensor.canvas) { var ctx = sensor.canvas.getContext('2d'); context.noFill = false; if (color) ctx.fillStyle = "black"; else ctx.fillStyle = "white"; } context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "fill(\"" + color + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.noFill = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.noFill = true; context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "NoFill()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.stroke = function(color, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("screen"); if (sensor && sensor.canvas) { var ctx = sensor.canvas.getContext('2d'); context.noStroke = false; if (color) ctx.strokeStyle = "black"; else ctx.strokeStyle = "white"; } context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "stroke(\"" + color + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.noStroke = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.noStroke = true; context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "noStroke()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.readAcceleration = function(axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("accelerometer"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; var state = context.getSensorState(sensor.name); context.waitDelay(callback, state[index]); } else { var cb = context.runner.waitCallback(callback); var command = "readAcceleration(\"" + axis + "\")"; context.quickPiConnection.sendCommand(command, function (returnVal) { cb(returnVal); }); } }; context.quickpi.computeRotation = function(rotationType, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("accelerometer"); var zsign = 1; var result = 0; if (sensor.state[2] < 0) zsign = -1; if (rotationType == "pitch") { result = 180 * Math.atan2 (sensor.state[0], zsign * Math.sqrt(sensor.state[1]*sensor.state[1] + sensor.state[2]*sensor.state[2]))/Math.PI; } else if (rotationType == "roll") { result = 180 * Math.atan2 (sensor.state[1], zsign * Math.sqrt(sensor.state[0]*sensor.state[0] + sensor.state[2]*sensor.state[2]))/Math.PI; } result = Math.round(result); context.waitDelay(callback, result); } else { var cb = context.runner.waitCallback(callback); var command = "computeRotation(\"" + rotationType + "\")"; context.quickPiConnection.sendCommand(command, function (returnVal) { cb(returnVal); }); } }; context.quickpi.readSoundLevel = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readMagneticForce = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("magnetometer"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; context.waitDelay(callback, sensor.state[index]); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("magnetometer", "i2c"); findSensorDefinition(sensor).getLiveState(axis, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }); } }; context.quickpi.computeCompassHeading = function (callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("magnetometer"); var heading = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; heading = Math.round(heading); context.runner.noDelay(callback, heading); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("magnetometer", "i2c"); context.quickPiConnection.sendCommand("readMagnetometerLSM303C()", function(returnVal) { sensor.state = returnVal; drawSensor(sensor); returnVal = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; returnVal = Math.floor(returnVal); cb(returnVal); }, true); } }; context.quickpi.readInfraredState = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state ? true : false); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.setInfraredState = function (name, state, callback) { var sensor = findSensorByName(name, true); context.registerQuickPiEvent(name, state ? true : false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).setLiveState(sensor, state, cb); } }; //// Gyroscope context.quickpi.readAngularVelocity = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("gyroscope"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; context.waitDelay(callback, sensor.state[index]); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("gyroscope", "i2c"); findSensorDefinition(sensor).getLiveState(axis, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }); } }; context.quickpi.setGyroZeroAngle = function (callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.runner.noDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("setGyroZeroAngle()", function(returnVal) { cb(); }, true); } }; context.quickpi.computeRotationGyro = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState("gyroscope", "i2c"); context.runner.noDelay(callback, 0); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("gyroscope", "i2c"); context.quickPiConnection.sendCommand("computeRotationGyro()", function(returnVal) { //sensor.state = returnVal; //drawSensor(sensor); var returnVal = JSON.parse(returnVal); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }, true); } }; context.quickpi.connectToCloudStore = function (prefix, password, callback) { var sensor = findSensorByType("cloudstore"); if (!context.display || context.autoGrading) { sensor.quickStore = new quickPiStore(true); } else { sensor.quickStore = QuickStore(prefix, password); } context.runner.noDelay(callback, 0); }; context.quickpi.writeToCloudStore = function (identifier, key, value, callback) { var sensor = findSensorByType("cloudstore"); if (!sensor.quickStore || !sensor.quickStore.connected) { context.success = false; throw("Cloud store not connected"); } if (!context.display || context.autoGrading) { sensor.quickStore.write(identifier, key, value); context.registerQuickPiEvent(sensor.name, sensor.quickStore.getStateData()); context.runner.noDelay(callback); } else { var cb = context.runner.waitCallback(callback); sensor.quickStore.write(identifier, key, value, function(data) { if (!data || !data.success) { if (data && data.message) context.failImmediately = "cloudstore: " + data.message; else context.failImmediately = "Error trying to communicate with cloud store"; } cb(); }); } }; context.quickpi.readFromCloudStore = function (identifier, key, callback) { var sensor = findSensorByType("cloudstore"); if (!sensor.quickStore) { if (!context.display || context.autoGrading) { sensor.quickStore = new quickPiStore(); } else { sensor.quickStore = QuickStore(); } } if (!context.display || context.autoGrading) { var state = context.getSensorState(sensor.name); var value = ""; if (state.hasOwnProperty(key)) { value = state[key]; } else { context.success = false; throw("Key not found"); } sensor.quickStore.write(identifier, key, value); context.registerQuickPiEvent(sensor.name, sensor.quickStore.getStateData()); context.runner.noDelay(callback, value); } else { var cb = context.runner.waitCallback(callback); sensor.quickStore.read(identifier, key, function(data) { var value = ""; if (data && data.success) { value = JSON.parse(data.value); } else { if (data && data.message) context.failImmediately = "cloudstore: " + data.message; else context.failImmediately = "Error trying to communicate with cloud store"; } cb(value); }); } }; /***** Blocks definitions *****/ /* Here we define all blocks/functions of the library. Structure is as follows: { group: [{ name: "someName", // category: "categoryName", // yieldsValue: optional true: Makes a block with return value rather than simple command // params: optional array of parameter types. The value 'null' denotes /any/ type. For specific types, see the Blockly documentation ([1,2]) // handler: optional handler function. Otherwise the function context.group.blockName will be used // blocklyJson: optional Blockly JSON objects // blocklyInit: optional function for Blockly.Blocks[name].init // if not defined, it will be defined to call 'this.jsonInit(blocklyJson); // blocklyXml: optional Blockly xml string // codeGenerators: optional object: // { Python: function that generates Python code // JavaScript: function that generates JS code // } }] } [1] https://developers.google.com/blockly/guides/create-custom-blocks/define-blocks [2] https://developers.google.com/blockly/guides/create-custom-blocks/type-checks */ function getSensorNames(sensorType) { return function () { var ports = []; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == sensorType) { ports.push([sensor.name, sensor.name]); } } if (sensorType == "button") { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); for (var iStick = 0; iStick < stickDefinition.gpiosNames.length; iStick++) { var name = sensor.name + "." + stickDefinition.gpiosNames[iStick]; ports.push([name, name]); } } } } if (ports.length == 0) { ports.push(["none", "none"]); } return ports; } } function findSensorByName(name, error=false) { if (isNaN(name.substring(0, 1)) && !isNaN(name.substring(1))) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.port.toUpperCase() == name.toUpperCase()) { return sensor; } } } else { var firstname = name.split(".")[0]; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.name.toUpperCase() == firstname.toUpperCase()) { return sensor; } } } if (error) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } return null; } function findSensorByType(type) { var firstname = name.split(".")[0]; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == type) { return sensor; } } return null; } function findSensorByPort(port) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.port == port) { return sensor; } } return null; } function getSensorSuggestedName(type, suggested) { if (suggested) { if (!findSensorByName(suggested)) return suggested; } var i = 0; var newName; do { i++; newName = type + i.toString(); } while (findSensorByName(newName)); return newName; } context.customBlocks = { // Define our blocks for our namespace "template" quickpi: { // Categories are reflected in the Blockly menu sensors: [ { name: "currentTime", yieldsValue: true }, { name: "waitForButton", params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") } ] } }, { name: "isButtonPressed", yieldsValue: true }, { name: "isButtonPressedWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") }, ] } }, { name: "buttonWasPressed", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") } ] } }, { name: "readTemperature", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("temperature") } ] } }, { name: "readRotaryAngle", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("potentiometer") } ] } }, { name: "readDistance", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("range") } ] } }, { name: "readLightIntensity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("light") } ] } }, { name: "readHumidity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("humidity") } ] } }, { name: "readAcceleration", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "computeRotation", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["pitch", "pitch"], ["roll", "roll"]] } ] } }, { name: "readSoundLevel", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("sound") } ] } }, { name: "readMagneticForce", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "computeCompassHeading", yieldsValue: true }, { name: "readInfraredState", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("irrecv") } ] } }, { name: "readAngularVelocity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "setGyroZeroAngle" }, { name: "computeRotationGyro", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, ], actions: [ { name: "turnLedOn" }, { name: "turnLedOff" }, { name: "turnBuzzerOn" }, { name: "turnBuzzerOff" }, { name: "setLedState", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "setBuzzerState", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "setBuzzerNote", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='setBuzzerNote'>" + "<value name='PARAM_1'><shadow type='math_number'><field name='NUM'>200</field></shadow></value>" + "</block>" }, { name: "getBuzzerNote", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, ] } }, { name: "setLedBrightness", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='setLedBrightness'>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "getLedBrightness", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "isLedOn", yieldsValue: true }, { name: "isLedOnWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "isBuzzerOn", yieldsValue: true }, { name: "isBuzzerOnWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, ] } }, { name: "toggleLedState", params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "setServoAngle", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("servo") }, { "type": "input_value", "name": "PARAM_1" }, ] }, blocklyXml: "<block type='setServoAngle'>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "getServoAngle", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("servo") }, ] } }, { name: "setInfraredState", params: ["String", "Number"], blocklyJson: { "args0": [ {"type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("irtrans")}, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "sleep", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "value": 0 }, ] } , blocklyXml: "<block type='sleep'>" + "<value name='PARAM_0'><shadow type='math_number'><field name='NUM'>1000</field></shadow></value>" + "</block>" }, ], display: [ { name: "displayText", params: ["String", "String"], variants: [[null], [null, null]], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "text": "" }, ] }, blocklyXml: "<block type='displayText'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'>Bonjour</field> </shadow></value>" + "</block>" }, { name: "displayText2Lines", params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "text": "" }, { "type": "input_value", "name": "PARAM_1", "text": "" }, ] }, blocklyXml: "<block type='displayText2Lines'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'>Bonjour</field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "drawPoint", params: ["Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='drawPoint'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "isPointSet", yieldsValue: true, params: ["Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='isPointSet'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawLine", params: ["Number", "Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, { "type": "input_value", "name": "PARAM_3"}, ] }, blocklyXml: "<block type='drawLine'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_3'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawRectangle", params: ["Number", "Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, { "type": "input_value", "name": "PARAM_3"}, ] }, blocklyXml: "<block type='drawRectangle'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_3'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawCircle", params: ["Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, ] }, blocklyXml: "<block type='drawCircle'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "clearScreen" }, { name: "updateScreen" }, { name: "autoUpdate", params: ["Boolean"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ], }, blocklyXml: "<block type='autoUpdate'>" + "<value name='PARAM_0'><shadow type='logic_boolean'></shadow></value>" + "</block>" }, { name: "fill", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ] }, blocklyXml: "<block type='fill'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "noFill" }, { name: "stroke", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ] }, blocklyXml: "<block type='stroke'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "noStroke" }, ], internet: [ { name: "getTemperature", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_input", "name": "PARAM_0", text: "Paris, France"}, ] }, }, { name: "connectToCloudStore", params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, ] }, blocklyXml: "<block type='connectToCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "writeToCloudStore", params: ["String", "String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, { "type": "input_value", "name": "PARAM_2", text: ""}, ] }, blocklyXml: "<block type='writeToCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_2'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "readFromCloudStore", yieldsValue: true, params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, ] }, blocklyXml: "<block type='readFromCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, ] } // We can add multiple namespaces by adding other keys to customBlocks. }; // Color indexes of block categories (as a hue in the range 0–420) context.provideBlocklyColours = function () { return { categories: { actions: 0, sensors: 100, internet: 200, display: 300, } }; }; // Constants available in Python context.customConstants = { quickpi: [ ] }; // Don't forget to return our newly created context! return context; } // Register the library; change "template" by the name of your library in lowercase if (window.quickAlgoLibraries) { quickAlgoLibraries.register('quickpi', getContext); } else { if (!window.quickAlgoLibrariesList) { window.quickAlgoLibrariesList = []; } window.quickAlgoLibrariesList.push(['quickpi', getContext]); } var sensorWithSlider = null; var removeRect = null; var sensorWithRemoveRect = null; window.addEventListener('click', function (e) { var keep = false; var keepremove = false; e = e || window.event; var target = e.target || e.srcElement; if (sensorWithRemoveRect && sensorWithRemoveRect.focusrect && target == sensorWithRemoveRect.focusrect.node) keepremove = true; if (removeRect && !keepremove) { removeRect.remove(); removeRect = null; } if (sensorWithSlider && sensorWithSlider.focusrect && target == sensorWithSlider.focusrect.node) keep = true; if (sensorWithSlider && sensorWithSlider.sliders) { for (var i = 0; i < sensorWithSlider.sliders.length; i++) { sensorWithSlider.sliders[i].slider.forEach(function (element) { if (target == element.node || target.parentNode == element.node) { keep = true; return false; } }); } } if (!keep) { hideSlider(sensorWithSlider); } }, false);//<-- we'll get to the false in a minute function hideSlider(sensor) { if (!sensor) return; if (sensor.sliders) { for (var i = 0; i < sensor.sliders.length; i++) { sensor.sliders[i].slider.remove(); } sensor.sliders = []; } if (sensor.focusrect && sensor.focusrect.paper && sensor.focusrect.paper.canvas) sensor.focusrect.toFront(); };
pemFioi/quickpi/blocklyQuickPi_lib.js
//"use strict"; var buzzerSound = { context: null, default_freq: 200, channels: {}, muted: {}, getContext: function() { if(!this.context) { this.context = ('AudioContext' in window) || ('webkitAudioContext' in window) ? new(window.AudioContext || window.webkitAudioContext)() : null; } return this.context; }, startOscillator: function(freq) { var o = this.context.createOscillator(); o.type = 'sine'; o.frequency.value = freq; o.connect(this.context.destination); o.start(); return o; }, start: function(channel, freq=this.default_freq) { if(!this.channels[channel]) { this.channels[channel] = { muted: false } } if(this.channels[channel].freq === freq) { return; } var context = this.getContext(); if(!context) { return; } this.stop(channel); if (freq == 0 || this.channels[channel].muted) { return; } this.channels[channel].oscillator = this.startOscillator(freq); this.channels[channel].freq = freq; }, stop: function(channel) { if(this.channels[channel]) { this.channels[channel].oscillator && this.channels[channel].oscillator.stop(); delete this.channels[channel].oscillator; delete this.channels[channel].freq; } }, mute: function(channel) { if(!this.channels[channel]) { this.channels[channel] = { muted: true } return; } this.channels[channel].muted = true; this.channels[channel].oscillator && this.channels[channel].oscillator.stop(); delete this.channels[channel].oscillator; }, unmute: function(channel) { if(!this.channels[channel]) { this.channels[channel] = { muted: false } return; } this.channels[channel].muted = false; if(this.channels[channel].freq) { this.channels[channel].oscillator = this.startOscillator(this.channels[channel].freq); } }, isMuted: function(channel) { if(this.channels[channel]) { return this.channels[channel].muted; } return false; }, stopAll: function() { for(var channel in this.channels) { if(this.channels.hasOwnProperty(channel)) { this.stop(channel); } } } } var gyroscope3D = (function() { var instance; function createInstance(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; // debug code start /* canvas.style.zIndex = 99999; canvas.style.position = 'fixed'; canvas.style.top = '0'; canvas.style.left = '0'; document.body.appendChild(canvas); */ // debug code end try { var renderer = new zen3d.Renderer(canvas, { antialias: true, alpha: true }); } catch(e) { return false; } renderer.glCore.state.colorBuffer.setClear(0, 0, 0, 0); var scene = new zen3d.Scene(); var lambert = new zen3d.LambertMaterial(); lambert.diffuse.setHex(0x468DDF); var cube_geometry = new zen3d.CubeGeometry(10, 2, 10); var cube = new zen3d.Mesh(cube_geometry, lambert); cube.position.x = 0; cube.position.y = 0; cube.position.z = 0; scene.add(cube); var ambientLight = new zen3d.AmbientLight(0xffffff, 2); scene.add(ambientLight); var pointLight = new zen3d.PointLight(0xffffff, 1, 100); pointLight.position.set(-20, 40, 10); scene.add(pointLight); var camera = new zen3d.Camera(); camera.position.set(0, 13, 13); camera.lookAt(new zen3d.Vector3(0, 0, 0), new zen3d.Vector3(0, 1, 0)); camera.setPerspective(45 / 180 * Math.PI, width / height, 1, 1000); scene.add(camera); return { resize: function(width, height) { camera.setPerspective( 45 / 180 * Math.PI, width / height, 1, 1000 ); }, render: function(ax, ay, az) { cube.euler.x = Math.PI * ax / 360; cube.euler.y = Math.PI * ay / 360; cube.euler.z = Math.PI * az / 360; renderer.render(scene, camera); return canvas; } } } return { getInstance: function(width, height) { if(!instance) { instance = createInstance(width, height); } else { instance.resize(width, height) } return instance; } } })(); function QuickStore(rwidentifier, rwpassword) { var url = 'http://cloud.quick-pi.org'; var connected = (rwidentifier === undefined); function post(path, data, callback) { $.ajax({ type: 'POST', url: url + path, crossDomain: true, data: data, dataType: 'json', success: callback }); } return { connected: rwpassword, read: function(identifier, key, callback) { var data = { prefix: identifier, key: key }; post('/api/data/read', data, callback); }, write: function(identifier, key, value, callback) { if (identifier != rwidentifier) { callback({ sucess: false, message: "Tried to write to read/only identifier", }); } else { var data = { prefix: identifier, password: rwpassword, key: key, value: JSON.stringify(value) }; post('/api/data/write', data, callback); } } } } // This is a template of library for use with quickAlgo. var getContext = function (display, infos, curLevel) { window.quickAlgoInterface.stepDelayMin = 0.0001; // Local language strings for each language var introControls = null; var localLanguageStrings = { fr: { // French strings label: { // Labels for the blocks sleep: "attendre %1 millisecondes", currentTime: "temps écoulé en millisecondes", turnLedOn: "allumer la LED", turnLedOff: "éteindre la LED", setLedState: "passer la LED %1 à %2 ", toggleLedState: "inverser la LED %1", isLedOn: "LED allumée", isLedOnWithName: "LED %1 allumée", setLedBrightness: "mettre la luminosité de %1 à %2", getLedBrightness: "lire la luminosité de %1", turnBuzzerOn: "allumer le buzzer", turnBuzzerOff: "éteindre le buzzer", setBuzzerState: "mettre le buzzer %1 à %2", isBuzzerOn: "buzzer allumé", isBuzzerOnWithName: "buzzer %1 allumé", setBuzzerNote: "jouer la fréquence %2Hz sur %1", getBuzzerNote: "fréquence du buzzer %1", isButtonPressed: "bouton enfoncé", isButtonPressedWithName: "bouton %1 enfoncé", waitForButton: "attendre une pression sur le bouton", buttonWasPressed: "le bouton a été enfoncé", displayText: "afficher %1", displayText2Lines: "afficher Ligne 1: %1 Ligne 2: %2", readTemperature: "température ambiante", getTemperature: "temperature de %1", readRotaryAngle: "état du potentiomètre %1", readDistance: "distance mesurée par %1", readLightIntensity: "intensité lumineuse", readHumidity: "humidité ambiante", setServoAngle: "mettre le servo %1 à l'angle %2", getServoAngle: "angle du servo %1", drawPoint: "draw pixel", isPointSet: "is pixel set in screen", drawLine: "ligne x₀: %1 y₀: %2 x₁: %3 y₁: %4", drawRectangle: "rectangle x₀: %1 y₀: %2 largeur₀: %3 hauteur₀: %4", drawCircle: "cercle x₀: %1 y₀: %2 diamètre₀: %3", clearScreen: "effacer tout l'écran", updateScreen: "mettre à jour l'écran", autoUpdate: "mode de mise à jour automatique de l'écran", fill: "mettre la couleur de fond à %1", noFill: "ne pas remplir les formes", stroke: "mettre la couleur de tracé à %1", noStroke: "ne pas dessiner les contours", readAcceleration: "accélération en (m/s²) dans l'axe %1", computeRotation: "compute rotation from accelerometer (°) %1", readSoundLevel: "volume sonore", readMagneticForce: "read Magnetic Force (µT) %1", computeCompassHeading: "compute Compass Heading (°)", readInfraredState: "read Infrared Receiver State %1", setInfraredState: "set Infrared transmiter State %1", // Gyroscope readAngularVelocity: "read angular velocity (°/s) %1", setGyroZeroAngle: "set the gyroscope zero point", computeRotationGyro: "compute rotation in the gyroscope %1", //Internet store connectToCloudStore: "Se connecter au cloud. Identifiant %1 Mot de passe %2", writeToCloudStore: "Écrire dans le cloud. Identifiant %1 Clé %2 Valeur %3", readFromCloudStore: "Lire dans le cloud. Identifiant %1 Clé %2", }, code: { // Names of the functions in Python, or Blockly translated in JavaScript turnLedOn: "turnLedOn", turnLedOff: "turnLedOff", setLedState: "setLedState", isButtonPressed: "isButtonPressed", isButtonPressedWithName : "isButtonPressed", waitForButton: "waitForButton", buttonWasPressed: "buttonWasPressed", toggleLedState: "toggleLedState", displayText: "displayText", displayText2Lines: "displayText", readTemperature: "readTemperature", sleep: "sleep", setServoAngle: "setServoAngle", readRotaryAngle: "readRotaryAngle", readDistance: "readDistance", readLightIntensity: "readLightIntensity", readHumidity: "readHumidity", currentTime: "currentTime", getTemperature: "getTemperature", isLedOn: "isLedOn", isLedOnWithName: "isLedOn", setBuzzerNote: "setBuzzerNote", getBuzzerNote: "getBuzzerNote", setLedBrightness: "setLedBrightness", getLedBrightness: "getLedBrightness", getServoAngle: "getServoAngle", setBuzzerState: "setBuzzerState", setBuzzerNote: "setBuzzerNote", turnBuzzerOn: "turnBuzzerOn", turnBuzzerOff: "turnBuzzerOff", isBuzzerOn: "isBuzzerOn", isBuzzerOnWithName: "isBuzzerOn", drawPoint: "drawPoint", isPointSet: "isPointSet", drawLine: "drawLine", drawRectangle: "drawRectangle", drawCircle: "drawCircle", clearScreen: "clearScreen", updateScreen: "updateScreen", autoUpdate: "autoUpdate", fill: "fill", noFill: "noFill", stroke: "stroke", noStroke: "noStroke", readAcceleration: "readAcceleration", computeRotation: "computeRotation", readSoundLevel: "readSoundLevel", readMagneticForce: "readMagneticForce", computeCompassHeading: "computeCompassHeading", readInfraredState: "readInfraredState", setInfraredState: "setInfraredState", // Gyroscope readAngularVelocity: "readAngularVelocity", setGyroZeroAngle: "setGyroZeroAngle", computeRotationGyro: "computeRotationGyro", //Internet store connectToCloudStore: "connectToCloudStore", writeToCloudStore: "writeToCloudStore", readFromCloudStore: "readFromCloudStore", }, description: { // Descriptions of the functions in Python (optional) turnLedOn: "turnLedOn() allume la LED", turnLedOff: "turnLedOff() éteint la LED", isButtonPressed: "isButtonPressed() retourne True si le bouton est enfoncé, False sinon", isButtonPressedWithName: "isButtonPressed(button) retourne True si le bouton est enfoncé, False sinon", waitForButton: "waitForButton(button) met en pause l'exécution jusqu'à ce que le bouton soit appuyé", buttonWasPressed: "buttonWasPressed(button) indique si le bouton a été appuyé depuis le dernier appel à cette fonction", setLedState: "setLedState(led, state) modifie l'état de la LED : True pour l'allumer, False pour l'éteindre", toggleLedState: "toggleLedState(led) inverse l'état de la LED", displayText: "displayText(line1, line2) affiche une ou deux lignes de texte. line2 est optionnel", displayText2Lines: "displayText(line1, line2) affiche une ou deux lignes de texte. line2 est optionnel", readTemperature: "readTemperature(thermometer) retourne la température ambiante", sleep: "sleep(milliseconds) met en pause l'exécution pendant une durée en ms", setServoAngle: "setServoAngle(servo, angle) change l'angle du servomoteur", readRotaryAngle: "readRotaryAngle(potentiometer) retourne la position potentiomètre", readDistance: "readDistance(distanceSensor) retourne la distance mesurée", readLightIntensity: "readLightIntensity(lightSensor) retourne l'intensité lumineuse", readHumidity: "readHumidity(hygrometer) retourne l'humidité ambiante", currentTime: "currentTime(milliseconds) temps en millisecondes depuis le début du programme", setLedBrightness: "setLedBrightness(led, brightness) règle l'intensité lumineuse de la LED", getLedBrightness: "getLedBrightness(led) retourne l'intensité lumineuse de la LED", getServoAngle: "getServoAngle(servo) retourne l'angle du servomoteur", isLedOn: "isLedOn() retourne True si la LED est allumée, False si elle est éteinte", isLedOnWithName: "isLedOn(led) retourne True si la LED est allumée, False sinon", turnBuzzerOn: "turnBuzzerOn() allume le buzzer", turnBuzzerOff: "turnBuzzerOff() éteint le buzzer", isBuzzerOn: "isBuzzerOn() retourne True si le buzzer est allumé, False sinon", isBuzzerOnWithName: "isBuzzerOn(buzzer) retourne True si le buzzer est allumé, False sinon", setBuzzerState: "setBuzzerState(buzzer, state) modifie l'état du buzzer: True pour allumé, False sinon", setBuzzerNote: "setBuzzerNote(buzzer, frequency) fait sonner le buzzer à la fréquence indiquée", getBuzzerNote: "getBuzzerNote(buzzer) retourne la fréquence actuelle du buzzer", getTemperature: "getTemperature(thermometer) ", drawPoint: "drawPoint(x, y)", isPointSet: "isPointSet(x, y)", drawLine: "drawLine(x0, y0, x1, y1)", drawRectangle: "drawRectangle(x0, y0, width, height)", drawCircle: "drawCircle(x0, y0, diameter)", clearScreen: "clearScreen()", updateScreen: "updateScreen()", autoUpdate: "autoUpdate(auto)", fill: "fill(color)", noFill: "noFill()", stroke: "stroke(color)", noStroke: "noStroke()", readAcceleration: "readAcceleration(axis)", computeRotation: "computeRotation()", readSoundLevel: "readSoundLevel(port)", readMagneticForce: "readMagneticForce(axis)", computeCompassHeading: "computeCompassHeading()", readInfraredState: "readInfraredState()", setInfraredState: "setInfraredState()", // Gyroscope readAngularVelocity: "readAngularVelocity()", setGyroZeroAngle: "setGyroZeroAngle()", computeRotationGyro: "computeRotationGyro()", //Internet store connectToCloudStore: "connectToCloudStore(identifier, password)", writeToCloudStore: "writeToCloudStore(identifier, key, value)", readFromCloudStore: "readFromCloudStore(identifier, key)", }, constant: { }, startingBlockName: "Programme", // Name for the starting block messages: { sensorNotFound: "Accès à un capteur ou actuateur inexistant : {0}.", manualTestSuccess: "Test automatique validé.", testSuccess: "Bravo ! La sortie est correcte", wrongState: "Test échoué : {0} a été dans l'état {1} au lieu de {2} à t={3}ms.", wrongStateDrawing: "Test échoué : {0} diffère de {1} pixels par rapport à l'affichage attendu à t={2}ms.", wrongStateSensor: "Test échoué : votre programme n'a pas lu l'état de {0} après t={1}ms.", programEnded: "programme terminé.", piPlocked: "L'appareil est verrouillé. Déverrouillez ou redémarrez.", cantConnect: "Impossible de se connecter à l'appareil.", wrongVersion: "Votre Raspberry Pi a une version trop ancienne, mettez le à jour.", sensorInOnlineMode: "Vous ne pouvez pas agir sur les capteurs en mode connecté.", actuatorsWhenRunning: "Impossible de modifier les actionneurs lors de l'exécution d'un programme", cantConnectoToUSB: 'Tentative de connexion par USB en cours, veuillez brancher votre Raspberry sur le port USB <i class="fas fa-circle-notch fa-spin"></i>', cantConnectoToBT: 'Tentative de connection par Bluetooth, veuillez connecter votre appareil au Raspberry par Bluetooth <i class="fas fa-circle-notch fa-spin"></i>', canConnectoToUSB: "Connecté en USB.", canConnectoToBT: "Connecté en Bluetooth.", noPortsAvailable: "Aucun port compatible avec ce {0} n'est disponible (type {1})", sensor: "capteur", actuator: "actionneur", removeConfirmation: "Êtes-vous certain de vouloir retirer ce capteur ou actuateur?", remove: "Retirer", keep: "Garder", minutesago: "Last seen {0} minutes ago", hoursago: "Last seen more than one hour ago", drawing: "dessin", connectionHTML: ` <div id="piui"> <button type="button" id="piconnect" class="btn"> <span class="fa fa-wifi"></span><span id="piconnecttext" class="btnText">Connecter</span> <span id="piconnectprogress" class="fas fa-spinner fa-spin"></span> </button> <span id="piinstallui"> <span class="fa fa-exchange-alt"></span> <button type="button" id="piinstall" class="btn"> <span class="fa fa-upload"></span><span>Installer</span><span id=piinstallprogresss class="fas fa-spinner fa-spin"></span><span id="piinstallcheck" class="fa fa-check"></span> </button> </span> <span id="pichangehatui"> <button type="button" id="pichangehat" class="btn"> <span class="fas fa-hat-wizard"></span><span>Changer de carte</span></span></span> </button> <button type="button" id="pihatsetup" class="btn"> <span class="fas fa-cog"></span><span>Config</span></span></span> </button> </span> </div>`, connectionDialogHTML: ` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Configuration du Raspberry Pi </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div id="piconnectionmainui"> <div class="switchRadio btn-group" id="piconsel"> <button type="button" class="btn active" id="piconwifi"><i class="fa fa-wifi icon"></i>WiFi</button> <button type="button" class="btn" id="piconusb"><i class="fab fa-usb icon"></i>USB</button> <button type="button" class="btn" id="piconbt"><i class="fab fa-bluetooth-b icon"></i>Bluetooth</button> </div> <div id="pischoolcon"> <div class="form-group"> <label id="pischoolkeylabel">Indiquez un identifiant d'école</label> <div class="input-group"> <div class="input-group-prepend">Aa</div> <input type="text" id="schoolkey" class="form-control"> </div> </div> <div class="form-group"> <label id="pilistlabel">Sélectionnez un appareil à connecter dans la liste suivante</label> <div class="input-group"> <button class="input-group-prepend" id=pigetlist disabled>Obtenir la liste</button> <select id="pilist" class="custom-select" disabled> </select> </div> </div> <div class="form-group"> <label id="piiplabel">ou entrez son adesse IP</label> <div class="input-group"> <div class="input-group-prepend">123</div> <input id=piaddress type="text" class="form-control"> </div> </div> <div> <input id="piusetunnel" disabled type="checkbox">Connecter à travers le France-ioi tunnel </div> </div> <div panel-body-usbbt> <label id="piconnectionlabel"></label> </div> </div> <div class="inlineButtons"> <button id="piconnectok" class="btn"><i class="fa fa-wifi icon"></i>Connecter l'appareil</button> <button id="pirelease" class="btn"><i class="fa fa-times icon"></i>Déconnecter</button> </div> </div> </div> `, stickPortsDialog: ` <div class="content qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Stick names and port </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div id="sensorPicker" class="panel-body"> <label></label> <div class="flex-container"> <table style="display:table-header-group;"> <tr> <th>Name</th> <th>Port</th> <th>State</th> <th>Direction</th> </tr> <tr> <td><label id="stickupname"></td><td><label id="stickupport"></td><td><label id="stickupstate"></td><td><label id="stickupdirection"><i class="fas fa-arrow-up"></i></td> </tr> <tr> <td><label id="stickdownname"></td><td><label id="stickdownport"></td><td><label id="stickdownstate"></td><td><label id="stickdowndirection"><i class="fas fa-arrow-down"></i></td> </tr> <tr> <td><label id="stickleftname"></td><td><label id="stickleftport"></td><td><label id="stickleftstate"></td><td><label id="stickleftdirection"><i class="fas fa-arrow-left"></i></td> </tr> <tr> <td><label id="stickrightname"></td><td><label id="stickrightport"></td><td><label id="stickrightstate"></td><td><label id="stickrightdirection"><i class="fas fa-arrow-right"></i></td> </tr> <tr> <td><label id="stickcentername"></td><td><label id="stickcenterport"></td><td><label id="stickcenterstate"></td><td><label id="stickcenterdirection"><i class="fas fa-circle"></i></td> </tr> </table> </div> </div> <div class="singleButton"> <button id="picancel2" class="btn btn-centered"><i class="icon fa fa-check"></i>Fermer</button> </div> </div> `, } }, none: { comment: { // Comments for each block, used in the auto-generated documentation for task writers turnLedOn: "Turns on a light connected to Raspberry", turnLedOff: "Turns off a light connected to Raspberry", isButtonPressed: "Returns the state of a button, Pressed means True and not pressed means False", waitForButton: "Stops program execution until a button is pressed", buttonWasPressed: "Returns true if the button has been pressed and will clear the value", setLedState: "Change led state in the given port", toggleLedState: "If led is on, turns it off, if it's off turns it on", isButtonPressedWithName: "Returns the state of a button, Pressed means True and not pressed means False", displayText: "Display text in LCD screen", displayText2Lines: "Display text in LCD screen (two lines)", readTemperature: "Read Ambient temperature", sleep: "pause program execute for a number of seconds", setServoAngle: "Set servo motor to an specified angle", readRotaryAngle: "Read state of potentiometer", readDistance: "Read distance using ultrasonic sensor", readLightIntensity: "Read light intensity", readHumidity: "lire l'humidité ambiante", currentTime: "returns current time", setBuzzerState: "sonnerie", setBuzzerNote: "sonnerie note", getTemperature: "Get temperature", setBuzzerNote: "Set buzzer note", getBuzzerNote: "Get buzzer note", setLedBrightness: "Set Led Brightness", getLedBrightness: "Get Led Brightness", getServoAngle: "Get Servo Angle", isLedOn: "Get led state", isLedOnWithName: "Get led state", turnBuzzerOn: "Turn Buzzer on", turnBuzzerOff: "Turn Buzzer off", isBuzzerOn: "Is Buzzer On", isBuzzerOnWithName: "get buzzer state", drawPoint: "drawPoint", isPointSet: "isPointSet", drawLine: "drawLine", drawRectangle: "drawRectangle", drawCircle: "drawCircle", clearScreen: "clearScreen", updateScreen: "updateScreen", autoUpdate: "autoUpdate", fill: "fill", noFill: "noFill", stroke: "stroke", noStroke: "noStroke", readAcceleration: "readAcceleration", computeRotation: "computeRotation", readSoundLevel: "readSoundLevel", readMagneticForce: "readMagneticForce", computeCompassHeading: "computeCompassHeading", readInfraredState: "readInfraredState", setInfraredState: "setInfraredState", // Gyroscope readAngularVelocity: "readAngularVelocity", setGyroZeroAngle: "setGyroZeroAngle", computeRotationGyro: "computeRotationGyro", //Internet store connectToCloudStore: "connectToCloudStore", writeToCloudStore: "writeToCloudStore", readFromCloudStore: "readFromCloudStore", } } } // Create a base context var context = quickAlgoContext(display, infos); // Import our localLanguageStrings into the global scope var strings = context.setLocalLanguageStrings(localLanguageStrings); // Some data can be made accessible by the library through the context object context.quickpi = {}; // List of concepts to be included by conceptViewer context.conceptList = [ {id: 'language', ignore: true}, { id: 'quickpi_start', name: 'Créer un programme', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_start', language: 'all', isBase: true, order: 1, python: [] }, { id: 'quickpi_validation', name: 'Valider son programme', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_validation', language: 'all', isBase: true, order: 2, python: [] }, { id: 'quickpi_buzzer', name: 'Buzzer', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_buzzer', language: 'all', order: 200, python: ['setBuzzerState', 'setBuzzerNote','turnBuzzerOn','turnBuzzerOff'] }, { id: 'quickpi_led', name: 'LEDs', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_led', language: 'all', order: 201, python: ['setLedState','toggleLedState','turnLedOn','turnLedOff'] }, { id: 'quickpi_button', name: 'Boutons et manette', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_button', language: 'all', order: 202, python: ['isButtonPressed', 'isButtonPressedWithName'] }, { id: 'quickpi_screen', name: 'Écran', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_screen', language: 'all', order: 203, python: ['displayText'] }, { id: 'quickpi_range', name: 'Capteur de distance', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_range', language: 'all', order: 204, python: ['readDistance'] }, { id: 'quickpi_servo', name: 'Servomoteur', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_servo', language: 'all', order: 205, python: ['setServoAngle', 'getServoAngle'] }, { id: 'quickpi_thermometer', name: 'Thermomètre', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_thermometer', language: 'all', order: 206, python: ['readTemperature'] }, { id: 'quickpi_microphone', name: 'Microphone', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_microphone', language: 'all', order: 207, python: ['readSoundLevel'] }, { id: 'quickpi_light_sensor', name: 'Capteur de luminosité', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_light_sensor', language: 'all', order: 208, python: ['readLightIntensity'] }, { id: 'quickpi_accelerometer', name: 'Accéléromètre', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_accelerometer', language: 'all', order: 209, python: ['readAcceleration'] }, { id: 'quickpi_wait', name: 'Gestion du temps', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_wait', language: 'all', order: 250, python: ['sleep'] }, { id: 'quickpi_cloud', name: 'Stockage dans le cloud', url: 'https://static4.castor-informatique.fr/help/quickpi.html#quickpi_cloud', language: 'all', order: 250, python: ['writeToCloudStore','connectToCloudStore','readFromCloudStore'] } ]; var boardDefinitions = [ { name: "grovepi", friendlyName: "Grove Base Hat for Raspberry Pi", image: "grovepihat.png", adc: "grovepi", portTypes: { "D": [5, 16, 18, 22, 24, 26], "A": [0, 2, 4, 6], "i2c": ["i2c"], }, default: [ { type: "screen", suggestedName: "screen1", port: "i2c", subType: "16x2lcd" }, { type: "led", suggestedName: "led1", port: 'D5', subType: "blue" }, { type: "servo", suggestedName: "servo1", port: "D16" }, { type: "range", suggestedName: "range1", port :"D18", subType: "ultrasonic"}, { type: "button", suggestedName: "button1", port: "D22" }, { type: "humidity", suggestedName: "humidity1", port: "D24"}, { type: "buzzer", suggestedName: "buzzer1", port: "D26", subType: "active"}, { type: "temperature", suggestedName: "temperature1", port: 'A0', subType: "groveanalog" }, { type: "potentiometer", suggestedName: "potentiometer1", port :"A4"}, { type: "light", suggestedName: "light1", port :"A6"}, ] }, { name: "quickpi", friendlyName: "France IOI QuickPi Hat", image: "quickpihat.png", adc: "ads1015", portTypes: { "D": [5, 16, 24], "A": [0], }, builtinSensors: [ { type: "screen", subType: "oled128x32", port: "i2c", suggestedName: "screen1", }, { type: "led", subType: "red", port: "D4", suggestedName: "led1", }, { type: "led", subType: "green", port: "D17", suggestedName: "led2", }, { type: "led", subType: "blue", port: "D27", suggestedName: "led3", }, { type: "irtrans", port: "D22", suggestedName: "infraredtransmiter1", }, { type: "irrecv", port: "D23", suggestedName: "infraredreceiver1", }, { type: "sound", port: "A1", suggestedName: "microphone1", }, { type: "buzzer", subType: "passive", port: "D12", suggestedName: "buzzer1", }, { type: "accelerometer", subType: "BMI160", port: "i2c", suggestedName: "accelerometer1", }, { type: "gyroscope", subType: "BMI160", port: "i2c", suggestedName: "gryscope1", }, { type: "magnetometer", subType: "LSM303C", port: "i2c", suggestedName: "magnetometer1", }, { type: "temperature", subType: "BMI160", port: "i2c", suggestedName: "temperature1", }, { type: "range", subType: "vl53l0x", port: "i2c", suggestedName: "distance1", }, { type: "button", port: "D26", suggestedName: "button1", }, { type: "light", port: "A2", suggestedName: "light1", }, { type: "stick", port: "D7", suggestedName: "stick1", } ], }, { name: "pinohat", image: "pinohat.png", friendlyName: "Raspberry Pi without hat", adc: ["ads1015", "none"], portTypes: { "D": [5, 16, 24], "A": [0], "i2c": ["i2c"], }, } ] var sensorDefinitions = [ /******************************** */ /* Actuators */ /**********************************/ { name: "led", description: "LED", isAnalog: false, isSensor: false, portType: "D", getInitialState: function (sensor) { return false; }, selectorImages: ["ledon-red.png"], valueType: "boolean", pluggable: true, getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setLedState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { return state ? "ON" : "OFF"; }, subTypes: [{ subType: "blue", description: "LED bleue", selectorImages: ["ledon-blue.png"], suggestedName: "blueled", }, { subType: "green", description: "LED verte", selectorImages: ["ledon-green.png"], suggestedName: "greenled", }, { subType: "orange", description: "LED orange", selectorImages: ["ledon-orange.png"], suggestedName: "orangeled", }, { subType: "red", description: "LED rouge", selectorImages: ["ledon-red.png"], suggestedName: "redled", } ], }, { name: "buzzer", description: "Buzzer", isAnalog: false, isSensor: false, getInitialState: function(sensor) { return false; }, portType: "D", selectorImages: ["buzzer-ringing.png"], valueType: "boolean", getPercentageFromState: function (state, sensor) { if (sensor.showAsAnalog) { return (state - sensor.minAnalog) / (sensor.maxAnalog - sensor.minAnalog); } else { if (state) return 1; else return 0; } }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setBuzzerState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { if(typeof state == 'number' && state != 1 && state != 0) { return state.toString() + "Hz"; } return state ? "ON" : "OFF"; }, subTypes: [{ subType: "active", description: "Grove Buzzer", pluggable: true, }, { subType: "passive", description: "Quick Pi Passive Buzzer", }], }, { name: "servo", description: "Servo motor", isAnalog: true, isSensor: false, getInitialState: function(sensor) { return 0; }, portType: "D", valueType: "number", pluggable: true, valueMin: 0, valueMax: 180, selectorImages: ["servo.png", "servo-pale.png", "servo-center.png"], getPercentageFromState: function (state) { return state / 180; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 180); }, setLiveState: function (sensor, state, callback) { var command = "setServoAngle(\"" + sensor.name + "\"," + state + ")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { return "" + state + "°"; } }, { name: "screen", description: "Screen", isAnalog: false, isSensor: false, getInitialState: function(sensor) { if (sensor.isDrawingScreen) return null; else return {line1: "", line2: ""}; }, cellsAmount: function(paper) { if(context.board == 'grovepi') { return 2; } if(paper.width < 250) { return 4; } else if(paper.width < 350) { return 3; } return 2; }, portType: "i2c", valueType: "object", selectorImages: ["screen.png"], compareState: function (state1, state2) { // Both are null are equal if (state1 == null && state2 == null) return true; // If only one is null they are different if ((state1 == null && state2) || (state1 && state2 == null)) return false; if (state1 && state1.isDrawingData) { // They are ImageData objects // The image data is RGBA so there are 4 bits per pixel var data1 = state1.getData(1).data; var data2 = state2.getData(1).data; for (var i = 0; i < data1.length; i+=4) { if (data1[i] != data2[i] || data1[i + 1] != data2[i + 1] || data1[i + 2] != data2[i + 2] || data1[i + 3] != data2[i + 3]) return false; } return true; } else { // Otherwise compare the strings return (state1.line1 == state2.line1) && ((state1.line2 == state2.line2) || (!state1.line2 && !state2.line2)); } }, setLiveState: function (sensor, state, callback) { var line2 = state.line2; if (!line2) line2 = ""; var command = "displayText(\"" + sensor.name + "\"," + state.line1 + "\", \"" + line2 + "\")"; context.quickPiConnection.sendCommand(command, callback); }, getStateString: function(state) { if(!state) { return '""'; } if (state.isDrawingData) return strings.messages.drawing; else return '"' + state.line1 + (state.line2 ? " / " + state.line2 : "") + '"'; }, getWrongStateString: function(failInfo) { if(!failInfo.expected || !failInfo.expected.isDrawingData || !failInfo.actual || !failInfo.actual.isDrawingData) { return null; // Use default message } var data1 = failInfo.expected.getData(1).data; var data2 = failInfo.actual.getData(1).data; var nbDiff = 0; for (var i = 0; i < data1.length; i+=4) { if(data1[i] != data2[i]) { nbDiff += 1; } } return strings.messages.wrongStateDrawing.format(failInfo.name, nbDiff, failInfo.time); }, subTypes: [{ subType: "16x2lcd", description: "Grove 16x2 LCD", pluggable: true, }, { subType: "oled128x32", description: "128x32 Oled Screen", }], }, { name: "irtrans", description: "IR Transmiter", isAnalog: true, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["irtranson.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, setLiveState: function (sensor, state, callback) { var ledstate = state ? 1 : 0; var command = "setInfraredState(\"" + sensor.name + "\"," + ledstate + ")"; context.quickPiConnection.sendCommand(command, callback); }, }, /******************************** */ /* sensors */ /**********************************/ { name: "button", description: "Button", isAnalog: false, isSensor: true, portType: "D", valueType: "boolean", pluggable: true, selectorImages: ["buttonoff.png"], getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("buttonStateInPort(\"" + sensor.name + "\")", function (retVal) { var intVal = parseInt(retVal, 10); callback(intVal != 0); }); }, }, { name: "stick", description: "5 way button", isAnalog: false, isSensor: true, portType: "D", valueType: "boolean", selectorImages: ["stick.png"], gpiosNames: ["up", "down", "left", "right", "center"], gpios: [10, 9, 11, 8, 7], getPercentageFromState: function (state) { if (state) return 1; else return 0; }, getStateFromPercentage: function (percentage) { if (percentage) return 1; else return 0; }, compareState: function (state1, state2) { if (state1 == null && state2 == null) return true; return state1[0] == state2[0] && state1[1] == state2[1] && state1[2] == state2[2] && state1[3] == state2[3] && state1[4] == state2[4]; }, getLiveState: function (sensor, callback) { var cmd = "readStick(" + this.gpios.join() + ")"; context.quickPiConnection.sendCommand("readStick(" + this.gpios.join() + ")", function (retVal) { var array = JSON.parse(retVal); callback(array); }); }, getButtonState: function(buttonname, state) { if (state) { var buttonparts = buttonname.split("."); var actualbuttonmame = buttonname; if (buttonparts.length == 2) { actualbuttonmame = buttonparts[1]; } var index = this.gpiosNames.indexOf(actualbuttonmame); if (index >= 0) { return state[index]; } } return false; } }, { name: "temperature", description: "Temperature sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["temperature-hot.png", "temperature-overlay.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readTemperature(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, subTypes: [{ subType: "groveanalog", description: "Grove Analog tempeature sensor", portType: "A", pluggable: true, }, { subType: "BMI160", description: "Quick Pi Accelerometer+Gyroscope temperature sensor", portType: "i2c", }, { subType: "DHT11", description: "DHT11 Tempeature Sensor", portType: "D", pluggable: true, }], }, { name: "potentiometer", description: "Potentiometer", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["potentiometer.png", "potentiometer-pale.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readRotaryAngle(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "light", description: "Light sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["light.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readLightIntensity(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "range", description: "Capteur de distance", isAnalog: true, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 5000, selectorImages: ["range.png"], getPercentageFromState: function (state) { return state / 500; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 500); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readDistance(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, subTypes: [{ subType: "vl53l0x", description: "Time of flight distance sensor", portType: "i2c", }, { subType: "ultrasonic", description: "Capteur de distance à ultrason", portType: "D", pluggable: true, }], }, { name: "humidity", description: "Humidity sensor", isAnalog: true, isSensor: true, portType: "D", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["humidity.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readHumidity(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "sound", description: "Sound sensor", isAnalog: true, isSensor: true, portType: "A", valueType: "number", pluggable: true, valueMin: 0, valueMax: 100, selectorImages: ["sound.png"], getPercentageFromState: function (state) { return state / 100; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 100); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readSoundLevel(\"" + sensor.name + "\")", function(val) { val = Math.round(val); callback(val); }); }, }, { name: "accelerometer", description: "Accelerometer sensor (BMI160)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, step: 0.1, selectorImages: ["accel.png"], getStateString: function (state) { if (state == null) return "0m/s²"; if (Array.isArray(state)) { return "X: " + state[0] + "m/s² Y: " + state[1] + "m/s² Z: " + state[2] + "m/s²"; } else { return state.toString() + "m/s²"; } }, getPercentageFromState: function (state) { return ((state + 78.48) / 156.96); }, getStateFromPercentage: function (percentage) { var value = ((percentage * 156.96) - 78.48); return parseFloat(value.toFixed(1)); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readAccelBMI160()", function(val) { var array = JSON.parse(val); callback(array); }); }, }, { name: "gyroscope", description: "Gyropscope sensor (BMI160)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, selectorImages: ["gyro.png"], getPercentageFromState: function (state) { return (state + 125) / 250; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 250) - 125; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readGyroBMI160()", function(val) { var array = JSON.parse(val); array[0] = Math.round(array[0]); array[1] = Math.round(array[1]); array[2] = Math.round(array[2]); callback(array); }); }, }, { name: "magnetometer", description: "Magnetometer sensor (LSM303C)", isAnalog: true, isSensor: true, portType: "i2c", valueType: "object", valueMin: 0, valueMax: 100, selectorImages: ["mag.png"], getPercentageFromState: function (state) { return (state + 1600) / 3200; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 3200) - 1600; }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("readMagnetometerLSM303C(False)", function(val) { var array = JSON.parse(val); array[0] = Math.round(array[0]); array[1] = Math.round(array[1]); array[2] = Math.round(array[2]); callback(array); }); }, }, { name: "irrecv", description: "IR Receiver", isAnalog: false, isSensor: true, portType: "D", valueType: "number", valueMin: 0, valueMax: 60, selectorImages: ["irrecvon.png"], getPercentageFromState: function (state) { return state / 60; }, getStateFromPercentage: function (percentage) { return Math.round(percentage * 60); }, getLiveState: function (sensor, callback) { context.quickPiConnection.sendCommand("buttonStateInPort(\"" + sensor.name + "\")", function (retVal) { var intVal = parseInt(retVal, 10); callback(intVal == 0); }); }, }, /******************************** */ /* dummy sensors */ /**********************************/ { name: "cloudstore", description: "Cloud store", isAnalog: false, isSensor: false, portType: "none", valueType: "object", selectorImages: ["cloudstore.png"], /*getInitialState: function(sensor) { return {}; },*/ compareState: function (state1, state2) { return quickPiStore.compareState(state1, state2); }, }, { name: "clock", description: "Cloud store", isAnalog: false, isSensor: false, portType: "none", valueType: "object", selectorImages: ["clock.png"], }, ]; function findSensorDefinition(sensor) { var sensorDef = null; for (var iType = 0; iType < sensorDefinitions.length; iType++) { var type = sensorDefinitions[iType]; if (sensor.type == type.name) { if (sensor.subType && type.subTypes) { for (var iSubType = 0; iSubType < type.subTypes.length; iSubType++) { var subType = type.subTypes[iSubType]; if (subType.subType == sensor.subType) { sensorDef = $.extend({}, type, subType); } } } else { sensorDef = type; } } } if(sensorDef && !sensorDef.compareState) { sensorDef.compareState = function(state1, state2) { return state1 == state2; }; } return sensorDef; } var defaultQuickPiOptions = { disableConnection: false, increaseTimeAfterCalls: 5 }; function getQuickPiOption(name) { if(name == 'disableConnection') { // TODO :: Legacy, remove when all tasks will have been updated return (context.infos && (context.infos.quickPiDisableConnection || (context.infos.quickPi && context.infos.quickPi.disableConnection))); } if(context.infos && context.infos.quickPi && typeof context.infos.quickPi[name] != 'undefined') { return context.infos.quickPi[name]; } else { return defaultQuickPiOptions[name]; } } function getWrongStateText(failInfo) { var actualStateStr = "" + failInfo.actual; var expectedStateStr = "" + failInfo.expected; var sensorDef = findSensorDefinition(failInfo.sensor); if(sensorDef) { if(sensorDef.isSensor) { return strings.messages.wrongStateSensor.format(failInfo.name, failInfo.time); } if(sensorDef.getWrongStateString) { var sensorWrongStr = sensorDef.getWrongStateString(failInfo); if(sensorWrongStr) { return sensorWrongStr; } } if(sensorDef.getStateString) { actualStateStr = sensorDef.getStateString(failInfo.actual); expectedStateStr = sensorDef.getStateString(failInfo.expected); } } return strings.messages.wrongState.format(failInfo.name, actualStateStr, expectedStateStr, failInfo.time); } function getCurrentBoard() { var found = boardDefinitions.find(function (element) { if (context.board == element.name) return element; }); return found; } function getSessionStorage(name) { // Use a try in case it gets blocked try { return sessionStorage[name]; } catch(e) { return null; } } function setSessionStorage(name, value) { // Use a try in case it gets blocked try { sessionStorage[name] = value; } catch(e) {} } if(window.getQuickPiConnection) { var lockstring = getSessionStorage('lockstring'); if(!lockstring) { lockstring = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); setSessionStorage('lockstring', lockstring); } context.quickPiConnection = getQuickPiConnection(lockstring, raspberryPiConnected, raspberryPiDisconnected, raspberryPiChangeBoard); } var paper; context.offLineMode = true; context.onExecutionEnd = function () { if (context.autoGrading) { buzzerSound.stopAll(); } }; infos.checkEndEveryTurn = true; infos.checkEndCondition = function (context, lastTurn) { if (!context.display && !context.autoGrading) { context.success = true; throw (strings.messages.manualTestSuccess); } if (context.failImmediately) { context.success = false; throw (context.failImmediately); } var testEnded = lastTurn || context.currentTime > context.maxTime; if (context.autoGrading) { if (!testEnded) { return; } if (lastTurn && context.display && !context.loopsForever) { context.currentTime = Math.floor(context.maxTime * 1.05); drawNewStateChanges(); drawCurrentTime(); } var failInfo = null; for(var sensorName in context.gradingStatesBySensor) { // Cycle through each sensor from the grading states var sensor = findSensorByName(sensorName); var sensorDef = findSensorDefinition(sensor); var expectedStates = context.gradingStatesBySensor[sensorName]; if(!expectedStates.length) { continue;} var actualStates = context.actualStatesBySensor[sensorName]; var actualIdx = 0; // Check that we went through all expected states for (var i = 0; i < context.gradingStatesBySensor[sensorName].length; i++) { var expectedState = context.gradingStatesBySensor[sensorName][i]; if(expectedState.hit) { continue; } // Was hit, valid var newFailInfo = null; if(actualStates) { // Scroll through actual states until we get the state at this time while(actualIdx + 1 < actualStates.length && actualStates[actualIdx+1].time <= expectedState.time) { actualIdx += 1; } if(!sensorDef.compareState(actualStates[actualIdx].state, expectedState.state)) { newFailInfo = { sensor: sensor, name: sensorName, time: expectedState.time, expected: expectedState.state, actual: actualStates[actualIdx].state }; } } else { // No actual states to compare to newFailInfo = { sensor: sensor, name: sensorName, time: expectedState.time, expected: expectedState.state, actual: null }; } if(newFailInfo) { // Only update failInfo if we found an error earlier failInfo = failInfo && failInfo.time < newFailInfo.time ? failInfo : newFailInfo; } } // Check that no actual state conflicts an expected state if(!actualStates) { continue; } var expectedIdx = 0; for(var i = 0; i < actualStates.length ; i++) { var actualState = actualStates[i]; while(expectedIdx + 1 < expectedStates.length && expectedStates[expectedIdx+1].time <= actualState.time) { expectedIdx += 1; } if(!sensorDef.compareState(actualState.state, expectedStates[expectedIdx].state)) { // Got an unexpected state change var newFailInfo = { sensor: sensor, name: sensorName, time: actualState.time, expected: expectedStates[expectedIdx].state, actual: actualState.state }; failInfo = failInfo && failInfo.time < newFailInfo.time ? failInfo : newFailInfo; } } } if(failInfo) { // Missed expected state context.success = false; throw (getWrongStateText(failInfo)); } else { // Success context.success = true; throw (strings.messages.programEnded); } } else { if (!context.offLineMode) { $('#piinstallcheck').hide(); } if (lastTurn) { context.success = true; throw (strings.messages.programEnded); } } }; context.generatePythonSensorTable = function() { var pythonSensorTable = "sensorTable = ["; var first = true; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; if (first) { first = false; } else { pythonSensorTable += ","; } if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); var firststick = true; for (var iStick = 0; iStick < stickDefinition.gpiosNames.length; iStick++) { var name = sensor.name + "." + stickDefinition.gpiosNames[iStick]; var port = "D" + stickDefinition.gpios[iStick]; if (firststick) { firststick = false; } else { pythonSensorTable += ","; } pythonSensorTable += "{\"type\":\"button\""; pythonSensorTable += ",\"name\":\"" + name + "\""; pythonSensorTable += ",\"port\":\"" + port + "\"}"; } } else { pythonSensorTable += "{\"type\":\"" + sensor.type + "\""; pythonSensorTable += ",\"name\":\"" + sensor.name + "\""; pythonSensorTable += ",\"port\":\"" + sensor.port + "\""; if (sensor.subType) pythonSensorTable += ",\"subType\":\"" + sensor.subType + "\""; pythonSensorTable += "}"; } } var board = getCurrentBoard(); pythonSensorTable += "]; currentADC = \"" + board.adc + "\""; return pythonSensorTable; } context.resetSensorTable = function() { var pythonSensorTable = context.generatePythonSensorTable(); context.quickPiConnection.sendCommand(pythonSensorTable, function(x) {}); } context.findSensor = function findSensor(type, port, error=true) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == type && sensor.port == port) return sensor; } if (error) { context.success = false; throw (strings.messages.sensorNotFound.format('type ' + type + ', port ' + port)); } return null; } function sensorAssignPort(sensor) { var board = getCurrentBoard(); var sensorDefinition = findSensorDefinition(sensor); sensor.port = null; // first try with built ins if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; // Search for the specified subtype if (builtinsensor.type == sensor.type && builtinsensor.subType == sensor.subType && !context.findSensor(builtinsensor.type, builtinsensor.port, false)) { sensor.port = builtinsensor.port; return; } } // Search without subtype for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; // Search for the specified subtype if (builtinsensor.type == sensor.type && !context.findSensor(builtinsensor.type, builtinsensor.port, false)) { sensor.port = builtinsensor.port; sensor.subType = builtinsensor.subType; return; } } // If this is a button try to set it to a stick if (!sensor.port && sensor.type == "button") { for (var i = 0; i < board.builtinSensors.length; i++) { var builtinsensor = board.builtinSensors[i]; if (builtinsensor.type == "stick") { sensor.port = builtinsensor.port; return; } } } } // Second try assign it a grove port if (!sensor.port) { var sensorDefinition = findSensorDefinition(sensor); var pluggable = sensorDefinition.pluggable; if (sensorDefinition.subTypes) { for (var iSubTypes = 0; iSubTypes < sensorDefinition.subTypes.length; iSubTypes++) { var subTypeDefinition = sensorDefinition.subTypes[iSubTypes]; if (pluggable || subTypeDefinition.pluggable) { var ports = board.portTypes[sensorDefinition.portType]; for (var iPorts = 0; iPorts < ports.length; iPorts++) { var port = sensorDefinition.portType; if (sensorDefinition.portType != "i2c") port = sensorDefinition.portType + ports[iPorts]; if (!findSensorByPort(port)) { sensor.port = port; if (!sensor.subType) sensor.subType = subTypeDefinition.subType; return; } } } } } else { if (pluggable) { var ports = board.portTypes[sensorDefinition.portType]; for (var iPorts = 0; iPorts < ports.length; iPorts++) { var port = sensorDefinition.portType + ports[iPorts]; if (!findSensorByPort(port)) { sensor.port = port; return; } } } } } } context.reset = function (taskInfos) { buzzerSound.stopAll(); context.failImmediately = null; if (!context.offLineMode) { $('#piinstallcheck').hide(); context.quickPiConnection.startNewSession(); context.resetSensorTable(); } context.currentTime = 0; if (taskInfos != undefined) { context.actualStatesBySensor = {}; context.tickIncrease = 100; context.autoGrading = taskInfos.autoGrading; context.loopsForever = taskInfos.loopsForever; context.allowInfiniteLoop = !context.autoGrading; if (context.autoGrading) { context.maxTime = 0; if (taskInfos.input) { for (var i = 0; i < taskInfos.input.length; i++) { taskInfos.input[i].input = true; } context.gradingStatesByTime = taskInfos.input.concat(taskInfos.output); } else { context.gradingStatesByTime = taskInfos.output; } // Copy states to avoid modifying the taskInfos states context.gradingStatesByTime = context.gradingStatesByTime.map( function(val) { return Object.assign({}, val); }); context.gradingStatesByTime.sort(function (a, b) { return a.time - b.time; }); context.gradingStatesBySensor = {}; for (var i = 0; i < context.gradingStatesByTime.length; i++) { var state = context.gradingStatesByTime[i]; if (!context.gradingStatesBySensor.hasOwnProperty(state.name)) context.gradingStatesBySensor[state.name] = []; context.gradingStatesBySensor[state.name].push(state); // state.hit = false; // state.badonce = false; if (state.time > context.maxTime) context.maxTime = state.time; } for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; if (sensor.type == "buzzer") { var states = context.gradingStatesBySensor[sensor.name]; if (states) { for (var iState = 0; iState < states.length; iState++) { var state = states[iState].state; if (typeof state == 'number' && state != 0 && state != 1) { sensor.showAsAnalog = true; break; } } } } var isAnalog = findSensorDefinition(sensor).isAnalog || sensor.showAsAnalog; if (isAnalog) { sensor.maxAnalog = Number.MIN_VALUE; sensor.minAnalog = Number.MAX_VALUE; if (context.gradingStatesBySensor.hasOwnProperty(sensor.name)) { var states = context.gradingStatesBySensor[sensor.name]; for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; if (state.state > sensor.maxAnalog) sensor.maxAnalog = state.state; if (state.state < sensor.minAnalog) sensor.minAnalog = state.state; } } } if (sensor.type == "screen") { var states = context.gradingStatesBySensor[sensor.name]; if (states) { for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; if (state.state.isDrawingData) sensor.isDrawingScreen = true; } } } } } if (infos.quickPiSensors == "default") { infos.quickPiSensors = []; addDefaultBoardSensors(); } } context.success = false; if (context.autoGrading) context.doNotStartGrade = false; else context.doNotStartGrade = true; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; sensor.state = null; sensor.screenDrawing = null; sensor.lastDrawnTime = 0; sensor.lastDrawnState = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; sensor.removed = false; sensor.quickStore = null; // If the sensor has no port assign one if (!sensor.port) { sensorAssignPort(sensor); } // Set initial state var sensorDef = findSensorDefinition(sensor); if(sensorDef && !sensorDef.isSensor && sensorDef.getInitialState) { var initialState = sensorDef.getInitialState(sensor); if (initialState != null) context.registerQuickPiEvent(sensor.name, initialState, true, true); } } if (context.display) { context.resetDisplay(); } else { context.success = false; } context.timeLineStates = []; startSensorPollInterval(); }; function clearSensorPollInterval() { if(context.sensorPollInterval) { clearInterval(context.sensorPollInterval); context.sensorPollInterval = null; } }; function startSensorPollInterval() { // Start polling the sensors on the raspberry if the raspberry is connected clearSensorPollInterval(); context.liveUpdateCount = 0; if(!context.quickPiConnection.isConnected()) { return; } context.sensorPollInterval = setInterval(function () { if((context.runner && context.runner.isRunning()) || context.offLineMode || context.liveUpdateCount != 0) { return; } context.quickPiConnection.startTransaction(); for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; updateLiveSensor(sensor); } context.quickPiConnection.endTransaction(); }, 200); }; function updateLiveSensor(sensor) { if (findSensorDefinition(sensor).isSensor && findSensorDefinition(sensor).getLiveState) { context.liveUpdateCount++; //console.log("updateLiveSensor " + sensor.name, context.liveUpdateCount); findSensorDefinition(sensor).getLiveState(sensor, function (returnVal) { context.liveUpdateCount--; //console.log("updateLiveSensor callback" + sensor.name, context.liveUpdateCount); if (!sensor.removed) { sensor.state = returnVal; drawSensor(sensor); } }); } } context.changeBoard = function(newboardname) { if (context.board == newboardname) return; var board = null; for (var i = 0; i < boardDefinitions.length; i++) { board = boardDefinitions[i]; if (board.name == newboardname) break; } if (board == null) return; context.board = newboardname; setSessionStorage('board', newboardname); if (infos.customSensors) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } infos.quickPiSensors = []; if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var sensor = board.builtinSensors[i]; var newSensor = { "type": sensor.type, "port": sensor.port, "builtin": true, }; if (sensor.subType) { newSensor.subType = sensor.subType; } newSensor.name = getSensorSuggestedName(sensor.type, sensor.suggestedName); sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(newSensor); } } } else { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensorAssignPort(sensor); } } context.resetSensorTable(); context.resetDisplay(); }; context.board = "quickpi"; if (getSessionStorage('board')) context.changeBoard(getSessionStorage('board')) context.savePrograms = function(xml) { if (context.infos.customSensors) { var node = goog.dom.createElement("quickpi"); xml.appendChild(node); for (var i = 0; i < infos.quickPiSensors.length; i++) { var currentSensor = infos.quickPiSensors[i]; var node = goog.dom.createElement("sensor"); node.setAttribute("type", currentSensor.type); node.setAttribute("port", currentSensor.port); node.setAttribute("name", currentSensor.name); if (currentSensor.subType) node.setAttribute("subtype", currentSensor.subType); var elements = xml.getElementsByTagName("quickpi"); elements[0].appendChild(node); } } } context.loadPrograms = function(xml) { if (context.infos.customSensors) { var elements = xml.getElementsByTagName("sensor"); if (elements.length > 0) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } infos.quickPiSensors = []; for (var i = 0; i < elements.length; i++) { var sensornode = elements[i]; var sensor = { "type" : sensornode.getAttribute("type"), "port" : sensornode.getAttribute("port"), "name" : sensornode.getAttribute("name"), }; if (sensornode.getAttribute("subtype")) { sensor.subType = sensornode.getAttribute("subtype"); } sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(sensor); } this.resetDisplay(); } } } // Reset the context's display context.resetDisplay = function () { // Do something here //$('#grid').html('Display for the library goes here.'); // Ask the parent to update sizes //context.blocklyHelper.updateSize(); //context.updateScale(); if (!context.display || !this.raphaelFactory) return; var piUi = getQuickPiOption('disableConnection') ? '' : strings.messages.connectionHTML; var hasIntroControls = $('#taskIntro').find('#introControls').length; if (!hasIntroControls) { $('#taskIntro').append(`<div id="introControls"></div>`); } if (introControls === null) { introControls = piUi + $('#introControls').html(); } $('#introControls').html(introControls) $('#taskIntro').addClass('piui'); $('#grid').html(` <div id="virtualSensors" style="height: 90%; width: 90%; padding: 5px;"> </div> ` ); this.raphaelFactory.destroyAll(); paper = this.raphaelFactory.create( "paperMain", "virtualSensors", $('#virtualSensors').width(), $('#virtualSensors').height() ); if (infos.quickPiSensors == "default") { infos.quickPiSensors = []; addDefaultBoardSensors(); } if (context.timeLineCurrent) { context.timeLineCurrent.remove(); context.timeLineCurrent = null; } if (context.timeLineCircle) { context.timeLineCircle.remove(); context.timeLineCircle = null; } if (context.timeLineTriangle) { context.timeLineTriangle.remove(); context.timeLineTriangle = null; } if (context.autoGrading) { var numSensors = infos.quickPiSensors.length; var sensorSize = Math.min(paper.height / numSensors * 0.80, paper.width / 10); context.sensorSize = sensorSize * .90; context.timelineStartx = context.sensorSize * 3; var maxTime = context.maxTime; if (maxTime == 0) maxTime = 1000; if (!context.loopsForever) maxTime = Math.floor(maxTime * 1.05); context.pixelsPerTime = (paper.width - context.timelineStartx - 30) / maxTime; for (var iSensor = 0; iSensor < infos.quickPiSensors.length; iSensor++) { var sensor = infos.quickPiSensors[iSensor]; sensor.drawInfo = { x: 0, y: 10 + (sensorSize * iSensor), width: sensorSize * .90, height: sensorSize * .90 } drawSensor(sensor); sensor.timelinelastxlabel = 0; if (context.gradingStatesBySensor.hasOwnProperty(sensor.name)) { var states = context.gradingStatesBySensor[sensor.name]; var startTime = 0; var lastState = null; sensor.lastAnalogState = null; for (var iState = 0; iState < states.length; iState++) { var state = states[iState]; drawSensorTimeLineState(sensor, lastState, startTime, state.time, "expected", true); startTime = state.time; lastState = state.state; } drawSensorTimeLineState(sensor, lastState, state.time, context.maxTime, "expected", true); if (!context.loopsForever) drawSensorTimeLineState(sensor, lastState, startTime, maxTime, "finnish", false); sensor.lastAnalogState = null; } } context.timeLineY = 10 + (sensorSize * (iSensor + 1)); drawTimeLine(); for (var iState = 0; iState < context.timeLineStates.length; iState++) { var timelinestate = context.timeLineStates[iState]; drawSensorTimeLineState(timelinestate.sensor, timelinestate.state, timelinestate.startTime, timelinestate.endTime, timelinestate.type, true); } } else { var nSensors = infos.quickPiSensors.length; infos.quickPiSensors.forEach(function (sensor) { var cellsAmount = findSensorDefinition(sensor).cellsAmount; if (cellsAmount) { nSensors += cellsAmount(paper) - 1; } }); if (infos.customSensors) { nSensors++; } if (nSensors < 4) nSensors = 4; var geometry = squareSize(paper.width, paper.height, nSensors); context.sensorSize = geometry.size * .10; var iSensor = 0; for (var col = 0; col < geometry.cols; col++) { var y = geometry.size * col; var line = paper.path(["M", 0, y, "L", paper.width, y]); line.attr({ "stroke-width": 1, "stroke": "lightgrey", "stroke-linecapstring": "round" }); for (var row = 0; row < geometry.rows; row++) { var x = paper.width / geometry.rows * row; var y1 = y + geometry.size / 4; var y2 = y + geometry.size * 3 / 4; line = paper.path(["M", x, y1, "L", x, y2]); line.attr({ "stroke-width": 1, "stroke": "lightgrey", "stroke-linecapstring": "round" }); if (iSensor == infos.quickPiSensors.length && infos.customSensors) { drawCustomSensorAdder(x, y, geometry.size); } else if (infos.quickPiSensors[iSensor]) { var sensor = infos.quickPiSensors[iSensor]; var cellsAmount = findSensorDefinition(sensor).cellsAmount; if (cellsAmount) { row += cellsAmount(paper) - 1; sensor.drawInfo = { x: x, y: y, width: geometry.size * cellsAmount(paper), height: geometry.size } } else { sensor.drawInfo = { x: x, y: y, width: geometry.size, height: geometry.size } } drawSensor(sensor); } iSensor++; } } } context.blocklyHelper.updateSize(); context.inUSBConnection = false; context.inBTConnection = false; context.releasing = false; context.offLineMode = true; showasReleased(); if (context.quickPiConnection.isConnecting()) { showasConnecting(); } if (context.quickPiConnection.isConnected()) { showasConnected(); context.offLineMode = false; } $('#piconnect').click(function () { window.displayHelper.showPopupDialog(strings.messages.connectionDialogHTML); if (context.offLineMode) { $('#pirelease').attr('disabled', true); } else { $('#pirelease').attr('disabled', false); } $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').hide(); if (context.quickPiConnection.isConnected()) { if (getSessionStorage('connectionMethod') == "USB") { $('#piconwifi').removeClass('active'); $('#piconusb').addClass('active'); $('#pischoolcon').hide(); $('#piaddress').val("192.168.233.1"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').text(strings.messages.canConnectoToUSB) context.inUSBConnection = true; context.inBTConnection = false; } else if (getSessionStorage('connectionMethod') == "BT") { $('#piconwifi').removeClass('active'); $('#piconbt').addClass('active'); $('#pischoolcon').hide(); $('#piaddress').val("192.168.233.2"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').text(strings.messages.canConnectoToBT) context.inUSBConnection = false; context.inBTConnection = true; } } else { setSessionStorage('connectionMethod', "WIFI"); } $('#piaddress').on('input', function (e) { if (context.offLineMode) { var content = $('#piaddress').val(); if (content) $('#piconnectok').attr('disabled', false); else $('#piconnectok').attr('disabled', true); } }); if (infos.runningOnQuickPi) { $('#piconnectionmainui').hide(); $('#piaddress').val(window.location.hostname); $('#piaddress').trigger("input"); } if (getSessionStorage('pilist')) { populatePiList(JSON.parse(getSessionStorage('pilist'))); } if (getSessionStorage('raspberryPiIpAddress')) { $('#piaddress').val(getSessionStorage('raspberryPiIpAddress')); $('#piaddress').trigger("input"); } if (getSessionStorage('schoolkey')) { $('#schoolkey').val(getSessionStorage('schoolkey')); $('#pigetlist').attr("disabled", false); } $('#piconnectok').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; if ($('#piusetunnel').is(":checked")) { var piname = $("#pilist option:selected").text().split("-")[0].trim(); var url = "ws://api.quick-pi.org/client/" + $('#schoolkey').val() + "-" + piname + "/api/v1/commands"; setSessionStorage('quickPiUrl', url); context.quickPiConnection.connect(url); } else { var ipaddress = $('#piaddress').val(); setSessionStorage('raspberryPiIpAddress', ipaddress); showasConnecting(); var url = "ws://" + ipaddress + ":5000/api/v1/commands"; setSessionStorage('quickPiUrl', url); context.quickPiConnection.connect(url); } }); $('#pirelease').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; // IF connected release lock context.releasing = true; context.quickPiConnection.releaseLock(); }); $('#picancel').click(function () { context.inUSBConnection = false; context.inBTConnection = false; $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#schoolkey').on('input', function (e) { var schoolkey = $('#schoolkey').val(); setSessionStorage('schoolkey', schoolkey); if (schoolkey) $('#pigetlist').attr("disabled", false); else $('#pigetlist').attr("disabled", true); }); $('#pigetlist').click(function () { var schoolkey = $('#schoolkey').val(); fetch('http://www.france-ioi.org/QuickPi/list.php?school=' + schoolkey) .then(function (response) { return response.json(); }) .then(function (jsonlist) { populatePiList(jsonlist); }); }); // Select device connexion methods $('#piconsel .btn').click(function () { if (!context.quickPiConnection.isConnected()) { if (!$(this).hasClass('active')) { $('#piconsel .btn').removeClass('active'); $(this).addClass('active'); } } }); $('#piconwifi').click(function () { if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "WIFI"); $(this).addClass('active'); $('#pischoolcon').show("slow"); $('#piconnectionlabel').hide(); } context.inUSBConnection = false; context.inBTConnection = false; }); $('#piconusb').click(function () { if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "USB"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').html(strings.messages.cantConnectoToUSB) $(this).addClass('active'); $('#pischoolcon').hide("slow"); $('#piaddress').val("192.168.233.1"); context.inUSBConnection = true; context.inBTConnection = false; function updateUSBAvailability(available) { if (context.inUSBConnection && context.offLineMode) { if (available) { $('#piconnectok').attr('disabled', false); $('#piconnectionlabel').text(strings.messages.canConnectoToUSB) } else { $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').html(strings.messages.cantConnectoToUSB) } context.quickPiConnection.isAvailable("192.168.233.1", updateUSBAvailability); } } updateUSBAvailability(false); } }); $('#piconbt').click(function () { $('#piconnectionlabel').show(); if (!context.quickPiConnection.isConnected()) { setSessionStorage('connectionMethod', "BT"); $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').show(); $('#piconnectionlabel').html(strings.messages.cantConnectoToBT) $(this).addClass('active'); $('#pischoolcon').hide("slow"); $('#piaddress').val("192.168.233.2"); context.inUSBConnection = false; context.inBTConnection = true; function updateBTAvailability(available) { if (context.inUSBConnection && context.offLineMode) { if (available) { $('#piconnectok').attr('disabled', false); $('#piconnectionlabel').text(strings.messages.canConnectoToBT) } else { $('#piconnectok').attr('disabled', true); $('#piconnectionlabel').html(strings.messages.cantConnectoToBT) } context.quickPiConnection.isAvailable("192.168.233.2", updateUSBAvailability); } } updateBTAvailability(false); } }); function populatePiList(jsonlist) { setSessionStorage('pilist', JSON.stringify(jsonlist)); var select = document.getElementById("pilist"); var first = true; $('#pilist').empty(); $('#piusetunnel').attr('disabled', true); for (var i = 0; i < jsonlist.length; i++) { var pi = jsonlist[i]; var el = document.createElement("option"); var minutes = Math.round(jsonlist[i].seconds_since_ping / 60); var timeago = ""; if (minutes < 60) timeago = strings.messages.minutesago.format(minutes); else timeago = strings.messages.hoursago; el.textContent = jsonlist[i].name + " - " + timeago; el.value = jsonlist[i].ip; select.appendChild(el); if (first) { $('#piaddress').val(jsonlist[i].ip); $('#piaddress').trigger("input"); first = false; $('#pilist').prop('disabled', false); $('#piusetunnel').attr('disabled', false); } } } $('#pilist').on('change', function () { $("#piaddress").val(this.value); }); }); $('#pichangehat').click(function () { window.displayHelper.showPopupDialog(` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Choisissez votre carte </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div id=boardlist> </div> <div panel-body-usbbt> <label id="piconnectionlabel"></label> </div> </div> </div>`); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); for (var i = 0; i < boardDefinitions.length; i++) { var board = boardDefinitions[i]; var image = document.createElement('img'); image.src = getImg(board.image); $('#boardlist').append(image).append("&nbsp;&nbsp;"); image.onclick = function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; context.changeBoard(board.name); } } }); $('#pihatsetup').click(function () { var command = "getBuzzerAudioOutput()"; context.quickPiConnection.sendCommand(command, function(val) { var buzzerstate = parseInt(val); window.displayHelper.showPopupDialog(` <div class="content connectPi qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> QuickPi Hat Settings </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div class="panel-body"> <div> <input type="checkbox" id="buzzeraudio" value="buzzeron"> Output audio trought audio buzzer<br> </div> <div class="inlineButtons"> <button id="pisetupok" class="btn"><i class="fas fa-cog icon"></i>Set</button> </div> </div> </div>`); $('#buzzeraudio').prop('checked', buzzerstate ? true : false); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#pisetupok').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; var radioValue = $('#buzzeraudio').is(":checked"); var command = "setBuzzerAudioOutput(" + (radioValue ? "True" : "False") + ")"; context.quickPiConnection.sendCommand(command, function(x) {}); }); }); }); $('#piinstall').click(function () { context.blocklyHelper.reportValues = false; python_code = context.generatePythonSensorTable(); python_code += "\n\n"; python_code += window.task.displayedSubTask.blocklyHelper.getCode('python'); python_code = python_code.replace("from quickpi import *", ""); if (context.runner) context.runner.stop(); context.installing = true; $('#piinstallprogresss').show(); $('#piinstallcheck').hide(); context.quickPiConnection.installProgram(python_code, function () { context.justinstalled = true; $('#piinstallprogresss').hide(); $('#piinstallcheck').show(); }); }); if (parseInt(getSessionStorage('autoConnect'))) { if (!context.quickPiConnection.isConnected() && !context.quickPiConnection.isConnecting()) { $('#piconnect').attr("disabled", true); context.quickPiConnection.connect(getSessionStorage('quickPiUrl')); } } }; function addDefaultBoardSensors() { var board = getCurrentBoard(); var boardDefaultSensors = board.default; if (!boardDefaultSensors) boardDefaultSensors = board.builtinSensors; if (boardDefaultSensors) { for (var i = 0; i < boardDefaultSensors.length; i++) { var sensor = boardDefaultSensors[i]; var newSensor = { "type": sensor.type, "port": sensor.port, "builtin": true, }; if (sensor.subType) { newSensor.subType = sensor.subType; } newSensor.name = getSensorSuggestedName(sensor.type, sensor.suggestedName); sensor.state = null; sensor.callsInTimeSlot = 0; sensor.lastTimeIncrease = 0; infos.quickPiSensors.push(newSensor); } } }; function getNewSensorSuggestedName(name) { var maxvalue = 0; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; var firstdigit = sensor.name.search(/\d/); if (firstdigit > 0) { var namepart = sensor.name.substring(0, firstdigit); var numberpart = parseInt(sensor.name.substring(firstdigit), 10); if (name == namepart && numberpart > maxvalue) { maxvalue = numberpart; } } } return name + (maxvalue + 1); } function drawCustomSensorAdder(x, y, size) { if (context.sensorAdder) { context.sensorAdder.remove(); } var centerx = x + size / 2; var centery = y + size / 2; var fontsize = size * .70; context.sensorAdder = paper.text(centerx, centery, "+"); context.sensorAdder.attr({ "font-size": fontsize + "px", fill: "lightgray" }); context.sensorAdder.node.style = "-moz-user-select: none; -webkit-user-select: none;"; context.sensorAdder.click(function () { window.displayHelper.showPopupDialog(` <div class="content qpi"> <div class="panel-heading"> <h2 class="sectionTitle"> <span class="iconTag"><i class="icon fas fa-list-ul"></i></span> Ajouter un composant </h2> <div class="exit" id="picancel"><i class="icon fas fa-times"></i></div> </div> <div id="sensorPicker" class="panel-body"> <label>Sélectionnez un composant à ajouter à votre Raspberry Pi et attachez-le à un port.</label> <div class="flex-container"> <div id="selector-image-container" class="flex-col half"> <img id="selector-sensor-image"> </div> <div class="flex-col half"> <div class="form-group"> <div class="input-group"> <select id="selector-sensor-list" class="custom-select"></select> </div> </div> <div class="form-group"> <div class="input-group"> <select id="selector-sensor-port" class="custom-select"></select> </div> <label id="selector-label"></label> </div> </div> </div> </div> <div class="singleButton"> <button id="selector-add-button" class="btn btn-centered"><i class="icon fa fa-check"></i>Ajouter</button> </div> </div> `); var select = document.getElementById("selector-sensor-list"); for (var iSensorDef = 0; iSensorDef < sensorDefinitions.length; iSensorDef++) { var sensorDefinition = sensorDefinitions[iSensorDef]; if (sensorDefinition.subTypes) { for (var iSubType = 0; iSubType < sensorDefinition.subTypes.length; iSubType++) { if (!sensorDefinition.pluggable && !sensorDefinition.subTypes[iSubType].pluggable) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description; if (sensorDefinition.subTypes[iSubType].description) el.textContent = sensorDefinition.subTypes[iSubType].description; el.value = sensorDefinition.name; el.value += "-" + sensorDefinition.subTypes[iSubType].subType; select.appendChild(el); } } else { if (!sensorDefinition.pluggable) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description; el.value = sensorDefinition.name; select.appendChild(el); } } var board = getCurrentBoard(); if (board.builtinSensors) { for (var i = 0; i < board.builtinSensors.length; i++) { var sensor = board.builtinSensors[i]; var sensorDefinition = findSensorDefinition(sensor); if (context.findSensor(sensor.type, sensor.port, false)) continue; var el = document.createElement("option"); el.textContent = sensorDefinition.description + "(builtin)"; el.value = sensorDefinition.name + "-"; if (sensor.subType) el.value += sensor.subType; el.value += "-" + sensor.port; select.appendChild(el); } } $('#selector-sensor-list').on('change', function () { var values = this.value.split("-"); var builtinport = false; var dummysensor = { type: values[0] }; if (values.length >= 2) if (values[1]) dummysensor.subType = values[1]; if (values.length >= 3) builtinport = values[2]; var sensorDefinition = findSensorDefinition(dummysensor); var imageContainer = document.getElementById("selector-image-container"); while (imageContainer.firstChild) { imageContainer.removeChild(imageContainer.firstChild); } for (var i = 0; i < sensorDefinition.selectorImages.length; i++) { var image = document.createElement('img'); image.src = getImg(sensorDefinition.selectorImages[i]); imageContainer.appendChild(image); //$('#selector-sensor-image').attr("src", getImg(sensorDefinition.selectorImages[0])); } var portSelect = document.getElementById("selector-sensor-port"); $('#selector-sensor-port').empty(); var hasPorts = false; if (builtinport) { var option = document.createElement('option'); option.innerText = builtinport; option.value = builtinport; portSelect.appendChild(option); hasPorts = true; } else { var ports = getCurrentBoard().portTypes[sensorDefinition.portType]; if (sensorDefinition.portType == "i2c") { ports = ["i2c"]; } for (var iPort = 0; iPort < ports.length; iPort++) { var port = sensorDefinition.portType + ports[iPort]; if (sensorDefinition.portType == "i2c") port = "i2c"; if (!isPortUsed(sensorDefinition.name, port)) { var option = document.createElement('option'); option.innerText = port; option.value = port; portSelect.appendChild(option); hasPorts = true; } } } if (!hasPorts) { $('#selector-add-button').attr("disabled", true); var object_function = strings.messages.actuator; if (sensorDefinition.isSensor) object_function = strings.messages.sensor; $('#selector-label').text(strings.messages.noPortsAvailable.format(object_function, sensorDefinition.portType)); $('#selector-label').show(); } else { $('#selector-add-button').attr("disabled", false); $('#selector-label').hide(); } }); $('#selector-add-button').click(function () { var sensorType = $("#selector-sensor-list option:selected").val(); var values = sensorType.split("-"); var dummysensor = { type: values[0] }; if (values.length == 2) dummysensor.subType = values[1]; var sensorDefinition = findSensorDefinition(dummysensor); var port = $("#selector-sensor-port option:selected").text(); var name = getNewSensorSuggestedName(sensorDefinition.name); if(name == 'screen1') { // prepend screen because squareSize func can't handle cells wrap infos.quickPiSensors.unshift({ type: sensorDefinition.name, subType: sensorDefinition.subType, port: port, name: name }); } else { infos.quickPiSensors.push({ type: sensorDefinition.name, subType: sensorDefinition.subType, port: port, name: name }); } $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; context.resetSensorTable(); context.resetDisplay(); }); $("#selector-sensor-list").trigger("change"); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); }); }; function isPortUsed(type, port) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (port == "i2c") { if (sensor.type == type) return true; } else { if (sensor.port == port) return true; } } return false; }; // Straight from stack overflow :) function squareSize(x, y, n) { // Compute number of rows and columns, and cell size var ratio = x / y; var ncols_float = Math.sqrt(n * ratio); var nrows_float = n / ncols_float; // Find best option filling the whole height var nrows1 = Math.ceil(nrows_float); var ncols1 = Math.ceil(n / nrows1); while (nrows1 * ratio < ncols1) { nrows1++; ncols1 = Math.ceil(n / nrows1); } var cell_size1 = y / nrows1; // Find best option filling the whole width var ncols2 = Math.ceil(ncols_float); var nrows2 = Math.ceil(n / ncols2); while (ncols2 < nrows2 * ratio) { ncols2++; nrows2 = Math.ceil(n / ncols2); } var cell_size2 = x / ncols2; // Find the best values var nrows, ncols, cell_size; if (cell_size1 < cell_size2) { nrows = nrows2; ncols = ncols2; cell_size = cell_size2; } else { nrows = nrows1; ncols = ncols1; cell_size = cell_size1; } return { rows: ncols, cols: nrows, size: cell_size }; } function showasConnected() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstallui').show(); if (context.board == "quickpi") $('#pihatsetup').show(); else $('#pihatsetup').hide(); $('#piconnect').css('background-color', '#F9A423'); $('#piinstall').css('background-color', "#488FE1"); $('#piconnecttext').hide(); } function showasConnecting() { $('#piconnectprogress').show(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); } function showasReleased() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstallui').hide(); $('#pihatsetup').hide(); $('#piconnect').css('background-color', '#F9A423'); $('#piconnecttext').show(); } function showasDisconnected() { $('#piconnectprogress').hide(); $('#piinstallcheck').hide(); $('#piinstallprogresss').hide(); $('#piinstall').css('background-color', 'gray'); $('#piconnect').css('background-color', 'gray'); $('#piconnecttext').hide(); } function raspberryPiConnected() { showasConnected(); context.resetSensorTable(); context.quickPiConnection.startNewSession(); context.liveUpdateCount = 0; context.offLineMode = false; setSessionStorage('autoConnect', "1"); context.resetDisplay(); startSensorPollInterval(); } function raspberryPiDisconnected(wasConnected, wrongversion) { if (context.releasing || !wasConnected) showasReleased(); else showasDisconnected(); window.task.displayedSubTask.context.offLineMode = true; if (context.quickPiConnection.wasLocked()) { window.displayHelper.showPopupMessage(strings.messages.piPlocked, 'blanket'); } else if (wrongversion) { window.displayHelper.showPopupMessage(strings.messages.wrongVersion, 'blanket'); } else if (!context.releasing && !wasConnected) { window.displayHelper.showPopupMessage(strings.messages.cantConnect, 'blanket'); } clearSensorPollInterval(); if (wasConnected && !context.releasing && !context.quickPiConnection.wasLocked() && !wrongversion) { context.quickPiConnection.connect(getSessionStorage('quickPiUrl')); } else { // If I was never connected don't attempt to autoconnect again setSessionStorage('autoConnect', "0"); window.task.displayedSubTask.context.resetDisplay(); } } function raspberryPiChangeBoard(board) { window.task.displayedSubTask.context.changeBoard(board); window.task.displayedSubTask.context.resetSensorTable(); } // Update the context's display to the new scale (after a window resize for instance) context.updateScale = function () { if (!context.display) { return; } var width = $('#virtualSensors').width(); var height = $('#virtualSensors').height(); if (!context.oldwidth || !context.oldheight || context.oldwidth != width || context.oldheight != height) { context.oldwidth = width; context.oldheight = height; context.resetDisplay(); } }; // When the context is unloaded, this function is called to clean up // anything the context may have created context.unload = function () { // Do something here clearSensorPollInterval(); if (context.display) { // Do something here } for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; sensor.removed = true; } }; function drawTimeLine() { if (paper == undefined || !context.display) return; if (context.timelineText) for (var i = 0; i < context.timelineText.length; i++) { context.timelineText[i].remove(); } context.timelineText = []; var step = 1000; if (context.maxTime <= 1000) step = 100; else if (context.maxTime <= 3000) step = 500; else step = 1000; var i = 0; for (; i <= context.maxTime; i += step) { var x = context.timelineStartx + (i * context.pixelsPerTime); var timelabel = paper.text(x, context.timeLineY, (i / 1000).toString() + "s"); var fontsize = context.pixelsPerTime * step * 0.4; if (fontsize > 15) fontsize = 15; timelabel.attr({ "font-size": fontsize.toString() + "px", 'text-anchor': 'center', 'font-weight': 'bold', fill: "gray" }); context.timelineText.push(timelabel); } context.timeLineHoverPath = paper.path(["M", context.timelineStartx, context.timeLineY, "L", context.timelineStartx + (context.maxTime * context.pixelsPerTime), (context.timeLineY)]); context.timeLineHoverPath.attr({ "stroke-width": 40, "opacity": 0, "stroke-linecap": "square", "stroke-linejoin": "round", }); context.timeLineHoverPath.mousemove(function(event){ $('#screentooltip').remove(); var ms = (event.clientX - context.timelineStartx) / context.pixelsPerTime; ms = Math.round(ms); if (ms < -4) return; if (ms < 0) ms = 0; $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); $('#screentooltip').css("left", event.clientX + 2).css("top", event.clientY + 2); $('#screentooltip').text(ms.toString() + "ms"); if (context.timeLineHoverLine) context.timeLineHoverLine.remove(); context.timeLineHoverLine = paper.path(["M", event.clientX, 0, "L", event.clientX, context.timeLineY]); context.timeLineHoverLine.attr({ "stroke-width": 4, "stroke": "blue", "opacity": 0.2, "stroke-linecap": "square", "stroke-linejoin": "round", }); }); context.timeLineHoverPath.mouseout(function() { if (context.timeLineHoverLine) context.timeLineHoverLine.remove(); $('#screentooltip').remove(); }); if (!context.loopsForever) { var endx = context.timelineStartx + (context.maxTime * context.pixelsPerTime); var x = context.timelineStartx + (i * context.pixelsPerTime); var timelabel = paper.text(x, context.timeLineY, '\uf11e'); timelabel.node.style.fontFamily = '"Font Awesome 5 Free"'; timelabel.node.style.fontWeight = "bold"; timelabel.attr({ "font-size": "20" + "px", 'text-anchor': 'middle', 'font-weight': 'bold', fill: "gray" }); context.timelineText.push(timelabel); if (context.timeLineEndLine) context.timeLineEndLine.remove(); context.timeLineEndLine = paper.path(["M", endx, 0, "L", endx, context.timeLineY]); if (context.endFlagEnd) context.endFlagEnd.remove(); context.endFlagEnd = paper.rect(endx, 0, x, context.timeLineY + 10); context.endFlagEnd.attr({ "fill": "lightgray", "stroke": "none", "opacity": 0.2, }); } /* paper.path(["M", context.timelineStartx, paper.height - context.sensorSize * 3 / 4, "L", paper.width, paper.height - context.sensorSize * 3 / 4]); */ } function drawCurrentTime() { if (!paper || !context.display || isNaN(context.currentTime)) return; /* if (context.currentTimeText) context.currentTimeText.remove(); context.currentTimeText = paper.text(0, paper.height - 40, context.currentTime.toString() + "ms"); context.currentTimeText.attr({ "font-size": "10px", 'text-anchor': 'start' }); */ if (!context.autoGrading) return; var animationSpeed = 200; // ms var startx = context.timelineStartx + (context.currentTime * context.pixelsPerTime); var targetpath = ["M", startx, 0, "L", startx, context.timeLineY]; if (context.timeLineCurrent) { context.timeLineCurrent.animate({path: targetpath}, animationSpeed); } else { context.timeLineCurrent = paper.path(targetpath); context.timeLineCurrent.attr({ "stroke-width": 5, "stroke": "#678AB4", "stroke-linecap": "round" }); } if (context.timeLineCircle) { context.timeLineCircle.animate({cx: startx}, animationSpeed); } else { var circleradius = 10; context.timeLineCircle = paper.circle(startx, context.timeLineY, 10); context.timeLineCircle.attr({ "fill": "white", "stroke": "#678AB4" }); } var trianglew = 10; var targetpath = ["M", startx, 0, "L", startx + trianglew, 0, "L", startx, trianglew, "L", startx - trianglew, 0, "L", startx, 0 ]; if (context.timeLineTriangle) { context.timeLineTriangle.animate({path: targetpath}, animationSpeed); } else { context.timeLineTriangle = paper.path(targetpath); context.timeLineTriangle.attr({ "fill": "#678AB4", "stroke": "#678AB4" }); } } function storeTimeLineState(sensor, state, startTime, endTime, type) { var found = false; var timelinestate = { sensor: sensor, state: state, startTime: startTime, endTime: endTime, type: type }; for (var i = 0; i < context.timeLineStates.length; i++) { var currenttlstate = context.timeLineStates[i]; if (currenttlstate.sensor == sensor && currenttlstate.startTime == startTime && currenttlstate.endTime == endTime && currenttlstate.type == type) { context.timeLineStates[i] = timelinestate; found = true; break; } } if (!found) { context.timeLineStates.push(timelinestate); } } function drawSensorTimeLineState(sensor, state, startTime, endTime, type, skipsave = false, expectedState = null) { if (paper == undefined || !context.display || !context.autoGrading) return; if (!skipsave) { storeTimeLineState(sensor, state, startTime, endTime, type); } var startx = context.timelineStartx + (startTime * context.pixelsPerTime); var stateLenght = (endTime - startTime) * context.pixelsPerTime; var ypositionmiddle = ((sensor.drawInfo.y + (sensor.drawInfo.height * .5)) + (sensor.drawInfo.height * .20)); var ypositiontop = sensor.drawInfo.y var ypositionbottom = sensor.drawInfo.y + sensor.drawInfo.height; var color = "green"; var strokewidth = 4; if (type == "expected" || type == "finnish") { color = "lightgrey"; strokewidth = 8; } else if (type == "wrong") { color = "red"; strokewidth = 4; } else if (type == "actual") { color = "yellow"; strokewidth = 4; } var isAnalog = findSensorDefinition(sensor).isAnalog; var percentage = + state; var drawnElements = []; var deleteLastDrawnElements = true; if (sensor.type == "accelerometer" || sensor.type == "gyroscope" || sensor.type == "magnetometer") { if (state != null) { for (var i = 0; i < 3; i++) { var startx = context.timelineStartx + (startTime * context.pixelsPerTime); var stateLenght = (endTime - startTime) * context.pixelsPerTime; var yspace = sensor.drawInfo.height / 3; var ypositiontop = sensor.drawInfo.y + (yspace * i) var ypositionbottom = ypositiontop + yspace; var offset = (ypositionbottom - ypositiontop) * findSensorDefinition(sensor).getPercentageFromState(state[i], sensor); if (type == "expected" || type == "finnish") { color = "lightgrey"; strokewidth = 4; } else if (type == "wrong") { color = "red"; strokewidth = 2; } else if (type == "actual") { color = "yellow"; strokewidth = 2; } if (sensor.lastAnalogState != null && sensor.lastAnalogState[i] != state[i]) { var oldStatePercentage = findSensorDefinition(sensor).getPercentageFromState(sensor.lastAnalogState[i], sensor); var previousOffset = (ypositionbottom - ypositiontop) * oldStatePercentage; var joinline = paper.path(["M", startx, ypositiontop + offset, "L", startx, ypositiontop + previousOffset]); joinline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); if (sensor.timelinelastxlabel == null) sensor.timelinelastxlabel = [0, 0, 0]; if ((startx) - sensor.timelinelastxlabel[i] > 40) { var sensorDef = findSensorDefinition(sensor); var stateText = state.toString(); if(sensorDef && sensorDef.getStateString) { stateText = sensorDef.getStateString(state[i]); } var paperText = paper.text(startx, ypositiontop + offset - 10, stateText); drawnElements.push(paperText); sensor.timelinelastxlabel[i] = startx; } } var stateline = paper.path(["M", startx, ypositiontop + offset, "L", startx + stateLenght, ypositiontop + offset]); stateline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); } sensor.lastAnalogState = state == null ? [0, 0, 0] : state; } } else if (isAnalog || sensor.showAsAnalog) { var offset = (ypositionbottom - ypositiontop) * findSensorDefinition(sensor).getPercentageFromState(state, sensor); if (type == "wrong") { color = "red"; ypositionmiddle += 4; } else if (type == "actual") { color = "yellow"; ypositionmiddle += 4; } if (sensor.lastAnalogState != null && sensor.lastAnalogState != state) { var oldStatePercentage = findSensorDefinition(sensor).getPercentageFromState(sensor.lastAnalogState, sensor); var previousOffset = (ypositionbottom - ypositiontop) * oldStatePercentage; var joinline = paper.path(["M", startx, ypositiontop + offset, "L", startx, ypositiontop + previousOffset]); joinline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); if (!sensor.timelinelastxlabel) sensor.timelinelastxlabel = 0; if (!sensor.timelinelastxlabel) sensor.timelinelastxlabel = 0; if ((startx) - sensor.timelinelastxlabel > 5) { var sensorDef = findSensorDefinition(sensor); var stateText = state.toString(); if(sensorDef && sensorDef.getStateString) { stateText = sensorDef.getStateString(state); } if (sensor.timelinestateup) { var paperText = paper.text(startx, ypositiontop + offset - 10, stateText); sensor.timelinestateup = false; } else { var paperText = paper.text(startx, ypositiontop + offset + 20, stateText); sensor.timelinestateup = true; } drawnElements.push(paperText); sensor.timelinelastxlabel = startx; } } sensor.lastAnalogState = state == null ? 0 : state; var stateline = paper.path(["M", startx, ypositiontop + offset, "L", startx + stateLenght, ypositiontop + offset]); stateline.attr({ "stroke-width": strokewidth, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); } else if (sensor.type == "stick") { var stateToFA = [ "\uf062", "\uf063", "\uf060", "\uf061", "\uf111", ] var spacing = sensor.drawInfo.height / 5; for (var i = 0; i < 5; i++) { if (state && state[i]) { var ypos = sensor.drawInfo.y + (i * spacing); var startingpath = ["M", startx, ypos, "L", startx, ypos]; var targetpath = ["M", startx, ypos, "L", startx + stateLenght, ypos]; if (type == "expected") { var stateline = paper.path(targetpath); } else { var stateline = paper.path(startingpath); stateline.animate({path: targetpath}, 200); } stateline.attr({ "stroke-width": 2, "stroke": color, "stroke-linejoin": "round", "stroke-linecap": "round" }); drawnElements.push(stateline); if (type == "expected") { sensor.stateArrow = paper.text(startx, ypos, stateToFA[i]); sensor.stateArrow.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (strokewidth * 2) + "px" }); sensor.stateArrow.node.style.fontFamily = '"Font Awesome 5 Free"'; sensor.stateArrow.node.style.fontWeight = "bold"; } } } } else if (sensor.type == "screen" && state) { var sensorDef = findSensorDefinition(sensor); if (type != "actual" || !sensor.lastScreenState || !sensorDef.compareState(sensor.lastScreenState, state)) { sensor.lastScreenState = state; if (state.isDrawingData) { var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf303'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (4 * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup(event) { if (!sensor.showingTooltip) { $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); $('#screentooltip').css("width", "262px"); $('#screentooltip').css("height", "70px"); $('#screentooltip').css("left", event.clientX+2).css("top", event.clientY+2); var canvas = document.createElement("canvas"); canvas.id = "tooltipcanvas"; canvas.width = 128 * 2; canvas.height = 32 * 2; $('#screentooltip').append(canvas); $(canvas).css("position", "absolute"); $(canvas).css("z-index", "1500"); $(canvas).css("left", 3).css("top", 3); var ctx = canvas.getContext('2d'); if (expectedState && type == "wrong") { screenDrawing.renderDifferences(expectedState, state, canvas, 2); } else { screenDrawing.renderToCanvas(state, canvas, 2); } sensor.showingTooltip = true; } }; $(stateBubble.node).mouseenter(showPopup); $(stateBubble.node).click(showPopup); $(stateBubble.node).mouseleave(function(event) { sensor.showingTooltip = false; $('#screentooltip').remove(); }); } else { var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf27a'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (strokewidth * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup() { if (!sensor.tooltip) { sensor.tooltipText = paper.text(startx, ypositionmiddle + 50, state.line1 + "\n" + (state.line2 ? state.line2 : "")); var textDimensions = sensor.tooltipText.getBBox(); sensor.tooltip = paper.rect(textDimensions.x - 15, textDimensions.y - 15, textDimensions.width + 30, textDimensions.height + 30); sensor.tooltip.attr({ "stroke": "black", "stroke-width": 2, "fill": "white", }); sensor.tooltipText.toFront(); } }; stateBubble.click(showPopup); stateBubble.hover(showPopup, function () { if (sensor.tooltip) { sensor.tooltip.remove(); sensor.tooltip = null; } if (sensor.tooltipText) { sensor.tooltipText.remove(); sensor.tooltipText = null; } }); } drawnElements.push(stateBubble); } else { deleteLastDrawnElements = false; } } else if (sensor.type == "cloudstore") { var sensorDef = findSensorDefinition(sensor); if (type != "actual" || !sensor.lastScreenState || !sensorDef.compareState(sensor.lastScreenState, state)) { sensor.lastScreenState = state; var stateBubble = paper.text(startx, ypositionmiddle + 10, '\uf044'); stateBubble.attr({ "font": "Font Awesome 5 Free", "stroke": color, "fill": color, "font-size": (4 * 2) + "px" }); stateBubble.node.style.fontFamily = '"Font Awesome 5 Free"'; stateBubble.node.style.fontWeight = "bold"; function showPopup(event) { if (!sensor.showingTooltip) { $( "body" ).append('<div id="screentooltip"></div>'); $('#screentooltip').css("position", "absolute"); $('#screentooltip').css("border", "1px solid gray"); $('#screentooltip').css("background-color", "#efefef"); $('#screentooltip').css("padding", "3px"); $('#screentooltip').css("z-index", "1000"); /* $('#screentooltip').css("width", "262px"); $('#screentooltip').css("height", "70px");*/ $('#screentooltip').css("left", event.clientX+2).css("top", event.clientY+2); if (expectedState && type == "wrong") { var div = quickPiStore.renderDifferences(expectedState, state); $('#screentooltip').append(div); } else { for (var property in state) { var div = document.createElement("div"); $(div).text(property + " = " + state[property]); $('#screentooltip').append(div); } } sensor.showingTooltip = true; } }; $(stateBubble.node).mouseenter(showPopup); $(stateBubble.node).click(showPopup); $(stateBubble.node).mouseleave(function(event) { sensor.showingTooltip = false; $('#screentooltip').remove(); }); drawnElements.push(stateBubble); } else { deleteLastDrawnElements = false; } } else if (percentage != 0) { if (type == "wrong" || type == "actual") { ypositionmiddle += 2; } if (type == "expected") { var c = paper.rect(startx, ypositionmiddle, stateLenght, strokewidth); c.attr({ "stroke": "none", "fill": color, }); } else { var c = paper.rect(startx, ypositionmiddle, 0, strokewidth); c.attr({ "stroke": "none", "fill": color, }); c.animate({ width: stateLenght }, 200); } drawnElements.push(c); } if (type == "wrong") { /* wrongindicator = paper.path(["M", startx, sensor.drawInfo.y, "L", startx + stateLenght, sensor.drawInfo.y + sensor.drawInfo.height, "M", startx, sensor.drawInfo.y + sensor.drawInfo.height, "L", startx + stateLenght, sensor.drawInfo.y ]); wrongindicator.attr({ "stroke-width": 5, "stroke" : "red", "stroke-linecap": "round" });*/ } if(type == 'actual' || type == 'wrong') { if(!sensor.drawnGradingElements) { sensor.drawnGradingElements = []; } else if(deleteLastDrawnElements) { for(var i = 0; i < sensor.drawnGradingElements.length; i++) { var dge = sensor.drawnGradingElements[i]; if(dge.time >= startTime) { for(var j = 0; j < dge.elements.length; j++) { dge.elements[j].remove(); } sensor.drawnGradingElements.splice(i, 1); i -= 1; } } } if(drawnElements.length) { sensor.drawnGradingElements.push({time: startTime, elements: drawnElements}); } } // Make sure the current time bar is always on top of states drawCurrentTime(); } function getImg(filename) { // Get the path to an image stored in bebras-modules return (window.modulesPath ? window.modulesPath : '../../modules/') + 'img/quickpi/' + filename; } function createSlider(sensor, max, min, x, y, w, h, index) { var sliderobj = {}; sliderobj.sliderdata = {}; sliderobj.index = index; sliderobj.min = min; sliderobj.max = max; var outsiderectx = x; var outsiderecty = y; var outsidewidth = w / 6; var outsideheight = h; var insidewidth = outsidewidth / 6; sliderobj.sliderdata.insideheight = h * 0.60; var insiderectx = outsiderectx + (outsidewidth / 2) - (insidewidth / 2); sliderobj.sliderdata.insiderecty = outsiderecty + (outsideheight / 2) - (sliderobj.sliderdata.insideheight / 2); var circleradius = (outsidewidth / 2) - 1; var pluscirclex = outsiderectx + (outsidewidth / 2); var pluscircley = outsiderecty + circleradius + 1; var minuscirclex = pluscirclex; var minuscircley = outsiderecty + outsideheight - circleradius - 1; paper.setStart(); sliderobj.sliderrect = paper.rect(outsiderectx, outsiderecty, outsidewidth, outsideheight, outsidewidth / 2); sliderobj.sliderrect.attr("fill", "#468DDF"); sliderobj.sliderrect.attr("stroke", "#468DDF"); sliderobj.sliderrect = paper.rect(insiderectx, sliderobj.sliderdata.insiderecty, insidewidth, sliderobj.sliderdata.insideheight, 2); sliderobj.sliderrect.attr("fill", "#2E5D94"); sliderobj.sliderrect.attr("stroke", "#2E5D94"); sliderobj.plusset = paper.set(); sliderobj.pluscircle = paper.circle(pluscirclex, pluscircley, circleradius); sliderobj.pluscircle.attr("fill", "#F5A621"); sliderobj.pluscircle.attr("stroke", "#F5A621"); sliderobj.plus = paper.text(pluscirclex, pluscircley, "+"); sliderobj.plus.attr({ fill: "white" }); sliderobj.plus.node.style = "-moz-user-select: none; -webkit-user-select: none;"; sliderobj.plusset.push(sliderobj.pluscircle, sliderobj.plus); sliderobj.plusset.click(function () { var step = 1; var sensorDef = findSensorDefinition(sensor); if (sensorDef.step) step = sensorDef.step; if (Array.isArray(sensor.state)) { if (sensor.state[sliderobj.index] < sliderobj.max) sensor.state[sliderobj.index] += step; } else { if (sensor.state < sliderobj.max) sensor.state += step; } drawSensor(sensor, true); }); sliderobj.minusset = paper.set(); sliderobj.minuscircle = paper.circle(minuscirclex, minuscircley, circleradius); sliderobj.minuscircle.attr("fill", "#F5A621"); sliderobj.minuscircle.attr("stroke", "#F5A621"); sliderobj.minus = paper.text(minuscirclex, minuscircley, "-"); sliderobj.minus.attr({ fill: "white" }); sliderobj.minus.node.style = "-moz-user-select: none; -webkit-user-select: none;"; sliderobj.minusset.push(sliderobj.minuscircle, sliderobj.minus); sliderobj.minusset.click(function () { var step = 1; var sensorDef = findSensorDefinition(sensor); if (sensorDef.step) step = sensorDef.step; if (Array.isArray(sensor.state)) { if (sensor.state[sliderobj.index] > sliderobj.min) sensor.state[sliderobj.index] -= step; } else { if (sensor.state > sliderobj.min) sensor.state -= step; } drawSensor(sensor, true); }); var thumbwidth = outsidewidth * .80; sliderobj.sliderdata.thumbheight = outsidewidth * 1.4; sliderobj.sliderdata.scale = (sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight); if (Array.isArray(sensor.state)) { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state[index], sensor); } else { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state, sensor); } var thumby = sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight - (percentage * sliderobj.sliderdata.scale); var thumbx = insiderectx + (insidewidth / 2) - (thumbwidth / 2); sliderobj.thumb = paper.rect(thumbx, thumby, thumbwidth, sliderobj.sliderdata.thumbheight, outsidewidth / 2); sliderobj.thumb.attr("fill", "#F5A621"); sliderobj.thumb.attr("stroke", "#F5A621"); sliderobj.slider = paper.setFinish(); sliderobj.thumb.drag( function (dx, dy, x, y, event) { var newy = sliderobj.sliderdata.zero + dy; if (newy < sliderobj.sliderdata.insiderecty) newy = sliderobj.sliderdata.insiderecty; if (newy > sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight) newy = sliderobj.sliderdata.insiderecty + sliderobj.sliderdata.insideheight - sliderobj.sliderdata.thumbheight; sliderobj.thumb.attr('y', newy); var percentage = 1 - ((newy - sliderobj.sliderdata.insiderecty) / sliderobj.sliderdata.scale); if (Array.isArray(sensor.state)) { sensor.state[sliderobj.index] = findSensorDefinition(sensor).getStateFromPercentage(percentage); } else { sensor.state = findSensorDefinition(sensor).getStateFromPercentage(percentage); } drawSensor(sensor, true); }, function (x, y, event) { sliderobj.sliderdata.zero = sliderobj.thumb.attr('y'); }, function (event) { } ); return sliderobj; } function setSlider(sensor, juststate, imgx, imgy, imgw, imgh, min, max, triaxial) { if (juststate) { if (Array.isArray(sensor.state)) { for (var i = 0; i < sensor.state.length; i++) { if (sensor.sliders[i] == undefined) continue; var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state[i], sensor); thumby = sensor.sliders[i].sliderdata.insiderecty + sensor.sliders[i].sliderdata.insideheight - sensor.sliders[i].sliderdata.thumbheight - (percentage * sensor.sliders[i].sliderdata.scale); sensor.sliders[i].thumb.attr('y', thumby); } } else { var percentage = findSensorDefinition(sensor).getPercentageFromState(sensor.state, sensor); thumby = sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight - (percentage * sensor.sliders[0].sliderdata.scale); sensor.sliders[0].thumb.attr('y', thumby); } return; } removeSlider(sensor); sensor.sliders = []; var actuallydragged; sensor.hasslider = true; sensor.focusrect.drag( function (dx, dy, x, y, event) { if (sensor.sliders.length != 1) return; var newy = sensor.sliders[0].sliderdata.zero + dy; if (newy < sensor.sliders[0].sliderdata.insiderecty) newy = sensor.sliders[0].sliderdata.insiderecty; if (newy > sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight) newy = sensor.sliders[0].sliderdata.insiderecty + sensor.sliders[0].sliderdata.insideheight - sensor.sliders[0].sliderdata.thumbheight; sensor.sliders[0].thumb.attr('y', newy); var percentage = 1 - ((newy - sensor.sliders[0].sliderdata.insiderecty) / sensor.sliders[0].sliderdata.scale); sensor.state = findSensorDefinition(sensor).getStateFromPercentage(percentage); drawSensor(sensor, true); actuallydragged++; }, function (x, y, event) { showSlider(); actuallydragged = 0; if (sensor.sliders.length == 1) sensor.sliders[0].sliderdata.zero = sensor.sliders[0].thumb.attr('y'); }, function (event) { if (actuallydragged > 4) { hideSlider(sensor); } } ); function showSlider() { hideSlider(sensorWithSlider); sensorWithSlider = sensor; if (Array.isArray(sensor.state)) { var offset = 0; var sign = -1; if (sensor.drawInfo.x - ((sensor.state.length - 1) * sensor.drawInfo.width / 5) < 0) { sign = 1; offset = sensor.drawInfo.width; } for (var i = 0; i < sensor.state.length; i++) { sliderobj = createSlider(sensor, max, min, sensor.drawInfo.x + offset + (sign * i * sensor.drawInfo.width / 5) , sensor.drawInfo.y, sensor.drawInfo.width, sensor.drawInfo.height, i); sensor.sliders.push(sliderobj); } } else { sliderobj = createSlider(sensor, max, min, sensor.drawInfo.x, sensor.drawInfo.y, sensor.drawInfo.width, sensor.drawInfo.height, 0); sensor.sliders.push(sliderobj); } } } function removeSlider(sensor) { if (sensor.hasslider && sensor.focusrect) { sensor.focusrect.undrag(); sensor.hasslider = false; } if (sensor.sliders) { for (var i = 0; i < sensor.sliders.length; i++) { sensor.sliders[i].slider.remove(); } sensor.sliders = []; } } function sensorInConnectedModeError() { window.displayHelper.showPopupMessage(strings.messages.sensorInOnlineMode, 'blanket'); } function actuatorsInRunningModeError() { window.displayHelper.showPopupMessage(strings.messages.actuatorsWhenRunning, 'blanket'); } function drawSensor(sensor, juststate = false, donotmovefocusrect = false) { if (paper == undefined || !context.display || !sensor.drawInfo) return; var imgw = sensor.drawInfo.width / 2; var imgh = sensor.drawInfo.height / 2; var imgx = sensor.drawInfo.x + imgw / 6; var imgy = sensor.drawInfo.y + (sensor.drawInfo.height / 2) - (imgh / 2); var state1x = (imgx + imgw) + 3; var state1y = imgy + imgh / 3; var portx = state1x; var porty = imgy; var namex = sensor.drawInfo.x + (sensor.drawInfo.height / 2); var namey = sensor.drawInfo.y + (imgh * 0.20); var nameanchor = "middle"; var portsize = sensor.drawInfo.height * 0.10; var statesize = sensor.drawInfo.height * 0.09; var namesize = sensor.drawInfo.height * 0.10; var drawPortText = true; var drawName = true; if (!sensor.focusrect || !sensor.focusrect.paper.canvas) sensor.focusrect = paper.rect(imgx, imgy, imgw, imgh); sensor.focusrect.attr({ "fill": "468DDF", "fill-opacity": 0, "opacity": 0, "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (context.autoGrading) { imgw = sensor.drawInfo.width * .80; imgh = sensor.drawInfo.height * .80; imgx = sensor.drawInfo.x + imgw * 0.75; imgy = sensor.drawInfo.y + (sensor.drawInfo.height / 2) - (imgh / 2); state1x = imgx + imgw * 1.2; state1y = imgy + (imgh / 2); portx = sensor.drawInfo.x; porty = imgy + (imgh / 2); portsize = imgh / 3; statesize = sensor.drawInfo.height * 0.2; namex = portx; namesize = portsize; nameanchor = "start"; } if (sensor.type == "led") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 0; if (!sensor.ledoff || !sensor.ledoff.paper.canvas) { sensor.ledoff = paper.image(getImg('ledoff.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } if (!sensor.ledon || !sensor.ledon.paper.canvas) { var imagename = "ledon-"; if (sensor.subType) imagename += sensor.subType; else imagename += "red"; imagename += ".png"; sensor.ledon = paper.image(getImg(imagename), imgx, imgy, imgw, imgh); } sensor.ledon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.ledoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.showAsAnalog) { sensor.stateText = paper.text(state1x, state1y, sensor.state); } else { if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.stateText = paper.text(state1x, state1y, "OFF"); } } if (sensor.state) { sensor.ledon.attr({ "opacity": 1 }); sensor.ledoff.attr({ "opacity": 0 }); } else { sensor.ledon.attr({ "opacity": 0 }); sensor.ledoff.attr({ "opacity": 1 }); } var x = typeof sensor.state; if(typeof sensor.state == 'number' ) { sensor.ledon.attr({ "opacity": sensor.state }); sensor.ledoff.attr({ "opacity": 1 }); } if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); } } else if (sensor.type == "buzzer") { if(typeof sensor.state == 'number' && sensor.state != 0 && sensor.state != 1) { buzzerSound.start(sensor.name, sensor.state); } else if (sensor.state) { buzzerSound.start(sensor.name); } else { buzzerSound.stop(sensor.name); } if(!juststate) { if(sensor.muteBtn) { sensor.muteBtn.remove(); } var muteBtnSize = sensor.drawInfo.width * 0.15; sensor.muteBtn = paper.text( state1x, state1y + imgh / 2, buzzerSound.isMuted(sensor.name) ? "\uf6a9" : "\uf028" ); sensor.muteBtn.node.style.fontWeight = "bold"; sensor.muteBtn.node.style.cursor = "default"; sensor.muteBtn.node.style.MozUserSelect = "none"; sensor.muteBtn.node.style.WebkitUserSelect = "none"; sensor.muteBtn.attr({ "font-size": muteBtnSize + "px", fill: buzzerSound.isMuted(sensor.name) ? "lightgray" : "#468DDF", "font-family": '"Font Awesome 5 Free"', 'text-anchor': 'start' }); sensor.muteBtn.click(function () { if(buzzerSound.isMuted(sensor.name)) { buzzerSound.unmute(sensor.name) } else { buzzerSound.mute(sensor.name) } drawSensor(sensor); }); } if (!sensor.buzzeron || !sensor.buzzeron.paper.canvas) sensor.buzzeron = paper.image(getImg('buzzer-ringing.png'), imgx, imgy, imgw, imgh); if (!sensor.buzzeroff || !sensor.buzzeroff.paper.canvas) { sensor.buzzeroff = paper.image(getImg('buzzer.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } if (sensor.state) { if (!sensor.buzzerInterval) { sensor.buzzerInterval = setInterval(function () { if (!sensor.removed) { sensor.ringingState = !sensor.ringingState; drawSensor(sensor, true, true); } else { clearInterval(sensor.buzzerInterval); } }, 100); } } else { if (sensor.buzzerInterval) { clearInterval(sensor.buzzerInterval); sensor.buzzerInterval = null; sensor.ringingState = null; } } sensor.buzzeron.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buzzeroff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); var drawState = sensor.state; if (sensor.ringingState != null) drawState = sensor.ringingState; if (drawState) { sensor.buzzeron.attr({ "opacity": 1 }); sensor.buzzeroff.attr({ "opacity": 0 }); } else { sensor.buzzeron.attr({ "opacity": 0 }); sensor.buzzeroff.attr({ "opacity": 1 }); } if (sensor.stateText) sensor.stateText.remove(); var stateText = findSensorDefinition(sensor).getStateString(sensor.state); sensor.stateText = paper.text(state1x, state1y, stateText); if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { var setLiveState = findSensorDefinition(sensor).setLiveState; if (setLiveState) { setLiveState(sensor, sensor.state, function(x) {}); } } } else if (sensor.type == "button") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.buttonon || !sensor.buttonon.paper.canvas) sensor.buttonon = paper.image(getImg('buttonon.png'), imgx, imgy, imgw, imgh); if (!sensor.buttonoff || !sensor.buttonoff.paper.canvas) sensor.buttonoff = paper.image(getImg('buttonoff.png'), imgx, imgy, imgw, imgh); if (sensor.state == null) sensor.state = false; sensor.buttonon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buttonoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.buttonon.attr({ "opacity": 1 }); sensor.buttonoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.buttonon.attr({ "opacity": 0 }); sensor.buttonoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if (!context.autoGrading && !sensor.buttonon.node.onmousedown) { sensor.focusrect.node.onmousedown = function () { if (context.offLineMode) { sensor.state = true; drawSensor(sensor); } else sensorInConnectedModeError(); }; sensor.focusrect.node.onmouseup = function () { if (context.offLineMode) { sensor.state = false; sensor.wasPressed = true; drawSensor(sensor); if (sensor.onPressed) sensor.onPressed(); } else sensorInConnectedModeError(); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } } else if (sensor.type == "screen") { if (sensor.stateText) { sensor.stateText.remove(); sensor.stateText = null; } var borderSize = 5; var screenScale = 2; if(sensor.drawInfo.width < 300) { screenScale = 1; } if(sensor.drawInfo.width < 150) { screenScale = 0.5; } var screenScalerSize = { width: 128 * screenScale, height: 32 * screenScale } borderSize = borderSize * screenScale; imgw = screenScalerSize.width + borderSize * 2; imgh = screenScalerSize.height + borderSize * 2; imgx = sensor.drawInfo.x + Math.max(0, (sensor.drawInfo.width - imgw) * 0.5); imgy = sensor.drawInfo.y + Math.max(0, (sensor.drawInfo.height - imgh) * 0.5); portx = imgx + imgw + borderSize; porty = imgy + imgh / 3; /* if (context.autoGrading) { state1x = imgx + imgw; state1y = imgy + (imgh / 2); portsize = imgh / 4; statesize = imgh / 6; } */ statesize = imgh / 3.5; if (!sensor.img || !sensor.img.paper.canvas) { sensor.img = paper.image(getImg('screen.png'), imgx, imgy, imgw, imgh); } sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { if (sensor.state.isDrawingData) { if (!sensor.screenrect || !sensor.screenrect.paper.canvas || !sensor.canvasNode) { sensor.screenrect = paper.rect(imgx, imgy, screenScalerSize.width, screenScalerSize.height); sensor.canvasNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignObject'); sensor.canvasNode.setAttribute("x",imgx + borderSize); //Set rect data sensor.canvasNode.setAttribute("y",imgy + borderSize); //Set rect data sensor.canvasNode.setAttribute("width", screenScalerSize.width); //Set rect data sensor.canvasNode.setAttribute("height", screenScalerSize.height); //Set rect data paper.canvas.appendChild(sensor.canvasNode); sensor.canvas = document.createElement("canvas"); sensor.canvas.id = "screencanvas"; sensor.canvas.width = screenScalerSize.width; sensor.canvas.height = screenScalerSize.height; sensor.canvasNode.appendChild(sensor.canvas); } sensor.canvasNode.setAttribute("x", imgx + borderSize); //Set rect data sensor.canvasNode.setAttribute("y", imgy + borderSize); //Set rect data sensor.canvasNode.setAttribute("width", screenScalerSize.width); //Set rect data sensor.canvasNode.setAttribute("height", screenScalerSize.height); //Set rect data sensor.screenrect.attr({ "x": imgx + borderSize, "y": imgy + borderSize, "width": 128, "height": 32, }); sensor.screenrect.attr({ "opacity": 0 }); sensor.screenDrawing.copyToCanvas(sensor.canvas, screenScale); } else { var statex = imgx + (imgw * .05); var statey = imgy + (imgh * .2); if (sensor.state.line1.length > 16) sensor.state.line1 = sensor.state.line1.substring(0, 16); if (sensor.state.line2 && sensor.state.line2.length > 16) sensor.state.line2 = sensor.state.line2.substring(0, 16); if (sensor.canvasNode) { $(sensor.canvasNode).remove(); sensor.canvasNode = null; } sensor.stateText = paper.text(statex, statey, sensor.state.line1 + "\n" + (sensor.state.line2 ? sensor.state.line2 : "")); sensor.stateText.attr("") } } } else if (sensor.type == "temperature") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 25; // FIXME if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('temperature-cold.png'), imgx, imgy, imgw, imgh); if (!sensor.img2 || !sensor.img2.paper.canvas) sensor.img2 = paper.image(getImg('temperature-hot.png'), imgx, imgy, imgw, imgh); if (!sensor.img3 || !sensor.img3.paper.canvas) sensor.img3 = paper.image(getImg('temperature-overlay.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.img2.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.img3.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); var scale = imgh / 60; var cliph = scale * sensor.state; sensor.img2.attr({ "clip-rect": imgx + "," + (imgy + imgh - cliph) + "," + (imgw) + "," + cliph }); sensor.stateText = paper.text(state1x, state1y, sensor.state + "C"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 60); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "servo") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('servo.png'), imgx, imgy, imgw, imgh); if (!sensor.pale || !sensor.pale.paper.canvas) sensor.pale = paper.image(getImg('servo-pale.png'), imgx, imgy, imgw, imgh); if (!sensor.center || !sensor.center.paper.canvas) sensor.center = paper.image(getImg('servo-center.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); sensor.center.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.rotate(sensor.state); if (sensor.state == null) sensor.state = 0; sensor.state = Math.round(sensor.state); sensor.stateText = paper.text(state1x, state1y, sensor.state + "°"); if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { if (!sensor.updatetimeout) { sensor.updatetimeout = setTimeout(function () { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); sensor.updatetimeout = null; }, 100); } } if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 180); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "potentiometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('potentiometer.png'), imgx, imgy, imgw, imgh); if (!sensor.pale || !sensor.pale.paper.canvas) sensor.pale = paper.image(getImg('potentiometer-pale.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.pale.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); if (sensor.state == null) sensor.state = 0; sensor.pale.rotate(sensor.state * 3.6); sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "range") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('range.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 500; if (sensor.rangedistance) sensor.rangedistance.remove(); if (sensor.rangedistancestart) sensor.rangedistancestart.remove(); if (sensor.rangedistanceend) sensor.rangedistanceend.remove(); var rangew; if (sensor.state < 30) { rangew = imgw * sensor.state / 100; } else { var firstpart = imgw * 30 / 100; var remaining = imgw - firstpart; rangew = firstpart + (remaining * (sensor.state) * 0.0015); } var centerx = imgx + (imgw / 2); sensor.rangedistance = paper.path(["M", centerx - (rangew / 2), imgy + imgw, "L", centerx + (rangew / 2), imgy + imgw]); var markh = 16; sensor.rangedistancestart = paper.path(["M", centerx - (rangew / 2), imgy + imgw - (markh / 2), "L", centerx - (rangew / 2), imgy + imgw + (markh / 2)]); sensor.rangedistanceend = paper.path(["M", centerx + (rangew / 2), imgy + imgw - (markh / 2), "L", centerx + (rangew / 2), imgy + imgw + (markh / 2)]); sensor.rangedistance.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); sensor.rangedistancestart.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); sensor.rangedistanceend.attr({ "stroke-width": 4, "stroke": "#468DDF", "stroke-linecapstring": "round" }); if (sensor.state >= 10) sensor.state = Math.round(sensor.state); sensor.stateText = paper.text(state1x, state1y, sensor.state + "cm"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 500); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "light") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('light.png'), imgx, imgy, imgw, imgh); if (!sensor.moon || !sensor.moon.paper.canvas) sensor.moon = paper.image(getImg('light-moon.png'), imgx, imgy, imgw, imgh); if (!sensor.sun || !sensor.sun.paper.canvas) sensor.sun = paper.image(getImg('light-sun.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 0; if (sensor.state > 50) { var opacity = (sensor.state - 50) * 0.02; sensor.sun.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": opacity * .80 }); sensor.moon.attr({ "opacity": 0 }); } else { var opacity = (50 - sensor.state) * 0.02; sensor.moon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": opacity * .80 }); sensor.sun.attr({ "opacity": 0 }); } sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "humidity") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('humidity.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state == null) sensor.state = 0; sensor.stateText = paper.text(state1x, state1y, sensor.state + "%"); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 100); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "accelerometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('accel.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.stateText) sensor.stateText.remove(); if (!sensor.state) { sensor.state = [0, 0, 1]; } if (sensor.state) { try { sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "m/s²\nY: " + sensor.state[1] + "m/s²\nZ: " + sensor.state[2] + "m/s²"); } catch (Err) { var a = 1; } } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -8 * 9.81, 8 * 9.81); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "gyroscope") { if (!sensor.state) { sensor.state = [0, 0, 0]; } if (sensor.stateText) { sensor.stateText.remove(); } sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "°/s\nY: " + sensor.state[1] + "°/s\nZ: " + sensor.state[2] + "°/s"); if (!context.autoGrading && context.offLineMode) { var img3d = gyroscope3D.getInstance(imgw, imgh); } if(img3d) { if (!sensor.screenrect || !sensor.screenrect.paper.canvas) { sensor.screenrect = paper.rect(imgx, imgy, imgw, imgh); sensor.screenrect.attr({ "opacity": 0 }); sensor.canvasNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignObject'); sensor.canvasNode.setAttribute("x", imgx); sensor.canvasNode.setAttribute("y", imgy); sensor.canvasNode.setAttribute("width", imgw); sensor.canvasNode.setAttribute("height", imgh); paper.canvas.appendChild(sensor.canvasNode); sensor.canvas = document.createElement("canvas"); sensor.canvas.width = imgw; sensor.canvas.height = imgh; sensor.canvasNode.appendChild(sensor.canvas); } var sensorCtx = sensor.canvas.getContext('2d'); sensorCtx.clearRect(0, 0, imgw, imgh); sensorCtx.drawImage(img3d.render( sensor.state[0], sensor.state[2], sensor.state[1] ), 0, 0); if(!juststate) { sensor.focusrect.drag( function(dx, dy, x, y, event) { sensor.state[0] = Math.max(-125, Math.min(125, sensor.old_state[0] + dy)); sensor.state[1] = Math.max(-125, Math.min(125, sensor.old_state[1] - dx)); drawSensor(sensor, true) }, function() { sensor.old_state = sensor.state.slice(); } ); } } else { if (!sensor.img || !sensor.img.paper.canvas) { sensor.img = paper.image(getImg('gyro.png'), imgx, imgy, imgw, imgh); } sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -125, 125); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } } else if (sensor.type == "magnetometer") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('mag.png'), imgx, imgy, imgw, imgh); if (!sensor.needle || !sensor.needle.paper.canvas) sensor.needle = paper.image(getImg('mag-needle.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.needle.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "transform": "" }); if (!sensor.state) { sensor.state = [0, 0, 0]; } if (sensor.state) { var heading = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; sensor.needle.rotate(heading); } if (sensor.stateText) sensor.stateText.remove(); if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, "X: " + sensor.state[0] + "μT\nY: " + sensor.state[1] + "μT\nZ: " + sensor.state[2] + "μT"); } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, -1600, 1600); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "sound") { if (sensor.stateText) sensor.stateText.remove(); if (sensor.state == null) sensor.state = 25; // FIXME if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('sound.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.stateText) sensor.stateText.remove(); if (sensor.state) { sensor.stateText = paper.text(state1x, state1y, sensor.state); } if (!context.autoGrading && context.offLineMode) { setSlider(sensor, juststate, imgx, imgy, imgw, imgh, 0, 60); } else { sensor.focusrect.click(function () { sensorInConnectedModeError(); }); removeSlider(sensor); } } else if (sensor.type == "irtrans") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.ledon || !sensor.ledon.paper.canvas) { sensor.ledon = paper.image(getImg("irtranson.png"), imgx, imgy, imgw, imgh); } if (!sensor.ledoff || !sensor.ledoff.paper.canvas) { sensor.ledoff = paper.image(getImg('irtransoff.png'), imgx, imgy, imgw, imgh); sensor.focusrect.click(function () { if (!context.autoGrading && (!context.runner || !context.runner.isRunning())) { sensor.state = !sensor.state; drawSensor(sensor); } else { actuatorsInRunningModeError(); } }); } sensor.ledon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.ledoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.ledon.attr({ "opacity": 1 }); sensor.ledoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.ledon.attr({ "opacity": 0 }); sensor.ledoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if ((!context.runner || !context.runner.isRunning()) && !context.offLineMode) { findSensorDefinition(sensor).setLiveState(sensor, sensor.state, function(x) {}); } } else if (sensor.type == "irrecv") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.buttonon || !sensor.buttonon.paper.canvas) sensor.buttonon = paper.image(getImg('irrecvon.png'), imgx, imgy, imgw, imgh); if (!sensor.buttonoff || !sensor.buttonoff.paper.canvas) sensor.buttonoff = paper.image(getImg('irrecvoff.png'), imgx, imgy, imgw, imgh); sensor.buttonon.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.buttonoff.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); if (sensor.state) { sensor.buttonon.attr({ "opacity": 1 }); sensor.buttonoff.attr({ "opacity": 0 }); sensor.stateText = paper.text(state1x, state1y, "ON"); } else { sensor.buttonon.attr({ "opacity": 0 }); sensor.buttonoff.attr({ "opacity": 1 }); sensor.stateText = paper.text(state1x, state1y, "OFF"); } if (!context.autoGrading && !sensor.buttonon.node.onmousedown) { sensor.focusrect.node.onmousedown = function () { if (context.offLineMode) { sensor.state = true; drawSensor(sensor); } else sensorInConnectedModeError(); }; sensor.focusrect.node.onmouseup = function () { if (context.offLineMode) { sensor.state = false; drawSensor(sensor); if (sensor.onPressed) sensor.onPressed(); } else sensorInConnectedModeError(); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } } else if (sensor.type == "stick") { if (sensor.stateText) sensor.stateText.remove(); if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('stick.png'), imgx, imgy, imgw, imgh); if (!sensor.imgup || !sensor.imgup.paper.canvas) sensor.imgup = paper.image(getImg('stickup.png'), imgx, imgy, imgw, imgh); if (!sensor.imgdown || !sensor.imgdown.paper.canvas) sensor.imgdown = paper.image(getImg('stickdown.png'), imgx, imgy, imgw, imgh); if (!sensor.imgleft || !sensor.imgleft.paper.canvas) sensor.imgleft = paper.image(getImg('stickleft.png'), imgx, imgy, imgw, imgh); if (!sensor.imgright || !sensor.imgright.paper.canvas) sensor.imgright = paper.image(getImg('stickright.png'), imgx, imgy, imgw, imgh); if (!sensor.imgcenter || !sensor.imgcenter.paper.canvas) sensor.imgcenter = paper.image(getImg('stickcenter.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.imgup.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgdown.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgleft.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgright.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); sensor.imgcenter.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, "opacity": 0, }); if (sensor.stateText) sensor.stateText.remove(); if (!sensor.state) sensor.state = [false, false, false, false, false]; var stateString = ""; if (sensor.state[0]) { stateString += "UP\n" sensor.imgup.attr({ "opacity": 1 }); } if (sensor.state[1]) { stateString += "DOWN\n" sensor.imgdown.attr({ "opacity": 1 }); } if (sensor.state[2]) { stateString += "LEFT\n" sensor.imgleft.attr({ "opacity": 1 }); } if (sensor.state[3]) { stateString += "RIGHT\n" sensor.imgright.attr({ "opacity": 1 }); } if (sensor.state[4]) { stateString += "CENTER\n" sensor.imgcenter.attr({ "opacity": 1 }); } sensor.stateText = paper.text(state1x, state1y, stateString); if (sensor.portText) sensor.portText.remove(); drawPortText = false; if (sensor.portText) sensor.portText.remove(); if (!context.autoGrading) { var gpios = findSensorDefinition(sensor).gpios; var min = 255; var max = 0; for (var i = 0; i < gpios.length; i++) { if (gpios[i] > max) max = gpios[i]; if (gpios[i] < min) min = gpios[i]; } sensor.portText = paper.text(portx, porty, "D" + min.toString() + "-D" + max.toString() + "?"); sensor.portText.attr({ "font-size": portsize + "px", 'text-anchor': 'start', fill: "blue" }); sensor.portText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; var b = sensor.portText._getBBox(); sensor.portText.translate(0, b.height / 2); $('#stickupstate').text(sensor.state[0] ? "ON" : "OFF"); $('#stickdownstate').text(sensor.state[1] ? "ON" : "OFF"); $('#stickleftstate').text(sensor.state[2] ? "ON" : "OFF"); $('#stickrightstate').text(sensor.state[3] ? "ON" : "OFF"); $('#stickcenterstate').text(sensor.state[4] ? "ON" : "OFF"); sensor.portText.click(function () { window.displayHelper.showPopupDialog(strings.messages.stickPortsDialog); $('#picancel').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#picancel2').click(function () { $('#popupMessage').hide(); window.displayHelper.popupMessageShown = false; }); $('#stickupname').text(sensor.name + ".up"); $('#stickdownname').text(sensor.name + ".down"); $('#stickleftname').text(sensor.name + ".left"); $('#stickrightname').text(sensor.name + ".right"); $('#stickcentername').text(sensor.name + ".center"); $('#stickupport').text("D" + gpios[0]); $('#stickdownport').text("D" + gpios[1]); $('#stickleftport').text("D" + gpios[2]); $('#stickrightport').text("D" + gpios[3]); $('#stickcenterport').text("D" + gpios[4]); $('#stickupstate').text(sensor.state[0] ? "ON" : "OFF"); $('#stickdownstate').text(sensor.state[1] ? "ON" : "OFF"); $('#stickleftstate').text(sensor.state[2] ? "ON" : "OFF"); $('#stickrightstate').text(sensor.state[3] ? "ON" : "OFF"); $('#stickcenterstate').text(sensor.state[4] ? "ON" : "OFF"); }); } function poinInRect(rect, x, y) { if (x > rect.left && x < rect.right && y > rect.top && y < rect.bottom) return true; return false; } function moveRect(rect, x, y) { rect.left += x; rect.right += x; rect.top += y; rect.bottom += y; } sensor.focusrect.node.onmousedown = function(evt) { if (!context.offLineMode) { sensorInConnectedModeError(); return; } var e = evt.target; var dim = e.getBoundingClientRect(); var rectsize = dim.width * .30; var rect = { left: dim.left, right: dim.left + rectsize, top: dim.top, bottom: dim.top + rectsize, } // Up left if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; sensor.state[2] = true; } // Up moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; } // Up right moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[0] = true; sensor.state[3] = true; } // Right moveRect(rect, 0, rectsize); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[3] = true; } // Center moveRect(rect, -rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[4] = true; } // Left moveRect(rect, -rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[2] = true; } // Down left moveRect(rect, 0, rectsize); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; sensor.state[2] = true; } // Down moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; } // Down right moveRect(rect, rectsize, 0); if (poinInRect(rect, evt.clientX, evt.clientY)) { sensor.state[1] = true; sensor.state[3] = true; } drawSensor(sensor); } sensor.focusrect.node.onmouseup = function(evt) { if (!context.offLineMode) { sensorInConnectedModeError(); return; } sensor.state = [false, false, false, false, false]; drawSensor(sensor); } sensor.focusrect.node.ontouchstart = sensor.focusrect.node.onmousedown; sensor.focusrect.node.ontouchend = sensor.focusrect.node.onmouseup; } else if (sensor.type == "cloudstore") { if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('cloudstore.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); drawPortText = false; drawName = false; } else if (sensor.type == "clock") { if (!sensor.img || !sensor.img.paper.canvas) sensor.img = paper.image(getImg('clock.png'), imgx, imgy, imgw, imgh); sensor.img.attr({ "x": imgx, "y": imgy, "width": imgw, "height": imgh, }); sensor.stateText = paper.text(state1x, state1y, context.currentTime.toString() + "ms"); drawPortText = false; drawName = false; } sensor.focusrect.mousedown(function () { if (infos.customSensors && !context.autoGrading) { if (context.removerect) { context.removerect.remove(); } if (!context.runner || !context.runner.isRunning()) { context.removerect = paper.text(portx, imgy, "\uf00d"); // fa-times char removeRect = context.removerect; sensorWithRemoveRect = sensor; context.removerect.attr({ "font-size": "30" + "px", fill: "lightgray", "font-family": "Font Awesome 5 Free", 'text-anchor': 'start', "x": portx, "y": imgy, }); context.removerect.node.style = "-moz-user-select: none; -webkit-user-select: none;"; context.removerect.node.style.fontFamily = '"Font Awesome 5 Free"'; context.removerect.node.style.fontWeight = "bold"; context.removerect.click(function (element) { window.displayHelper.showPopupMessage(strings.messages.removeConfirmation, 'blanket', strings.messages.remove, function () { for (var i = 0; i < infos.quickPiSensors.length; i++) { if (infos.quickPiSensors[i] === sensor) { sensor.removed = true; infos.quickPiSensors.splice(i, 1); } } context.resetDisplay(); }, strings.messages.keep); }); } } }); if (sensor.stateText) { try { sensor.stateText.attr({ "font-size": statesize + "px", 'text-anchor': 'start', 'font-weight': 'bold', fill: "gray" }); var b = sensor.stateText._getBBox(); sensor.stateText.translate(0, b.height/2); sensor.stateText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; } catch (err) { } } if (drawPortText) { if (sensor.portText) sensor.portText.remove(); sensor.portText = paper.text(portx, porty, sensor.port); sensor.portText.attr({ "font-size": portsize + "px", 'text-anchor': 'start', fill: "gray" }); sensor.portText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; var b = sensor.portText._getBBox(); sensor.portText.translate(0,b.height/2); } if (sensor.nameText) { sensor.nameText.remove(); } if (drawName) { if (sensor.name) { sensor.nameText = paper.text(namex, namey, sensor.name ); sensor.nameText.attr({ "font-size": namesize + "px", 'text-anchor': nameanchor, fill: "#7B7B7B" }); sensor.nameText.node.style = "-moz-user-select: none; -webkit-user-select: none;"; } } if (!donotmovefocusrect) { // This needs to be in front of everything sensor.focusrect.toFront(); } } context.registerQuickPiEvent = function (name, newState, setInSensor = true, allowFail = false) { var sensor = findSensorByName(name); if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } if (setInSensor) { sensor.state = newState; drawSensor(sensor); } if (context.autoGrading && context.gradingStatesBySensor != undefined) { var fail = false; var type = "actual"; if(!context.actualStatesBySensor[name]) { context.actualStatesBySensor[name] = []; } var actualStates = context.actualStatesBySensor[name]; var lastRealState = actualStates.length > 0 ? actualStates[actualStates.length-1] : null; if(lastRealState) { if(lastRealState.time == context.currentTime) { lastRealState.state = newState; } else { actualStates.push({time: context.currentTime, state: newState}); } } else { actualStates.push({time: context.currentTime, state: newState}); } drawNewStateChangesSensor(name, newState); context.increaseTime(sensor); } } function drawNewStateChangesSensor(name, newState=null) { var sensor = findSensorByName(name); if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } var sensorDef = findSensorDefinition(sensor); if(sensor.lastDrawnState !== null) { // Get all states between the last drawn time and now var expectedStates = context.getSensorExpectedState(name, sensor.lastDrawnTime, context.currentTime); for(var i = 0; expectedStates && i < expectedStates.length; i++) { // Draw the line up to the next expected state var expectedState = expectedStates[i]; var nextTime = i+1 < expectedStates.length ? expectedStates[i+1].time : context.currentTime; var type = "actual"; // Check the previous state if(!sensorDef.compareState(sensor.lastDrawnState, expectedState.state)) { type = "wrong"; } drawSensorTimeLineState(sensor, sensor.lastDrawnState, sensor.lastDrawnTime, nextTime, type, false, expectedState.state); sensor.lastDrawnTime = nextTime; } } sensor.lastDrawnTime = context.currentTime; if(newState !== null && sensor.lastDrawnState != newState) { // Draw the new state change if(sensor.lastDrawnState === null) { sensor.lastDrawnState = newState; } var type = "actual"; // Check the new state var expectedState = context.getSensorExpectedState(name, context.currentTime); if (expectedState !== null && !sensorDef.compareState(expectedState.state, newState)) { type = "wrong"; } drawSensorTimeLineState(sensor, newState, context.currentTime, context.currentTime, type, false, expectedState && expectedState.state); sensor.lastDrawnState = newState; } } function drawNewStateChanges() { // Draw all sensors if(!context.gradingStatesBySensor) { return; } for(var sensorName in context.gradingStatesBySensor) { drawNewStateChangesSensor(sensorName); } } context.increaseTime = function (sensor) { if (!sensor.lastTimeIncrease) { sensor.lastTimeIncrease = 0; } if (sensor.callsInTimeSlot == undefined) sensor.callsInTimeSlot = 0; if (sensor.lastTimeIncrease == context.currentTime) { sensor.callsInTimeSlot += 1; } else { sensor.lastTimeIncrease = context.currentTime; sensor.callsInTimeSlot = 1; } if (sensor.callsInTimeSlot > getQuickPiOption('increaseTimeAfterCalls')) { context.currentTime += context.tickIncrease; sensor.lastTimeIncrease = context.currentTime; sensor.callsInTimeSlot = 0; } drawCurrentTime(); if(context.autoGrading) { drawNewStateChanges(); } if(context.runner) { // Tell the runner an "action" happened context.runner.signalAction(); } } context.increaseTimeBy = function (time) { var iStates = 0; var newTime = context.currentTime + time; if (context.gradingStatesByTime) { // Advance until current time, ignore everything in the past. while (iStates < context.gradingStatesByTime.length && context.gradingStatesByTime[iStates].time < context.currentTime) iStates++; for (; iStates < context.gradingStatesByTime.length; iStates++) { var sensorState = context.gradingStatesByTime[iStates]; // Until the new time if (sensorState.time >= newTime) break; // Mark all inputs as hit if (sensorState.input) { sensorState.hit = true; // context.currentTime = sensorState.time; context.getSensorState(sensorState.name); } } } if(context.runner) { // Tell the runner an "action" happened context.runner.signalAction(); } context.currentTime = newTime; drawCurrentTime(); if (context.autoGrading) { drawNewStateChanges(); } } context.getSensorExpectedState = function (name, targetTime = null, upToTime = null) { var state = null; if(targetTime === null) { targetTime = context.currentTime; } if (!context.gradingStatesBySensor) { return null; } var actualname = name; var parts = name.split("."); if (parts.length == 2) { actualname = parts[0]; } var sensorStates = context.gradingStatesBySensor[actualname]; if (!sensorStates) return null; // Fail?? var lastState; var startTime = -1; for (var idx = 0; idx < sensorStates.length; idx++) { if (startTime >= 0 && targetTime >= startTime && targetTime < sensorStates[idx].time) { state = lastState; break; } startTime = sensorStates[idx].time; lastState = sensorStates[idx]; } // This is the end state if(state === null && targetTime >= startTime) { state = lastState; } if(state && upToTime !== null) { // If upToTime is given, return an array of states instead var states = [state]; for(var idx2 = idx+1; idx2 < sensorStates.length; idx2++) { if(sensorStates[idx2].time < upToTime) { states.push(sensorStates[idx2]); } else { break; } } return states; } else { return state; } } context.getSensorState = function (name) { var state = null; var sensor = findSensorByName(name); if (!context.display || context.autoGrading) { var stateTime = context.getSensorExpectedState(name); if (stateTime != null) { stateTime.hit = true; state = stateTime.state; if(sensor) { // Redraw from the beginning of this state sensor.lastDrawnTime = Math.min(sensor.lastDrawnTime, stateTime.time); } } else { state = 0; } } if (!sensor) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } if (state == null) { state = sensor.state; } else { sensor.state = state; drawSensor(sensor); } drawNewStateChangesSensor(sensor.name, sensor.state); context.increaseTime(sensor); return state; } // This will advance grading time to the next button release for waitForButton // will return false if the next event wasn't a button press context.advanceToNextRelease = function (sensorType, port) { var retval = false; var iStates = 0; // Advance until current time, ignore everything in the past. while (context.gradingStatesByTime[iStates].time <= context.currentTime) iStates++; for (; iStates < context.gradingStatesByTime.length; iStates++) { sensorState = context.gradingStatesByTime[iStates]; if (sensorState.type == sensorType && sensorState.port == port) { sensorState.hit = true; if (!sensorState.state) { context.currentTime = sensorState.time; retval = true; break; } } else { retval = false; break; } } return retval; }; /***** Functions *****/ /* Here we define each function of the library. Blocks will generally use context.group.blockName as their handler function, hence we generally use this name for the functions. */ context.quickpi.turnLedOn = function (callback) { context.registerQuickPiEvent("led1", true); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnLedOn()", cb); } }; context.quickpi.turnLedOff = function (callback) { context.registerQuickPiEvent("led1", false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnLedOff()", cb); } }; context.quickpi.turnBuzzerOn = function (callback) { context.registerQuickPiEvent("buzzer1", true); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnBuzzerOn()", cb); } }; context.quickpi.turnBuzzerOff = function (callback) { context.registerQuickPiEvent("buzzer1", false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("turnBuzzerOff()", cb); } }; context.quickpi.waitForButton = function (name, callback) { // context.registerQuickPiEvent("button", "D22", "wait", false); var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading) { context.advanceToNextRelease("button", sensor.port); context.waitDelay(callback); } else if (context.offLineMode) { if (sensor) { var cb = context.runner.waitCallback(callback); sensor.onPressed = function () { cb(); } } else { context.waitDelay(callback); } } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("waitForButton(\"" + name + "\")", cb); } }; context.quickpi.isButtonPressed = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("button"); var name = sensor.name; } else { var callback = arg2; var sensor = findSensorByName(arg1, true); var name = arg1; } if (!context.display || context.autoGrading || context.offLineMode) { if (sensor.type == "stick") { var state = context.getSensorState(name); var stickDefinition = findSensorDefinition(sensor); var buttonstate = stickDefinition.getButtonState(name, sensor.state); context.runner.noDelay(callback, buttonstate); } else { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } } else { var cb = context.runner.waitCallback(callback); if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); stickDefinition.getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); var buttonstate = stickDefinition.getButtonState(name, sensor.state); cb(buttonstate); }); } else { findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal != "0"; drawSensor(sensor); cb(returnVal != "0"); }); } } }; context.quickpi.isButtonPressedWithName = context.quickpi.isButtonPressed; context.quickpi.buttonWasPressed = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("buttonWasPressed(\"" + name + "\")", function (returnVal) { cb(returnVal != "0"); }); } }; context.quickpi.setLedState = function (name, state, callback) { var sensor = findSensorByName(name, true); var command = "setLedState(\"" + sensor.port + "\"," + (state ? "True" : "False") + ")"; context.registerQuickPiEvent(name, state ? true : false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.setBuzzerState = function (name, state, callback) { var sensor = findSensorByName(name, true); var command = "setBuzzerState(\"" + name + "\"," + (state ? "True" : "False") + ")"; context.registerQuickPiEvent(name, state ? true : false); if(context.display) { state ? buzzerSound.start(name) : buzzerSound.stop(name); } if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.isBuzzerOn = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("buzzer"); } else { var callback = arg2; var sensor = findSensorByName(arg1, true); } var command = "isBuzzerOn(\"" + sensor.name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState("buzzer1"); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isBuzzerOnWithName = context.quickpi.isBuzzerOn; context.quickpi.setBuzzerNote = function (name, frequency, callback) { var sensor = findSensorByName(name, true); var command = "setBuzzerNote(\"" + name + "\"," + frequency + ")"; context.registerQuickPiEvent(name, frequency); if(context.display && context.offLineMode) { buzzerSound.start(name, frequency); } if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.getBuzzerNote = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getBuzzerNote(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.setLedBrightness = function (name, level, callback) { var sensor = findSensorByName(name, true); if (typeof level == "object") { level = level.valueOf(); } var command = "setLedBrightness(\"" + name + "\"," + level + ")"; context.registerQuickPiEvent(name, level); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.getLedBrightness = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getLedBrightness(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isLedOn = function (arg1, arg2) { if(typeof arg2 == "undefined") { // no arguments var callback = arg1; var sensor = findSensorByType("led"); } else { var callback = arg2; var sensor = findSensorByName(arg1, true); } var command = "getLedState(\"" + sensor.name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.isLedOnWithName = context.quickpi.isLedOn; context.quickpi.toggleLedState = function (name, callback) { var sensor = findSensorByName(name, true); var command = "toggleLedState(\"" + name + "\")"; var state = sensor.state; context.registerQuickPiEvent(name, !state); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { return returnVal != "0"; }); } }; context.quickpi.displayText = function (line1, arg2, arg3) { if(typeof arg3 == "undefined") { // Only one argument var line2 = null; var callback = arg2; } else { var line2 = arg2; var callback = arg3; } var sensor = findSensorByType("screen"); var command = "displayText(\"" + line1 + "\", \"\")"; context.registerQuickPiEvent(sensor.name, { line1: line1, line2: line2 } ); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function (retval) { cb(); }); } }; context.quickpi.displayText2Lines = context.quickpi.displayText; context.quickpi.readTemperature = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.sleep = function (time, callback) { context.increaseTimeBy(time); if (!context.display || context.autoGrading) { context.runner.noDelay(callback); } else { context.runner.waitDelay(callback, null, time); } }; context.quickpi.setServoAngle = function (name, angle, callback) { var sensor = findSensorByName(name, true); if (angle > 180) angle = 180; else if (angle < 0) angle = 0; context.registerQuickPiEvent(name, angle); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var command = "setServoAngle(\"" + name + "\"," + angle + ")"; cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, cb); } }; context.quickpi.getServoAngle = function (name, callback) { var sensor = findSensorByName(name, true); var command = "getServoAngle(\"" + name + "\")"; if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, sensor.state); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand(command, function(returnVal) { returnVal = parseFloat(returnVal) cb(returnVal); }); } }; context.quickpi.readRotaryAngle = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readDistance = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readLightIntensity = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readHumidity = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.waitDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.currentTime = function (callback) { var millis = new Date().getTime(); if (context.autoGrading) { millis = context.currentTime; } context.runner.waitDelay(callback, millis); }; context.quickpi.getTemperature = function(location, callback) { var retVal = 25; context.waitDelay(callback, retVal); }; context.initScreenDrawing = function(sensor) { if (!sensor.screenDrawing) sensor.screenDrawing = new screenDrawing(sensor.canvas); } context.quickpi.drawPoint = function(x, y, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawPoint(x, y); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawPoint(" + x + "," + y + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.isPointSet = function(x, y, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); var value = sensor.screenDrawing.isPointSet(x, y); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback, value); } else { var cb = context.runner.waitCallback(callback); var command = "drawPoint(" + x + "," + y + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawLine = function(x0, y0, x1, y1, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawLine(x0, y0, x1, y1); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawLine(" + x0 + "," + y0 + "," + x1 + "," + y1 + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawRectangle = function(x0, y0, width, height, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawRectangle(x0, y0, width, height); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawRectangle(" + x0 + "," + y0 + "," + width + "," + height + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.drawCircle = function(x0, y0, diameter, callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.drawCircle(x0, y0, diameter, diameter); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "drawCircle(" + x0 + "," + y0 + "," + diameter + ")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.clearScreen = function(callback) { var sensor = findSensorByType("screen"); context.initScreenDrawing(sensor); sensor.screenDrawing.clearScreen(); context.registerQuickPiEvent(sensor.name, sensor.screenDrawing.getStateData()); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "clearScreen()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.updateScreen = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "updateScreen()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.autoUpdate = function(autoupdate, callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "autoUpdate(\"" + (autoupdate ? "True" : "False") + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.fill = function(color, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("screen"); if (sensor && sensor.canvas) { var ctx = sensor.canvas.getContext('2d'); context.noFill = false; if (color) ctx.fillStyle = "black"; else ctx.fillStyle = "white"; } context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "fill(\"" + color + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.noFill = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.noFill = true; context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "NoFill()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.stroke = function(color, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("screen"); if (sensor && sensor.canvas) { var ctx = sensor.canvas.getContext('2d'); context.noStroke = false; if (color) ctx.strokeStyle = "black"; else ctx.strokeStyle = "white"; } context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "stroke(\"" + color + "\")"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.noStroke = function(callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.noStroke = true; context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); var command = "noStroke()"; context.quickPiConnection.sendCommand(command, function () { cb(); }); } }; context.quickpi.readAcceleration = function(axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("accelerometer"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; var state = context.getSensorState(sensor.name); context.waitDelay(callback, state[index]); } else { var cb = context.runner.waitCallback(callback); var command = "readAcceleration(\"" + axis + "\")"; context.quickPiConnection.sendCommand(command, function (returnVal) { cb(returnVal); }); } }; context.quickpi.computeRotation = function(rotationType, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("accelerometer"); var zsign = 1; var result = 0; if (sensor.state[2] < 0) zsign = -1; if (rotationType == "pitch") { result = 180 * Math.atan2 (sensor.state[0], zsign * Math.sqrt(sensor.state[1]*sensor.state[1] + sensor.state[2]*sensor.state[2]))/Math.PI; } else if (rotationType == "roll") { result = 180 * Math.atan2 (sensor.state[1], zsign * Math.sqrt(sensor.state[0]*sensor.state[0] + sensor.state[2]*sensor.state[2]))/Math.PI; } result = Math.round(result); context.waitDelay(callback, result); } else { var cb = context.runner.waitCallback(callback); var command = "computeRotation(\"" + rotationType + "\")"; context.quickPiConnection.sendCommand(command, function (returnVal) { cb(returnVal); }); } }; context.quickpi.readSoundLevel = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.readMagneticForce = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("magnetometer"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; context.waitDelay(callback, sensor.state[index]); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("magnetometer", "i2c"); findSensorDefinition(sensor).getLiveState(axis, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }); } }; context.quickpi.computeCompassHeading = function (callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("magnetometer"); var heading = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; heading = Math.round(heading); context.runner.noDelay(callback, heading); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("magnetometer", "i2c"); context.quickPiConnection.sendCommand("readMagnetometerLSM303C()", function(returnVal) { sensor.state = returnVal; drawSensor(sensor); returnVal = Math.atan2(sensor.state[0],sensor.state[1])*(180/Math.PI) + 180; returnVal = Math.floor(returnVal); cb(returnVal); }, true); } }; context.quickpi.readInfraredState = function (name, callback) { var sensor = findSensorByName(name, true); if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState(name); context.runner.noDelay(callback, state ? true : false); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).getLiveState(sensor, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); cb(returnVal); }); } }; context.quickpi.setInfraredState = function (name, state, callback) { var sensor = findSensorByName(name, true); context.registerQuickPiEvent(name, state ? true : false); if (!context.display || context.autoGrading || context.offLineMode) { context.waitDelay(callback); } else { var cb = context.runner.waitCallback(callback); findSensorDefinition(sensor).setLiveState(sensor, state, cb); } }; //// Gyroscope context.quickpi.readAngularVelocity = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var sensor = findSensorByType("gyroscope"); var index = 0; if (axis == "x") index = 0; else if (axis == "y") index = 1; else if (axis == "z") index = 2; context.waitDelay(callback, sensor.state[index]); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("gyroscope", "i2c"); findSensorDefinition(sensor).getLiveState(axis, function(returnVal) { sensor.state = returnVal; drawSensor(sensor); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }); } }; context.quickpi.setGyroZeroAngle = function (callback) { if (!context.display || context.autoGrading || context.offLineMode) { context.runner.noDelay(callback); } else { var cb = context.runner.waitCallback(callback); context.quickPiConnection.sendCommand("setGyroZeroAngle()", function(returnVal) { cb(); }, true); } }; context.quickpi.computeRotationGyro = function (axis, callback) { if (!context.display || context.autoGrading || context.offLineMode) { var state = context.getSensorState("gyroscope", "i2c"); context.runner.noDelay(callback, 0); } else { var cb = context.runner.waitCallback(callback); var sensor = context.findSensor("gyroscope", "i2c"); context.quickPiConnection.sendCommand("computeRotationGyro()", function(returnVal) { //sensor.state = returnVal; //drawSensor(sensor); var returnVal = JSON.parse(returnVal); if (axis == "x") returnVal = returnVal[0]; else if (axis == "y") returnVal = returnVal[1]; else if (axis == "z") returnVal = returnVal[2]; cb(returnVal); }, true); } }; context.quickpi.connectToCloudStore = function (prefix, password, callback) { var sensor = findSensorByType("cloudstore"); if (!context.display || context.autoGrading) { sensor.quickStore = new quickPiStore(true); } else { sensor.quickStore = QuickStore(prefix, password); } context.runner.noDelay(callback, 0); }; context.quickpi.writeToCloudStore = function (identifier, key, value, callback) { var sensor = findSensorByType("cloudstore"); if (!sensor.quickStore || !sensor.quickStore.connected) { context.success = false; throw("Cloud store not connected"); } if (!context.display || context.autoGrading) { sensor.quickStore.write(identifier, key, value); context.registerQuickPiEvent(sensor.name, sensor.quickStore.getStateData()); context.runner.noDelay(callback); } else { var cb = context.runner.waitCallback(callback); sensor.quickStore.write(identifier, key, value, function(data) { if (!data || !data.success) { if (data && data.message) context.failImmediately = "cloudstore: " + data.message; else context.failImmediately = "Error trying to communicate with cloud store"; } cb(); }); } }; context.quickpi.readFromCloudStore = function (identifier, key, callback) { var sensor = findSensorByType("cloudstore"); if (!sensor.quickStore) { if (!context.display || context.autoGrading) { sensor.quickStore = new quickPiStore(); } else { sensor.quickStore = QuickStore(); } } if (!context.display || context.autoGrading) { var state = context.getSensorState(sensor.name); var value = ""; if (state.hasOwnProperty(key)) { value = state[key]; } else { context.success = false; throw("Key not found"); } sensor.quickStore.write(identifier, key, value); context.registerQuickPiEvent(sensor.name, sensor.quickStore.getStateData()); context.runner.noDelay(callback, value); } else { var cb = context.runner.waitCallback(callback); sensor.quickStore.read(identifier, key, function(data) { var value = ""; if (data && data.success) { value = JSON.parse(data.value); } else { if (data && data.message) context.failImmediately = "cloudstore: " + data.message; else context.failImmediately = "Error trying to communicate with cloud store"; } cb(value); }); } }; /***** Blocks definitions *****/ /* Here we define all blocks/functions of the library. Structure is as follows: { group: [{ name: "someName", // category: "categoryName", // yieldsValue: optional true: Makes a block with return value rather than simple command // params: optional array of parameter types. The value 'null' denotes /any/ type. For specific types, see the Blockly documentation ([1,2]) // handler: optional handler function. Otherwise the function context.group.blockName will be used // blocklyJson: optional Blockly JSON objects // blocklyInit: optional function for Blockly.Blocks[name].init // if not defined, it will be defined to call 'this.jsonInit(blocklyJson); // blocklyXml: optional Blockly xml string // codeGenerators: optional object: // { Python: function that generates Python code // JavaScript: function that generates JS code // } }] } [1] https://developers.google.com/blockly/guides/create-custom-blocks/define-blocks [2] https://developers.google.com/blockly/guides/create-custom-blocks/type-checks */ function getSensorNames(sensorType) { return function () { var ports = []; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == sensorType) { ports.push([sensor.name, sensor.name]); } } if (sensorType == "button") { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == "stick") { var stickDefinition = findSensorDefinition(sensor); for (var iStick = 0; iStick < stickDefinition.gpiosNames.length; iStick++) { var name = sensor.name + "." + stickDefinition.gpiosNames[iStick]; ports.push([name, name]); } } } } if (ports.length == 0) { ports.push(["none", "none"]); } return ports; } } function findSensorByName(name, error=false) { if (isNaN(name.substring(0, 1)) && !isNaN(name.substring(1))) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.port.toUpperCase() == name.toUpperCase()) { return sensor; } } } else { var firstname = name.split(".")[0]; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.name.toUpperCase() == firstname.toUpperCase()) { return sensor; } } } if (error) { context.success = false; throw (strings.messages.sensorNotFound.format(name)); } return null; } function findSensorByType(type) { var firstname = name.split(".")[0]; for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.type == type) { return sensor; } } return null; } function findSensorByPort(port) { for (var i = 0; i < infos.quickPiSensors.length; i++) { var sensor = infos.quickPiSensors[i]; if (sensor.port == port) { return sensor; } } return null; } function getSensorSuggestedName(type, suggested) { if (suggested) { if (!findSensorByName(suggested)) return suggested; } var i = 0; var newName; do { i++; newName = type + i.toString(); } while (findSensorByName(newName)); return newName; } context.customBlocks = { // Define our blocks for our namespace "template" quickpi: { // Categories are reflected in the Blockly menu sensors: [ { name: "currentTime", yieldsValue: true }, { name: "waitForButton", params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") } ] } }, { name: "isButtonPressed", yieldsValue: true }, { name: "isButtonPressedWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") }, ] } }, { name: "buttonWasPressed", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("button") } ] } }, { name: "readTemperature", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("temperature") } ] } }, { name: "readRotaryAngle", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("potentiometer") } ] } }, { name: "readDistance", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("range") } ] } }, { name: "readLightIntensity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("light") } ] } }, { name: "readHumidity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("humidity") } ] } }, { name: "readAcceleration", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "computeRotation", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["pitch", "pitch"], ["roll", "roll"]] } ] } }, { name: "readSoundLevel", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("sound") } ] } }, { name: "readMagneticForce", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "computeCompassHeading", yieldsValue: true }, { name: "readInfraredState", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("irrecv") } ] } }, { name: "readAngularVelocity", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, { name: "setGyroZeroAngle" }, { name: "computeRotationGyro", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": [["x", "x"], ["y", "y"], ["z", "z"] ] } ] } }, ], actions: [ { name: "turnLedOn" }, { name: "turnLedOff" }, { name: "turnBuzzerOn" }, { name: "turnBuzzerOff" }, { name: "setLedState", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "setBuzzerState", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "setBuzzerNote", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='setBuzzerNote'>" + "<value name='PARAM_1'><shadow type='math_number'><field name='NUM'>200</field></shadow></value>" + "</block>" }, { name: "getBuzzerNote", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, ] } }, { name: "setLedBrightness", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='setLedBrightness'>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "getLedBrightness", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "isLedOn", yieldsValue: true }, { name: "isLedOnWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "isBuzzerOn", yieldsValue: true }, { name: "isBuzzerOnWithName", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("buzzer") }, ] } }, { name: "toggleLedState", params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("led") }, ] } }, { name: "setServoAngle", params: ["String", "Number"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("servo") }, { "type": "input_value", "name": "PARAM_1" }, ] }, blocklyXml: "<block type='setServoAngle'>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "getServoAngle", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("servo") }, ] } }, { name: "setInfraredState", params: ["String", "Number"], blocklyJson: { "args0": [ {"type": "field_dropdown", "name": "PARAM_0", "options": getSensorNames("irtrans")}, { "type": "field_dropdown", "name": "PARAM_1", "options": [["ON", "1"], ["OFF", "0"]] }, ] } }, { name: "sleep", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "value": 0 }, ] } , blocklyXml: "<block type='sleep'>" + "<value name='PARAM_0'><shadow type='math_number'><field name='NUM'>1000</field></shadow></value>" + "</block>" }, ], display: [ { name: "displayText", params: ["String", "String"], variants: [[null], [null, null]], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "text": "" }, ] }, blocklyXml: "<block type='displayText'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'>Bonjour</field> </shadow></value>" + "</block>" }, { name: "displayText2Lines", params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", "text": "" }, { "type": "input_value", "name": "PARAM_1", "text": "" }, ] }, blocklyXml: "<block type='displayText2Lines'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'>Bonjour</field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "drawPoint", params: ["Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='drawPoint'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "isPointSet", yieldsValue: true, params: ["Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, ] }, blocklyXml: "<block type='isPointSet'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawLine", params: ["Number", "Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, { "type": "input_value", "name": "PARAM_3"}, ] }, blocklyXml: "<block type='drawLine'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_3'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawRectangle", params: ["Number", "Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, { "type": "input_value", "name": "PARAM_3"}, ] }, blocklyXml: "<block type='drawRectangle'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_3'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "drawCircle", params: ["Number", "Number", "Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, { "type": "input_value", "name": "PARAM_1"}, { "type": "input_value", "name": "PARAM_2"}, ] }, blocklyXml: "<block type='drawCircle'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_1'><shadow type='math_number'></shadow></value>" + "<value name='PARAM_2'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "clearScreen" }, { name: "updateScreen" }, { name: "autoUpdate", params: ["Boolean"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ], }, blocklyXml: "<block type='autoUpdate'>" + "<value name='PARAM_0'><shadow type='logic_boolean'></shadow></value>" + "</block>" }, { name: "fill", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ] }, blocklyXml: "<block type='fill'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "noFill" }, { name: "stroke", params: ["Number"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0"}, ] }, blocklyXml: "<block type='stroke'>" + "<value name='PARAM_0'><shadow type='math_number'></shadow></value>" + "</block>" }, { name: "noStroke" }, ], internet: [ { name: "getTemperature", yieldsValue: true, params: ["String"], blocklyJson: { "args0": [ { "type": "field_input", "name": "PARAM_0", text: "Paris, France"}, ] }, }, { name: "connectToCloudStore", params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, ] }, blocklyXml: "<block type='connectToCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "writeToCloudStore", params: ["String", "String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, { "type": "input_value", "name": "PARAM_2", text: ""}, ] }, blocklyXml: "<block type='writeToCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_2'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, { name: "readFromCloudStore", yieldsValue: true, params: ["String", "String"], blocklyJson: { "args0": [ { "type": "input_value", "name": "PARAM_0", text: ""}, { "type": "input_value", "name": "PARAM_1", text: ""}, ] }, blocklyXml: "<block type='readFromCloudStore'>" + "<value name='PARAM_0'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "<value name='PARAM_1'><shadow type='text'><field name='TEXT'></field> </shadow></value>" + "</block>" }, ] } // We can add multiple namespaces by adding other keys to customBlocks. }; // Color indexes of block categories (as a hue in the range 0–420) context.provideBlocklyColours = function () { return { categories: { actions: 0, sensors: 100, internet: 200, display: 300, } }; }; // Constants available in Python context.customConstants = { quickpi: [ ] }; // Don't forget to return our newly created context! return context; } // Register the library; change "template" by the name of your library in lowercase if (window.quickAlgoLibraries) { quickAlgoLibraries.register('quickpi', getContext); } else { if (!window.quickAlgoLibrariesList) { window.quickAlgoLibrariesList = []; } window.quickAlgoLibrariesList.push(['quickpi', getContext]); } var sensorWithSlider = null; var removeRect = null; var sensorWithRemoveRect = null; window.addEventListener('click', function (e) { var keep = false; var keepremove = false; e = e || window.event; var target = e.target || e.srcElement; if (sensorWithRemoveRect && sensorWithRemoveRect.focusrect && target == sensorWithRemoveRect.focusrect.node) keepremove = true; if (removeRect && !keepremove) { removeRect.remove(); removeRect = null; } if (sensorWithSlider && sensorWithSlider.focusrect && target == sensorWithSlider.focusrect.node) keep = true; if (sensorWithSlider && sensorWithSlider.sliders) { for (var i = 0; i < sensorWithSlider.sliders.length; i++) { sensorWithSlider.sliders[i].slider.forEach(function (element) { if (target == element.node || target.parentNode == element.node) { keep = true; return false; } }); } } if (!keep) { hideSlider(sensorWithSlider); } }, false);//<-- we'll get to the false in a minute function hideSlider(sensor) { if (!sensor) return; if (sensor.sliders) { for (var i = 0; i < sensor.sliders.length; i++) { sensor.sliders[i].slider.remove(); } sensor.sliders = []; } if (sensor.focusrect && sensor.focusrect.paper && sensor.focusrect.paper.canvas) sensor.focusrect.toFront(); };
quickPi: Check that both objects are drawing data in screen comparison
pemFioi/quickpi/blocklyQuickPi_lib.js
quickPi: Check that both objects are drawing data in screen comparison
<ide><path>emFioi/quickpi/blocklyQuickPi_lib.js <ide> // If only one is null they are different <ide> if ((state1 == null && state2) || <ide> (state1 && state2 == null)) <add> return false; <add> <add> if (state1.isDrawingData != <add> state2.isDrawingData) <ide> return false; <ide> <ide> if (state1 && state1.isDrawingData) {
Java
mit
be2e439db5e330c9f60b60d3561dfdb9b9d8c39f
0
ryanseys/bomberman
import java.net.*; import org.json.JSONArray; import org.json.JSONObject; public class Client { MessageQueue toSendMsgs; MessageQueue receivedMsgs; ClientReceiver cr; ClientSender cs; DatagramSocket dsocket; String board; // state of the game private int playerid; boolean isGameOn = false; public Client(String IPAddress, int port) throws SocketException, UnknownHostException { this.toSendMsgs = new MessageQueue(); this.receivedMsgs = new MessageQueue(); this.board = ""; dsocket = new DatagramSocket(); // sender and receiver must use the same socket! cs = new ClientSender(toSendMsgs, InetAddress.getByName(IPAddress), port, dsocket); cr = new ClientReceiver(receivedMsgs, dsocket); // start the threads for receiving and sending cs.start(); cr.start(); } public void startGame() { isGameOn = true; JSONObject startMsg = new JSONObject(); startMsg.put("command", "button"); startMsg.put("button", "start"); startMsg.put("pid", playerid); send(startMsg.toString()); } public void endGame() { isGameOn = false; } /** * Send a message to the server * @param msg String message to send */ public void send(String msg) { System.out.println("Sending message: " + msg); synchronized(toSendMsgs) { toSendMsgs.add(msg); toSendMsgs.notify(); } } /** * Receive a message from the server * @return String message received */ public String receive() { String s; synchronized(receivedMsgs) { while(receivedMsgs.isEmpty()) { try { receivedMsgs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } s = receivedMsgs.pop(); } System.out.println("Received message: " + s); return s; } /** * Connect to the server as a player. Get a player id. */ public void connect() { JSONObject connMsg = new JSONObject(); connMsg.put("command", "join"); connMsg.put("type", "player"); send(connMsg.toString()); } /** * Set the state of the game * @param s String of the game state */ public void setState(String s) { JSONObject resp = new JSONObject(s); JSONObject game = null; if(resp.getString("type").equals("game_over")) { endGame(); } else if(resp.getString("type").equals("player_join") && resp.getString("resp").equals("Success")) { playerid = resp.getInt("pid"); } if(resp.keySet().contains("game")) { game = resp.getJSONObject("game"); this.board = stringifyBoard(game.getJSONArray("board")); } } public String stringifyBoard(JSONArray board) { String result = ""; for(int col = 0; col < board.length(); col++) { for(int row = 0; row < board.length(); row++) { result += "[" + board.getJSONArray(row).getInt(col) + "]"; } result += "\n"; } return result; } String[] directions = {"up", "down", "right", "left"}; public void move(Direction d) { JSONObject moveMsg = new JSONObject(); moveMsg.put("command", "move"); moveMsg.put("direction", directions[d.ordinal()]); moveMsg.put("pid", playerid); send(moveMsg.toString()); } /** * Get the state of the game * @return String representation of the game state */ public String getGameBoard() { return this.board; } public int getPlayerID() { return playerid; } public boolean isGameOn() { return isGameOn; } }
code/Client/src/Client.java
import java.net.*; import org.json.JSONArray; import org.json.JSONObject; public class Client { MessageQueue toSendMsgs; MessageQueue receivedMsgs; ClientReceiver cr; ClientSender cs; DatagramSocket dsocket; String board; // state of the game private int playerid; boolean isGameOn = false; public Client(String IPAddress, int port) throws SocketException, UnknownHostException { this.toSendMsgs = new MessageQueue(); this.receivedMsgs = new MessageQueue(); this.board = "<< initial state >>"; dsocket = new DatagramSocket(); // sender and receiver must use the same socket! cs = new ClientSender(toSendMsgs, InetAddress.getByName(IPAddress), port, dsocket); cr = new ClientReceiver(receivedMsgs, dsocket); // start the threads for receiving and sending cs.start(); cr.start(); } public void startGame() { isGameOn = true; send("{ command: \"button\", pid: " + playerid + ", button:\"start\"}"); } public void endGame() { isGameOn = false; } /** * Send a message to the server * @param msg String message to send */ public void send(String msg) { System.out.println("Sending message: " + msg); synchronized(toSendMsgs) { toSendMsgs.add(msg); toSendMsgs.notify(); } } /** * Receive a message from the server * @return String message received */ public String receive() { String s; synchronized(receivedMsgs) { while(receivedMsgs.isEmpty()) { try { receivedMsgs.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } s = receivedMsgs.pop(); } System.out.println("Received message: " + s); return s; } public void connect() { send("{\"command\":\"join\", \"type\":\"player\"}"); } /** * Set the state of the game * @param s String of the game state */ public void setState(String s) { String new_board = ""; JSONObject resp = new JSONObject(s); JSONObject game = null; if(resp.getString("type").equals("game_over")) { endGame(); } else if(resp.getString("type").equals("player_join") && resp.getString("resp").equals("Success")) { playerid = resp.getInt("pid"); } if(resp.keySet().contains("game")) { game = resp.getJSONObject("game"); JSONArray boardArray = game.getJSONArray("board"); for (int i = 0; i < boardArray.length(); i++) { for(int j = 0; j < boardArray.length(); j++) { new_board += ("[" + boardArray.getJSONArray(j).getInt(i) + "]") ; } new_board += "\n"; } } this.board = new_board; } String[] directions = {"up", "down", "right", "left"}; public void move(Direction d) { send("{ command: \"move\", direction: \"" + directions[d.ordinal()] + "\", pid: " + playerid + "}"); } /** * Get the state of the game * @return String representation of the game state */ public String getGameBoard() { return this.board; } public int getPlayerID() { return playerid; } public boolean isGameOn() { return isGameOn; } }
StringifyBoard for easy board generation
code/Client/src/Client.java
StringifyBoard for easy board generation
<ide><path>ode/Client/src/Client.java <ide> public Client(String IPAddress, int port) throws SocketException, UnknownHostException { <ide> this.toSendMsgs = new MessageQueue(); <ide> this.receivedMsgs = new MessageQueue(); <del> this.board = "<< initial state >>"; <add> this.board = ""; <ide> dsocket = new DatagramSocket(); <ide> <ide> // sender and receiver must use the same socket! <ide> <ide> public void startGame() { <ide> isGameOn = true; <del> send("{ command: \"button\", pid: " + playerid + ", button:\"start\"}"); <add> JSONObject startMsg = new JSONObject(); <add> startMsg.put("command", "button"); <add> startMsg.put("button", "start"); <add> startMsg.put("pid", playerid); <add> send(startMsg.toString()); <ide> } <ide> <ide> public void endGame() { <ide> return s; <ide> } <ide> <add> /** <add> * Connect to the server as a player. Get a player id. <add> */ <ide> public void connect() { <del> send("{\"command\":\"join\", \"type\":\"player\"}"); <add> JSONObject connMsg = new JSONObject(); <add> connMsg.put("command", "join"); <add> connMsg.put("type", "player"); <add> send(connMsg.toString()); <ide> } <ide> <ide> /** <ide> * @param s String of the game state <ide> */ <ide> public void setState(String s) { <del> String new_board = ""; <ide> JSONObject resp = new JSONObject(s); <ide> <ide> JSONObject game = null; <ide> <ide> if(resp.keySet().contains("game")) { <ide> game = resp.getJSONObject("game"); <del> <del> JSONArray boardArray = game.getJSONArray("board"); <del> <del> for (int i = 0; i < boardArray.length(); i++) { <del> for(int j = 0; j < boardArray.length(); j++) { <del> new_board += ("[" + boardArray.getJSONArray(j).getInt(i) + "]") ; <del> } <del> new_board += "\n"; <add> this.board = stringifyBoard(game.getJSONArray("board")); <add> } <add> } <add> <add> public String stringifyBoard(JSONArray board) { <add> String result = ""; <add> for(int col = 0; col < board.length(); col++) { <add> for(int row = 0; row < board.length(); row++) { <add> result += "[" + board.getJSONArray(row).getInt(col) + "]"; <ide> } <add> result += "\n"; <ide> } <del> this.board = new_board; <add> return result; <ide> } <ide> <ide> String[] directions = {"up", "down", "right", "left"}; <ide> <ide> public void move(Direction d) { <del> send("{ command: \"move\", direction: \"" + directions[d.ordinal()] + "\", pid: " + playerid + "}"); <add> JSONObject moveMsg = new JSONObject(); <add> moveMsg.put("command", "move"); <add> moveMsg.put("direction", directions[d.ordinal()]); <add> moveMsg.put("pid", playerid); <add> send(moveMsg.toString()); <ide> } <ide> <ide> /** <ide> public boolean isGameOn() { <ide> return isGameOn; <ide> } <del> <ide> }
JavaScript
mit
41922281a48564febb1af26d34740a2926b2137f
0
TheTommyTwitch/pokedex-promise-v2,PokeAPI/pokedex-promise-v2,PokeAPI/pokedex-promise-v2
const pMap = require('p-map'); const { endpoints } = require('./endpoints.js') const { rootEndpoints } = require('./rootEndpoints.js') const { getJSON } = require('./getter.js') const { values } = require('./default.js') const configurator = require('./configurator.js') const { handleError } = require('./error.js') class Pokedex { constructor(config) { configurator.setPokedexConfiguration(config); // add to Pokedex.prototype all our endpoint functions endpoints.forEach(endpoint => { this[endpoint[0]] = async (input, cb) => { try { const mapper = async name => { const queryRes = await getJSON(`${values.protocol}${values.hostName}${values.versionPath}${endpoint[1]}/${name}/`) return queryRes; }; if (input) { // if the user has submitted a Name or an Id, return the Json promise if (typeof input === 'number' || typeof input === 'string') { return getJSON(`${values.protocol}${values.hostName}${values.versionPath}${endpoint[1]}/${input}/`, cb); } // if the user has submitted an Array // return a new promise which will resolve when all getJSON calls are ended else if (typeof input === 'object') { // fetch data asynchronously to be faster const mappedResults = await pMap(input, mapper, {concurrency: 4}) if (cb) { cb(mappedResults); } return mappedResults; } } } catch (error) { handleError(error, cb) } } }); rootEndpoints.forEach(rootEndpoint => { this[rootEndpoint[0]] = async (config, cb) => { try { configurator.setRootEndpointConfiguration(config); return getJSON(`${values.protocol}${values.hostName}${values.versionPath}${rootEndpoint[1]}?limit=${values.limit}&offset=${values.offset}`, cb) } catch (error) { handleError(error, cb) } } }); } async resource(path, cb) { let result try { if (typeof path === 'string') { result = getJSON(path) } else if (typeof path === 'object') { result = Promise.all(path.map(p => getJSON(p))); } else { throw 'String or Array required' } if (cb) { cb(result) } return result } catch (error) { throw new Error(error) } } }; module.exports = Pokedex
src/index.js
const pMap = require('p-map'); const { endpoints } = require('./endpoints.js') const { rootEndpoints } = require('./rootEndpoints.js') const { getJSON } = require('./getter.js') const { values } = require('./default.js') const configurator = require('./configurator.js') const { handleError } = require('./error.js') class Pokedex { constructor(config) { configurator.setPokedexConfiguration(config); // add to Pokedex.prototype all our endpoint functions endpoints.forEach(endpoint => { this[endpoint[0]] = async (input, cb) => { try { const mapper = async name => { const queryRes = await getJSON(`${values.protocol}${values.hostName}${values.versionPath}${endpoint[1]}/${name}/`) return queryRes; }; if (input) { // if the user has submitted a Name or an Id, return the Json promise if (typeof input === 'number' || typeof input === 'string') { return getJSON(`${values.protocol}${values.hostName}${values.versionPath}${endpoint[1]}/${input}/`, cb); } // if the user has submitted an Array // return a new promise which will resolve when all getJSON calls are ended else if (typeof input === 'object') { // fetch data asynchronously to be faster const mappedResults = await pMap(input, mapper, {concurrency: 4}) if (cb) { cb(mappedResults); } return mappedResults; } } } catch (error) { handleError(error, cb) } } }); rootEndpoints.forEach(rootEndpoint => { this[rootEndpoint[0]] = async (config, cb) => { try { configurator.setRootEndpointConfiguration(config); return getJSON(`${values.protocol}${values.hostName}${values.versionPath}${rootEndpoint[1]}?limit=${values.limit}&offset=${values.offset}`, cb) } catch (error) { handleError(error, cb) } } }); } async resource(path) { try{ if (typeof path === 'string') { return getJSON(path) } else if (typeof path === 'object') { return Promise.all(path.map(p => getJSON(p))); } else { throw 'String or Array required' } } catch (error) { throw new Error(error) } } }; module.exports = Pokedex
feat: add callback to .resource()
src/index.js
feat: add callback to .resource()
<ide><path>rc/index.js <ide> }); <ide> } <ide> <del> async resource(path) { <del> try{ <add> async resource(path, cb) { <add> let result <add> try { <ide> if (typeof path === 'string') { <del> return getJSON(path) <add> result = getJSON(path) <ide> } else if (typeof path === 'object') { <del> return Promise.all(path.map(p => getJSON(p))); <add> result = Promise.all(path.map(p => getJSON(p))); <ide> } else { <ide> throw 'String or Array required' <ide> } <add> if (cb) { <add> cb(result) <add> } <add> return result <ide> } catch (error) { <ide> throw new Error(error) <ide> }
JavaScript
mit
7c2d8432780b246e7de804aad8a5a41d3630d09f
0
Turfjs/turf-centroid
var each = require('turf-meta').coordEach; var point = require('turf-point'); /** * Takes features and calculates the centroid using the arithmetic mean of all vertices. * This lessens the effect of small islands and artifacts when calculating * the centroid of a set of polygons. * * @module turf/centroid * @category measurement * @param {(Feature<(Point|LineString|Polygon)>|FeatureCollection<(Point|LineString|Polygon)>)} features input features * @return {Feature<Point>} the centroid of the input features * @example * var poly = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [105.818939,21.004714], * [105.818939,21.061754], * [105.890007,21.061754], * [105.890007,21.004714], * [105.818939,21.004714] * ]] * } * }; * * var centroidPt = turf.centroid(poly); * * var result = { * "type": "FeatureCollection", * "features": [poly, centroidPt] * }; * * //=result */ module.exports = function(features){ var xSum = 0, ySum = 0, len = 0; each(features, function(coord) { xSum += coord[0]; ySum += coord[1]; len++; }, true); return point([xSum / len, ySum / len]); };
index.js
var each = require('turf-meta').coordEach; var point = require('turf-point'); /** * Takes a {@link Feature} or {@link FeatureCollection} of any type and calculates the centroid using the arithmetic mean of all vertices. * This lessens the effect of small islands and artifacts when calculating * the centroid of a set of polygons. * * @module turf/centroid * @category measurement * @param {GeoJSON} features a {@link Feature} or FeatureCollection of any type * @return {Point} a Point feature at the centroid of the input feature(s) * @example * var poly = { * "type": "Feature", * "properties": {}, * "geometry": { * "type": "Polygon", * "coordinates": [[ * [105.818939,21.004714], * [105.818939,21.061754], * [105.890007,21.061754], * [105.890007,21.004714], * [105.818939,21.004714] * ]] * } * }; * * var centroidPt = turf.centroid(poly); * * var result = { * "type": "FeatureCollection", * "features": [poly, centroidPt] * }; * * //=result */ module.exports = function(features){ var xSum = 0, ySum = 0, len = 0; each(features, function(coord) { xSum += coord[0]; ySum += coord[1]; len++; }, true); return point([xSum / len, ySum / len]); };
Switch doc to closure compiler templating
index.js
Switch doc to closure compiler templating
<ide><path>ndex.js <ide> var point = require('turf-point'); <ide> <ide> /** <del> * Takes a {@link Feature} or {@link FeatureCollection} of any type and calculates the centroid using the arithmetic mean of all vertices. <add> * Takes features and calculates the centroid using the arithmetic mean of all vertices. <ide> * This lessens the effect of small islands and artifacts when calculating <ide> * the centroid of a set of polygons. <ide> * <ide> * @module turf/centroid <ide> * @category measurement <del> * @param {GeoJSON} features a {@link Feature} or FeatureCollection of any type <del> * @return {Point} a Point feature at the centroid of the input feature(s) <add> * @param {(Feature<(Point|LineString|Polygon)>|FeatureCollection<(Point|LineString|Polygon)>)} features input features <add> * @return {Feature<Point>} the centroid of the input features <ide> * @example <ide> * var poly = { <ide> * "type": "Feature",
JavaScript
mit
ae12ba339a423b6f68b92bab8a9f73c78fd793df
0
hishamabdelrahman/osgjs,jmirabel/osgjs,kkuunnddaannkk/osgjs,jtorresfabra/osgjs,cedricpinson/osgjs,gideonmay/osgjs,cedricpinson/osgjs,gideonmay/osgjs,kkuunnddaannkk/osgjs,hishamabdelrahman/osgjs,jtorresfabra/osgjs,gideonmay/osgjs,hishamabdelrahman/osgjs,jmirabel/osgjs,jmirabel/osgjs,cedricpinson/osgjs,kkuunnddaannkk/osgjs,jtorresfabra/osgjs
/** -*- compile-command: "jslint-cli ShaderParameterVisitor.js" -*- * Authors: * Cedric Pinson <[email protected]> */ osgUtil.ParameterVisitor = function() { osg.NodeVisitor.call(this); this.targetHTML = document.body; var ArraySlider = function() { this.params = {}; }; ArraySlider.prototype = { setTargetHTML: function(target) { this.parent = target; }, selectParamFromName: function(name) { var keys = Object.keys(this.params); if (keys.length === 1) { return this.params[ keys[0] ]; } for (var i = 0; i < keys.length; i++) { var p = this.params[ keys[i] ]; var matchs = p.match; if (matchs === undefined) { matchs = [ keys[i] ]; } for (var m = 0; m < matchs.length; m++) { if (name.search(matchs[m]) !== -1) { return p; } } } return this.params.default; }, getValue: function(name) { if (window.localStorage) { var value = window.localStorage.getItem(name); return value; } return null; }, setValue: function(name, value) { if (window.localStorage) { window.localStorage.setItem(name, value); } }, addToDom: function(content) { var mydiv = document.createElement('div'); mydiv.innerHTML = content; this.parent.appendChild(mydiv); }, createSlider: function(min, max, step, value, name, cbname) { var input = '<div>NAME [ MIN - MAX ] <input type="range" min="MIN" max="MAX" value="VALUE" step="STEP" onchange="ONCHANGE" /><span id="UPDATE"></span></div>'; var onchange = cbname + '(this.value)'; input = input.replace(/MIN/g, min); input = input.replace(/MAX/g, (max+step)); input = input.replace('STEP', step); input = input.replace('VALUE', value); input = input.replace(/NAME/g, name); input = input.replace(/UPDATE/g, cbname); input = input.replace('ONCHANGE', onchange); return input; }, createUniformFunction: function(name, index, uniform, cbnameIndex) { self = this; return (function() { var cname = name; var cindex = index; var cuniform = uniform; var id = cbnameIndex; var func = function(value) { cuniform.get()[cindex] = value; cuniform.dirty(); osg.log(cname + ' value ' + value); document.getElementById(cbnameIndex).innerHTML = Number(value).toFixed(4); self.setValue(id, value); // store the value to localstorage }; return func; })(); }, createFunction: function(name, index, object, field, cbnameIndex) { self = this; return (function() { var cname = name; var cindex = index; var cfield = field; var id = cbnameIndex; var obj = object; var func = function(value) { if (typeof(value) === 'string') { value = parseFloat(value); } if (typeof(object[cfield]) === 'number') { obj[cfield] = value; } else { obj[cfield][index] = value; } osg.log(cname + ' value ' + value); document.getElementById(cbnameIndex).innerHTML = Number(value).toFixed(4); self.setValue(id, value); // store the value to localstorage }; return func; })(); }, getCallbackName: function(name, prgId) { return 'change_'+prgId+"_"+name; }, createInternalSliderUniform: function(name, dim, uniformFunc, prgId, originalUniform) { var params = this.selectParamFromName(name); var uvalue = params.value(); var uniform = originalUniform; if (uniform === undefined) { uniform = uniformFunc(uvalue, name); } var cbname = this.getCallbackName(name, prgId); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value = uvalue[i]; // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else if (originalUniform && originalUniform.get()[i]) { // read value from original uniform value = originalUniform.get()[i]; } var dom = this.createSlider(params.min, params.max, params.step, value, nameIndex, cbnameIndex); this.addToDom(dom); window[cbnameIndex] = this.createUniformFunction(nameIndex, i, uniform, cbnameIndex); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } this.uniform = uniform; return uniform; }, createInternalSlider: function(name, dim, id, object, field) { var params = this.selectParamFromName(name); var uvalue = params.value(); var cbname = this.getCallbackName(name, id); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value = uvalue[i]; // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else { if (typeof object[field] === 'number') { value = object[field]; } else { value = object[field][i]; } } var dom = this.createSlider(params.min, params.max, params.step, value, nameIndex, cbnameIndex); this.addToDom(dom); window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } } }; var Vec4Slider = function() { ArraySlider.call(this); this.params['color'] = { 'min': 0, 'max': 1.0, 'step':0.01, 'value': function() { return [0.5, 0.5, 0.5, 1.0]; }, 'match' : ['color', 'diffuse', 'specular', 'ambient', 'emission'] }; this.params['default'] = this.params['color']; }; Vec4Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 4, osg.Uniform.createFloat4, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 4, id, object, field); } }); var Vec3Slider = function() { ArraySlider.call(this); this.params['position'] = { 'min': -50, 'max': 50.0, 'step':0.1, 'value': function() { return [0.0, 0.0, 0.0]; }, 'match' : ['position'] }; this.params['normalized'] = { 'min': 0, 'max': 1.0, 'step':0.01, 'value': function() { return [1.0, 0.0, 0.0]; }, 'match' : ['normal', 'direction'] }; this.params['default'] = this.params['position']; }; Vec3Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 3, osg.Uniform.createFloat3, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 3, id, object, field); } }); var Vec2Slider = function() { ArraySlider.call(this); this.params['uv'] = { 'min': -1, 'max': 1.0, 'step':0.01, 'value': function() { return [0.0, 0.0]; }, 'match' : ['texcoord, uv'] }; this.params['default'] = this.params['uv']; }; Vec2Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 2, osg.Uniform.createFloat2, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 2, id, object, field); } }); var FloatSlider = function() { ArraySlider.call(this); this.params['default'] = { 'min': -1, 'max': 1.0, 'step':0.01, 'value': function() { return [0.0]; }, 'match' : [] }; }; FloatSlider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 1, osg.Uniform.createFloat1, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 1, id, object, field); } }); this.types = {}; this.types.vec4 = new Vec4Slider(); this.types.vec3 = new Vec3Slider(); this.types.vec2 = new Vec2Slider(); this.types.float = new FloatSlider(); this.setTargetHTML(document.body); }; osgUtil.ParameterVisitor.prototype = osg.objectInehrit(osg.NodeVisitor.prototype, { setTargetHTML: function(html) { this.targetHTML = html; var keys = Object.keys(this.types); for (var i = 0, l = keys.length; i < l; i++) { var k = keys[i]; this.types[k].setTargetHTML(this.targetHTML); } }, getUniformList: function(str, map) { var r = str.match(/uniform\s+\w+\s+\w+/g); var list = map; if (r !== null) { for (var i = 0, l = r.length; i < l; i++) { var result = r[i].match(/uniform\s+(\w+)\s+(\w+)/); var name = result[2]; var uniform = { 'type': result[1], 'name': name}; list[name] = uniform; } } return list; }, getUniformFromStateSet: function(stateSet, uniformMap) { var maps = stateSet.getUniformList(); if (!maps) { return; } var keys = Object.keys(uniformMap); for (var i = 0, l = keys.length; i < l; i++) { var k = keys[i]; // get the first one found in the tree if (maps[k] !== undefined && uniformMap[k].uniform === undefined) { uniformMap[k].uniform = maps[k].object; } } }, findExistingUniform: function(node, uniformMap) { var BackVisitor = function() { osg.NodeVisitor.call(this, osg.NodeVisitor.TRAVERSE_PARENTS); }; BackVisitor.prototype = osg.objectInehrit(osg.NodeVisitor.prototype, { setUniformMap: function(map) { this.uniformMap = map; }, apply: function(node) { var stateSet = node.getStateSet(); var getUniformFromStateSet = osgUtil.ShaderParameterVisitor.prototype.getUniformFromStateSet; if (stateSet) { getUniformFromStateSet(stateSet, this.uniformMap); } this.traverse(node); } }); var visitor = new BackVisitor(); visitor.setUniformMap(uniformMap); node.accept(visitor); }, applyProgram: function(node, stateset) { var program = stateset.getAttribute('Program'); var programName = program.getName(); var string = program.getVertexShader().getText(); var uniformMap = {}; this.getUniformList(program.getVertexShader().getText(), uniformMap); this.getUniformList(program.getFragmentShader().getText(), uniformMap); var keys = Object.keys(uniformMap); if (programName === undefined) { var hashCode = function(str) { var hash = 0; var char = 0; if (str.length == 0) return hash; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } if (hash < 0) { hash = -hash; } return hash; } var str = keys.join(''); programName = hashCode(str).toString(); } this.findExistingUniform(node, uniformMap); var addedSlider = false; for (var i = 0; i < keys.length; i++) { var k = keys[i]; var entry = uniformMap[k]; var type = entry.type; var name = entry.name; if (this.types[type] !== undefined) { var uniform = this.types[type].createSliderUniform(name, programName, entry.uniform); if (entry.uniform === undefined && uniform) { stateset.addUniform(uniform); } addedSlider = true; } } // add a separator if (addedSlider) { var mydiv = document.createElement('div'); mydiv.innerHTML = "<p> </p>"; this.targetHTML.appendChild(mydiv); } osg.log(uniformMap); }, applyLight: function(node, stateset) { var attribute = stateset.getAttribute('Light0'); this.types.float.params['spotCutoff'] = { min: 0, max: 180, step: 1, value: function() { return 180;} }; this.types.float.params['spotCutoffEnd'] = this.types.float.params['spotCutoff']; this.types.vec4.params['position'] = { min: -50, max: 50, step: 1, value: function() { return [0,0,1,0];} }; this.types.vec4.createSliderObject("ambient", attribute.getTypeMember()+"_ambient", attribute, '_ambient'); this.types.vec4.createSliderObject("diffuse", attribute.getTypeMember()+"_diffuse", attribute, '_diffuse'); this.types.vec4.createSliderObject("specular", attribute.getTypeMember()+"_specular", attribute, '_specular'); this.types.vec3.createSliderObject("direction", attribute.getTypeMember()+"_direction", attribute, '_direction'); this.types.vec4.createSliderObject("position", attribute.getTypeMember()+"_position", attribute, '_position'); this.types.float.createSliderObject("spotCutoff", attribute.getTypeMember()+"_spotCutoff", attribute, '_spotCutoff'); this.types.float.createSliderObject("spotCutoffEnd", attribute.getTypeMember()+"_spotCutoffEnd", attribute, '_spotCutoffEnd'); // add a separator var mydiv = document.createElement('div'); mydiv.innerHTML = "<p> </p>"; this.targetHTML.appendChild(mydiv); }, applyStateSet: function(node, stateset) { if (stateset.getAttribute('Program') !== undefined) { this.applyProgram(node, stateset); } else if (stateset.getAttribute('Light0') !== undefined) { this.applyLight(node, stateset); } }, apply: function(node) { var element = this.targetHTML; if (element === undefined || element === null) { return; } var st = node.getStateSet(); if (st !== undefined) { this.applyStateSet(node, st); } this.traverse(node); } }); osgUtil.ParameterVisitor.SliderParameter = function() {}; osgUtil.ParameterVisitor.SliderParameter.prototype = { addToDom: function(parent, content) { var mydiv = document.createElement('div'); mydiv.innerHTML = content; parent.appendChild(mydiv); }, createInternalSlider: function(name, dim, id, params, object, field) { var cbname = this.getCallbackName(name, id); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value; if (typeof(params.value) === 'number') { value = params.value; } else { value = params.value[i]; } // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else { if (typeof object[field] === 'number') { value = object[field]; } else { value = object[field][i]; } } var dom = this.createDomSlider(value, params.min, params.max, params.step, nameIndex, cbnameIndex); this.addToDom(params.dom, dom); window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex, params.onchange); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } }, createDomSlider: function(value, min, max, step, name, cbname) { var input = '<div>NAME [ MIN - MAX ] <input type="range" min="MIN" max="MAX" value="VALUE" step="STEP" onchange="ONCHANGE" /><span id="UPDATE"></span></div>'; var onchange = cbname + '(this.value)'; input = input.replace(/MIN/g, min); input = input.replace(/MAX/g, (max+1e-3)); input = input.replace('STEP', step); input = input.replace('VALUE', value); input = input.replace(/NAME/g, name); input = input.replace(/UPDATE/g, cbname); input = input.replace('ONCHANGE', onchange); return input; }, getCallbackName: function(name, prgId) { return 'change_'+prgId+"_"+name; }, createFunction: function(name, index, object, field, callbackName, userOnChange) { self = this; return (function() { var cname = name; var cindex = index; var cfield = field; var obj = object; var func = function(value) { if (typeof(value) === 'string') { value = parseFloat(value); } if (typeof(object[cfield]) === 'number') { obj[cfield] = value; } else { obj[cfield][index] = value; } osg.log(cname + ' value ' + value); document.getElementById(callbackName).innerHTML = Number(value).toFixed(4); self.setValue(callbackName, value); if (userOnChange) { userOnChange(obj[cfield]); } // store the value to localstorage }; return func; })(); }, getValue: function(name) { if (window.localStorage) { var value = window.localStorage.getItem(name); return value; } return null; }, setValue: function(name, value) { if (window.localStorage) { window.localStorage.setItem(name, value); } }, }; osgUtil.ParameterVisitor.createSlider = function (label, uniqNameId, object, field, value, min, max, step, dom, onchange) { var scope = osgUtil.ParameterVisitor; if (scope.sliders === undefined) { scope.sliders = new scope.SliderParameter(); } var params = { value: value, min: min, max: max, step: step, onchange: onchange, dom: dom }; if (typeof(object[field]) === 'number') { return scope.sliders.createInternalSlider(label, 1, uniqNameId, params, object, field); } else { return scope.sliders.createInternalSlider(label, object[field].length, uniqNameId, params, object, field); } }; osgUtil.ShaderParameterVisitor = osgUtil.ParameterVisitor;
js/osgUtil/ShaderParameterVisitor.js
/** -*- compile-command: "jslint-cli ShaderParameterVisitor.js" -*- * Authors: * Cedric Pinson <[email protected]> */ osgUtil.ParameterVisitor = function() { osg.NodeVisitor.call(this); this.targetHTML = document.body; var ArraySlider = function() { this.params = {}; }; ArraySlider.prototype = { setTargetHTML: function(target) { this.parent = target; }, selectParamFromName: function(name) { var keys = Object.keys(this.params); if (keys.length === 1) { return this.params[ keys[0] ]; } for (var i = 0; i < keys.length; i++) { var p = this.params[ keys[i] ]; var matchs = p.match; if (matchs === undefined) { matchs = [ keys[i] ]; } for (var m = 0; m < matchs.length; m++) { if (name.search(matchs[m]) !== -1) { return p; } } } return this.params.default; }, getValue: function(name) { if (window.localStorage) { var value = window.localStorage.getItem(name); return value; } return null; }, setValue: function(name, value) { if (window.localStorage) { window.localStorage.setItem(name, value); } }, addToDom: function(content) { var mydiv = document.createElement('div'); mydiv.innerHTML = content; this.parent.appendChild(mydiv); }, createSlider: function(min, max, step, value, name, cbname) { var input = '<div>NAME [ MIN - MAX ] <input type="range" min="MIN" max="MAX" value="VALUE" step="STEP" onchange="ONCHANGE" /><span id="UPDATE"></span></div>'; var onchange = cbname + '(this.value)'; input = input.replace(/MIN/g, min); input = input.replace(/MAX/g, (max+step)); input = input.replace('STEP', step); input = input.replace('VALUE', value); input = input.replace(/NAME/g, name); input = input.replace(/UPDATE/g, cbname); input = input.replace('ONCHANGE', onchange); return input; }, createUniformFunction: function(name, index, uniform, cbnameIndex) { self = this; return (function() { var cname = name; var cindex = index; var cuniform = uniform; var id = cbnameIndex; var func = function(value) { cuniform.get()[cindex] = value; cuniform.dirty(); osg.log(cname + ' value ' + value); document.getElementById(cbnameIndex).innerHTML = Number(value).toFixed(4); self.setValue(id, value); // store the value to localstorage }; return func; })(); }, createFunction: function(name, index, object, field, cbnameIndex) { self = this; return (function() { var cname = name; var cindex = index; var cfield = field; var id = cbnameIndex; var obj = object; var func = function(value) { if (typeof(value) === 'string') { value = parseFloat(value); } if (typeof(object[cfield]) === 'number') { obj[cfield] = value; } else { obj[cfield][index] = value; } osg.log(cname + ' value ' + value); document.getElementById(cbnameIndex).innerHTML = Number(value).toFixed(4); self.setValue(id, value); // store the value to localstorage }; return func; })(); }, getCallbackName: function(name, prgId) { return 'change_'+prgId+"_"+name; }, createInternalSliderUniform: function(name, dim, uniformFunc, prgId, originalUniform) { var params = this.selectParamFromName(name); var uvalue = params.value(); var uniform = originalUniform; if (uniform === undefined) { uniform = uniformFunc(uvalue, name); } var cbname = this.getCallbackName(name, prgId); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value = uvalue[i]; // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else if (originalUniform && originalUniform.get()[i]) { // read value from original uniform value = originalUniform.get()[i]; } var dom = this.createSlider(params.min, params.max, params.step, value, nameIndex, cbnameIndex); this.addToDom(dom); window[cbnameIndex] = this.createUniformFunction(nameIndex, i, uniform, cbnameIndex); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } this.uniform = uniform; return uniform; }, createInternalSlider: function(name, dim, id, object, field) { var params = this.selectParamFromName(name); var uvalue = params.value(); var cbname = this.getCallbackName(name, id); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value = uvalue[i]; // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else { if (typeof object[field] === 'number') { value = object[field]; } else { value = object[field][i]; } } var dom = this.createSlider(params.min, params.max, params.step, value, nameIndex, cbnameIndex); this.addToDom(dom); window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } } }; var Vec4Slider = function() { ArraySlider.call(this); this.params['color'] = { 'min': 0, 'max': 1.0, 'step':0.01, 'value': function() { return [0.5, 0.5, 0.5, 1.0]; }, 'match' : ['color', 'diffuse', 'specular', 'ambient', 'emission'] }; this.params['default'] = this.params['color']; }; Vec4Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 4, osg.Uniform.createFloat4, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 4, id, object, field); } }); var Vec3Slider = function() { ArraySlider.call(this); this.params['position'] = { 'min': -50, 'max': 50.0, 'step':0.1, 'value': function() { return [0.0, 0.0, 0.0]; }, 'match' : ['position'] }; this.params['normalized'] = { 'min': 0, 'max': 1.0, 'step':0.01, 'value': function() { return [1.0, 0.0, 0.0]; }, 'match' : ['normal', 'direction'] }; this.params['default'] = this.params['position']; }; Vec3Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 3, osg.Uniform.createFloat3, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 3, id, object, field); } }); var Vec2Slider = function() { ArraySlider.call(this); this.params['uv'] = { 'min': -1, 'max': 1.0, 'step':0.01, 'value': function() { return [0.0, 0.0]; }, 'match' : ['texcoord, uv'] }; this.params['default'] = this.params['uv']; }; Vec2Slider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 2, osg.Uniform.createFloat2, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 2, id, object, field); } }); var FloatSlider = function() { ArraySlider.call(this); this.params['default'] = { 'min': -1, 'max': 1.0, 'step':0.01, 'value': function() { return [0.0]; }, 'match' : [] }; }; FloatSlider.prototype = osg.objectInehrit(ArraySlider.prototype, { createSliderUniform: function(name, prgId, uniform) { return this.createInternalSliderUniform(name, 1, osg.Uniform.createFloat1, prgId, uniform); }, createSliderObject: function(name, id, object, field) { return this.createInternalSlider(name, 1, id, object, field); } }); this.types = {}; this.types.vec4 = new Vec4Slider(); this.types.vec3 = new Vec3Slider(); this.types.vec2 = new Vec2Slider(); this.types.float = new FloatSlider(); this.setTargetHTML(document.body); }; osgUtil.ParameterVisitor.prototype = osg.objectInehrit(osg.NodeVisitor.prototype, { setTargetHTML: function(html) { this.targetHTML = html; var keys = Object.keys(this.types); for (var i = 0, l = keys.length; i < l; i++) { var k = keys[i]; this.types[k].setTargetHTML(this.targetHTML); } }, getUniformList: function(str, map) { var r = str.match(/uniform\s+\w+\s+\w+/g); var list = map; if (r !== null) { for (var i = 0, l = r.length; i < l; i++) { var result = r[i].match(/uniform\s+(\w+)\s+(\w+)/); var name = result[2]; var uniform = { 'type': result[1], 'name': name}; list[name] = uniform; } } return list; }, getUniformFromStateSet: function(stateSet, uniformMap) { var maps = stateSet.getUniformList(); if (!maps) { return; } var keys = Object.keys(uniformMap); for (var i = 0, l = keys.length; i < l; i++) { var k = keys[i]; // get the first one found in the tree if (maps[k] !== undefined && uniformMap[k].uniform === undefined) { uniformMap[k].uniform = maps[k].object; } } }, findExistingUniform: function(node, uniformMap) { var BackVisitor = function() { osg.NodeVisitor.call(this, osg.NodeVisitor.TRAVERSE_PARENTS); }; BackVisitor.prototype = osg.objectInehrit(osg.NodeVisitor.prototype, { setUniformMap: function(map) { this.uniformMap = map; }, apply: function(node) { var stateSet = node.getStateSet(); var getUniformFromStateSet = osgUtil.ShaderParameterVisitor.prototype.getUniformFromStateSet; if (stateSet) { getUniformFromStateSet(stateSet, this.uniformMap); } this.traverse(node); } }); var visitor = new BackVisitor(); visitor.setUniformMap(uniformMap); node.accept(visitor); }, applyProgram: function(node, stateset) { var program = stateset.getAttribute('Program'); var programName = program.getName(); var string = program.getVertexShader().getText(); var uniformMap = {}; this.getUniformList(program.getVertexShader().getText(), uniformMap); this.getUniformList(program.getFragmentShader().getText(), uniformMap); var keys = Object.keys(uniformMap); if (programName === undefined) { var hashCode = function(str) { var hash = 0; var char = 0; if (str.length == 0) return hash; for (i = 0; i < str.length; i++) { char = str.charCodeAt(i); hash = ((hash<<5)-hash)+char; hash = hash & hash; // Convert to 32bit integer } if (hash < 0) { hash = -hash; } return hash; } var str = keys.join(''); programName = hashCode(str).toString(); } this.findExistingUniform(node, uniformMap); var addedSlider = false; for (var i = 0; i < keys.length; i++) { var k = keys[i]; var entry = uniformMap[k]; var type = entry.type; var name = entry.name; if (this.types[type] !== undefined) { var uniform = this.types[type].createSliderUniform(name, programName, entry.uniform); if (entry.uniform === undefined && uniform) { stateset.addUniform(uniform); } addedSlider = true; } } // add a separator if (addedSlider) { var mydiv = document.createElement('div'); mydiv.innerHTML = "<p> </p>"; this.targetHTML.appendChild(mydiv); } osg.log(uniformMap); }, applyLight: function(node, stateset) { var attribute = stateset.getAttribute('Light0'); this.types.float.params['spotCutoff'] = { min: 0, max: 180, step: 1, value: function() { return 180;} }; this.types.float.params['spotCutoffEnd'] = this.types.float.params['spotCutoff']; this.types.vec4.params['position'] = { min: -50, max: 50, step: 1, value: function() { return [0,0,1,0];} }; this.types.vec4.createSliderObject("ambient", attribute.getTypeMember()+"_ambient", attribute, '_ambient'); this.types.vec4.createSliderObject("diffuse", attribute.getTypeMember()+"_diffuse", attribute, '_diffuse'); this.types.vec4.createSliderObject("specular", attribute.getTypeMember()+"_specular", attribute, '_specular'); this.types.vec3.createSliderObject("direction", attribute.getTypeMember()+"_direction", attribute, '_direction'); this.types.vec4.createSliderObject("position", attribute.getTypeMember()+"_position", attribute, '_position'); this.types.float.createSliderObject("spotCutoff", attribute.getTypeMember()+"_spotCutoff", attribute, '_spotCutoff'); this.types.float.createSliderObject("spotCutoffEnd", attribute.getTypeMember()+"_spotCutoffEnd", attribute, '_spotCutoffEnd'); // add a separator var mydiv = document.createElement('div'); mydiv.innerHTML = "<p> </p>"; this.targetHTML.appendChild(mydiv); }, applyStateSet: function(node, stateset) { if (stateset.getAttribute('Program') !== undefined) { this.applyProgram(node, stateset); } else if (stateset.getAttribute('Light0') !== undefined) { this.applyLight(node, stateset); } }, apply: function(node) { var st = node.getStateSet(); if (st !== undefined) { this.applyStateSet(node, st); } this.traverse(node); } }); osgUtil.ParameterVisitor.SliderParameter = function() {}; osgUtil.ParameterVisitor.SliderParameter.prototype = { addToDom: function(parent, content) { var mydiv = document.createElement('div'); mydiv.innerHTML = content; parent.appendChild(mydiv); }, createInternalSlider: function(name, dim, id, params, object, field) { var cbname = this.getCallbackName(name, id); for (var i = 0; i < dim; i++) { var istring = i.toString(); var nameIndex = name + istring; var cbnameIndex = cbname+istring; // default value var value; if (typeof(params.value) === 'number') { value = params.value; } else { value = params.value[i]; } // read local storage value if it exist var readValue = this.getValue(cbnameIndex); if (readValue !== null) { value = readValue; } else { if (typeof object[field] === 'number') { value = object[field]; } else { value = object[field][i]; } } var dom = this.createDomSlider(value, params.min, params.max, params.step, nameIndex, cbnameIndex); this.addToDom(params.dom, dom); window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex); osg.log(nameIndex + " " + value); window[cbnameIndex](value); } }, createDomSlider: function(value, min, max, step, name, cbname) { var input = '<div>NAME [ MIN - MAX ] <input type="range" min="MIN" max="MAX" value="VALUE" step="STEP" onchange="ONCHANGE" /><span id="UPDATE"></span></div>'; var onchange = cbname + '(this.value)'; input = input.replace(/MIN/g, min); input = input.replace(/MAX/g, (max+1e-3)); input = input.replace('STEP', step); input = input.replace('VALUE', value); input = input.replace(/NAME/g, name); input = input.replace(/UPDATE/g, cbname); input = input.replace('ONCHANGE', onchange); return input; }, getCallbackName: function(name, prgId) { return 'change_'+prgId+"_"+name; }, createFunction: function(name, index, object, field, callbackName) { self = this; return (function() { var cname = name; var cindex = index; var cfield = field; var obj = object; var func = function(value) { if (typeof(value) === 'string') { value = parseFloat(value); } if (typeof(object[cfield]) === 'number') { obj[cfield] = value; } else { obj[cfield][index] = value; } osg.log(cname + ' value ' + value); document.getElementById(callbackName).innerHTML = Number(value).toFixed(4); self.setValue(callbackName, value); // store the value to localstorage }; return func; })(); }, getValue: function(name) { if (window.localStorage) { var value = window.localStorage.getItem(name); return value; } return null; }, setValue: function(name, value) { if (window.localStorage) { window.localStorage.setItem(name, value); } }, }; osgUtil.ParameterVisitor.createSlider = function (label, uniqNameId, object, field, value, min, max, step, dom) { var scope = osgUtil.ParameterVisitor; if (scope.sliders === undefined) { scope.sliders = new scope.SliderParameter(); } var params = { value: value, min: min, max: max, step: step, dom: dom }; if (typeof(object[field]) === 'number') { return scope.sliders.createInternalSlider(label, 1, uniqNameId, params, object, field); } else { return scope.sliders.createInternalSlider(label, object[field].length, uniqNameId, params, object, field); } }; osgUtil.ShaderParameterVisitor = osgUtil.ParameterVisitor;
Add onChange callback
js/osgUtil/ShaderParameterVisitor.js
Add onChange callback
<ide><path>s/osgUtil/ShaderParameterVisitor.js <ide> }, <ide> <ide> apply: function(node) { <add> var element = this.targetHTML; <add> if (element === undefined || element === null) { <add> return; <add> } <add> <ide> var st = node.getStateSet(); <ide> if (st !== undefined) { <ide> this.applyStateSet(node, st); <ide> <ide> var dom = this.createDomSlider(value, params.min, params.max, params.step, nameIndex, cbnameIndex); <ide> this.addToDom(params.dom, dom); <del> window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex); <add> window[cbnameIndex] = this.createFunction(nameIndex, i, object, field, cbnameIndex, params.onchange); <ide> osg.log(nameIndex + " " + value); <ide> window[cbnameIndex](value); <ide> } <ide> return 'change_'+prgId+"_"+name; <ide> }, <ide> <del> createFunction: function(name, index, object, field, callbackName) { <add> createFunction: function(name, index, object, field, callbackName, userOnChange) { <ide> self = this; <ide> return (function() { <ide> var cname = name; <ide> osg.log(cname + ' value ' + value); <ide> document.getElementById(callbackName).innerHTML = Number(value).toFixed(4); <ide> self.setValue(callbackName, value); <add> if (userOnChange) { <add> userOnChange(obj[cfield]); <add> } <ide> // store the value to localstorage <ide> }; <ide> return func; <ide> }, <ide> }; <ide> <del>osgUtil.ParameterVisitor.createSlider = function (label, uniqNameId, object, field, value, min, max, step, dom) { <add>osgUtil.ParameterVisitor.createSlider = function (label, uniqNameId, object, field, value, min, max, step, dom, onchange) { <ide> var scope = osgUtil.ParameterVisitor; <ide> if (scope.sliders === undefined) { <ide> scope.sliders = new scope.SliderParameter(); <ide> min: min, <ide> max: max, <ide> step: step, <add> onchange: onchange, <ide> dom: dom }; <ide> <ide> if (typeof(object[field]) === 'number') { <ide> } <ide> }; <ide> <add> <ide> osgUtil.ShaderParameterVisitor = osgUtil.ParameterVisitor;
Java
bsd-2-clause
6dc70f62c1f0c5c089cc0680053389798a8f7da0
0
ONatalia/Masterarbeit,ONatalia/Masterarbeit,ONatalia/Masterarbeit,ONatalia/Masterarbeit
package org.cocolab.inpro.apps; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.cocolab.inpro.apps.util.TextCommandLineParser; import org.cocolab.inpro.incremental.PushBuffer; import org.cocolab.inpro.incremental.listener.HypothesisChangeListener; import org.cocolab.inpro.incremental.processor.CurrentASRHypothesis; import org.cocolab.inpro.incremental.processor.FloorManager; import org.cocolab.inpro.incremental.unit.AtomicWordIU; import org.cocolab.inpro.incremental.unit.EditMessage; import org.cocolab.inpro.incremental.unit.EditType; import org.cocolab.inpro.incremental.unit.IUList; import edu.cmu.sphinx.util.props.ConfigurationManager; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Component; import edu.cmu.sphinx.util.props.S4ComponentList; /** * simple interactive (and non-interactive) ASR simulator for the inpro project * * Words are added to the IU list (and sent off to CurrentASRHypothesis' * HypothesisChangeListeners) as you type, revoked when you delete them * and committed when you press enter (or click on the "commit" button). * * Floor management (EoT-detection) is simulated by pressing enter twice * in a row (effectively: pressing enter when the textfield is empty) or * by clicking the "EoT" button. * * Notice: double-pressing enter and clicking on "EoT" is actually different, * because in the former case, all words will have been committed, while * in the latter case some words may be left uncommitted. Our system should * be able to cope with both cases (at least with EoT slightly preceding * ASR-commit), and this is a way for us to test this. * * * TODO: implement revocation of words when running non-interactively. * specification more or less follows Verbmobil: an exclamation mark * is followed by the number of words to be revoked. !2 would revoke the * two words preceding the exclamation mark. * * @author timo * */ @SuppressWarnings("serial") public class SimpleText extends JPanel implements ActionListener { private static final Logger logger = Logger.getLogger(SimpleText.class); @S4Component(type = CurrentASRHypothesis.class) public final static String PROP_CURRENT_HYPOTHESIS = "currentASRHypothesis"; @S4ComponentList(type = HypothesisChangeListener.class) public final static String PROP_HYP_CHANGE_LISTENERS = CurrentASRHypothesis.PROP_HYP_CHANGE_LISTENERS; @S4Component(type = FloorManager.class) public final static String PROP_FLOOR_MANAGER = "floorManager"; @S4Component(type = FloorManager.Listener.class) public final static String PROP_FLOOR_MANAGER_LISTENERS = FloorManager.PROP_STATE_LISTENERS; IUDocument iuDocument; List<FloorManager.Listener> floorListeners; JTextField textField; SimpleText(List<FloorManager.Listener> floorListeners) { iuDocument = new IUDocument(); iuDocument.listeners = new ArrayList<PushBuffer>(); textField = new JTextField(40); textField.setFont(new Font("Dialog", Font.BOLD, 24)); textField.setDocument(iuDocument); textField.addActionListener(this); JButton commitButton = new JButton("Commit"); commitButton.addActionListener(this); add(textField); add(commitButton); this.floorListeners = floorListeners; // clicking this button is actually not identical to // double pressing enter in the text field JButton floorButton = new JButton("EoT"); floorButton.addActionListener(this); add(floorButton); // add(new JLabel("you can only edit at the right")); } public void notifyFloorAvailable() { for (FloorManager.Listener l : floorListeners) { l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); } } public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("Commit")) { notifyFloorAvailable(); } else { iuDocument.commit(); // hitting enter on empty lines results in an EoT-marker if (iuDocument.getLength() == 0) { notifyFloorAvailable(); } } textField.requestFocusInWindow(); } public static void createAndShowGUI(List<PushBuffer> hypListeners, List<FloorManager.Listener> floorListeners) { JFrame frame = new JFrame("SimpleText"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SimpleText contentPane = new SimpleText(floorListeners); contentPane.iuDocument.setListeners(hypListeners); contentPane.setOpaque(true); frame.setContentPane(contentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void runFromReader(Reader reader, List<PushBuffer> hypListeners, List<FloorManager.Listener> floorListeners) throws IOException { IUDocument iuDocument = new IUDocument(); iuDocument.setListeners(hypListeners); BufferedReader bReader = new BufferedReader(reader); String line; while ((line = bReader.readLine()) != null) { try { iuDocument.insertString(0, line, null); } catch (BadLocationException e) { logger.error("wow, this should really not happen (I thought I could always add a string at position 0)"); e.printStackTrace(); } iuDocument.commit(); // empty lines results in an EoT-marker if ("".equals(line)) { for (FloorManager.Listener l : floorListeners) { l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); } } } } public static void main(String[] args) throws IOException { BasicConfigurator.configure(); TextCommandLineParser clp = new TextCommandLineParser(args); if (!clp.parsedSuccessfully()) { System.exit(1); } // abort on error ConfigurationManager cm = new ConfigurationManager(clp.getConfigURL()); PropertySheet ps = cm.getPropertySheet(PROP_CURRENT_HYPOTHESIS); @SuppressWarnings("unchecked") final List<PushBuffer> hypListeners = (List<PushBuffer>) ps.getComponentList(PROP_HYP_CHANGE_LISTENERS); ps = cm.getPropertySheet(PROP_FLOOR_MANAGER); @SuppressWarnings("unchecked") final List<FloorManager.Listener> floorListeners = (List<FloorManager.Listener>) ps.getComponentList(PROP_FLOOR_MANAGER_LISTENERS); if (clp.hasTextFromReader()) { // if we already know the text: logger.info("running in non-interactive mode"); // run non-interactively runFromReader(clp.getReader(), hypListeners, floorListeners); System.exit(0); // } else { // run interactively logger.info("running in interactive mode"); SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(hypListeners, floorListeners); } }); } } /** * An IUDocument stores a list of current IUs, * edits since the last update and * the string for the (partial) next IU * * It handles HypothesisChangeListeners * which are notified, when the IUList changes (or is committed) * (and can be set via setListeners()) * * IUs are committed and the list is reset after an explicit call to commit() * (when used as the document of a JTextField, this can be done by * calling commit() from a JTextField's ActionListener) * * @see javax.swing.text.Document Document * @author timo */ static class IUDocument extends PlainDocument { List<PushBuffer> listeners; IUList<AtomicWordIU> wordIUs = new IUList<AtomicWordIU>(); List<EditMessage<AtomicWordIU>> edits = new ArrayList<EditMessage<AtomicWordIU>>(); String currentWord = ""; int currentFrame = 0; public void setListeners(List<PushBuffer> listeners) { this.listeners = listeners; } public void notifyListeners() { if (edits.size() > 0) { //logger.debug("notifying about" + edits); currentFrame += 100; for (PushBuffer listener : listeners) { if (listener instanceof HypothesisChangeListener) { ((HypothesisChangeListener) listener).setCurrentFrame(currentFrame); } // notify if (wordIUs != null && edits != null) listener.hypChange(wordIUs, edits); } edits = new ArrayList<EditMessage<AtomicWordIU>>(); } } private void addCurrentWord() { //logger.debug("adding " + currentWord); AtomicWordIU sll = (wordIUs.size() > 0) ? wordIUs.get(wordIUs.size() - 1) : AtomicWordIU.FIRST_ATOMIC_WORD_IU; AtomicWordIU iu = new AtomicWordIU(currentWord, sll); EditMessage<AtomicWordIU> edit = new EditMessage<AtomicWordIU>(EditType.ADD, iu); edits.add(edit); wordIUs.add(iu); //logger.debug(edit.toString()); currentWord = ""; } public void commit() { // handle last word (if there is one) if (!"".equals(currentWord)) { addCurrentWord(); } // add commit messages for (AtomicWordIU iu : wordIUs) { edits.add(new EditMessage<AtomicWordIU>(EditType.COMMIT, iu)); iu.update(EditType.COMMIT); } // notify notifyListeners(); // reset try { super.remove(0,getLength()); } catch (BadLocationException e) { e.printStackTrace(); } wordIUs = new IUList<AtomicWordIU>(); edits = new ArrayList<EditMessage<AtomicWordIU>>(); } /* Overrides over PlainDocument: */ /** * only allow removal at the right end * and correctly handle removals beyond the current word */ @Override public void remove(int offs, int len) throws BadLocationException { if (offs + len == getLength()) { // only allow removal at the right end super.remove(offs, len); // if (getText(getLength() - 1, 1).) while (len > currentWord.length()) { // +1 because the whitespace has to be accounted for len -= currentWord.length(); len--; // to account for whitespace AtomicWordIU iu = wordIUs.remove(wordIUs.size() - 1); EditMessage<AtomicWordIU> edit = new EditMessage<AtomicWordIU>(EditType.REVOKE, iu); edits.add(edit); //logger.debug(edit.toString()); currentWord = iu.getWord(); } currentWord = currentWord.substring(0, currentWord.length() - len); //logger.debug("now it's " + currentWord); notifyListeners(); } } /** * only allow insertion at the right end */ @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (offs == getLength()) { /* character by character: * check validity (for example, we don't like multiple whitespace) * add them to the current word, if it's not whitespace * add current word to IUList if it is whitespace * finally, add the (possibly changed characters) to the superclass's data handling */ char[] chars = str.toCharArray(); String outStr = ""; for (char ch : chars) { if (Character.isWhitespace(ch)) { if (currentWord.length() > 0) { addCurrentWord(); outStr += " "; // add a space, no matter what whitespace was added } else { //logger.debug("ignoring additional whitespace"); } } else { //logger.debug("appending to currentWord"); currentWord += ch; //logger.debug("now it's " + currentWord); outStr += ch; } } super.insertString(offs, outStr, a); } notifyListeners(); } } }
src/org/cocolab/inpro/apps/SimpleText.java
package org.cocolab.inpro.apps; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.cocolab.inpro.apps.util.TextCommandLineParser; import org.cocolab.inpro.incremental.PushBuffer; import org.cocolab.inpro.incremental.listener.HypothesisChangeListener; import org.cocolab.inpro.incremental.processor.CurrentASRHypothesis; import org.cocolab.inpro.incremental.processor.FloorManager; import org.cocolab.inpro.incremental.unit.AtomicWordIU; import org.cocolab.inpro.incremental.unit.EditMessage; import org.cocolab.inpro.incremental.unit.EditType; import org.cocolab.inpro.incremental.unit.IUList; import edu.cmu.sphinx.util.props.ConfigurationManager; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Component; import edu.cmu.sphinx.util.props.S4ComponentList; /** * simple interactive (and non-interactive) ASR simulator for the inpro project * * Words are added to the IU list (and sent off to CurrentASRHypothesis' * HypothesisChangeListeners) as you type, revoked when you delete them * and committed when you press enter (or click on the "commit" button). * * Floor management (EoT-detection) is simulated by pressing enter twice * in a row (effectively: pressing enter when the textfield is empty) or * by clicking the "EoT" button. * * Notice: double-pressing enter and clicking on "EoT" is actually different, * because in the former case, all words will have been committed, while * in the latter case some words may be left uncommitted. Our system should * be able to cope with both cases (at least with EoT slightly preceding * ASR-commit), and this is a way for us to test this. * * * @author timo * */ @SuppressWarnings("serial") public class SimpleText extends JPanel implements ActionListener { private static final Logger logger = Logger.getLogger(SimpleText.class); @S4Component(type = CurrentASRHypothesis.class) public final static String PROP_CURRENT_HYPOTHESIS = "currentASRHypothesis"; @S4ComponentList(type = HypothesisChangeListener.class) public final static String PROP_HYP_CHANGE_LISTENERS = CurrentASRHypothesis.PROP_HYP_CHANGE_LISTENERS; @S4Component(type = FloorManager.class) public final static String PROP_FLOOR_MANAGER = "floorManager"; @S4Component(type = FloorManager.Listener.class) public final static String PROP_FLOOR_MANAGER_LISTENERS = FloorManager.PROP_STATE_LISTENERS; IUDocument iuDocument; List<FloorManager.Listener> floorListeners; JTextField textField; SimpleText(List<FloorManager.Listener> floorListeners) { iuDocument = new IUDocument(); iuDocument.listeners = new ArrayList<PushBuffer>(); textField = new JTextField(40); textField.setFont(new Font("Dialog", Font.BOLD, 24)); textField.setDocument(iuDocument); textField.addActionListener(this); JButton commitButton = new JButton("Commit"); commitButton.addActionListener(this); add(textField); add(commitButton); this.floorListeners = floorListeners; // clicking this button is actually not identical to // double pressing enter in the text field JButton floorButton = new JButton("EoT"); floorButton.addActionListener(this); add(floorButton); // add(new JLabel("you can only edit at the right")); } public void actionPerformed(ActionEvent arg0) { iuDocument.commit(); // hitting enter on empty lines results in an EoT-marker if (iuDocument.getLength() == 0) { for (FloorManager.Listener l : floorListeners) { l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); } } textField.requestFocusInWindow(); } public static void createAndShowGUI(List<PushBuffer> hypListeners, List<FloorManager.Listener> floorListeners) { JFrame frame = new JFrame("SimpleText"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SimpleText contentPane = new SimpleText(floorListeners); contentPane.iuDocument.setListeners(hypListeners); contentPane.setOpaque(true); frame.setContentPane(contentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void runFromReader(Reader reader, List<PushBuffer> hypListeners, List<FloorManager.Listener> floorListeners) throws IOException { IUDocument iuDocument = new IUDocument(); iuDocument.setListeners(hypListeners); BufferedReader bReader = new BufferedReader(reader); String line; while ((line = bReader.readLine()) != null) { try { iuDocument.insertString(0, line, null); } catch (BadLocationException e) { logger.error("wow, this should really not happen (I thought I could always add a string at position 0)"); e.printStackTrace(); } iuDocument.commit(); // empty lines results in an EoT-marker if ("".equals(line)) { for (FloorManager.Listener l : floorListeners) { l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); } } } } public static void main(String[] args) throws IOException { BasicConfigurator.configure(); TextCommandLineParser clp = new TextCommandLineParser(args); if (!clp.parsedSuccessfully()) { System.exit(1); } // abort on error ConfigurationManager cm = new ConfigurationManager(clp.getConfigURL()); PropertySheet ps = cm.getPropertySheet(PROP_CURRENT_HYPOTHESIS); @SuppressWarnings("unchecked") final List<PushBuffer> hypListeners = (List<PushBuffer>) ps.getComponentList(PROP_HYP_CHANGE_LISTENERS); ps = cm.getPropertySheet(PROP_FLOOR_MANAGER); @SuppressWarnings("unchecked") final List<FloorManager.Listener> floorListeners = (List<FloorManager.Listener>) ps.getComponentList(PROP_FLOOR_MANAGER_LISTENERS); if (clp.hasTextFromReader()) { // if we already know the text: logger.info("running in non-interactive mode"); // run non-interactively runFromReader(clp.getReader(), hypListeners, floorListeners); System.exit(0); // } else { // run interactively logger.info("running in interactive mode"); SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(hypListeners, floorListeners); } }); } } /** * An IUDocument stores a list of current IUs, * edits since the last update and * the string for the (partial) next IU * * It handles HypothesisChangeListeners * which are notified, when the IUList changes (or is committed) * (and can be set via setListeners()) * * IUs are committed and the list is reset after an explicit call to commit() * (when used as the document of a JTextField, this can be done by * calling commit() from a JTextField's ActionListener) * * @see javax.swing.text.Document Document * @author timo */ static class IUDocument extends PlainDocument { List<PushBuffer> listeners; IUList<AtomicWordIU> wordIUs = new IUList<AtomicWordIU>(); List<EditMessage<AtomicWordIU>> edits = new ArrayList<EditMessage<AtomicWordIU>>(); String currentWord = ""; int currentFrame = 0; public void setListeners(List<PushBuffer> listeners) { this.listeners = listeners; } public void notifyListeners() { if (edits.size() > 0) { //logger.debug("notifying about" + edits); currentFrame += 100; for (PushBuffer listener : listeners) { if (listener instanceof HypothesisChangeListener) { ((HypothesisChangeListener) listener).setCurrentFrame(currentFrame); } // notify if (wordIUs != null && edits != null) listener.hypChange(wordIUs, edits); } edits = new ArrayList<EditMessage<AtomicWordIU>>(); } } private void addCurrentWord() { //logger.debug("adding " + currentWord); AtomicWordIU sll = (wordIUs.size() > 0) ? wordIUs.get(wordIUs.size() - 1) : AtomicWordIU.FIRST_ATOMIC_WORD_IU; AtomicWordIU iu = new AtomicWordIU(currentWord, sll); EditMessage<AtomicWordIU> edit = new EditMessage<AtomicWordIU>(EditType.ADD, iu); edits.add(edit); wordIUs.add(iu); //logger.debug(edit.toString()); currentWord = ""; } public void commit() { // handle last word (if there is one) if (!"".equals(currentWord)) { addCurrentWord(); } // add commit messages for (AtomicWordIU iu : wordIUs) { edits.add(new EditMessage<AtomicWordIU>(EditType.COMMIT, iu)); iu.update(EditType.COMMIT); } // notify notifyListeners(); // reset try { super.remove(0,getLength()); } catch (BadLocationException e) { e.printStackTrace(); } wordIUs = new IUList<AtomicWordIU>(); edits = new ArrayList<EditMessage<AtomicWordIU>>(); } /* Overrides over PlainDocument: */ /** * only allow removal at the right end * and correctly handle removals beyond the current word */ @Override public void remove(int offs, int len) throws BadLocationException { if (offs + len == getLength()) { // only allow removal at the right end super.remove(offs, len); // if (getText(getLength() - 1, 1).) while (len > currentWord.length()) { // +1 because the whitespace has to be accounted for len -= currentWord.length(); len--; // to account for whitespace AtomicWordIU iu = wordIUs.remove(wordIUs.size() - 1); EditMessage<AtomicWordIU> edit = new EditMessage<AtomicWordIU>(EditType.REVOKE, iu); edits.add(edit); //logger.debug(edit.toString()); currentWord = iu.getWord(); } currentWord = currentWord.substring(0, currentWord.length() - len); //logger.debug("now it's " + currentWord); notifyListeners(); } } /** * only allow insertion at the right end */ @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (offs == getLength()) { /* character by character: * check validity (for example, we don't like multiple whitespace) * add them to the current word, if it's not whitespace * add current word to IUList if it is whitespace * finally, add the (possibly changed characters) to the superclass's data handling */ char[] chars = str.toCharArray(); String outStr = ""; for (char ch : chars) { if (Character.isWhitespace(ch)) { if (currentWord.length() > 0) { addCurrentWord(); outStr += " "; // add a space, no matter what whitespace was added } else { //logger.debug("ignoring additional whitespace"); } } else { //logger.debug("appending to currentWord"); currentWord += ch; //logger.debug("now it's " + currentWord); outStr += ch; } } super.insertString(offs, outStr, a); } notifyListeners(); } } }
hook up the nice commit-button, which didn't do anything yet. git-svn-id: 0dc367cf2a1f0872b31aed51a516e91b94972fba@1451 19460358-522e-0410-942e-fdb976ae3ca2
src/org/cocolab/inpro/apps/SimpleText.java
hook up the nice commit-button, which didn't do anything yet.
<ide><path>rc/org/cocolab/inpro/apps/SimpleText.java <ide> * be able to cope with both cases (at least with EoT slightly preceding <ide> * ASR-commit), and this is a way for us to test this. <ide> * <add> * <add> * TODO: implement revocation of words when running non-interactively. <add> * specification more or less follows Verbmobil: an exclamation mark <add> * is followed by the number of words to be revoked. !2 would revoke the <add> * two words preceding the exclamation mark. <ide> * <ide> * @author timo <ide> * <ide> // add(new JLabel("you can only edit at the right")); <ide> } <ide> <del> public void actionPerformed(ActionEvent arg0) { <del> iuDocument.commit(); <del> // hitting enter on empty lines results in an EoT-marker <del> if (iuDocument.getLength() == 0) { <del> for (FloorManager.Listener l : floorListeners) { <del> l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); <add> public void notifyFloorAvailable() { <add> for (FloorManager.Listener l : floorListeners) { <add> l.floor(FloorManager.State.AVAILABLE, FloorManager.State.UNAVAILABLE, null); <add> } <add> } <add> <add> public void actionPerformed(ActionEvent ae) { <add> if (ae.getActionCommand().equals("Commit")) { <add> notifyFloorAvailable(); <add> } else { <add> iuDocument.commit(); <add> // hitting enter on empty lines results in an EoT-marker <add> if (iuDocument.getLength() == 0) { <add> notifyFloorAvailable(); <ide> } <ide> } <ide> textField.requestFocusInWindow();
Java
mit
8209a54c6b1e7290140e7d32fd495cd5d557386e
0
Adam8234/the-blue-alliance-android,nwalters512/the-blue-alliance-android,Zero2848/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android,1fish2/the-blue-alliance-android,nwalters512/the-blue-alliance-android,1fish2/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,nwalters512/the-blue-alliance-android,1fish2/the-blue-alliance-android,Adam8234/the-blue-alliance-android,phil-lopreiato/the-blue-alliance-android,Zero2848/the-blue-alliance-android,the-blue-alliance/the-blue-alliance-android
package com.thebluealliance.androidclient.activities; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.accounts.AccountHelper; import com.thebluealliance.androidclient.background.UpdateMyTBA; import com.thebluealliance.androidclient.datafeed.RequestParams; import com.thebluealliance.androidclient.eventbus.ConnectivityChangeEvent; import com.thebluealliance.androidclient.helpers.AnalyticsHelper; import com.thebluealliance.androidclient.interfaces.RefreshListener; import com.thebluealliance.androidclient.interfaces.RefreshableHost; import java.util.ArrayList; import de.greenrobot.event.EventBus; /** * Created by Nathan on 4/29/2014. */ public abstract class RefreshableHostActivity extends BaseActivity implements RefreshableHost { private ArrayList<RefreshListener> mRefreshListeners = new ArrayList<>(); private ArrayList<RefreshListener> mCompletedRefreshListeners = new ArrayList<>(); private boolean mRefreshed = false; Menu mOptionsMenu; private boolean mRefreshInProgress = false; private boolean mRefreshEnabled = true; private boolean mProgressBarShowing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRefreshed = false; startRefresh(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (mRefreshEnabled) { getMenuInflater().inflate(R.menu.refresh_menu, menu); mOptionsMenu = menu; if (mRefreshInProgress) { setMenuProgressBarVisible(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: if (shouldRefresh()) { // If a refresh is already in progress, restart it. Otherwise, begin a refresh. if (!mRefreshInProgress) { startRefresh(true); } else { restartRefresh(true); } } break; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); if (!mRefreshed) { startRefresh(); } } @Override protected void onPause() { super.onPause(); cancelRefresh(); EventBus.getDefault().unregister(this); } public void setRefreshEnabled(boolean enabled) { mRefreshEnabled = enabled; invalidateOptionsMenu(); } public synchronized void registerRefreshListener(RefreshListener listener) { if (listener != null && !mRefreshListeners.contains(listener)) { mRefreshListeners.add(listener); } } public synchronized void unregisterRefreshListener(RefreshListener listener) { if (listener != null && mRefreshListeners.contains(listener)) { mRefreshListeners.remove(listener); } if (listener != null && mCompletedRefreshListeners.contains(listener)) { mCompletedRefreshListeners.remove(listener); } } /* This can be overridden by child classes to check whether or not a refresh should take place. For example, this might return false if there is no network connection and a network connection is required to refresh data. The default return value is true. @return true if a refresh can and should be triggered, false if otherwise */ protected boolean shouldRefresh() { return true; } /* Registered listeners call this to notify the activity that they have finished refreshing. Once all registered listeners have indicated that they have finished refreshing, the list of listeners that have reported completion is cleared and onRefreshComplete() is called. @param listener the listener that has finished refreshing */ public synchronized void notifyRefreshComplete(RefreshListener completedListener) { if (completedListener == null || !mRefreshListeners.contains(completedListener)) { return; } if (!mCompletedRefreshListeners.contains(completedListener)) { mCompletedRefreshListeners.add(completedListener); } if (mCompletedRefreshListeners.size() >= mRefreshListeners.size()) { onRefreshComplete(); mCompletedRefreshListeners.clear(); } } /* Called when all registered listeners have reported that they are done refreshing. This can be overridden to do custom things when refreshing is completed. However, the child class should ALWAYS call super.onRefreshComplete() to ensure proper behavior. */ protected void onRefreshComplete() { setMenuProgressBarVisible(false); mRefreshInProgress = false; mRefreshed = true; //update myTBA after content loads if (AccountHelper.isAccountSelected(this)) { new UpdateMyTBA(this, new RequestParams()).execute(); } } /* * Notifies all registered listeners that they should start their refresh. * Passes parameter if toolbar icon initiated refresh (defaults to false) */ public void startRefresh() { startRefresh(false); } public void startRefresh(boolean actionIconPressed) { if (mRefreshInProgress) { //if a refresh is already happening, don't start another return; } if (mRefreshListeners.isEmpty()) { return; } mRefreshInProgress = true; setMenuProgressBarVisible(true); for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStart(actionIconPressed); } AnalyticsHelper.sendRefreshUpdate(this, modelKey); } /* Refreshes a specific listener */ public void startRefresh(RefreshListener listener) { if (!mRefreshListeners.contains(listener)) { mRefreshListeners.add(listener); } listener.onRefreshStart(false); setMenuProgressBarVisible(true); } /* Notifies all registered listeners that they should cancel their refresh */ public void cancelRefresh() { for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStop(); } mRefreshInProgress = false; setMenuProgressBarVisible(false); } /* Notifies all refresh listeners that they should stop, and immediately notifies them that they should start again. */ public void restartRefresh(boolean actionIconPressed) { for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStop(); } for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStart(actionIconPressed); } mRefreshInProgress = true; setMenuProgressBarVisible(true); } private void setMenuProgressBarVisible(boolean visible) { MenuItem refresh; if (mOptionsMenu != null) { refresh = mOptionsMenu.findItem(R.id.refresh); } else { return; } if (mProgressBarShowing && !visible) { // Hide progress indicator Log.d("RHA", "hidden"); refresh.setActionView(null); mProgressBarShowing = false; } else if (!mProgressBarShowing && visible) { // Show progress indicator Log.d("RHA", "shown!"); refresh.setActionView(R.layout.actionbar_indeterminate_progress); mProgressBarShowing = true; } else { Log.d("RHA", "did nothing! showing: " + mProgressBarShowing + "; desired: " + visible); // Do nothing } } public void onEvent(ConnectivityChangeEvent event) { if (event.getConnectivityChangeType() == ConnectivityChangeEvent.CONNECTION_FOUND) { hideWarningMessage(); startRefresh(); } else { showWarningMessage(getString(R.string.warning_no_internet_connection)); } } }
android/src/main/java/com/thebluealliance/androidclient/activities/RefreshableHostActivity.java
package com.thebluealliance.androidclient.activities; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.accounts.AccountHelper; import com.thebluealliance.androidclient.background.UpdateMyTBA; import com.thebluealliance.androidclient.datafeed.RequestParams; import com.thebluealliance.androidclient.eventbus.ConnectivityChangeEvent; import com.thebluealliance.androidclient.helpers.AnalyticsHelper; import com.thebluealliance.androidclient.interfaces.RefreshListener; import com.thebluealliance.androidclient.interfaces.RefreshableHost; import java.util.ArrayList; import de.greenrobot.event.EventBus; /** * Created by Nathan on 4/29/2014. */ public abstract class RefreshableHostActivity extends BaseActivity implements RefreshableHost { private ArrayList<RefreshListener> mRefreshListeners = new ArrayList<>(); private ArrayList<RefreshListener> mCompletedRefreshListeners = new ArrayList<>(); private boolean mRefreshed = false; Menu mOptionsMenu; private boolean mRefreshInProgress = false; private boolean mProgressBarShowing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRefreshed = false; startRefresh(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.refresh_menu, menu); mOptionsMenu = menu; if (mRefreshInProgress) { setMenuProgressBarVisible(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.refresh: if (shouldRefresh()) { // If a refresh is already in progress, restart it. Otherwise, begin a refresh. if (!mRefreshInProgress) { startRefresh(true); } else { restartRefresh(true); } } break; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); EventBus.getDefault().register(this); if (!mRefreshed) { startRefresh(); } } @Override protected void onPause() { super.onPause(); cancelRefresh(); EventBus.getDefault().unregister(this); } public synchronized void registerRefreshListener(RefreshListener listener) { if (listener != null && !mRefreshListeners.contains(listener)) { mRefreshListeners.add(listener); } } public synchronized void unregisterRefreshListener(RefreshListener listener) { if (listener != null && mRefreshListeners.contains(listener)) { mRefreshListeners.remove(listener); } if (listener != null && mCompletedRefreshListeners.contains(listener)) { mCompletedRefreshListeners.remove(listener); } } /* This can be overridden by child classes to check whether or not a refresh should take place. For example, this might return false if there is no network connection and a network connection is required to refresh data. The default return value is true. @return true if a refresh can and should be triggered, false if otherwise */ protected boolean shouldRefresh() { return true; } /* Registered listeners call this to notify the activity that they have finished refreshing. Once all registered listeners have indicated that they have finished refreshing, the list of listeners that have reported completion is cleared and onRefreshComplete() is called. @param listener the listener that has finished refreshing */ public synchronized void notifyRefreshComplete(RefreshListener completedListener) { if (completedListener == null || !mRefreshListeners.contains(completedListener)) { return; } if (!mCompletedRefreshListeners.contains(completedListener)) { mCompletedRefreshListeners.add(completedListener); } if (mCompletedRefreshListeners.size() >= mRefreshListeners.size()) { onRefreshComplete(); mCompletedRefreshListeners.clear(); } } /* Called when all registered listeners have reported that they are done refreshing. This can be overridden to do custom things when refreshing is completed. However, the child class should ALWAYS call super.onRefreshComplete() to ensure proper behavior. */ protected void onRefreshComplete() { setMenuProgressBarVisible(false); mRefreshInProgress = false; mRefreshed = true; //update myTBA after content loads if (AccountHelper.isAccountSelected(this)) { new UpdateMyTBA(this, new RequestParams()).execute(); } } /* * Notifies all registered listeners that they should start their refresh. * Passes parameter if toolbar icon initiated refresh (defaults to false) */ public void startRefresh() { startRefresh(false); } public void startRefresh(boolean actionIconPressed) { if (mRefreshInProgress) { //if a refresh is already happening, don't start another return; } if (mRefreshListeners.isEmpty()) { return; } mRefreshInProgress = true; setMenuProgressBarVisible(true); for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStart(actionIconPressed); } AnalyticsHelper.sendRefreshUpdate(this, modelKey); } /* Refreshes a specific listener */ public void startRefresh(RefreshListener listener) { if (!mRefreshListeners.contains(listener)) { mRefreshListeners.add(listener); } listener.onRefreshStart(false); setMenuProgressBarVisible(true); } /* Notifies all registered listeners that they should cancel their refresh */ public void cancelRefresh() { for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStop(); } mRefreshInProgress = false; setMenuProgressBarVisible(false); } /* Notifies all refresh listeners that they should stop, and immediately notifies them that they should start again. */ public void restartRefresh(boolean actionIconPressed) { for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStop(); } for (RefreshListener listener : mRefreshListeners) { listener.onRefreshStart(actionIconPressed); } mRefreshInProgress = true; setMenuProgressBarVisible(true); } private void setMenuProgressBarVisible(boolean visible) { MenuItem refresh; if (mOptionsMenu != null) { refresh = mOptionsMenu.findItem(R.id.refresh); } else { return; } if (mProgressBarShowing && !visible) { // Hide progress indicator Log.d("RHA", "hidden"); refresh.setActionView(null); mProgressBarShowing = false; } else if (!mProgressBarShowing && visible) { // Show progress indicator Log.d("RHA", "shown!"); refresh.setActionView(R.layout.actionbar_indeterminate_progress); mProgressBarShowing = true; } else { Log.d("RHA", "did nothing! showing: " + mProgressBarShowing + "; desired: " + visible); // Do nothing } } public void onEvent(ConnectivityChangeEvent event) { if (event.getConnectivityChangeType() == ConnectivityChangeEvent.CONNECTION_FOUND) { hideWarningMessage(); startRefresh(); } else { showWarningMessage(getString(R.string.warning_no_internet_connection)); } } }
Added ability to disable refresh in refreshable activities.
android/src/main/java/com/thebluealliance/androidclient/activities/RefreshableHostActivity.java
Added ability to disable refresh in refreshable activities.
<ide><path>ndroid/src/main/java/com/thebluealliance/androidclient/activities/RefreshableHostActivity.java <ide> <ide> private boolean mRefreshInProgress = false; <ide> <add> private boolean mRefreshEnabled = true; <add> <ide> private boolean mProgressBarShowing = false; <ide> <ide> @Override <ide> @Override <ide> public boolean onCreateOptionsMenu(Menu menu) { <ide> super.onCreateOptionsMenu(menu); <del> getMenuInflater().inflate(R.menu.refresh_menu, menu); <del> mOptionsMenu = menu; <del> if (mRefreshInProgress) { <del> setMenuProgressBarVisible(true); <add> if (mRefreshEnabled) { <add> getMenuInflater().inflate(R.menu.refresh_menu, menu); <add> mOptionsMenu = menu; <add> if (mRefreshInProgress) { <add> setMenuProgressBarVisible(true); <add> } <ide> } <ide> return true; <ide> } <ide> super.onPause(); <ide> cancelRefresh(); <ide> EventBus.getDefault().unregister(this); <add> } <add> <add> public void setRefreshEnabled(boolean enabled) { <add> mRefreshEnabled = enabled; <add> invalidateOptionsMenu(); <ide> } <ide> <ide> public synchronized void registerRefreshListener(RefreshListener listener) {
Java
mit
error: pathspec '2.JavaCore/src/com/javarush/task/task14/task1420/Solution.java' did not match any file(s) known to git
8deda0db35cd3cfb73d66cec0ad122c81783a326
1
nphl/JavaRushTasks
package com.javarush.task.task14.task1420; /* НОД */ import java.io.BufferedReader; import java.io.InputStreamReader; public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int firstNumber, secondNumber; firstNumber = Integer.parseInt(reader.readLine()); secondNumber = Integer.parseInt(reader.readLine()); if (firstNumber < 1 || secondNumber < 1) { reader.close(); throw new Exception(); } System.out.println(GCD(firstNumber, secondNumber)); reader.close(); } private static int GCD(int a, int b) { while (b != 0) { int tmp = a % b; a = b; b = tmp; } return a; } }
2.JavaCore/src/com/javarush/task/task14/task1420/Solution.java
Complete task1420
2.JavaCore/src/com/javarush/task/task14/task1420/Solution.java
Complete task1420
<ide><path>.JavaCore/src/com/javarush/task/task14/task1420/Solution.java <add>package com.javarush.task.task14.task1420; <add> <add>/* <add>НОД <add>*/ <add> <add>import java.io.BufferedReader; <add>import java.io.InputStreamReader; <add> <add>public class Solution { <add> public static void main(String[] args) throws Exception { <add> BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); <add> int firstNumber, secondNumber; <add> <add> firstNumber = Integer.parseInt(reader.readLine()); <add> secondNumber = Integer.parseInt(reader.readLine()); <add> if (firstNumber < 1 || secondNumber < 1) { <add> reader.close(); <add> throw new Exception(); <add> } <add> System.out.println(GCD(firstNumber, secondNumber)); <add> reader.close(); <add> } <add> <add> <add> <add> private static int GCD(int a, int b) { <add> while (b != 0) { <add> int tmp = a % b; <add> a = b; <add> b = tmp; <add> } <add> return a; <add> } <add>}
Java
lgpl-2.1
d3ebdef581db3944b417385469de05288429880f
0
99sono/wildfly,jstourac/wildfly,golovnin/wildfly,wildfly/wildfly,rhusar/wildfly,jstourac/wildfly,wildfly/wildfly,jstourac/wildfly,wildfly/wildfly,pferraro/wildfly,99sono/wildfly,iweiss/wildfly,rhusar/wildfly,tomazzupan/wildfly,golovnin/wildfly,golovnin/wildfly,iweiss/wildfly,tadamski/wildfly,pferraro/wildfly,jstourac/wildfly,rhusar/wildfly,99sono/wildfly,pferraro/wildfly,iweiss/wildfly,rhusar/wildfly,tadamski/wildfly,iweiss/wildfly,tadamski/wildfly,tomazzupan/wildfly,xasx/wildfly,xasx/wildfly,xasx/wildfly,wildfly/wildfly,tomazzupan/wildfly,pferraro/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.demos; import static org.jboss.as.protocol.StreamUtils.safeClose; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.client.helpers.domain.DuplicateDeploymentNameException; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * Used to deploy/undeploy deployments to a running <b>domain controller</b> * * @author <a href="[email protected]">Kabir Khan</a> * @author Brian Stansberry * @version $Revision: 1.1 $ */ public class DomainDeploymentUtils implements Closeable { private final List<Deployment> deployments = new ArrayList<Deployment>(); private final ModelControllerClient client; // private final DomainDeploymentManager manager; private boolean injectedClient = true; public DomainDeploymentUtils() throws UnknownHostException { this(ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999)); this.injectedClient = false; } public DomainDeploymentUtils(ModelControllerClient client) throws UnknownHostException { this.client = client; } public DomainDeploymentUtils(String archiveName, Package pkg) throws UnknownHostException { this(); addDeployment(archiveName, pkg); } public DomainDeploymentUtils(String archiveName, Package pkg, boolean show) throws UnknownHostException { this(); addDeployment(archiveName, pkg, show); } public synchronized void addDeployment(String archiveName, Package pkg) { addDeployment(archiveName, pkg, false); } public synchronized void addDeployment(String archiveName, Package pkg, boolean show) { deployments.add(new Deployment(archiveName, pkg, show)); } public synchronized void deploy() throws DuplicateDeploymentNameException, IOException, ExecutionException, InterruptedException { ModelNode op = new ModelNode(); OperationBuilder builder = OperationBuilder.Factory.create(op); op.get(ClientConstants.OP).set("composite"); op.get(ClientConstants.OP_ADDR).setEmptyList(); ModelNode steps = op.get("steps"); for (Deployment deployment : deployments) { steps.add(deployment.addDeployment(builder)); } op.get(ClientConstants.OPERATION_HEADERS, ClientConstants.ROLLBACK_ON_RUNTIME_FAILURE).set(getRolloutPlan()); execute(builder.build()); } public synchronized void undeploy() throws IOException { ModelNode op = new ModelNode(); op.get(ClientConstants.OP).set("composite"); op.get(ClientConstants.OP_ADDR).setEmptyList(); ModelNode steps = op.get("steps"); boolean execute = false; Set<String> deployed = getDeploymentNames(); for (Deployment deployment : deployments) { if (deployed.contains(deployment.archiveName)) { steps.add(deployment.removeDeployment()); execute = true; } } if (execute) { op.get(ClientConstants.OPERATION_HEADERS, ClientConstants.ROLLBACK_ON_RUNTIME_FAILURE).set(getRolloutPlan()); ModelNode result = client.execute(op); } } public MBeanServerConnection getServerOneConnection() throws Exception { return JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi"), new HashMap<String, Object>()).getMBeanServerConnection(); } public String showServerOneJndi() throws Exception { return (String)getServerOneConnection().invoke(new ObjectName("jboss:type=JNDIView"), "list", new Object[] {true}, new String[] {"boolean"}); } public MBeanServerConnection getServerTwoConnection() throws Exception { return JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1240/jmxrmi"), new HashMap<String, Object>()).getMBeanServerConnection(); } public String showServerTwoJndi() throws Exception { return (String)getServerTwoConnection().invoke(new ObjectName("jboss:type=JNDIView"), "list", new Object[] {true}, new String[] {"boolean"}); } @Override public void close() throws IOException { if (!injectedClient) { safeClose(client); } } private Set<String> getDeploymentNames() throws IOException { ModelNode op = new ModelNode(); op.get("operation").set("read-children-names"); op.get("child-type").set("deployment"); ModelNode result = execute(op); Set<String> names = new HashSet<String>(); if(! result.isDefined()) { return Collections.emptySet(); } for (ModelNode deployment : result.asList()) { names.add(deployment.asString()); } return names; } private ModelNode execute(ModelNode op) throws IOException { return execute(OperationBuilder.Factory.create(op).build()); } private ModelNode execute(Operation op) throws IOException { ModelNode result = client.execute(op); if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) { return result.get("result"); } else if (result.hasDefined("failure-description")) { System.out.println(result); throw new RuntimeException(result.get("failure-description").toString()); } else if (result.hasDefined("domain-failure-description")) { System.out.println(result); throw new RuntimeException(result.get("domain-failure-description").toString()); } else if (result.hasDefined("host-failure-descriptions")) { System.out.println(result); throw new RuntimeException(result.get("host-failure-descriptions").toString()); } else { System.out.println(result); throw new RuntimeException("Operation outcome is " + result.get("outcome").asString()); } } private static ModelNode getRolloutPlan() { ModelNode result = new ModelNode(); ModelNode series = result.get("in-series"); series.add().get("server-group", "main-server-group"); series.add().get("server-group", "other-server-group"); result.get("rollback-across-groups").set(true); return result; } private class Deployment { final String archiveName; final Package pkg; final JavaArchive archive; final File realArchive; public Deployment(String archiveName, Package pkg, boolean show) { this.archiveName = archiveName; this.pkg = pkg; ArchivePath metaInf = ArchivePaths.create("META-INF"); archive = ShrinkWrap.create(JavaArchive.class, archiveName); archive.addPackage(pkg); File sourceMetaInf = getSourceMetaInfDir(); addFiles(archive, sourceMetaInf, metaInf); System.out.println(archive.toString(show)); realArchive = new File(getOutputDir(), archive.getName()); archive.as(ZipExporter.class).exportZip(realArchive, true); } private void addFiles(JavaArchive archive, File dir, ArchivePath dest) { for (String name : dir.list()) { File file = new File(dir, name); if (file.isDirectory()) { addFiles(archive, file, ArchivePaths.create(dest, name)); } else { archive.addResource(file, ArchivePaths.create(dest, name)); } } } public synchronized ModelNode addDeployment(OperationBuilder context) throws IOException { System.out.println("Deploying " + realArchive.getName()); Set<String> deployments = getDeploymentNames(); int index = context.getInputStreamCount(); context.addInputStream(new FileInputStream(realArchive)); ModelNode result = new ModelNode(); if (deployments.contains(archiveName)) { result.get("operation").set("full-replace-deployment"); result.get("name").set(archiveName); result.get("input-stream-index").set(index); } else { result.get("operation").set("composite"); ModelNode steps = result.get("steps"); ModelNode add = steps.add(); add.get("operation").set("add"); add.get("address").add("deployment", archiveName); add.get("input-stream-index").set(index); ModelNode mainAdd = steps.add(); mainAdd.get("operation").set("add"); mainAdd.get("address").add("server-group", "main-server-group"); mainAdd.get("address").add("deployment", archiveName); ModelNode mainDeploy = steps.add(); mainDeploy.get("operation").set("deploy"); mainDeploy.get("address").add("server-group", "main-server-group"); mainDeploy.get("address").add("deployment", archiveName); ModelNode otherAdd = steps.add(); otherAdd.get("operation").set("add"); otherAdd.get("address").add("server-group", "other-server-group"); otherAdd.get("address").add("deployment", archiveName); ModelNode otherDeploy = steps.add(); otherDeploy.get("operation").set("deploy"); otherDeploy.get("address").add("server-group", "other-server-group"); otherDeploy.get("address").add("deployment", archiveName); } return result; } public synchronized ModelNode removeDeployment() { System.out.println("Undeploying " + realArchive.getName()); ModelNode result = new ModelNode(); result.get("operation").set("composite"); ModelNode steps = result.get("steps"); ModelNode mainUndeploy = steps.add(); mainUndeploy.get("operation").set("undeploy"); mainUndeploy.get("address").add("server-group", "main-server-group"); mainUndeploy.get("address").add("deployment", archiveName); ModelNode mainRemove = steps.add(); mainRemove.get("operation").set("remove"); mainRemove.get("address").add("server-group", "main-server-group"); mainRemove.get("address").add("deployment", archiveName); ModelNode otherUndeploy = steps.add(); otherUndeploy.get("operation").set("undeploy"); otherUndeploy.get("address").add("server-group", "other-server-group"); otherUndeploy.get("address").add("deployment", archiveName); ModelNode otherRemove = steps.add(); otherRemove.get("operation").set("remove"); otherRemove.get("address").add("server-group", "other-server-group"); otherRemove.get("address").add("deployment", archiveName); ModelNode domainRemove = steps.add(); domainRemove.get("operation").set("remove"); domainRemove.get("address").add("deployment", archiveName); return result; } private File getSourceMetaInfDir() { String name = "archives/" + archiveName + "/META-INF/MANIFEST.MF"; URL url = Thread.currentThread().getContextClassLoader().getResource(name); if (url == null) { throw new IllegalArgumentException("No resource called " + name); } try { File file = new File(url.toURI()); return file.getParentFile(); } catch (URISyntaxException e) { throw new RuntimeException("Could not get file for " + url); } } private File getOutputDir() { File file = new File("target"); if (!file.exists()) { throw new IllegalStateException("target/ does not exist"); } if (!file.isDirectory()) { throw new IllegalStateException("target/ is not a directory"); } file = new File(file, "archives"); if (file.exists()) { if (!file.isDirectory()) { throw new IllegalStateException("target/archives/ already exists and is not a directory"); } } else { file.mkdir(); } return file.getAbsoluteFile(); } private void close(Closeable c) { try { if (c != null) { c.close(); } } catch (IOException ignore) { } } } }
demos/src/main/java/org/jboss/as/demos/DomainDeploymentUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.demos; import static org.jboss.as.protocol.StreamUtils.safeClose; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.jboss.as.controller.client.Operation; import org.jboss.as.controller.client.OperationBuilder; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.client.helpers.ClientConstants; import org.jboss.as.controller.client.helpers.domain.DuplicateDeploymentNameException; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.api.spec.JavaArchive; /** * Used to deploy/undeploy deployments to a running <b>domain controller</b> * * @author <a href="[email protected]">Kabir Khan</a> * @author Brian Stansberry * @version $Revision: 1.1 $ */ public class DomainDeploymentUtils implements Closeable { private final List<Deployment> deployments = new ArrayList<Deployment>(); private final ModelControllerClient client; // private final DomainDeploymentManager manager; private boolean injectedClient = true; public DomainDeploymentUtils() throws UnknownHostException { this(ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999)); this.injectedClient = false; } public DomainDeploymentUtils(ModelControllerClient client) throws UnknownHostException { this.client = client; } public DomainDeploymentUtils(String archiveName, Package pkg) throws UnknownHostException { this(); addDeployment(archiveName, pkg); } public DomainDeploymentUtils(String archiveName, Package pkg, boolean show) throws UnknownHostException { this(); addDeployment(archiveName, pkg, show); } public synchronized void addDeployment(String archiveName, Package pkg) { addDeployment(archiveName, pkg, false); } public synchronized void addDeployment(String archiveName, Package pkg, boolean show) { deployments.add(new Deployment(archiveName, pkg, show)); } public synchronized void deploy() throws DuplicateDeploymentNameException, IOException, ExecutionException, InterruptedException { ModelNode op = new ModelNode(); OperationBuilder builder = OperationBuilder.Factory.create(op); op.get(ClientConstants.OP).set("composite"); op.get(ClientConstants.OP_ADDR).setEmptyList(); ModelNode steps = op.get("steps"); for (Deployment deployment : deployments) { steps.add(deployment.addDeployment(builder)); } op.get(ClientConstants.OPERATION_HEADERS, ClientConstants.ROLLBACK_ON_RUNTIME_FAILURE).set(getRolloutPlan()); execute(builder.build()); } public synchronized void undeploy() throws IOException { ModelNode op = new ModelNode(); op.get(ClientConstants.OP).set("composite"); op.get(ClientConstants.OP_ADDR).setEmptyList(); ModelNode steps = op.get("steps"); boolean execute = false; Set<String> deployed = getDeploymentNames(); for (Deployment deployment : deployments) { if (deployed.contains(deployment.archiveName)) { steps.add(deployment.removeDeployment()); execute = true; } } if (execute) { op.get(ClientConstants.OPERATION_HEADERS, ClientConstants.ROLLBACK_ON_RUNTIME_FAILURE).set(getRolloutPlan()); ModelNode result = client.execute(op); } } public MBeanServerConnection getServerOneConnection() throws Exception { return JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1090/jmxrmi"), new HashMap<String, Object>()).getMBeanServerConnection(); } public String showServerOneJndi() throws Exception { return (String)getServerOneConnection().invoke(new ObjectName("jboss:type=JNDIView"), "list", new Object[] {true}, new String[] {"boolean"}); } public MBeanServerConnection getServerTwoConnection() throws Exception { return JMXConnectorFactory.connect(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1240/jmxrmi"), new HashMap<String, Object>()).getMBeanServerConnection(); } public String showServerTwoJndi() throws Exception { return (String)getServerTwoConnection().invoke(new ObjectName("jboss:type=JNDIView"), "list", new Object[] {true}, new String[] {"boolean"}); } @Override public void close() throws IOException { if (!injectedClient) { safeClose(client); } } private Set<String> getDeploymentNames() throws IOException { ModelNode op = new ModelNode(); op.get("operation").set("read-children-names"); op.get("child-type").set("deployment"); ModelNode result = execute(op); Set<String> names = new HashSet<String>(); if(! result.isDefined()) { return Collections.emptySet(); } for (ModelNode deployment : result.asList()) { names.add(deployment.asString()); } return names; } private ModelNode execute(ModelNode op) throws IOException { return execute(OperationBuilder.Factory.create(op).build()); } private ModelNode execute(Operation op) throws IOException { ModelNode result = client.execute(op); if (result.hasDefined("outcome") && "success".equals(result.get("outcome").asString())) { return result.get("result"); } else if (result.hasDefined("failure-description")) { throw new RuntimeException(result.get("failure-description").toString()); } else if (result.hasDefined("domain-failure-description")) { throw new RuntimeException(result.get("domain-failure-description").toString()); } else if (result.hasDefined("host-failure-descriptions")) { throw new RuntimeException(result.get("host-failure-descriptions").toString()); } else { System.out.println(result); throw new RuntimeException("Operation outcome is " + result.get("outcome").asString()); } } private static ModelNode getRolloutPlan() { ModelNode result = new ModelNode(); ModelNode series = result.get("in-series"); series.add().get("server-group", "main-server-group"); series.add().get("server-group", "other-server-group"); result.get("rollback-across-groups").set(true); return result; } private class Deployment { final String archiveName; final Package pkg; final JavaArchive archive; final File realArchive; public Deployment(String archiveName, Package pkg, boolean show) { this.archiveName = archiveName; this.pkg = pkg; ArchivePath metaInf = ArchivePaths.create("META-INF"); archive = ShrinkWrap.create(JavaArchive.class, archiveName); archive.addPackage(pkg); File sourceMetaInf = getSourceMetaInfDir(); addFiles(archive, sourceMetaInf, metaInf); System.out.println(archive.toString(show)); realArchive = new File(getOutputDir(), archive.getName()); archive.as(ZipExporter.class).exportZip(realArchive, true); } private void addFiles(JavaArchive archive, File dir, ArchivePath dest) { for (String name : dir.list()) { File file = new File(dir, name); if (file.isDirectory()) { addFiles(archive, file, ArchivePaths.create(dest, name)); } else { archive.addResource(file, ArchivePaths.create(dest, name)); } } } public synchronized ModelNode addDeployment(OperationBuilder context) throws IOException { System.out.println("Deploying " + realArchive.getName()); Set<String> deployments = getDeploymentNames(); int index = context.getInputStreamCount(); context.addInputStream(new FileInputStream(realArchive)); ModelNode result = new ModelNode(); if (deployments.contains(archiveName)) { result.get("operation").set("full-replace-deployment"); result.get("name").set(archiveName); result.get("input-stream-index").set(index); } else { result.get("operation").set("composite"); ModelNode steps = result.get("steps"); ModelNode add = steps.add(); add.get("operation").set("add"); add.get("address").add("deployment", archiveName); add.get("input-stream-index").set(index); ModelNode mainAdd = steps.add(); mainAdd.get("operation").set("add"); mainAdd.get("address").add("server-group", "main-server-group"); mainAdd.get("address").add("deployment", archiveName); ModelNode mainDeploy = steps.add(); mainDeploy.get("operation").set("deploy"); mainDeploy.get("address").add("server-group", "main-server-group"); mainDeploy.get("address").add("deployment", archiveName); ModelNode otherAdd = steps.add(); otherAdd.get("operation").set("add"); otherAdd.get("address").add("server-group", "other-server-group"); otherAdd.get("address").add("deployment", archiveName); ModelNode otherDeploy = steps.add(); otherDeploy.get("operation").set("deploy"); otherDeploy.get("address").add("server-group", "other-server-group"); otherDeploy.get("address").add("deployment", archiveName); } return result; } public synchronized ModelNode removeDeployment() { System.out.println("Undeploying " + realArchive.getName()); ModelNode result = new ModelNode(); result.get("operation").set("composite"); ModelNode steps = result.get("steps"); ModelNode mainUndeploy = steps.add(); mainUndeploy.get("operation").set("undeploy"); mainUndeploy.get("address").add("server-group", "main-server-group"); mainUndeploy.get("address").add("deployment", archiveName); ModelNode mainRemove = steps.add(); mainRemove.get("operation").set("remove"); mainRemove.get("address").add("server-group", "main-server-group"); mainRemove.get("address").add("deployment", archiveName); ModelNode otherUndeploy = steps.add(); otherUndeploy.get("operation").set("undeploy"); otherUndeploy.get("address").add("server-group", "other-server-group"); otherUndeploy.get("address").add("deployment", archiveName); ModelNode otherRemove = steps.add(); otherRemove.get("operation").set("remove"); otherRemove.get("address").add("server-group", "other-server-group"); otherRemove.get("address").add("deployment", archiveName); ModelNode domainRemove = steps.add(); domainRemove.get("operation").set("remove"); domainRemove.get("address").add("deployment", archiveName); return result; } private File getSourceMetaInfDir() { String name = "archives/" + archiveName + "/META-INF/MANIFEST.MF"; URL url = Thread.currentThread().getContextClassLoader().getResource(name); if (url == null) { throw new IllegalArgumentException("No resource called " + name); } try { File file = new File(url.toURI()); return file.getParentFile(); } catch (URISyntaxException e) { throw new RuntimeException("Could not get file for " + url); } } private File getOutputDir() { File file = new File("target"); if (!file.exists()) { throw new IllegalStateException("target/ does not exist"); } if (!file.isDirectory()) { throw new IllegalStateException("target/ is not a directory"); } file = new File(file, "archives"); if (file.exists()) { if (!file.isDirectory()) { throw new IllegalStateException("target/archives/ already exists and is not a directory"); } } else { file.mkdir(); } return file.getAbsoluteFile(); } private void close(Closeable c) { try { if (c != null) { c.close(); } } catch (IOException ignore) { } } } }
Demo debug logging
demos/src/main/java/org/jboss/as/demos/DomainDeploymentUtils.java
Demo debug logging
<ide><path>emos/src/main/java/org/jboss/as/demos/DomainDeploymentUtils.java <ide> return result.get("result"); <ide> } <ide> else if (result.hasDefined("failure-description")) { <add> System.out.println(result); <ide> throw new RuntimeException(result.get("failure-description").toString()); <ide> } <ide> else if (result.hasDefined("domain-failure-description")) { <add> System.out.println(result); <ide> throw new RuntimeException(result.get("domain-failure-description").toString()); <ide> } <ide> else if (result.hasDefined("host-failure-descriptions")) { <add> System.out.println(result); <ide> throw new RuntimeException(result.get("host-failure-descriptions").toString()); <ide> } <ide> else {
Java
mit
1b4d5fc20166fdf5fc6569270985045f3626c0f5
0
jenkinsci/ec2-plugin,mkozell/ec2-plugin,mkozell/ec2-plugin,mkozell/ec2-plugin,mkozell/ec2-plugin,jenkinsci/ec2-plugin,jenkinsci/ec2-plugin,jenkinsci/ec2-plugin
/* * The MIT License * * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package hudson.plugins.ec2; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.slaves.iterators.api.NodeIterator; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; import hudson.Extension; import hudson.Util; import hudson.model.*; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtom; import hudson.plugins.ec2.util.DeviceMappingParser; import hudson.util.FormValidation; import hudson.util.ListBoxModel; /** * Template of {@link EC2AbstractSlave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName()); public String ami; public final String description; public final String zone; public final SpotConfiguration spotConfig; public final String securityGroups; public final String remoteFS; public final InstanceType type; public final boolean ebsOptimized; public final boolean monitoring; public final String labels; public final Node.Mode mode; public final String initScript; public final String tmpDir; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String jvmopts; public final String subnetId; public final String idleTerminationMinutes; public final String iamInstanceProfile; public final boolean deleteRootOnTermination; public final boolean useEphemeralDevices; public final String customDeviceMapping; public int instanceCap; public final boolean stopOnTerminate; private final List<EC2Tag> tags; public final boolean usePrivateDnsName; public final boolean associatePublicIp; protected transient EC2Cloud parent; public final boolean useDedicatedTenancy; public AMITypeData amiType; public int launchTimeout; public boolean connectBySSHProcess; public final boolean connectUsingPublicIp; public int nextSubnet; public String currentSubnetId; private transient/* almost final */Set<LabelAtom> labelSet; private transient/* almost final */Set<String> securityGroupSet; /* * Necessary to handle reading from old configurations. The UnixData object is created in readResolve() */ @Deprecated public transient String sshPort; @Deprecated public transient String rootCommandPrefix; @Deprecated public transient String slaveCommandPrefix; @DataBoundConstructor public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp, boolean monitoring) { if(StringUtils.isNotBlank(remoteAdmin) || StringUtils.isNotBlank(jvmopts) || StringUtils.isNotBlank(tmpDir)){ LOGGER.log(Level.FINE, "As remoteAdmin, jvmopts or tmpDir is not blank, we must ensure the user has RUN_SCRIPTS rights."); Jenkins j = Jenkins.getInstance(); if(j != null){ j.checkPermission(Jenkins.RUN_SCRIPTS); } } this.ami = ami; this.zone = zone; this.spotConfig = spotConfig; this.securityGroups = securityGroups; this.remoteFS = remoteFS; this.amiType = amiType; this.type = type; this.ebsOptimized = ebsOptimized; this.labels = Util.fixNull(labelString); this.mode = mode != null ? mode : Node.Mode.NORMAL; this.description = description; this.initScript = initScript; this.tmpDir = tmpDir; this.userData = StringUtils.trimToEmpty(userData); this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.jvmopts = jvmopts; this.stopOnTerminate = stopOnTerminate; this.subnetId = subnetId; this.tags = tags; this.idleTerminationMinutes = idleTerminationMinutes; this.usePrivateDnsName = usePrivateDnsName; this.associatePublicIp = associatePublicIp; this.connectUsingPublicIp = connectUsingPublicIp; this.useDedicatedTenancy = useDedicatedTenancy; this.connectBySSHProcess = connectBySSHProcess; this.monitoring = monitoring; this.nextSubnet = 0; if (null == instanceCapStr || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } try { this.launchTimeout = Integer.parseInt(launchTimeoutStr); } catch (NumberFormatException nfe) { this.launchTimeout = Integer.MAX_VALUE; } this.iamInstanceProfile = iamInstanceProfile; this.deleteRootOnTermination = deleteRootOnTermination; this.useEphemeralDevices = useEphemeralDevices; this.customDeviceMapping = customDeviceMapping; readResolve(); // initialize } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, connectUsingPublicIp, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false); } /** * Backward compatible constructor for reloading previous version data */ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String slaveCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null); } public boolean isConnectBySSHProcess() { // See // src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html return connectBySSHProcess; } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public Node.Mode getMode() { return mode; } public String getDisplayName() { return description + " (" + ami + ")"; } String getZone() { return zone; } public String getSecurityGroupString() { return securityGroups; } public Set<String> getSecurityGroupSet() { return securityGroupSet; } public Set<String> parseSecurityGroups() { if (securityGroups == null || "".equals(securityGroups.trim())) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*"))); } } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2AbstractSlave.toNumExecutors(type); } } public int getSshPort() { try { String sshPort = ""; if (amiType.isUnix()) { sshPort = ((UnixData) amiType).getSshPort(); } return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : ""; } public String getSlaveCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getSlaveCommandPrefix() : ""; } public String chooseSubnetId() { if (StringUtils.isBlank(subnetId)) { return null; } else { String[] subnetIdList= getSubnetId().split(" "); // Round-robin subnet selection. String subnet = subnetIdList[nextSubnet]; currentSubnetId = subnet; nextSubnet = (nextSubnet + 1) % subnetIdList.length; return subnet; } } public String getSubnetId() { return subnetId; } public String getCurrentSubnetId() { return currentSubnetId; } public boolean getAssociatePublicIp() { return associatePublicIp; } public boolean isConnectUsingPublicIp() { return connectUsingPublicIp; } public List<EC2Tag> getTags() { if (null == tags) return null; return Collections.unmodifiableList(tags); } public String getidleTerminationMinutes() { return idleTerminationMinutes; } public boolean getUseDedicatedTenancy() { return useDedicatedTenancy; } public Set<LabelAtom> getLabelSet() { return labelSet; } public String getAmi() { return ami; } public void setAmi(String ami) { this.ami = ami; } public AMITypeData getAmiType() { return amiType; } public void setAmiType(AMITypeData amiType) { this.amiType = amiType; } public int getInstanceCap() { return instanceCap; } public String getInstanceCapStr() { if (instanceCap == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(instanceCap); } } public String getSpotMaxBidPrice() { if (spotConfig == null) return null; return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice); } public String getIamInstanceProfile() { return iamInstanceProfile; } @Override public String toString() { return "SlaveTemplate{" + "ami='" + ami + '\'' + ", labels='" + labels + '\'' + '}'; } public enum ProvisionOptions { ALLOW_CREATE, FORCE_CREATE } /** * Provisions a new EC2 slave or starts a previously stopped on-demand instance. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public List<EC2AbstractSlave> provision(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { if (this.spotConfig != null) { if (provisionOptions.contains(ProvisionOptions.ALLOW_CREATE) || provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) return provisionSpot(number); return null; } return provisionOndemand(number, provisionOptions); } /** * Safely we can pickup only instance that is not known by Jenkins at all. */ private boolean checkInstance(Instance instance) { for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (node.getInstanceId().equals(instance.getInstanceId())) { logInstanceCheck(instance, ". false - found existing corresponding Jenkins slave: " + node.getInstanceId()); return false; } } logInstanceCheck(instance, " true - Instance is not connected to Jenkins"); return true; } private void logInstanceCheck(Instance instance, String message) { logProvisionInfo("checkInstance: " + instance.getInstanceId() + "." + message); } private boolean isSameIamInstanceProfile(Instance instance) { return StringUtils.isBlank(getIamInstanceProfile()) || (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())); } private boolean isTerminatingOrShuttindDown(String instanceStateName) { return instanceStateName.equalsIgnoreCase(InstanceStateName.Terminated.toString()) || instanceStateName.equalsIgnoreCase(InstanceStateName.ShuttingDown.toString()); } private void logProvisionInfo(String message) { LOGGER.info(this + ". " + message); } /** * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance. */ private List<EC2AbstractSlave> provisionOndemand(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); logProvisionInfo("Considering launching"); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, number).withInstanceType(type); riRequest.setEbsOptimized(ebsOptimized); riRequest.setMonitoring(monitoring); setupBlockDeviceMappings(riRequest.getBlockDeviceMappings()); if(stopOnTerminate){ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop"); }else{ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate"); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); diFilters.add(new Filter("instance-type").withValues(type.toString())); KeyPair keyPair = getKeyPair(ec2); riRequest.setUserData(Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8))); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } String subnetId = chooseSubnetId(); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (StringUtils.isNotBlank(subnetId)) { if (getAssociatePublicIp()) { net.setSubnetId(subnetId); } else { riRequest.setSubnetId(subnetId); } diFilters.add(new Filter("subnet-id").withValues(subnetId)); /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { riRequest.setSecurityGroupIds(groupIds); } diFilters.add(new Filter("instance.group-id").withValues(groupIds)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (!securityGroupSet.isEmpty()) { diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } } if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } HashSet<Tag> instTags = buildTags(EC2Cloud.EC2_SLAVE_TYPE_DEMAND); for (Tag tag : instTags) { diFilters.add(new Filter("tag:" + tag.getKey()).withValues(tag.getValue())); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diRequest.setFilters(diFilters); logProvisionInfo("Looking for existing instances with describe-instance: " + diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); List<Instance> orphans = findOrphans(diResult, number); if (orphans.isEmpty() && !provisionOptions.contains(ProvisionOptions.FORCE_CREATE) && !provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) { logProvisionInfo("No existing instance found - but cannot create new instance"); return null; } wakeOrphansUp(ec2, orphans); if (orphans.size() == number) { return toSlaves(orphans); } riRequest.setMaxCount(number - orphans.size()); if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } TagSpecification tagSpecification = new TagSpecification(); tagSpecification.setResourceType(ResourceType.Instance); tagSpecification.setTags(instTags); Set<TagSpecification> tagSpecifications = Collections.singleton(tagSpecification); riRequest.setTagSpecifications(tagSpecifications); // Have to create a new instance List<Instance> newInstances = ec2.runInstances(riRequest).getReservation().getInstances(); if (newInstances.isEmpty()) { logProvisionInfo("No new instances were created"); } newInstances.addAll(orphans); return toSlaves(newInstances); } private void wakeOrphansUp(AmazonEC2 ec2, List<Instance> orphans) { List<String> instances = new ArrayList<>(); for(Instance instance : orphans) { if (instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopping.toString()) || instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopped.toString())) { logProvisionInfo("Found stopped instances - will start it: " + instance); instances.add(instance.getInstanceId()); } else { // Should be pending or running at this point, just let it come up logProvisionInfo("Found existing pending or running: " + instance.getState().getName() + " instance: " + instance); } } if (!instances.isEmpty()) { StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logProvisionInfo("Result of starting stopped instances:" + siResult); } } private List<EC2AbstractSlave> toSlaves(List<Instance> newInstances) throws IOException { try { List<EC2AbstractSlave> slaves = new ArrayList<>(newInstances.size()); for (Instance instance : newInstances) { slaves.add(newOndemandSlave(instance)); logProvisionInfo("Return instance: " + instance); } return slaves; } catch (FormException e) { throw new AssertionError(e); // we should have discovered all // configuration issues upfront } } private List<Instance> findOrphans(DescribeInstancesResult diResult, int number) { List<Instance> orphans = new ArrayList<>(); int count = 0; for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (!isSameIamInstanceProfile(instance)) { logInstanceCheck(instance, ". false - IAM Instance profile does not match: " + instance.getIamInstanceProfile()); continue; } if (isTerminatingOrShuttindDown(instance.getState().getName())) { logInstanceCheck(instance, ". false - Instance is terminated or shutting down"); continue; } if (checkInstance(instance)) { logProvisionInfo("Found existing instance: " + instance); orphans.add(instance); count++; } if (count == number) { return orphans; } } } return orphans; } private void setupRootDevice(List<BlockDeviceMapping> deviceMappings) { if (deleteRootOnTermination && getImage().getRootDeviceType().equals("ebs")) { // get the root device (only one expected in the blockmappings) final List<BlockDeviceMapping> rootDeviceMappings = getAmiBlockDeviceMappings(); BlockDeviceMapping rootMapping = null; for (final BlockDeviceMapping deviceMapping : rootDeviceMappings) { System.out.println("AMI had " + deviceMapping.getDeviceName()); System.out.println(deviceMapping.getEbs()); rootMapping = deviceMapping; break; } // Check if the root device is already in the mapping and update it for (final BlockDeviceMapping mapping : deviceMappings) { System.out.println("Request had " + mapping.getDeviceName()); if (rootMapping.getDeviceName().equals(mapping.getDeviceName())) { mapping.getEbs().setDeleteOnTermination(Boolean.TRUE); return; } } // Create a shadow of the AMI mapping (doesn't like reusing rootMapping directly) BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(rootMapping.getDeviceName()); EbsBlockDevice newEbs = new EbsBlockDevice(); newEbs.setDeleteOnTermination(Boolean.TRUE); newMapping.setEbs(newEbs); deviceMappings.add(0, newMapping); } } private List<BlockDeviceMapping> getNewEphemeralDeviceMapping() { final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings(); final Set<String> occupiedDevices = new HashSet<String>(); for (final BlockDeviceMapping mapping : oldDeviceMapping) { occupiedDevices.add(mapping.getDeviceName()); } final List<String> available = new ArrayList<String>( Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3")); final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4); for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) { final String deviceName = String.format("/dev/xvd%s", suffix); if (occupiedDevices.contains(deviceName)) continue; final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName( available.get(0)); newDeviceMapping.add(newMapping); available.remove(0); } return newDeviceMapping; } private void setupEphemeralDeviceMapping(List<BlockDeviceMapping> deviceMappings) { // Don't wipe out pre-existing mappings deviceMappings.addAll(getNewEphemeralDeviceMapping()); } private List<BlockDeviceMapping> getAmiBlockDeviceMappings() { /* * AmazonEC2#describeImageAttribute does not work due to a bug * https://forums.aws.amazon.com/message.jspa?messageID=231972 */ return getImage().getBlockDeviceMappings(); } private Image getImage() { DescribeImagesRequest request = new DescribeImagesRequest().withImageIds(ami); for (final Image image : getParent().connect().describeImages(request).getImages()) { if (ami.equals(image.getImageId())) { return image; } } throw new AmazonClientException("Unable to find AMI " + ami); } private void setupCustomDeviceMapping(List<BlockDeviceMapping> deviceMappings) { if (StringUtils.isNotBlank(customDeviceMapping)) { deviceMappings.addAll(DeviceMappingParser.parse(customDeviceMapping)); } } /** * Provision a new slave for an EC2 spot instance to call back to Jenkins */ private List<EC2AbstractSlave> provisionSpot(int number) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); try { LOGGER.info("Launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest(); // Validate spot bid before making the request if (getSpotMaxBidPrice() == null) { throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice()); } spotRequest.setSpotPrice(getSpotMaxBidPrice()); spotRequest.setInstanceCount(number); LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId(ami); launchSpecification.setInstanceType(type); launchSpecification.setEbsOptimized(ebsOptimized); launchSpecification.setMonitoringEnabled(monitoring); if (StringUtils.isNotBlank(getZone())) { SpotPlacement placement = new SpotPlacement(getZone()); launchSpecification.setPlacement(placement); } InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); String subnetId = chooseSubnetId(); if (StringUtils.isNotBlank(subnetId)) { if (getAssociatePublicIp()) { net.setSubnetId(subnetId); } else { launchSpecification.setSubnetId(subnetId); } /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>(); for (String group_id : groupIds) { GroupIdentifier group = new GroupIdentifier(); group.setGroupId(group_id); groups.add(group); } if (!groups.isEmpty()) launchSpecification.setAllSecurityGroups(groups); } } } } else { /* No subnet: we can use standard security groups by name */ if (!securityGroupSet.isEmpty()) { launchSpecification.setSecurityGroups(securityGroupSet); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); launchSpecification.setUserData(userDataString); launchSpecification.setKeyName(keyPair.getKeyName()); launchSpecification.setInstanceType(type.toString()); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); launchSpecification.withNetworkInterfaces(net); } HashSet<Tag> instTags = buildTags(EC2Cloud.EC2_SLAVE_TYPE_SPOT); if (StringUtils.isNotBlank(getIamInstanceProfile())) { launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } setupBlockDeviceMappings(launchSpecification.getBlockDeviceMappings()); spotRequest.setLaunchSpecification(launchSpecification); // Make the request for a new Spot instance RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest); List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests(); if (reqInstances.isEmpty()) { throw new AmazonClientException("No spot instances found"); } List<EC2AbstractSlave> slaves = new ArrayList<>(reqInstances.size()); for(SpotInstanceRequest spotInstReq : reqInstances) { if (spotInstReq == null) { throw new AmazonClientException("Spot instance request is null"); } String slaveName = spotInstReq.getSpotInstanceRequestId(); // Now that we have our Spot request, we can set tags on it updateRemoteTags(ec2, instTags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId()); // That was a remote request - we should also update our local instance data spotInstReq.setTags(instTags); LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); slaves.add(newSpotSlave(spotInstReq, slaveName)); } return slaves; } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private void setupBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { setupRootDevice(blockDeviceMappings); if (useEphemeralDevices) { setupEphemeralDeviceMapping(blockDeviceMappings); } else { setupCustomDeviceMapping(blockDeviceMappings); } } private HashSet<Tag> buildTags(String slaveType) { boolean hasCustomTypeTag = false; HashSet<Tag> instTags = new HashSet<Tag>(); if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue( slaveType, description))); } return instTags; } protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException { return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript, tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName, useDedicatedTenancy, getLaunchTimeout(), amiType); } protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException { return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript, tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name, usePrivateDnsName, getLaunchTimeout(), amiType); } /** * Get a KeyPair from the configured information for the slave template */ private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } return keyPair; } /** * Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by * catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound * * @param ec2 * @param instTags * @param catchErrorCode * @param params * @throws InterruptedException */ private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> instTags, String catchErrorCode, String... params) throws InterruptedException { for (int i = 0; i < 5; i++) { try { CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(params).setTags(instTags); ec2.createTags(tagRequest); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals(catchErrorCode)) { Thread.sleep(5000); continue; } LOGGER.log(Level.SEVERE, e.getErrorMessage(), e); } } } /** * Get a list of security group ids for the slave */ private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException { List<String> groupIds = new ArrayList<String>(); DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2); if (groupResult.getSecurityGroups().size() == 0) { groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2); } for (SecurityGroup group : groupResult.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getCurrentSubnetId())); DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest(); subnetReq.withFilters(filters); DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq); List<Subnet> subnets = subnetResult.getSubnets(); if (subnets != null && !subnets.isEmpty()) { groupIds.add(group.getGroupId()); } } } if (securityGroupSet.size() != groupIds.size()) { throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context"); } return groupIds; } private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) { DescribeSecurityGroupsRequest groupReq = new DescribeSecurityGroupsRequest(); groupReq.withFilters(new Filter(filterName).withValues(filterValues)); return ec2.describeSecurityGroups(groupReq); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one. */ public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Attaching to " + instanceId); LOGGER.info("Attaching to " + instanceId); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(Collections.singletonList(instanceId)); Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0); return newOndemandSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); labelSet = Label.parse(labels); securityGroupSet = parseSecurityGroups(); /** * In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not * enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with * no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a * configuration has a cap of zero for a template, no instances will be launched from that template. Since there * is no practical value of intentionally setting the cap to zero, this block will override such a setting to a * value that means 'no cap'. */ if (instanceCap == 0) { instanceCap = Integer.MAX_VALUE; } if (amiType == null) { amiType = new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort); } return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Jenkins.getInstance().getDescriptor(getClass()); } public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; } public String getLaunchTimeoutStr() { if (launchTimeout == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(launchTimeout); } } public boolean isWindowsSlave() { return amiType.isWindows(); } public boolean isUnixSlave() { return amiType.isUnix(); } public Secret getAdminPassword() { return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString(""); } public boolean isUseHTTPS() { return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS(); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { @Override public String getDisplayName() { return null; } public List<Descriptor<AMITypeData>> getAMITypeDescriptors() { return Jenkins.getInstance().<AMITypeData, Descriptor<AMITypeData>> getDescriptorList(AMITypeData.class); } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName); return p; } @Restricted(NoExternalUse.class) public FormValidation doCheckRemoteAdmin(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckTmpDir(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckJvmopts(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String ec2endpoint, @QueryParameter String region, final @QueryParameter String ami) throws IOException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2; if (region != null) { ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); } else { ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint)); } if (ec2 != null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); DescribeImagesRequest request = new DescribeImagesRequest(); request.setImageIds(images); request.setOwners(owners); request.setExecutableUsers(users); List<Image> img = ec2.describeImages(request).getImages(); if (img == null || img.isEmpty()) { // de-registered AMI causes an empty list to be // returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: " + ami); } String ownerAlias = img.get(0).getImageOwnerAlias(); return FormValidation.ok(img.get(0).getImageLocation() + (ownerAlias != null ? " by " + ownerAlias : "")); } catch (AmazonClientException e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) { if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim().isEmpty())) { return FormValidation.warning("You may want to assign labels to this node;" + " it's marked to only run jobs that are exclusively tied to itself or a label."); } return FormValidation.ok(); } public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= -59) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Idle Termination time must be a greater than -59 (or null)"); } public FormValidation doCheckInstanceCapStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val > 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("InstanceCap must be a non-negative integer (or null)"); } public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Launch Timeout must be a non-negative integer (or null)"); } public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region) throws IOException, ServletException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); return EC2AbstractSlave.fillZoneItems(credentialsProvider, region); } /* * Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */ public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) { if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) { return FormValidation.ok(); } return FormValidation.error("Not a correct bid price"); } // Retrieve the availability zones for the region private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) { ArrayList<String> availabilityZones = new ArrayList<String>(); DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones(); List<AvailabilityZone> zoneList = zones.getAvailabilityZones(); for (AvailabilityZone z : zoneList) { availabilityZones.add(z.getZoneName()); } return availabilityZones; } /* * Check the current Spot price of the selected instance type for the selected region */ public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region, @QueryParameter String type, @QueryParameter String zone) throws IOException, ServletException { String cp = ""; String zoneStr = ""; // Connect to the EC2 cloud with the access id, secret key, and // region queried from the created cloud AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); if (ec2 != null) { try { // Build a new price history request with the currently // selected type DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest(); // If a zone is specified, set the availability zone in the // request // Else, proceed with no availability zone which will result // with the cheapest Spot price if (getAvailabilityZones(ec2).contains(zone)) { request.setAvailabilityZone(zone); zoneStr = zone + " availability zone"; } else { zoneStr = region + " region"; } /* * Iterate through the AWS instance types to see if can find a match for the databound String type. * This is necessary because the AWS API needs the instance type string formatted a particular way * to retrieve prices and the form gives us the strings in a different format. For example "T1Micro" * vs "t1.micro". */ InstanceType ec2Type = null; for (InstanceType it : InstanceType.values()) { if (it.name().equals(type)) { ec2Type = it; break; } } /* * If the type string cannot be matched with an instance type, throw a Form error */ if (ec2Type == null) { return FormValidation.error("Could not resolve instance type: " + type); } Collection<String> instanceType = new ArrayList<String>(); instanceType.add(ec2Type.toString()); request.setInstanceTypes(instanceType); request.setStartTime(new Date()); // Retrieve the price history request result and store the // current price DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request); if (!result.getSpotPriceHistory().isEmpty()) { SpotPrice currentPrice = result.getSpotPriceHistory().get(0); cp = currentPrice.getSpotPrice(); } } catch (AmazonServiceException e) { return FormValidation.error(e.getMessage()); } } /* * If we could not return the current price of the instance display an error Else, remove the additional * zeros from the current price and return it to the interface in the form of a message */ if (cp.isEmpty()) { return FormValidation.error("Could not retrieve current Spot price"); } else { cp = cp.substring(0, cp.length() - 3); return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp); } } } }
src/main/java/hudson/plugins/ec2/SlaveTemplate.java
/* * The MIT License * * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package hudson.plugins.ec2; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.slaves.iterators.api.NodeIterator; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; import hudson.Extension; import hudson.Util; import hudson.model.*; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtom; import hudson.plugins.ec2.util.DeviceMappingParser; import hudson.util.FormValidation; import hudson.util.ListBoxModel; /** * Template of {@link EC2AbstractSlave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName()); public String ami; public final String description; public final String zone; public final SpotConfiguration spotConfig; public final String securityGroups; public final String remoteFS; public final InstanceType type; public final boolean ebsOptimized; public final boolean monitoring; public final String labels; public final Node.Mode mode; public final String initScript; public final String tmpDir; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String jvmopts; public final String subnetId; public final String idleTerminationMinutes; public final String iamInstanceProfile; public final boolean deleteRootOnTermination; public final boolean useEphemeralDevices; public final String customDeviceMapping; public int instanceCap; public final boolean stopOnTerminate; private final List<EC2Tag> tags; public final boolean usePrivateDnsName; public final boolean associatePublicIp; protected transient EC2Cloud parent; public final boolean useDedicatedTenancy; public AMITypeData amiType; public int launchTimeout; public boolean connectBySSHProcess; public final boolean connectUsingPublicIp; public int nextSubnet; public String currentSubnetId; private transient/* almost final */Set<LabelAtom> labelSet; private transient/* almost final */Set<String> securityGroupSet; /* * Necessary to handle reading from old configurations. The UnixData object is created in readResolve() */ @Deprecated public transient String sshPort; @Deprecated public transient String rootCommandPrefix; @Deprecated public transient String slaveCommandPrefix; @DataBoundConstructor public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp, boolean monitoring) { if(StringUtils.isNotBlank(remoteAdmin) || StringUtils.isNotBlank(jvmopts) || StringUtils.isNotBlank(tmpDir)){ LOGGER.log(Level.FINE, "As remoteAdmin, jvmopts or tmpDir is not blank, we must ensure the user has RUN_SCRIPTS rights."); Jenkins j = Jenkins.getInstance(); if(j != null){ j.checkPermission(Jenkins.RUN_SCRIPTS); } } this.ami = ami; this.zone = zone; this.spotConfig = spotConfig; this.securityGroups = securityGroups; this.remoteFS = remoteFS; this.amiType = amiType; this.type = type; this.ebsOptimized = ebsOptimized; this.labels = Util.fixNull(labelString); this.mode = mode != null ? mode : Node.Mode.NORMAL; this.description = description; this.initScript = initScript; this.tmpDir = tmpDir; this.userData = StringUtils.trimToEmpty(userData); this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.jvmopts = jvmopts; this.stopOnTerminate = stopOnTerminate; this.subnetId = subnetId; this.tags = tags; this.idleTerminationMinutes = idleTerminationMinutes; this.usePrivateDnsName = usePrivateDnsName; this.associatePublicIp = associatePublicIp; this.connectUsingPublicIp = connectUsingPublicIp; this.useDedicatedTenancy = useDedicatedTenancy; this.connectBySSHProcess = connectBySSHProcess; this.monitoring = monitoring; this.nextSubnet = 0; if (null == instanceCapStr || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } try { this.launchTimeout = Integer.parseInt(launchTimeoutStr); } catch (NumberFormatException nfe) { this.launchTimeout = Integer.MAX_VALUE; } this.iamInstanceProfile = iamInstanceProfile; this.deleteRootOnTermination = deleteRootOnTermination; this.useEphemeralDevices = useEphemeralDevices; this.customDeviceMapping = customDeviceMapping; readResolve(); // initialize } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, connectUsingPublicIp, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false); } /** * Backward compatible constructor for reloading previous version data */ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String slaveCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null); } public boolean isConnectBySSHProcess() { // See // src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html return connectBySSHProcess; } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public Node.Mode getMode() { return mode; } public String getDisplayName() { return description + " (" + ami + ")"; } String getZone() { return zone; } public String getSecurityGroupString() { return securityGroups; } public Set<String> getSecurityGroupSet() { return securityGroupSet; } public Set<String> parseSecurityGroups() { if (securityGroups == null || "".equals(securityGroups.trim())) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*"))); } } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2AbstractSlave.toNumExecutors(type); } } public int getSshPort() { try { String sshPort = ""; if (amiType.isUnix()) { sshPort = ((UnixData) amiType).getSshPort(); } return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : ""; } public String getSlaveCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getSlaveCommandPrefix() : ""; } public String chooseSubnetId() { if (StringUtils.isBlank(subnetId)) { return null; } else { String[] subnetIdList= getSubnetId().split(" "); // Round-robin subnet selection. String subnet = subnetIdList[nextSubnet]; currentSubnetId = subnet; nextSubnet = (nextSubnet + 1) % subnetIdList.length; return subnet; } } public String getSubnetId() { return subnetId; } public String getCurrentSubnetId() { return currentSubnetId; } public boolean getAssociatePublicIp() { return associatePublicIp; } public boolean isConnectUsingPublicIp() { return connectUsingPublicIp; } public List<EC2Tag> getTags() { if (null == tags) return null; return Collections.unmodifiableList(tags); } public String getidleTerminationMinutes() { return idleTerminationMinutes; } public boolean getUseDedicatedTenancy() { return useDedicatedTenancy; } public Set<LabelAtom> getLabelSet() { return labelSet; } public String getAmi() { return ami; } public void setAmi(String ami) { this.ami = ami; } public AMITypeData getAmiType() { return amiType; } public void setAmiType(AMITypeData amiType) { this.amiType = amiType; } public int getInstanceCap() { return instanceCap; } public String getInstanceCapStr() { if (instanceCap == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(instanceCap); } } public String getSpotMaxBidPrice() { if (spotConfig == null) return null; return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice); } public String getIamInstanceProfile() { return iamInstanceProfile; } @Override public String toString() { return "SlaveTemplate{" + "ami='" + ami + '\'' + ", labels='" + labels + '\'' + '}'; } public enum ProvisionOptions { ALLOW_CREATE, FORCE_CREATE } /** * Provisions a new EC2 slave or starts a previously stopped on-demand instance. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public List<EC2AbstractSlave> provision(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { if (this.spotConfig != null) { if (provisionOptions.contains(ProvisionOptions.ALLOW_CREATE) || provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) return provisionSpot(number); return null; } return provisionOndemand(number, provisionOptions); } /** * Safely we can pickup only instance that is not known by Jenkins at all. */ private boolean checkInstance(Instance instance) { for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (node.getInstanceId().equals(instance.getInstanceId())) { logInstanceCheck(instance, ". false - found existing corresponding Jenkins slave: " + node.getInstanceId()); return false; } } logInstanceCheck(instance, " true - Instance is not connected to Jenkins"); return true; } private void logInstanceCheck(Instance instance, String message) { logProvisionInfo("checkInstance: " + instance.getInstanceId() + "." + message); } private boolean isSameIamInstanceProfile(Instance instance) { return StringUtils.isBlank(getIamInstanceProfile()) || (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())); } private boolean isTerminatingOrShuttindDown(String instanceStateName) { return instanceStateName.equalsIgnoreCase(InstanceStateName.Terminated.toString()) || instanceStateName.equalsIgnoreCase(InstanceStateName.ShuttingDown.toString()); } private void logProvisionInfo(String message) { LOGGER.info(this + ". " + message); } /** * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance. */ private List<EC2AbstractSlave> provisionOndemand(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); logProvisionInfo("Considering launching"); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, number).withInstanceType(type); riRequest.setEbsOptimized(ebsOptimized); riRequest.setMonitoring(monitoring); setupBlockDeviceMappings(riRequest.getBlockDeviceMappings()); if(stopOnTerminate){ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop"); }else{ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate"); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); diFilters.add(new Filter("instance-type").withValues(type.toString())); KeyPair keyPair = getKeyPair(ec2); riRequest.setUserData(Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8))); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } String subnetId = chooseSubnetId(); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (StringUtils.isNotBlank(subnetId)) { if (getAssociatePublicIp()) { net.setSubnetId(subnetId); } else { reRequest.setSubnetId(subnetId); } diFilters.add(new Filter("subnet-id").withValues(subnetId)); /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { riRequest.setSecurityGroupIds(groupIds); } diFilters.add(new Filter("instance.group-id").withValues(groupIds)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (!securityGroupSet.isEmpty()) { diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } } if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } HashSet<Tag> instTags = buildTags(EC2Cloud.EC2_SLAVE_TYPE_DEMAND); for (Tag tag : instTags) { diFilters.add(new Filter("tag:" + tag.getKey()).withValues(tag.getValue())); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diRequest.setFilters(diFilters); logProvisionInfo("Looking for existing instances with describe-instance: " + diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); List<Instance> orphans = findOrphans(diResult, number); if (orphans.isEmpty() && !provisionOptions.contains(ProvisionOptions.FORCE_CREATE) && !provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) { logProvisionInfo("No existing instance found - but cannot create new instance"); return null; } wakeOrphansUp(ec2, orphans); if (orphans.size() == number) { return toSlaves(orphans); } riRequest.setMaxCount(number - orphans.size()); if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } TagSpecification tagSpecification = new TagSpecification(); tagSpecification.setResourceType(ResourceType.Instance); tagSpecification.setTags(instTags); Set<TagSpecification> tagSpecifications = Collections.singleton(tagSpecification); riRequest.setTagSpecifications(tagSpecifications); // Have to create a new instance List<Instance> newInstances = ec2.runInstances(riRequest).getReservation().getInstances(); if (newInstances.isEmpty()) { logProvisionInfo("No new instances were created"); } newInstances.addAll(orphans); return toSlaves(newInstances); } private void wakeOrphansUp(AmazonEC2 ec2, List<Instance> orphans) { List<String> instances = new ArrayList<>(); for(Instance instance : orphans) { if (instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopping.toString()) || instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopped.toString())) { logProvisionInfo("Found stopped instances - will start it: " + instance); instances.add(instance.getInstanceId()); } else { // Should be pending or running at this point, just let it come up logProvisionInfo("Found existing pending or running: " + instance.getState().getName() + " instance: " + instance); } } if (!instances.isEmpty()) { StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logProvisionInfo("Result of starting stopped instances:" + siResult); } } private List<EC2AbstractSlave> toSlaves(List<Instance> newInstances) throws IOException { try { List<EC2AbstractSlave> slaves = new ArrayList<>(newInstances.size()); for (Instance instance : newInstances) { slaves.add(newOndemandSlave(instance)); logProvisionInfo("Return instance: " + instance); } return slaves; } catch (FormException e) { throw new AssertionError(e); // we should have discovered all // configuration issues upfront } } private List<Instance> findOrphans(DescribeInstancesResult diResult, int number) { List<Instance> orphans = new ArrayList<>(); int count = 0; for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (!isSameIamInstanceProfile(instance)) { logInstanceCheck(instance, ". false - IAM Instance profile does not match: " + instance.getIamInstanceProfile()); continue; } if (isTerminatingOrShuttindDown(instance.getState().getName())) { logInstanceCheck(instance, ". false - Instance is terminated or shutting down"); continue; } if (checkInstance(instance)) { logProvisionInfo("Found existing instance: " + instance); orphans.add(instance); count++; } if (count == number) { return orphans; } } } return orphans; } private void setupRootDevice(List<BlockDeviceMapping> deviceMappings) { if (deleteRootOnTermination && getImage().getRootDeviceType().equals("ebs")) { // get the root device (only one expected in the blockmappings) final List<BlockDeviceMapping> rootDeviceMappings = getAmiBlockDeviceMappings(); BlockDeviceMapping rootMapping = null; for (final BlockDeviceMapping deviceMapping : rootDeviceMappings) { System.out.println("AMI had " + deviceMapping.getDeviceName()); System.out.println(deviceMapping.getEbs()); rootMapping = deviceMapping; break; } // Check if the root device is already in the mapping and update it for (final BlockDeviceMapping mapping : deviceMappings) { System.out.println("Request had " + mapping.getDeviceName()); if (rootMapping.getDeviceName().equals(mapping.getDeviceName())) { mapping.getEbs().setDeleteOnTermination(Boolean.TRUE); return; } } // Create a shadow of the AMI mapping (doesn't like reusing rootMapping directly) BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(rootMapping.getDeviceName()); EbsBlockDevice newEbs = new EbsBlockDevice(); newEbs.setDeleteOnTermination(Boolean.TRUE); newMapping.setEbs(newEbs); deviceMappings.add(0, newMapping); } } private List<BlockDeviceMapping> getNewEphemeralDeviceMapping() { final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings(); final Set<String> occupiedDevices = new HashSet<String>(); for (final BlockDeviceMapping mapping : oldDeviceMapping) { occupiedDevices.add(mapping.getDeviceName()); } final List<String> available = new ArrayList<String>( Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3")); final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4); for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) { final String deviceName = String.format("/dev/xvd%s", suffix); if (occupiedDevices.contains(deviceName)) continue; final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName( available.get(0)); newDeviceMapping.add(newMapping); available.remove(0); } return newDeviceMapping; } private void setupEphemeralDeviceMapping(List<BlockDeviceMapping> deviceMappings) { // Don't wipe out pre-existing mappings deviceMappings.addAll(getNewEphemeralDeviceMapping()); } private List<BlockDeviceMapping> getAmiBlockDeviceMappings() { /* * AmazonEC2#describeImageAttribute does not work due to a bug * https://forums.aws.amazon.com/message.jspa?messageID=231972 */ return getImage().getBlockDeviceMappings(); } private Image getImage() { DescribeImagesRequest request = new DescribeImagesRequest().withImageIds(ami); for (final Image image : getParent().connect().describeImages(request).getImages()) { if (ami.equals(image.getImageId())) { return image; } } throw new AmazonClientException("Unable to find AMI " + ami); } private void setupCustomDeviceMapping(List<BlockDeviceMapping> deviceMappings) { if (StringUtils.isNotBlank(customDeviceMapping)) { deviceMappings.addAll(DeviceMappingParser.parse(customDeviceMapping)); } } /** * Provision a new slave for an EC2 spot instance to call back to Jenkins */ private List<EC2AbstractSlave> provisionSpot(int number) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); try { LOGGER.info("Launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest(); // Validate spot bid before making the request if (getSpotMaxBidPrice() == null) { throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice()); } spotRequest.setSpotPrice(getSpotMaxBidPrice()); spotRequest.setInstanceCount(number); LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId(ami); launchSpecification.setInstanceType(type); launchSpecification.setEbsOptimized(ebsOptimized); launchSpecification.setMonitoringEnabled(monitoring); if (StringUtils.isNotBlank(getZone())) { SpotPlacement placement = new SpotPlacement(getZone()); launchSpecification.setPlacement(placement); } InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); String subnetId = chooseSubnetId(); if (StringUtils.isNotBlank(subnetId)) { if (getAssociatePublicIp()) { net.setSubnetId(subnetId); } else { launchSpecification.setSubnetId(subnetId); } /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>(); for (String group_id : groupIds) { GroupIdentifier group = new GroupIdentifier(); group.setGroupId(group_id); groups.add(group); } if (!groups.isEmpty()) launchSpecification.setAllSecurityGroups(groups); } } } } else { /* No subnet: we can use standard security groups by name */ if (!securityGroupSet.isEmpty()) { launchSpecification.setSecurityGroups(securityGroupSet); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); launchSpecification.setUserData(userDataString); launchSpecification.setKeyName(keyPair.getKeyName()); launchSpecification.setInstanceType(type.toString()); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); launchSpecification.withNetworkInterfaces(net); } HashSet<Tag> instTags = buildTags(EC2Cloud.EC2_SLAVE_TYPE_SPOT); if (StringUtils.isNotBlank(getIamInstanceProfile())) { launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } setupBlockDeviceMappings(launchSpecification.getBlockDeviceMappings()); spotRequest.setLaunchSpecification(launchSpecification); // Make the request for a new Spot instance RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest); List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests(); if (reqInstances.isEmpty()) { throw new AmazonClientException("No spot instances found"); } List<EC2AbstractSlave> slaves = new ArrayList<>(reqInstances.size()); for(SpotInstanceRequest spotInstReq : reqInstances) { if (spotInstReq == null) { throw new AmazonClientException("Spot instance request is null"); } String slaveName = spotInstReq.getSpotInstanceRequestId(); // Now that we have our Spot request, we can set tags on it updateRemoteTags(ec2, instTags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId()); // That was a remote request - we should also update our local instance data spotInstReq.setTags(instTags); LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); slaves.add(newSpotSlave(spotInstReq, slaveName)); } return slaves; } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private void setupBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { setupRootDevice(blockDeviceMappings); if (useEphemeralDevices) { setupEphemeralDeviceMapping(blockDeviceMappings); } else { setupCustomDeviceMapping(blockDeviceMappings); } } private HashSet<Tag> buildTags(String slaveType) { boolean hasCustomTypeTag = false; HashSet<Tag> instTags = new HashSet<Tag>(); if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue( slaveType, description))); } return instTags; } protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException { return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript, tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName, useDedicatedTenancy, getLaunchTimeout(), amiType); } protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException { return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript, tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name, usePrivateDnsName, getLaunchTimeout(), amiType); } /** * Get a KeyPair from the configured information for the slave template */ private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } return keyPair; } /** * Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by * catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound * * @param ec2 * @param instTags * @param catchErrorCode * @param params * @throws InterruptedException */ private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> instTags, String catchErrorCode, String... params) throws InterruptedException { for (int i = 0; i < 5; i++) { try { CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(params).setTags(instTags); ec2.createTags(tagRequest); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals(catchErrorCode)) { Thread.sleep(5000); continue; } LOGGER.log(Level.SEVERE, e.getErrorMessage(), e); } } } /** * Get a list of security group ids for the slave */ private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException { List<String> groupIds = new ArrayList<String>(); DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2); if (groupResult.getSecurityGroups().size() == 0) { groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2); } for (SecurityGroup group : groupResult.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getCurrentSubnetId())); DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest(); subnetReq.withFilters(filters); DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq); List<Subnet> subnets = subnetResult.getSubnets(); if (subnets != null && !subnets.isEmpty()) { groupIds.add(group.getGroupId()); } } } if (securityGroupSet.size() != groupIds.size()) { throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context"); } return groupIds; } private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) { DescribeSecurityGroupsRequest groupReq = new DescribeSecurityGroupsRequest(); groupReq.withFilters(new Filter(filterName).withValues(filterValues)); return ec2.describeSecurityGroups(groupReq); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one. */ public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Attaching to " + instanceId); LOGGER.info("Attaching to " + instanceId); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(Collections.singletonList(instanceId)); Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0); return newOndemandSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); labelSet = Label.parse(labels); securityGroupSet = parseSecurityGroups(); /** * In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not * enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with * no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a * configuration has a cap of zero for a template, no instances will be launched from that template. Since there * is no practical value of intentionally setting the cap to zero, this block will override such a setting to a * value that means 'no cap'. */ if (instanceCap == 0) { instanceCap = Integer.MAX_VALUE; } if (amiType == null) { amiType = new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort); } return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Jenkins.getInstance().getDescriptor(getClass()); } public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; } public String getLaunchTimeoutStr() { if (launchTimeout == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(launchTimeout); } } public boolean isWindowsSlave() { return amiType.isWindows(); } public boolean isUnixSlave() { return amiType.isUnix(); } public Secret getAdminPassword() { return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString(""); } public boolean isUseHTTPS() { return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS(); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { @Override public String getDisplayName() { return null; } public List<Descriptor<AMITypeData>> getAMITypeDescriptors() { return Jenkins.getInstance().<AMITypeData, Descriptor<AMITypeData>> getDescriptorList(AMITypeData.class); } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName); return p; } @Restricted(NoExternalUse.class) public FormValidation doCheckRemoteAdmin(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckTmpDir(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckJvmopts(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String ec2endpoint, @QueryParameter String region, final @QueryParameter String ami) throws IOException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2; if (region != null) { ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); } else { ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint)); } if (ec2 != null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); DescribeImagesRequest request = new DescribeImagesRequest(); request.setImageIds(images); request.setOwners(owners); request.setExecutableUsers(users); List<Image> img = ec2.describeImages(request).getImages(); if (img == null || img.isEmpty()) { // de-registered AMI causes an empty list to be // returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: " + ami); } String ownerAlias = img.get(0).getImageOwnerAlias(); return FormValidation.ok(img.get(0).getImageLocation() + (ownerAlias != null ? " by " + ownerAlias : "")); } catch (AmazonClientException e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) { if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim().isEmpty())) { return FormValidation.warning("You may want to assign labels to this node;" + " it's marked to only run jobs that are exclusively tied to itself or a label."); } return FormValidation.ok(); } public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= -59) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Idle Termination time must be a greater than -59 (or null)"); } public FormValidation doCheckInstanceCapStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val > 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("InstanceCap must be a non-negative integer (or null)"); } public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Launch Timeout must be a non-negative integer (or null)"); } public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region) throws IOException, ServletException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); return EC2AbstractSlave.fillZoneItems(credentialsProvider, region); } /* * Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */ public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) { if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) { return FormValidation.ok(); } return FormValidation.error("Not a correct bid price"); } // Retrieve the availability zones for the region private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) { ArrayList<String> availabilityZones = new ArrayList<String>(); DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones(); List<AvailabilityZone> zoneList = zones.getAvailabilityZones(); for (AvailabilityZone z : zoneList) { availabilityZones.add(z.getZoneName()); } return availabilityZones; } /* * Check the current Spot price of the selected instance type for the selected region */ public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region, @QueryParameter String type, @QueryParameter String zone) throws IOException, ServletException { String cp = ""; String zoneStr = ""; // Connect to the EC2 cloud with the access id, secret key, and // region queried from the created cloud AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); if (ec2 != null) { try { // Build a new price history request with the currently // selected type DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest(); // If a zone is specified, set the availability zone in the // request // Else, proceed with no availability zone which will result // with the cheapest Spot price if (getAvailabilityZones(ec2).contains(zone)) { request.setAvailabilityZone(zone); zoneStr = zone + " availability zone"; } else { zoneStr = region + " region"; } /* * Iterate through the AWS instance types to see if can find a match for the databound String type. * This is necessary because the AWS API needs the instance type string formatted a particular way * to retrieve prices and the form gives us the strings in a different format. For example "T1Micro" * vs "t1.micro". */ InstanceType ec2Type = null; for (InstanceType it : InstanceType.values()) { if (it.name().equals(type)) { ec2Type = it; break; } } /* * If the type string cannot be matched with an instance type, throw a Form error */ if (ec2Type == null) { return FormValidation.error("Could not resolve instance type: " + type); } Collection<String> instanceType = new ArrayList<String>(); instanceType.add(ec2Type.toString()); request.setInstanceTypes(instanceType); request.setStartTime(new Date()); // Retrieve the price history request result and store the // current price DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request); if (!result.getSpotPriceHistory().isEmpty()) { SpotPrice currentPrice = result.getSpotPriceHistory().get(0); cp = currentPrice.getSpotPrice(); } } catch (AmazonServiceException e) { return FormValidation.error(e.getMessage()); } } /* * If we could not return the current price of the instance display an error Else, remove the additional * zeros from the current price and return it to the interface in the form of a message */ if (cp.isEmpty()) { return FormValidation.error("Could not retrieve current Spot price"); } else { cp = cp.substring(0, cp.length() - 3); return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp); } } } }
Fix variable name typo.
src/main/java/hudson/plugins/ec2/SlaveTemplate.java
Fix variable name typo.
<ide><path>rc/main/java/hudson/plugins/ec2/SlaveTemplate.java <ide> if (getAssociatePublicIp()) { <ide> net.setSubnetId(subnetId); <ide> } else { <del> reRequest.setSubnetId(subnetId); <add> riRequest.setSubnetId(subnetId); <ide> } <ide> <ide> diFilters.add(new Filter("subnet-id").withValues(subnetId));
Java
apache-2.0
4cda90622e87dd3c6e4f9772397e93ad994f6737
0
phax/ph-schematron,phax/ph-schematron
/** * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.schematron.supplementary; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Test; import com.helger.commons.io.resource.FileSystemResource; import com.helger.commons.io.resourceresolver.DefaultResourceResolver; import com.helger.schematron.ISchematronResource; import com.helger.schematron.sch.SchematronResourceSCH; public final class Issue110Test { @Test // @Ignore ("Relies on Saxon bug") public void testIncludedFilesNotDeleted () throws Exception { DefaultResourceResolver.setDebugResolve (true); final String sPath = "target/test-classes/issues/github110/"; final ISchematronResource aSV = SchematronResourceSCH.fromClassPath (sPath + "ATGOV-UBL-T10.sch"); aSV.applySchematronValidation (new FileSystemResource (sPath + "test.xml")); assertTrue (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); Files.delete (Paths.get (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").getAsURL ().toURI ())); assertFalse (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); } }
ph-schematron-xslt/src/test/java/com/helger/schematron/supplementary/Issue110Test.java
/** * Copyright (C) 2014-2021 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.schematron.supplementary; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.Test; import com.helger.commons.io.resource.ClassPathResource; import com.helger.commons.io.resourceresolver.DefaultResourceResolver; import com.helger.schematron.ISchematronResource; import com.helger.schematron.sch.SchematronResourceSCH; public final class Issue110Test { @Test // @Ignore ("Relies on Saxon bug") public void testIncludedFilesNotDeleted () throws Exception { DefaultResourceResolver.setDebugResolve (true); final String sPath = "issues/github110/"; final ISchematronResource aSV = SchematronResourceSCH.fromClassPath (sPath + "ATGOV-UBL-T10.sch"); aSV.applySchematronValidation (new ClassPathResource (sPath + "test.xml")); assertTrue (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); Files.delete (Paths.get (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").getAsURL ().toURI ())); assertFalse (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); } }
Using file instead of classpath
ph-schematron-xslt/src/test/java/com/helger/schematron/supplementary/Issue110Test.java
Using file instead of classpath
<ide><path>h-schematron-xslt/src/test/java/com/helger/schematron/supplementary/Issue110Test.java <ide> <ide> import org.junit.Test; <ide> <del>import com.helger.commons.io.resource.ClassPathResource; <add>import com.helger.commons.io.resource.FileSystemResource; <ide> import com.helger.commons.io.resourceresolver.DefaultResourceResolver; <ide> import com.helger.schematron.ISchematronResource; <ide> import com.helger.schematron.sch.SchematronResourceSCH; <ide> public void testIncludedFilesNotDeleted () throws Exception <ide> { <ide> DefaultResourceResolver.setDebugResolve (true); <del> final String sPath = "issues/github110/"; <add> final String sPath = "target/test-classes/issues/github110/"; <ide> final ISchematronResource aSV = SchematronResourceSCH.fromClassPath (sPath + "ATGOV-UBL-T10.sch"); <del> aSV.applySchematronValidation (new ClassPathResource (sPath + "test.xml")); <del> assertTrue (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); <del> Files.delete (Paths.get (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").getAsURL ().toURI ())); <del> assertFalse (new ClassPathResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); <add> aSV.applySchematronValidation (new FileSystemResource (sPath + "test.xml")); <add> assertTrue (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); <add> Files.delete (Paths.get (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").getAsURL ().toURI ())); <add> assertFalse (new FileSystemResource (sPath + "include/ATGOV-T10-abstract.sch").exists ()); <ide> } <ide> }
Java
apache-2.0
787b3d73d0d3d61f1a7c531fee25f123da252be7
0
terryrao/dubbo-demo
package chapter6.permission.realm; import chapter6.permission.entity.User; import chapter6.permission.service.UserService; import chapter6.permission.service.impl.UserServiceImpl; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; /** * @author terryrao on 2016/7/10. */ public class UserRealm extends AuthorizingRealm { private UserService userService = new UserServiceImpl(); @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) throws AuthenticationException { String name = (String) token.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(userService.findRoles(name)); authorizationInfo.setStringPermissions(userService.findPermission(name)); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String name = (String) token.getPrincipal(); User user = userService.findByUsername(name); if (user== null) { throw new UnknownAccountException("没有该账号"); } if (user.getLocked()) { throw new LockedAccountException(); } return new SimpleAuthenticationInfo( user.getUserName(), user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), getName() ); } }
shiro-demo/src/main/java/chapter6/permission/realm/UserRealm.java
package chapter6.permission.realm; import chapter6.permission.entity.User; import chapter6.permission.service.UserService; import chapter6.permission.service.impl.UserServiceImpl; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthenticatingRealm; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.realm.Realm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import javax.security.auth.login.AccountNotFoundException; /** * @author terryrao on 2016/7/10. */ public class UserRealm extends AuthorizingRealm { private UserService userService = new UserServiceImpl(); @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection token) throws AuthenticationException { String name = (String) token.getPrimaryPrincipal(); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(userService.findRoles(name)); authorizationInfo.setStringPermissions(userService.findPermission(name)); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { String name = (String) token.getPrincipal(); User user = userService.findByUsername(name); if (user== null) { throw new UnknownAccountException("没有该账号"); } if (user.getLocked()) { throw new LockedAccountException(); } return new SimpleAuthenticationInfo( user.getUserName(), user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), getName() ); } }
permssion
shiro-demo/src/main/java/chapter6/permission/realm/UserRealm.java
permssion
<ide><path>hiro-demo/src/main/java/chapter6/permission/realm/UserRealm.java <ide> import org.apache.shiro.authc.*; <ide> import org.apache.shiro.authz.AuthorizationInfo; <ide> import org.apache.shiro.authz.SimpleAuthorizationInfo; <del>import org.apache.shiro.realm.AuthenticatingRealm; <ide> import org.apache.shiro.realm.AuthorizingRealm; <del>import org.apache.shiro.realm.Realm; <ide> import org.apache.shiro.subject.PrincipalCollection; <ide> import org.apache.shiro.util.ByteSource; <del> <del>import javax.security.auth.login.AccountNotFoundException; <ide> <ide> /** <ide> * @author terryrao on 2016/7/10.
Java
apache-2.0
3f524abdeb62f0c3f9e835b5f0cfcf8abe7373ab
0
apurtell/hbase,mahak/hbase,apurtell/hbase,Apache9/hbase,mahak/hbase,Apache9/hbase,mahak/hbase,Apache9/hbase,francisliu/hbase,mahak/hbase,apurtell/hbase,ndimiduk/hbase,francisliu/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,Apache9/hbase,apurtell/hbase,mahak/hbase,apurtell/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,ndimiduk/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,ndimiduk/hbase,mahak/hbase,mahak/hbase,apurtell/hbase,apurtell/hbase,Apache9/hbase,ndimiduk/hbase,francisliu/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,ChinmaySKulkarni/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,Apache9/hbase,apurtell/hbase,ChinmaySKulkarni/hbase,mahak/hbase,ndimiduk/hbase,francisliu/hbase,ndimiduk/hbase,Apache9/hbase,mahak/hbase,ndimiduk/hbase,mahak/hbase,apurtell/hbase
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import org.apache.yetus.audience.InterfaceAudience; /** * A byte sequence that is usable as a key or value. Based on * {@link org.apache.hadoop.io.BytesWritable} only this class is NOT resizable * and DOES NOT distinguish between the size of the sequence and the current * capacity as {@link org.apache.hadoop.io.BytesWritable} does. Hence its * comparatively 'immutable'. When creating a new instance of this class, * the underlying byte [] is not copied, just referenced. The backing * buffer is accessed when we go to serialize. */ @InterfaceAudience.Public @edu.umd.cs.findbugs.annotations.SuppressWarnings( value="EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification="It has been like this forever") public class ImmutableBytesWritable implements WritableComparable<ImmutableBytesWritable> { private byte[] bytes; private int offset; private int length; /** * Create a zero-size sequence. */ public ImmutableBytesWritable() { super(); } /** * Create a ImmutableBytesWritable using the byte array as the initial value. * @param bytes This array becomes the backing storage for the object. */ public ImmutableBytesWritable(byte[] bytes) { this(bytes, 0, bytes.length); } /** * Set the new ImmutableBytesWritable to the contents of the passed * <code>ibw</code>. * @param ibw the value to set this ImmutableBytesWritable to. */ public ImmutableBytesWritable(final ImmutableBytesWritable ibw) { this(ibw.get(), ibw.getOffset(), ibw.getLength()); } /** * Set the value to a given byte range * @param bytes the new byte range to set to * @param offset the offset in newData to start at * @param length the number of bytes in the range */ public ImmutableBytesWritable(final byte[] bytes, final int offset, final int length) { this.bytes = bytes; this.offset = offset; this.length = length; } /** * Get the data from the BytesWritable. * @return The data is only valid between offset and offset+length. */ public byte [] get() { if (this.bytes == null) { throw new IllegalStateException("Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); } return this.bytes; } /** * @param b Use passed bytes as backing array for this instance. */ public void set(final byte [] b) { set(b, 0, b.length); } /** * @param b Use passed bytes as backing array for this instance. * @param offset * @param length */ public void set(final byte [] b, final int offset, final int length) { this.bytes = b; this.offset = offset; this.length = length; } /** * @return the number of valid bytes in the buffer */ public int getLength() { if (this.bytes == null) { throw new IllegalStateException("Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); } return this.length; } /** * @return offset */ public int getOffset(){ return this.offset; } @Override public void readFields(final DataInput in) throws IOException { this.length = in.readInt(); this.bytes = new byte[this.length]; in.readFully(this.bytes, 0, this.length); this.offset = 0; } @Override public void write(final DataOutput out) throws IOException { out.writeInt(this.length); out.write(this.bytes, this.offset, this.length); } // Below methods copied from BytesWritable @Override public int hashCode() { int hash = 1; for (int i = offset; i < offset + length; i++) hash = (31 * hash) + (int)bytes[i]; return hash; } /** * Define the sort order of the BytesWritable. * @param that The other bytes writable * @return Positive if left is bigger than right, 0 if they are equal, and * negative if left is smaller than right. */ @Override public int compareTo(ImmutableBytesWritable that) { return WritableComparator.compareBytes( this.bytes, this.offset, this.length, that.bytes, that.offset, that.length); } /** * Compares the bytes in this object to the specified byte array * @param that * @return Positive if left is bigger than right, 0 if they are equal, and * negative if left is smaller than right. */ public int compareTo(final byte [] that) { return WritableComparator.compareBytes( this.bytes, this.offset, this.length, that, 0, that.length); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object right_obj) { if (right_obj instanceof byte []) { return compareTo((byte [])right_obj) == 0; } if (right_obj instanceof ImmutableBytesWritable) { return compareTo((ImmutableBytesWritable)right_obj) == 0; } return false; } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(3*this.length); final int endIdx = this.offset + this.length; for (int idx = this.offset; idx < endIdx ; idx++) { sb.append(' '); String num = Integer.toHexString(0xff & this.bytes[idx]); // if it is only one digit, add a leading 0. if (num.length() < 2) { sb.append('0'); } sb.append(num); } return sb.length() > 0 ? sb.substring(1) : ""; } /** A Comparator optimized for ImmutableBytesWritable. */ @InterfaceAudience.Public public static class Comparator extends WritableComparator { private BytesWritable.Comparator comparator = new BytesWritable.Comparator(); /** constructor */ public Comparator() { super(ImmutableBytesWritable.class); } /** * @see org.apache.hadoop.io.WritableComparator#compare(byte[], int, int, byte[], int, int) */ @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return comparator.compare(b1, s1, l1, b2, s2, l2); } } static { // register this comparator WritableComparator.define(ImmutableBytesWritable.class, new Comparator()); } /** * @param array List of byte []. * @return Array of byte []. */ public static byte [][] toArray(final List<byte []> array) { // List#toArray doesn't work on lists of byte []. byte[][] results = new byte[array.size()][]; for (int i = 0; i < array.size(); i++) { results[i] = array.get(i); } return results; } /** * Returns a copy of the bytes referred to by this writable */ public byte[] copyBytes() { return Arrays.copyOfRange(bytes, offset, offset+length); } }
hbase-common/src/main/java/org/apache/hadoop/hbase/io/ImmutableBytesWritable.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.io; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import org.apache.yetus.audience.InterfaceAudience; /** * A byte sequence that is usable as a key or value. Based on * {@link org.apache.hadoop.io.BytesWritable} only this class is NOT resizable * and DOES NOT distinguish between the size of the sequence and the current * capacity as {@link org.apache.hadoop.io.BytesWritable} does. Hence its * comparatively 'immutable'. When creating a new instance of this class, * the underlying byte [] is not copied, just referenced. The backing * buffer is accessed when we go to serialize. */ @InterfaceAudience.Public @edu.umd.cs.findbugs.annotations.SuppressWarnings( value="EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", justification="It has been like this forever") public class ImmutableBytesWritable implements WritableComparable<ImmutableBytesWritable> { private byte[] bytes; private int offset; private int length; /** * Create a zero-size sequence. */ public ImmutableBytesWritable() { super(); } /** * Create a ImmutableBytesWritable using the byte array as the initial value. * @param bytes This array becomes the backing storage for the object. */ public ImmutableBytesWritable(byte[] bytes) { this(bytes, 0, bytes.length); } /** * Set the new ImmutableBytesWritable to the contents of the passed * <code>ibw</code>. * @param ibw the value to set this ImmutableBytesWritable to. */ public ImmutableBytesWritable(final ImmutableBytesWritable ibw) { this(ibw.get(), ibw.getOffset(), ibw.getLength()); } /** * Set the value to a given byte range * @param bytes the new byte range to set to * @param offset the offset in newData to start at * @param length the number of bytes in the range */ public ImmutableBytesWritable(final byte[] bytes, final int offset, final int length) { this.bytes = bytes; this.offset = offset; this.length = length; } /** * Get the data from the BytesWritable. * @return The data is only valid between offset and offset+length. */ public byte [] get() { if (this.bytes == null) { throw new IllegalStateException("Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); } return this.bytes; } /** * @param b Use passed bytes as backing array for this instance. */ public void set(final byte [] b) { set(b, 0, b.length); } /** * @param b Use passed bytes as backing array for this instance. * @param offset * @param length */ public void set(final byte [] b, final int offset, final int length) { this.bytes = b; this.offset = offset; this.length = length; } /** * @return the number of valid bytes in the buffer * @deprecated since 0.98.5. Use {@link #getLength()} instead * @see #getLength() * @see <a href="https://issues.apache.org/jira/browse/HBASE-11561">HBASE-11561</a> */ @Deprecated public int getSize() { if (this.bytes == null) { throw new IllegalStateException("Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); } return this.length; } /** * @return the number of valid bytes in the buffer */ public int getLength() { if (this.bytes == null) { throw new IllegalStateException("Uninitialiized. Null constructor " + "called w/o accompaying readFields invocation"); } return this.length; } /** * @return offset */ public int getOffset(){ return this.offset; } @Override public void readFields(final DataInput in) throws IOException { this.length = in.readInt(); this.bytes = new byte[this.length]; in.readFully(this.bytes, 0, this.length); this.offset = 0; } @Override public void write(final DataOutput out) throws IOException { out.writeInt(this.length); out.write(this.bytes, this.offset, this.length); } // Below methods copied from BytesWritable @Override public int hashCode() { int hash = 1; for (int i = offset; i < offset + length; i++) hash = (31 * hash) + (int)bytes[i]; return hash; } /** * Define the sort order of the BytesWritable. * @param that The other bytes writable * @return Positive if left is bigger than right, 0 if they are equal, and * negative if left is smaller than right. */ @Override public int compareTo(ImmutableBytesWritable that) { return WritableComparator.compareBytes( this.bytes, this.offset, this.length, that.bytes, that.offset, that.length); } /** * Compares the bytes in this object to the specified byte array * @param that * @return Positive if left is bigger than right, 0 if they are equal, and * negative if left is smaller than right. */ public int compareTo(final byte [] that) { return WritableComparator.compareBytes( this.bytes, this.offset, this.length, that, 0, that.length); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object right_obj) { if (right_obj instanceof byte []) { return compareTo((byte [])right_obj) == 0; } if (right_obj instanceof ImmutableBytesWritable) { return compareTo((ImmutableBytesWritable)right_obj) == 0; } return false; } /** * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(3*this.length); final int endIdx = this.offset + this.length; for (int idx = this.offset; idx < endIdx ; idx++) { sb.append(' '); String num = Integer.toHexString(0xff & this.bytes[idx]); // if it is only one digit, add a leading 0. if (num.length() < 2) { sb.append('0'); } sb.append(num); } return sb.length() > 0 ? sb.substring(1) : ""; } /** A Comparator optimized for ImmutableBytesWritable. */ @InterfaceAudience.Public public static class Comparator extends WritableComparator { private BytesWritable.Comparator comparator = new BytesWritable.Comparator(); /** constructor */ public Comparator() { super(ImmutableBytesWritable.class); } /** * @see org.apache.hadoop.io.WritableComparator#compare(byte[], int, int, byte[], int, int) */ @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return comparator.compare(b1, s1, l1, b2, s2, l2); } } static { // register this comparator WritableComparator.define(ImmutableBytesWritable.class, new Comparator()); } /** * @param array List of byte []. * @return Array of byte []. */ public static byte [][] toArray(final List<byte []> array) { // List#toArray doesn't work on lists of byte []. byte[][] results = new byte[array.size()][]; for (int i = 0; i < array.size(); i++) { results[i] = array.get(i); } return results; } /** * Returns a copy of the bytes referred to by this writable */ public byte[] copyBytes() { return Arrays.copyOfRange(bytes, offset, offset+length); } }
HBASE-22789 Removed deprecated method from ImmutableBytesWritable Signed-off-by: stack <[email protected]>
hbase-common/src/main/java/org/apache/hadoop/hbase/io/ImmutableBytesWritable.java
HBASE-22789 Removed deprecated method from ImmutableBytesWritable
<ide><path>base-common/src/main/java/org/apache/hadoop/hbase/io/ImmutableBytesWritable.java <ide> <ide> /** <ide> * @return the number of valid bytes in the buffer <del> * @deprecated since 0.98.5. Use {@link #getLength()} instead <del> * @see #getLength() <del> * @see <a href="https://issues.apache.org/jira/browse/HBASE-11561">HBASE-11561</a> <del> */ <del> @Deprecated <del> public int getSize() { <del> if (this.bytes == null) { <del> throw new IllegalStateException("Uninitialiized. Null constructor " + <del> "called w/o accompaying readFields invocation"); <del> } <del> return this.length; <del> } <del> <del> /** <del> * @return the number of valid bytes in the buffer <ide> */ <ide> public int getLength() { <ide> if (this.bytes == null) {
JavaScript
mit
6724be9d20b14c514072061efe6bdf2a4dd2e958
0
LightningStormServer/Lightning-Storm,LightningStormServer/Lightning-Storm,FakeSloth/wulu,LightningStormServer/Lightning-Storm
var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ name: { type: String, lowercase: true }, group: String }); var User = exports.User = mongoose.model('user', userSchema); exports.connect_database = function() { var url = process.env.MONGODB || 'mongodb://localhost:27017/ps'; mongoose.connect(url); mongoose.connection.on('error', function() { console.error('MongoDB Connection Error. Make sure MongoDB is running.'); }); }; exports.importUsergroups = function(usergroups, Config) { User.find({}, function(err, users) { if (err) return; users.forEach(function(user) { usergroups[user.name] = (user.group || Config.groupsranking[0]) + user.name; }); }); }; exports.exportUsergroups = function(usergroups) { var users = []; for (var i in usergroups) { users.push({ name: usergroups[i].substr(1).replace(/,/g, ''), group: usergroups[i].substr(0, 1) }); } users.forEach(function(user) { User.findOne({ name: user.name.toLowerCase() }, function(err, userModel) { if (err) return; if (!userModel) { user = new User({ name: user.name, group: user.group }); return user.save(function(err) { if (err) return err; }); } userModel.group = user.group; userModel.save(function(err) { if (err) return; }); }); }); users = users.map(function(user) { return user.name; }); User.find({}, function(err, usersModel) { if (err) return; usersModel.forEach(function(user) { if (users.indexOf(user.name) < 0) { User.findOne({name: user.name}, function(err, user) { if (err) return; user.group = ''; user.save(function(err) { if (err) return; }); }); } }); }); };
mongo.js
var mongoose = require('mongoose'); var userSchema = new mongoose.Schema({ name: { type: String, lowercase: true }, group: String }); var User = exports.User = mongoose.model('user', userSchema); exports.connect_database = function() { var url = process.env.MONGODB || 'mongodb://localhost:27017/ps'; mongoose.connect(url); mongoose.connection.on('error', function() { console.error('MongoDB Connection Error. Make sure MongoDB is running.'); }); }; exports.importUsergroups = function(usergroups, Config) { User.find({}, function(err, users) { if (err) return; users.forEach(function(user) { usergroups[user.name] = (user.group || Config.groupsranking[0]) + user.name; }); }); }; exports.exportUsergroups = function(usergroups) { var users = []; for (var i in usergroups) { users.push({ name: usergroups[i].substr(1).replace(/,/g, ''), group: usergroups[i].substr(0, 1) }); } users.forEach(function(user) { User.findOne({ name: user.name.toLowerCase() }, function(err, userModel) { if (err) return; if (!userModel) { user = new User({ name: user.name, group: user.group }); return user.save(function(err) { if (err) return err; }); } userModel.group = user.group; userModel.save(function(err) { if (err) return; }); }); }); };
Fix demotion to regular user
mongo.js
Fix demotion to regular user
<ide><path>ongo.js <ide> }); <ide> }); <ide> }); <add> users = users.map(function(user) { <add> return user.name; <add> }); <add> User.find({}, function(err, usersModel) { <add> if (err) return; <add> usersModel.forEach(function(user) { <add> if (users.indexOf(user.name) < 0) { <add> User.findOne({name: user.name}, function(err, user) { <add> if (err) return; <add> user.group = ''; <add> user.save(function(err) { <add> if (err) return; <add> }); <add> }); <add> } <add> }); <add> }); <ide> };
Java
mit
e6e6bdf261acacee4ca1ce0f8950ba69c6be58b2
0
kfpotts1/mp.Me,kfpotts1/mp.Me,kfpotts1/mp.Me,kfpotts1/mp.Me
package test; import org.junit.Test; import splash.*; import java.io.IOException; /** * Created by jack on 3/27/2017. */ public class splashScreenTest { @Test public void operatingSystemTestMac(){ System.out.println("*******************************************"); System.out.println("*****SPLASH - OPERATING SYSTEM MAC TEST****"); System.out.println("*******************************************"); splash.Main splashScreen = new splash.Main(); String operatingSystemTester; } }
src/test/splashScreenTest.java
package test; import org.junit.Test; import splash.*; import java.io.IOException; /** * Created by jack on 3/27/2017. */ public class splashScreenTest { @Test public void operatingSystemTest(){ System.out.println("Test"); } }
i hate testing the splash screen
src/test/splashScreenTest.java
i hate testing the splash screen
<ide><path>rc/test/splashScreenTest.java <ide> */ <ide> public class splashScreenTest { <ide> @Test <del> public void operatingSystemTest(){ <del> System.out.println("Test"); <add> public void operatingSystemTestMac(){ <add> System.out.println("*******************************************"); <add> System.out.println("*****SPLASH - OPERATING SYSTEM MAC TEST****"); <add> System.out.println("*******************************************"); <add> splash.Main splashScreen = new splash.Main(); <add> String operatingSystemTester; <add> <add> <ide> <ide> <ide> }
Java
apache-2.0
be70ffc1b22967e3cfacf89e65eb38b16e7c7dca
0
apache/commons-validator,apache/commons-validator,apache/commons-validator
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.validator.ResultPair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * Performs Validation Test for e-mail validations. * * * @version $Revision$ */ public class EmailValidatorTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "emailForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "email"; private EmailValidator validator; @Before public void setUp() { validator = EmailValidator.getInstance(); } /** * Tests the e-mail validation. */ @Test public void testEmail() { assertTrue(validator.isValid("[email protected]")); } /** * Tests the email validation with numeric domains. */ @Test public void testEmailWithNumericAddress() { assertTrue(validator.isValid("someone@[216.109.118.76]")); assertTrue(validator.isValid("[email protected]")); } /** * Tests the e-mail validation. */ @Test public void testEmailExtension() { assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("jsmith@apache.")); assertFalse(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); } /** * <p>Tests the e-mail validation with a dash in * the address.</p> */ @Test public void testEmailWithDash() { assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); } /** * Tests the e-mail validation with a dot at the end of * the address. */ @Test public void testEmailWithDotEnd() { assertFalse(validator.isValid("[email protected].")); } /** * Tests the e-mail validation with an RCS-noncompliant character in * the address. */ @Test public void testEmailWithBogusCharacter() { assertFalse(validator.isValid("andy.noble@\u008fdata-workshop.com")); // The ' character is valid in an email username. assertTrue(validator.isValid("andy.o'[email protected]")); // But not in the domain name. assertFalse(validator.isValid("andy@o'reilly.data-workshop.com")); // The + character is valid in an email username. assertTrue(validator.isValid("[email protected]")); // But not in the domain name assertFalse(validator.isValid("foo+bar@example+3.com")); // Domains with only special characters aren't allowed (VALIDATOR-286) assertFalse(validator.isValid("test@%*.com")); assertFalse(validator.isValid("test@^&#.com")); } @Test public void testVALIDATOR_315() { assertFalse(validator.isValid("me@at&t.net")); assertTrue(validator.isValid("[email protected]")); // Make sure TLD is not the cause of the failure } @Test public void testVALIDATOR_278() { assertFalse(validator.isValid("[email protected]"));// hostname starts with dash/hyphen assertFalse(validator.isValid("[email protected]"));// hostname ends with dash/hyphen } @Test public void testValidator235() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("[email protected]")); assertTrue("президент.рф should validate", validator.isValid("someone@президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("[email protected]\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("[email protected]\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch")); } /** * Tests the email validation with commas. */ @Test public void testEmailWithCommas() { assertFalse(validator.isValid("joeblow@apa,che.org")); assertFalse(validator.isValid("[email protected],rg")); assertFalse(validator.isValid("joeblow@apache,org")); } /** * Tests the email validation with spaces. */ @Test public void testEmailWithSpaces() { assertFalse(validator.isValid("joeblow @apache.org")); assertFalse(validator.isValid("joeblow@ apache.org")); assertFalse(validator.isValid(" [email protected]")); assertFalse(validator.isValid("[email protected] ")); assertFalse(validator.isValid("joe [email protected] ")); assertFalse(validator.isValid("joeblow@apa che.org ")); assertTrue(validator.isValid("\"joeblow \"@apache.org")); assertTrue(validator.isValid("\" joeblow\"@apache.org")); assertTrue(validator.isValid("\" joe blow \"@apache.org")); } /** * Tests the email validation with ascii control characters. * (i.e. Ascii chars 0 - 31 and 127) */ @Test public void testEmailWithControlChars() { for (char c = 0; c < 32; c++) { assertFalse("Test control char " + ((int)c), validator.isValid("foo" + c + "[email protected]")); } assertFalse("Test control char 127", validator.isValid("foo" + ((char)127) + "[email protected]")); } /** * Test that @localhost and @localhost.localdomain * addresses are declared as valid when requested. */ @Test public void testEmailLocalhost() { // Check the default is not to allow EmailValidator noLocal = EmailValidator.getInstance(false); EmailValidator allowLocal = EmailValidator.getInstance(true); assertEquals(validator, noLocal); // Depends on the validator assertTrue( "@localhost.localdomain should be accepted but wasn't", allowLocal.isValid("[email protected]") ); assertTrue( "@localhost should be accepted but wasn't", allowLocal.isValid("joe@localhost") ); assertFalse( "@localhost.localdomain should be accepted but wasn't", noLocal.isValid("[email protected]") ); assertFalse( "@localhost should be accepted but wasn't", noLocal.isValid("joe@localhost") ); } /** * VALIDATOR-296 - A / or a ! is valid in the user part, * but not in the domain part */ @Test public void testEmailWithSlashes() { assertTrue( "/ and ! valid in username", validator.isValid("joe!/[email protected]") ); assertFalse( "/ not valid in domain", validator.isValid("joe@ap/ache.org") ); assertFalse( "! not valid in domain", validator.isValid("joe@apac!he.org") ); } /** * Write this test according to parts of RFC, as opposed to the type of character * that is being tested. */ @Test public void testEmailUserName() { assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("joe*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("joe'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("joe%[email protected]")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("joe&@apache.org")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("*[email protected]")); // * is valid unquoted assertTrue(validator.isValid("'[email protected]")); // ' is valid unquoted assertTrue(validator.isValid("%[email protected]")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("&[email protected]")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("%@apache.org")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("&@apache.org")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto //UnQuoted Special characters are invalid assertFalse(validator.isValid("[email protected]")); // . not allowed at end of local part assertFalse(validator.isValid("[email protected]")); // . not allowed at start of local part assertFalse(validator.isValid("[email protected]")); // . not allowed alone assertTrue(validator.isValid("[email protected]")); // . allowed embedded assertFalse(validator.isValid("[email protected]")); // .. not allowed embedded assertFalse(validator.isValid("[email protected]")); // .. not allowed alone assertFalse(validator.isValid("joe(@apache.org")); assertFalse(validator.isValid("joe)@apache.org")); assertFalse(validator.isValid("joe,@apache.org")); assertFalse(validator.isValid("joe;@apache.org")); //Quoted Special characters are valid assertTrue(validator.isValid("\"joe.\"@apache.org")); assertTrue(validator.isValid("\".joe\"@apache.org")); assertTrue(validator.isValid("\"joe+\"@apache.org")); assertTrue(validator.isValid("\"joe@\"@apache.org")); assertTrue(validator.isValid("\"joe!\"@apache.org")); assertTrue(validator.isValid("\"joe*\"@apache.org")); assertTrue(validator.isValid("\"joe'\"@apache.org")); assertTrue(validator.isValid("\"joe(\"@apache.org")); assertTrue(validator.isValid("\"joe)\"@apache.org")); assertTrue(validator.isValid("\"joe,\"@apache.org")); assertTrue(validator.isValid("\"joe%45\"@apache.org")); assertTrue(validator.isValid("\"joe;\"@apache.org")); assertTrue(validator.isValid("\"joe?\"@apache.org")); assertTrue(validator.isValid("\"joe&\"@apache.org")); assertTrue(validator.isValid("\"joe=\"@apache.org")); assertTrue(validator.isValid("\"..\"@apache.org")); // escaped quote character valid in quoted string assertTrue(validator.isValid("\"john\\\"doe\"@apache.org")); assertTrue(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john@example.com")); assertFalse(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john5@example.com")); assertTrue(validator.isValid("\\>escape\\\\special\\^characters\\<@example.com")); assertTrue(validator.isValid("Abc\\@[email protected]")); assertFalse(validator.isValid("Abc@[email protected]")); assertTrue(validator.isValid("space\\ [email protected]")); } /** * These test values derive directly from RFC 822 & * Mail::RFC822::Address & RFC::RFC822::Address perl test.pl * For traceability don't combine these test values with other tests. */ private static final ResultPair[] testEmailFromPerl = { new ResultPair("[email protected]", true), new ResultPair("[email protected] ", true), new ResultPair(" [email protected]", true), new ResultPair("abigail @example.com ", true), new ResultPair("*@example.net", true), new ResultPair("\"\\\"\"@foo.bar", true), new ResultPair("fred&[email protected]", true), new ResultPair("[email protected]", true), new ResultPair("[email protected]", true), new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true), new ResultPair("Abigail <[email protected]>", true), new ResultPair("Abigail<[email protected]>", true), new ResultPair("Abigail<@a,@b,@c:[email protected]>", true), new ResultPair("\"This is a phrase\"<[email protected]>", true), new ResultPair("\"Abigail \"<[email protected]>", true), new ResultPair("\"Joe & J. Harvey\" <example @Org>", true), new ResultPair("Abigail <abigail @ example.com>", true), new ResultPair("Abigail made this < abigail @ example . com >", true), new ResultPair("Abigail(the bitch)@example.com", true), new ResultPair("Abigail <abigail @ example . (bar) com >", true), new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail <abigail(fo\\(o)@example.com>", true), new ResultPair("Abigail <abigail(fo\\)o)@example.com> ", true), new ResultPair("(foo) [email protected]", true), new ResultPair("[email protected] (foo)", true), new ResultPair("\"Abi\\\"gail\" <[email protected]>", true), new ResultPair("abigail@[example.com]", true), new ResultPair("abigail@[exa\\[ple.com]", true), new ResultPair("abigail@[exa\\]ple.com]", true), new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true), new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true), new ResultPair("mailbox.sub1.sub2@this-domain", true), new ResultPair("[email protected]", true), new ResultPair("name:;", true), new ResultPair("':;", true), new ResultPair("name: ;", true), new ResultPair("Alfred Neuman <Neuman@BBN-TENEXA>", true), new ResultPair("Neuman@BBN-TENEXA", true), new ResultPair("\"George, Ted\" <[email protected]>", true), new ResultPair("Wilt . (the Stilt) [email protected]", true), new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true), new ResultPair("$@[]", true), new ResultPair("*()@[]", true), new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true), new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A <ddd\\@ Org>", true), new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" <ddd \\@ Org>", true), new ResultPair("Gourmets: Pompous Person <WhoZiWhatZit\\@Cordon-Bleu>,\\x0D\\x0A" + " Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" + " ANT.Down-Under (Australian National Television),\\x0D\\x0A" + " Cheapie\\@Discount-Liquors;", true), new ResultPair(" Just a string", false), new ResultPair("string", false), new ResultPair("(comment)", false), new ResultPair("()@example.com", false), new ResultPair("fred(&)[email protected]", false), new ResultPair("fred\\ [email protected]", false), new ResultPair("Abigail <abi gail @ example.com>", false), new ResultPair("Abigail <abigail(fo(o)@example.com>", false), new ResultPair("Abigail <abigail(fo)o)@example.com>", false), new ResultPair("\"Abi\"gail\" <[email protected]>", false), new ResultPair("abigail@[exa]ple.com]", false), new ResultPair("abigail@[exa[ple.com]", false), new ResultPair("abigail@[exaple].com]", false), new ResultPair("abigail@", false), new ResultPair("@example.com", false), new ResultPair("phrase: [email protected] [email protected] ;", false), new ResultPair("invalid�[email protected]", false) }; /** * Write this test based on perl Mail::RFC822::Address * which takes its example email address directly from RFC822 * * This test fails so disable it * The real solution is to fix the email parsing. */ @Ignore("VALIDATOR-267") @Test public void testEmailFromPerl() { int errors = 0; for (int index = 0; index < testEmailFromPerl.length; index++) { String item = testEmailFromPerl[index].item; boolean exp = testEmailFromPerl[index].valid; boolean act = validator.isValid(item); if (act != exp) { System.out.printf("%s: expected %s actual %s%n", item, exp, act); errors += 1; } } assertEquals("Expected 0 errors", 0, errors); } @Test public void testValidator293(){ assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("abc@abc_def.com")); } @Test public void testValidator365() { assertFalse(validator.isValid( "Loremipsumdolorsitametconsecteturadipiscingelit.Nullavitaeligulamattisrhoncusnuncegestasmattisleo."+ "Donecnonsapieninmagnatristiquedictumaacturpis.Fusceorciduifacilisisutsapieneuconsequatpharetralectus."+ "Quisqueenimestpulvinarutquamvitaeportamattisex.Nullamquismaurisplaceratconvallisjustoquisportamauris."+ "Innullalacusconvalliseufringillautvenenatissitametdiam.Maecenasluctusligulascelerisquepulvinarfeugiat."+ "Sedmolestienullaaliquetorciluctusidpharetranislfinibus.Suspendissemalesuadatinciduntduisitametportaarcusollicitudinnec."+ "Donecetmassamagna.Curabitururnadiampretiumveldignissimporttitorfringillaeuneque."+ "Duisantetelluspharetraidtinciduntinterdummolestiesitametfelis.Utquisquamsitametantesagittisdapibusacnonodio."+ "Namrutrummolestiediamidmattis.Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus."+ "Morbiposueresedmetusacconsectetur.Etiamquisipsumvitaejustotempusmaximus.Sedultriciesplaceratvolutpat."+ "Integerlacuslectusmaximusacornarequissagittissitametjusto."+ "Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus.Maecenasindictumpurussedrutrumex.Nullafacilisi."+ "Integerfinibusfinibusmietpharetranislfaucibusvel.Maecenasegetdolorlacinialobortisjustovelullamcorpersem."+ "Vivamusaliquetpurusidvariusornaresapienrisusrutrumnisitinciduntmollissemnequeidmetus."+ "Etiamquiseleifendpurus.Nuncfelisnuncscelerisqueiddignissimnecfinibusalibero."+ "Nuncsemperenimnequesitamethendreritpurusfacilisisac.Maurisdapibussemperfelisdignissimgravida."+ "Aeneanultricesblanditnequealiquamfinibusodioscelerisqueac.Aliquamnecmassaeumaurisfaucibusfringilla."+ "Etiamconsequatligulanisisitametaliquamnibhtemporquis.Nuncinterdumdignissimnullaatsodalesarcusagittiseu."+ "Proinpharetrametusneclacuspulvinarsedvolutpatliberoornare.Sedligulanislpulvinarnonlectuseublanditfacilisisante."+ "Sedmollisnislalacusauctorsuscipit.Inhachabitasseplateadictumst.Phasellussitametvelittemporvenenatisfeliseuegestasrisus."+ "Aliquameteratsitametnibhcommodofinibus.Morbiefficiturodiovelpulvinariaculis."+ "Aeneantemporipsummassaaconsecteturturpisfaucibusultrices.Praesentsodalesmaurisquisportafermentum."+ "Etiamnisinislvenenatisvelauctorutullamcorperinjusto.Proinvelligulaerat.Phasellusvestibulumgravidamassanonfeugiat."+ "Maecenaspharetraeuismodmetusegetefficitur.Suspendisseamet@gmail.com")); } /** * Tests the e-mail validation with a user at a TLD * * http://tools.ietf.org/html/rfc5321#section-2.3.5 * (In the case of a top-level domain used by itself in an * email address, a single string is used without any dots) */ @Test public void testEmailAtTLD() { EmailValidator val = EmailValidator.getInstance(false, true); assertTrue(val.isValid("test@com")); } @Test public void testValidator359() { EmailValidator val = EmailValidator.getInstance(false, true); assertFalse(val.isValid("[email protected]")); } @Test public void testValidator374() { assertTrue(validator.isValid("[email protected]")); } @Test(expected = IllegalArgumentException.class) public void testValidator473_1() { // reject null DomainValidator new EmailValidator(false, false, null); } @Test(expected = IllegalArgumentException.class) public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal List<DomainValidator.Item> items = new ArrayList<>(); new EmailValidator(false, false, DomainValidator.getInstance(true, items)); } @Test(expected = IllegalArgumentException.class) public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal List<DomainValidator.Item> items = new ArrayList<>(); new EmailValidator(true, false, DomainValidator.getInstance(false, items)); } @Test public void testValidator473_4() { // Show that can override domain validation assertFalse(validator.isValidDomain("test.local")); List<DomainValidator.Item> items = new ArrayList<>(); items.add(new DomainValidator.Item(DomainValidator.ArrayType.GENERIC_PLUS, new String[]{"local"})); EmailValidator val = new EmailValidator(true, false, DomainValidator.getInstance(true, items)); assertTrue(val.isValidDomain("test.local")); } public static void main(String[] args) { EmailValidator validator = EmailValidator.getInstance(); for(String arg : args) { System.out.printf("%s: %s%n", arg, validator.isValid(arg)); } } }
src/test/java/org/apache/commons/validator/routines/EmailValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.validator.ResultPair; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * Performs Validation Test for e-mail validations. * * * @version $Revision$ */ public class EmailValidatorTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "emailForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "email"; private EmailValidator validator; @Before public void setUp() { validator = EmailValidator.getInstance(); } /** * Tests the e-mail validation. */ @Test public void testEmail() { assertTrue(validator.isValid("[email protected]")); } /** * Tests the email validation with numeric domains. */ @Test public void testEmailWithNumericAddress() { assertTrue(validator.isValid("someone@[216.109.118.76]")); assertTrue(validator.isValid("[email protected]")); } /** * Tests the e-mail validation. */ @Test public void testEmailExtension() { assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("jsmith@apache.")); assertFalse(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); } /** * <p>Tests the e-mail validation with a dash in * the address.</p> */ @Test public void testEmailWithDash() { assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); assertFalse(validator.isValid("[email protected]")); } /** * Tests the e-mail validation with a dot at the end of * the address. */ @Test public void testEmailWithDotEnd() { assertFalse(validator.isValid("[email protected].")); } /** * Tests the e-mail validation with an RCS-noncompliant character in * the address. */ @Test public void testEmailWithBogusCharacter() { assertFalse(validator.isValid("andy.noble@\u008fdata-workshop.com")); // The ' character is valid in an email username. assertTrue(validator.isValid("andy.o'[email protected]")); // But not in the domain name. assertFalse(validator.isValid("andy@o'reilly.data-workshop.com")); // The + character is valid in an email username. assertTrue(validator.isValid("[email protected]")); // But not in the domain name assertFalse(validator.isValid("foo+bar@example+3.com")); // Domains with only special characters aren't allowed (VALIDATOR-286) assertFalse(validator.isValid("test@%*.com")); assertFalse(validator.isValid("test@^&#.com")); } @Test public void testVALIDATOR_315() { assertFalse(validator.isValid("me@at&t.net")); assertTrue(validator.isValid("[email protected]")); // Make sure TLD is not the cause of the failure } @Test public void testVALIDATOR_278() { assertFalse(validator.isValid("[email protected]"));// hostname starts with dash/hyphen assertFalse(validator.isValid("[email protected]"));// hostname ends with dash/hyphen } @Test public void testValidator235() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("[email protected]")); assertTrue("президент.рф should validate", validator.isValid("someone@президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("[email protected]\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("[email protected]\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("someone@www.\uFFFD.ch")); } /** * Tests the email validation with commas. */ @Test public void testEmailWithCommas() { assertFalse(validator.isValid("joeblow@apa,che.org")); assertFalse(validator.isValid("[email protected],rg")); assertFalse(validator.isValid("joeblow@apache,org")); } /** * Tests the email validation with spaces. */ @Test public void testEmailWithSpaces() { assertFalse(validator.isValid("joeblow @apache.org")); assertFalse(validator.isValid("joeblow@ apache.org")); assertFalse(validator.isValid(" [email protected]")); assertFalse(validator.isValid("[email protected] ")); assertFalse(validator.isValid("joe [email protected] ")); assertFalse(validator.isValid("joeblow@apa che.org ")); assertTrue(validator.isValid("\"joeblow \"@apache.org")); assertTrue(validator.isValid("\" joeblow\"@apache.org")); assertTrue(validator.isValid("\" joe blow \"@apache.org")); } /** * Tests the email validation with ascii control characters. * (i.e. Ascii chars 0 - 31 and 127) */ @Test public void testEmailWithControlChars() { for (char c = 0; c < 32; c++) { assertFalse("Test control char " + ((int)c), validator.isValid("foo" + c + "[email protected]")); } assertFalse("Test control char 127", validator.isValid("foo" + ((char)127) + "[email protected]")); } /** * Test that @localhost and @localhost.localdomain * addresses are declared as valid when requested. */ @Test public void testEmailLocalhost() { // Check the default is not to allow EmailValidator noLocal = EmailValidator.getInstance(false); EmailValidator allowLocal = EmailValidator.getInstance(true); assertEquals(validator, noLocal); // Depends on the validator assertTrue( "@localhost.localdomain should be accepted but wasn't", allowLocal.isValid("[email protected]") ); assertTrue( "@localhost should be accepted but wasn't", allowLocal.isValid("joe@localhost") ); assertFalse( "@localhost.localdomain should be accepted but wasn't", noLocal.isValid("[email protected]") ); assertFalse( "@localhost should be accepted but wasn't", noLocal.isValid("joe@localhost") ); } /** * VALIDATOR-296 - A / or a ! is valid in the user part, * but not in the domain part */ @Test public void testEmailWithSlashes() { assertTrue( "/ and ! valid in username", validator.isValid("joe!/[email protected]") ); assertFalse( "/ not valid in domain", validator.isValid("joe@ap/ache.org") ); assertFalse( "! not valid in domain", validator.isValid("joe@apac!he.org") ); } /** * Write this test according to parts of RFC, as opposed to the type of character * that is being tested. */ @Test public void testEmailUserName() { assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("joe*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("joe'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("joe%[email protected]")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("joe&@apache.org")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("*[email protected]")); // * is valid unquoted assertTrue(validator.isValid("'[email protected]")); // ' is valid unquoted assertTrue(validator.isValid("%[email protected]")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("&[email protected]")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto assertTrue(validator.isValid("[email protected]")); // + is valid unquoted assertTrue(validator.isValid("[email protected]")); // ! is valid unquoted assertTrue(validator.isValid("*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("%@apache.org")); // % is valid unquoted assertTrue(validator.isValid("[email protected]")); // ? is valid unquoted assertTrue(validator.isValid("&@apache.org")); // & ditto assertTrue(validator.isValid("[email protected]")); // = ditto //UnQuoted Special characters are invalid assertFalse(validator.isValid("[email protected]")); // . not allowed at end of local part assertFalse(validator.isValid("[email protected]")); // . not allowed at start of local part assertFalse(validator.isValid("[email protected]")); // . not allowed alone assertTrue(validator.isValid("[email protected]")); // . allowed embedded assertFalse(validator.isValid("[email protected]")); // .. not allowed embedded assertFalse(validator.isValid("[email protected]")); // .. not allowed alone assertFalse(validator.isValid("joe(@apache.org")); assertFalse(validator.isValid("joe)@apache.org")); assertFalse(validator.isValid("joe,@apache.org")); assertFalse(validator.isValid("joe;@apache.org")); //Quoted Special characters are valid assertTrue(validator.isValid("\"joe.\"@apache.org")); assertTrue(validator.isValid("\".joe\"@apache.org")); assertTrue(validator.isValid("\"joe+\"@apache.org")); assertTrue(validator.isValid("\"joe@\"@apache.org")); assertTrue(validator.isValid("\"joe!\"@apache.org")); assertTrue(validator.isValid("\"joe*\"@apache.org")); assertTrue(validator.isValid("\"joe'\"@apache.org")); assertTrue(validator.isValid("\"joe(\"@apache.org")); assertTrue(validator.isValid("\"joe)\"@apache.org")); assertTrue(validator.isValid("\"joe,\"@apache.org")); assertTrue(validator.isValid("\"joe%45\"@apache.org")); assertTrue(validator.isValid("\"joe;\"@apache.org")); assertTrue(validator.isValid("\"joe?\"@apache.org")); assertTrue(validator.isValid("\"joe&\"@apache.org")); assertTrue(validator.isValid("\"joe=\"@apache.org")); assertTrue(validator.isValid("\"..\"@apache.org")); // escaped quote character valid in quoted string assertTrue(validator.isValid("\"john\\\"doe\"@apache.org")); assertTrue(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john@example.com")); assertFalse(validator.isValid("john56789.john56789.john56789.john56789.john56789.john56789.john5@example.com")); assertTrue(validator.isValid("\\>escape\\\\special\\^characters\\<@example.com")); assertTrue(validator.isValid("Abc\\@[email protected]")); assertFalse(validator.isValid("Abc@[email protected]")); assertTrue(validator.isValid("space\\ [email protected]")); } /** * These test values derive directly from RFC 822 & * Mail::RFC822::Address & RFC::RFC822::Address perl test.pl * For traceability don't combine these test values with other tests. */ private static final ResultPair[] testEmailFromPerl = { new ResultPair("[email protected]", true), new ResultPair("[email protected] ", true), new ResultPair(" [email protected]", true), new ResultPair("abigail @example.com ", true), new ResultPair("*@example.net", true), new ResultPair("\"\\\"\"@foo.bar", true), new ResultPair("fred&[email protected]", true), new ResultPair("[email protected]", true), new ResultPair("[email protected]", true), new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true), new ResultPair("Abigail <[email protected]>", true), new ResultPair("Abigail<[email protected]>", true), new ResultPair("Abigail<@a,@b,@c:[email protected]>", true), new ResultPair("\"This is a phrase\"<[email protected]>", true), new ResultPair("\"Abigail \"<[email protected]>", true), new ResultPair("\"Joe & J. Harvey\" <example @Org>", true), new ResultPair("Abigail <abigail @ example.com>", true), new ResultPair("Abigail made this < abigail @ example . com >", true), new ResultPair("Abigail(the bitch)@example.com", true), new ResultPair("Abigail <abigail @ example . (bar) com >", true), new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail <abigail(fo\\(o)@example.com>", true), new ResultPair("Abigail <abigail(fo\\)o)@example.com> ", true), new ResultPair("(foo) [email protected]", true), new ResultPair("[email protected] (foo)", true), new ResultPair("\"Abi\\\"gail\" <[email protected]>", true), new ResultPair("abigail@[example.com]", true), new ResultPair("abigail@[exa\\[ple.com]", true), new ResultPair("abigail@[exa\\]ple.com]", true), new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true), new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true), new ResultPair("mailbox.sub1.sub2@this-domain", true), new ResultPair("[email protected]", true), new ResultPair("name:;", true), new ResultPair("':;", true), new ResultPair("name: ;", true), new ResultPair("Alfred Neuman <Neuman@BBN-TENEXA>", true), new ResultPair("Neuman@BBN-TENEXA", true), new ResultPair("\"George, Ted\" <[email protected]>", true), new ResultPair("Wilt . (the Stilt) [email protected]", true), new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true), new ResultPair("$@[]", true), new ResultPair("*()@[]", true), new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true), new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A <ddd\\@ Org>", true), new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" <ddd \\@ Org>", true), new ResultPair("Gourmets: Pompous Person <WhoZiWhatZit\\@Cordon-Bleu>,\\x0D\\x0A" + " Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" + " ANT.Down-Under (Australian National Television),\\x0D\\x0A" + " Cheapie\\@Discount-Liquors;", true), new ResultPair(" Just a string", false), new ResultPair("string", false), new ResultPair("(comment)", false), new ResultPair("()@example.com", false), new ResultPair("fred(&)[email protected]", false), new ResultPair("fred\\ [email protected]", false), new ResultPair("Abigail <abi gail @ example.com>", false), new ResultPair("Abigail <abigail(fo(o)@example.com>", false), new ResultPair("Abigail <abigail(fo)o)@example.com>", false), new ResultPair("\"Abi\"gail\" <[email protected]>", false), new ResultPair("abigail@[exa]ple.com]", false), new ResultPair("abigail@[exa[ple.com]", false), new ResultPair("abigail@[exaple].com]", false), new ResultPair("abigail@", false), new ResultPair("@example.com", false), new ResultPair("phrase: [email protected] [email protected] ;", false), new ResultPair("invalid�[email protected]", false) }; /** * Write this test based on perl Mail::RFC822::Address * which takes its example email address directly from RFC822 * * This test fails so disable it * The real solution is to fix the email parsing. */ @Ignore("VALIDATOR-267") @Test public void testEmailFromPerl() { int errors = 0; for (int index = 0; index < testEmailFromPerl.length; index++) { String item = testEmailFromPerl[index].item; boolean exp = testEmailFromPerl[index].valid; boolean act = validator.isValid(item); if (act != exp) { System.out.printf("%s: expected %s actual %s%n", item, exp, act); errors += 1; } } assertEquals("Expected 0 errors", 0, errors); } @Test public void testValidator293(){ assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertTrue(validator.isValid("[email protected]")); assertFalse(validator.isValid("abc@abc_def.com")); } @Test public void testValidator365() { assertFalse(validator.isValid( "Loremipsumdolorsitametconsecteturadipiscingelit.Nullavitaeligulamattisrhoncusnuncegestasmattisleo."+ "Donecnonsapieninmagnatristiquedictumaacturpis.Fusceorciduifacilisisutsapieneuconsequatpharetralectus."+ "Quisqueenimestpulvinarutquamvitaeportamattisex.Nullamquismaurisplaceratconvallisjustoquisportamauris."+ "Innullalacusconvalliseufringillautvenenatissitametdiam.Maecenasluctusligulascelerisquepulvinarfeugiat."+ "Sedmolestienullaaliquetorciluctusidpharetranislfinibus.Suspendissemalesuadatinciduntduisitametportaarcusollicitudinnec."+ "Donecetmassamagna.Curabitururnadiampretiumveldignissimporttitorfringillaeuneque."+ "Duisantetelluspharetraidtinciduntinterdummolestiesitametfelis.Utquisquamsitametantesagittisdapibusacnonodio."+ "Namrutrummolestiediamidmattis.Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus."+ "Morbiposueresedmetusacconsectetur.Etiamquisipsumvitaejustotempusmaximus.Sedultriciesplaceratvolutpat."+ "Integerlacuslectusmaximusacornarequissagittissitametjusto."+ "Cumsociisnatoquepenatibusetmagnisdisparturientmontesnasceturridiculusmus.Maecenasindictumpurussedrutrumex.Nullafacilisi."+ "Integerfinibusfinibusmietpharetranislfaucibusvel.Maecenasegetdolorlacinialobortisjustovelullamcorpersem."+ "Vivamusaliquetpurusidvariusornaresapienrisusrutrumnisitinciduntmollissemnequeidmetus."+ "Etiamquiseleifendpurus.Nuncfelisnuncscelerisqueiddignissimnecfinibusalibero."+ "Nuncsemperenimnequesitamethendreritpurusfacilisisac.Maurisdapibussemperfelisdignissimgravida."+ "Aeneanultricesblanditnequealiquamfinibusodioscelerisqueac.Aliquamnecmassaeumaurisfaucibusfringilla."+ "Etiamconsequatligulanisisitametaliquamnibhtemporquis.Nuncinterdumdignissimnullaatsodalesarcusagittiseu."+ "Proinpharetrametusneclacuspulvinarsedvolutpatliberoornare.Sedligulanislpulvinarnonlectuseublanditfacilisisante."+ "Sedmollisnislalacusauctorsuscipit.Inhachabitasseplateadictumst.Phasellussitametvelittemporvenenatisfeliseuegestasrisus."+ "Aliquameteratsitametnibhcommodofinibus.Morbiefficiturodiovelpulvinariaculis."+ "Aeneantemporipsummassaaconsecteturturpisfaucibusultrices.Praesentsodalesmaurisquisportafermentum."+ "Etiamnisinislvenenatisvelauctorutullamcorperinjusto.Proinvelligulaerat.Phasellusvestibulumgravidamassanonfeugiat."+ "Maecenaspharetraeuismodmetusegetefficitur.Suspendisseamet@gmail.com")); } /** * Tests the e-mail validation with a user at a TLD * * http://tools.ietf.org/html/rfc5321#section-2.3.5 * (In the case of a top-level domain used by itself in an * email address, a single string is used without any dots) */ @Test public void testEmailAtTLD() { EmailValidator val = EmailValidator.getInstance(false, true); assertTrue(val.isValid("test@com")); } @Test public void testValidator359() { EmailValidator val = EmailValidator.getInstance(false, true); assertFalse(val.isValid("[email protected]")); } @Test public void testValidator374() { assertTrue(validator.isValid("[email protected]")); } @Test(expected = IllegalArgumentException.class) public void testValidator473_1() { // reject null DomainValidator new EmailValidator(false, false, null); } @Test(expected = IllegalArgumentException.class) public void testValidator473_2() { // reject null DomainValidator with mismatched allowLocal List<DomainValidator.Item> items = new ArrayList<>(); new EmailValidator(false, false, DomainValidator.getInstance(true, items)); } @Test(expected = IllegalArgumentException.class) public void testValidator473_3() { // reject null DomainValidator with mismatched allowLocal List<DomainValidator.Item> items = new ArrayList<>(); new EmailValidator(true, false, DomainValidator.getInstance(false, items)); } @Test public void testValidator473_4() { // Show that can override domain validation assertFalse(validator.isValidDomain("test.local")); List<DomainValidator.Item> items = new ArrayList<>(); items.add(new DomainValidator.Item(DomainValidator.ArrayType.GENERIC_PLUS, new String[]{"local"})); EmailValidator val = new EmailValidator(true, false, DomainValidator.getInstance(true, items)); assertTrue(val.isValidDomain("test.local")); } }
For manual testing
src/test/java/org/apache/commons/validator/routines/EmailValidatorTest.java
For manual testing
<ide><path>rc/test/java/org/apache/commons/validator/routines/EmailValidatorTest.java <ide> assertTrue(val.isValidDomain("test.local")); <ide> } <ide> <add> public static void main(String[] args) { <add> EmailValidator validator = EmailValidator.getInstance(); <add> for(String arg : args) { <add> System.out.printf("%s: %s%n", arg, validator.isValid(arg)); <add> } <add> } <ide> }
Java
mpl-2.0
31fdb4b9d6cfe73826bb622ffd47f0bc6bbec3b4
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: AccessBridge.java,v $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package org.openoffice.accessibility; import com.sun.star.awt.XTopWindow; import com.sun.star.awt.XTopWindowListener; import com.sun.star.awt.XWindow; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.*; import com.sun.star.uno.*; import com.sun.star.comp.loader.FactoryHelper; import org.openoffice.accessibility.internal.*; import org.openoffice.java.accessibility.*; import com.sun.star.accessibility.XAccessible; import drafts.com.sun.star.accessibility.bridge.XAccessibleTopWindowMap; import com.sun.star.awt.XExtendedToolkit; import javax.accessibility.Accessible; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; public class AccessBridge { // static public class _AccessBridge implements XAccessibleTopWindowMap, XInitialization { static final String _serviceName = "com.sun.star.accessibility.AccessBridge"; XMultiServiceFactory serviceManager; java.util.Hashtable frameMap; public _AccessBridge(XMultiServiceFactory xMultiServiceFactory) { serviceManager = xMultiServiceFactory; frameMap = new java.util.Hashtable(); } /* * XInitialization */ public void initialize(java.lang.Object[] arguments) { try { // Currently there is no way to determine if key event forwarding is needed or not, // so we have to do it always .. XExtendedToolkit unoToolkit = (XExtendedToolkit) AnyConverter.toObject(new Type(XExtendedToolkit.class), arguments[0]); if(unoToolkit != null) { unoToolkit.addKeyHandler(new KeyHandler()); } else if( Build.DEBUG) { System.err.println("argument 0 is not of type XExtendedToolkit."); } } catch(com.sun.star.lang.IllegalArgumentException e) { // FIXME: output } } /* * XAccessibleNativeFrameMap */ public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){ try { // The office sometimes registers frames more than once, so check here if already done Integer handle = new Integer(AnyConverter.toInt(any)); if (! frameMap.containsKey(handle)) { if( Build.DEBUG ) { System.out.println("register native frame: " + handle); } java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible); if (w != null) { frameMap.put(handle, w); } } } catch (com.sun.star.lang.IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch (java.lang.Exception e) { System.err.println("Exception caught: " + e.getMessage()); } } public void revokeAccessibleNativeFrame(Object any) { try { Integer handle = new Integer(AnyConverter.toInt(any)); // Remember the accessible object associated to this frame java.awt.Window w = (java.awt.Window) frameMap.remove(handle); if (w != null) { if (Build.DEBUG) { System.out.println("revoke native frame: " + handle); } w.dispose(); } } catch (com.sun.star.lang.IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } } } static public class _WinAccessBridge extends _AccessBridge { Method registerVirtualFrame; Method revokeVirtualFrame; public _WinAccessBridge(XMultiServiceFactory xMultiServiceFactory) { super(xMultiServiceFactory); // java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); // tk.addAWTEventListener(new WindowsAccessBridgeAdapter(), java.awt.AWTEvent.WINDOW_EVENT_MASK); // On Windows all native frames must be registered to the access bridge. Therefor // the bridge exports two methods that we try to find here. try { Class bridge = Class.forName("com.sun.java.accessibility.AccessBridge"); Class[] parameterTypes = { javax.accessibility.Accessible.class, Integer.class }; if(bridge != null) { registerVirtualFrame = bridge.getMethod("registerVirtualFrame", parameterTypes); revokeVirtualFrame = bridge.getMethod("revokeVirtualFrame", parameterTypes); } } catch(NoSuchMethodException e) { System.err.println("ERROR: incompatible AccessBridge found: " + e.getMessage()); // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("incompatible AccessBridge class: " + e.getMessage()); } catch(java.lang.SecurityException e) { System.err.println("ERROR: no access to AccessBridge: " + e.getMessage()); // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("Security exception caught: " + e.getMessage()); } catch(ClassNotFoundException e) { // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("ClassNotFound exception caught: " + e.getMessage()); } } // Registers the native frame at the Windows access bridge protected void registerAccessibleNativeFrameImpl(Integer handle, Accessible a) { // register this frame to the access bridge Object[] args = { a, handle }; try { registerVirtualFrame.invoke(null, args); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException caught: " + e.getMessage()); } catch(IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch(InvocationTargetException e) { System.err.println("InvokationTargetException caught: " + e.getMessage()); } } // Revokes the native frame from the Windows access bridge protected void revokeAccessibleNativeFrameImpl(Integer handle, Accessible a) { Object[] args = { a, handle }; try { revokeVirtualFrame.invoke(null, args); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException caught: " + e.getMessage()); } catch(IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch(InvocationTargetException e) { System.err.println("InvokationTargetException caught: " + e.getMessage()); } } /* * XAccessibleNativeFrameMap */ public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){ try { // The office sometimes registers frames more than once, so check here if already done Integer handle = new Integer(AnyConverter.toInt(any)); if (! frameMap.containsKey(handle)) { java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible); if (Build.DEBUG) { System.out.println("register native frame: " + handle); } if (w != null) { // Add the window proxy object to the frame list frameMap.put(handle, w); // Also register the frame with the access bridge object registerAccessibleNativeFrameImpl(handle,w); } } } catch(com.sun.star.lang.IllegalArgumentException exception) { System.err.println("IllegalArgumentException caught: " + exception.getMessage()); } } public void revokeAccessibleNativeFrame(Object any) { try { Integer handle = new Integer(AnyConverter.toInt(any)); // Remember the accessible object associated to this frame java.awt.Window w = (java.awt.Window) frameMap.remove(handle); if (w != null) { // Revoke the frame with the access bridge object revokeAccessibleNativeFrameImpl(handle, w); if (Build.DEBUG) { System.out.println("revoke native frame: " + handle); } // It seems that we have to do this synchronously, because otherwise on exit // the main thread of the office terminates before AWT has shut down and the // process will hang .. w.dispose(); /* class DisposeAction implements Runnable { java.awt.Window window; DisposeAction(java.awt.Window w) { window = w; } public void run() { window.dispose(); } } java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().invokeLater(new DisposeAction(w)); */ } } catch(com.sun.star.lang.IllegalArgumentException exception) { System.err.println("IllegalArgumentException caught: " + exception.getMessage()); } } } public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; if (implName.equals(AccessBridge.class.getName()) ) { // Initialize toolkit to register at Java <-> Windows access bridge java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); Class serviceClass; String os = (String) System.getProperty("os.name"); if(os.startsWith("Windows")) { serviceClass = _WinAccessBridge.class; } else { serviceClass = _AccessBridge.class; } xSingleServiceFactory = FactoryHelper.getServiceFactory( serviceClass, _AccessBridge._serviceName, multiFactory, regKey ); } return xSingleServiceFactory; } public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return FactoryHelper.writeRegistryServiceInfo(AccessBridge.class.getName(), _AccessBridge._serviceName, regKey); } }
accessibility/bridge/org/openoffice/accessibility/AccessBridge.java
/************************************************************************* * * $RCSfile: AccessBridge.java,v $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package org.openoffice.accessibility; import com.sun.star.awt.XTopWindow; import com.sun.star.awt.XTopWindowListener; import com.sun.star.awt.XWindow; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.*; import com.sun.star.uno.*; import com.sun.star.comp.loader.FactoryHelper; import org.openoffice.accessibility.internal.*; import org.openoffice.java.accessibility.*; import com.sun.star.accessibility.XAccessible; import drafts.com.sun.star.accessibility.bridge.XAccessibleTopWindowMap; import com.sun.star.awt.XExtendedToolkit; import javax.accessibility.Accessible; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; public class AccessBridge { // static public class _AccessBridge implements XAccessibleTopWindowMap, XInitialization { static final String _serviceName = "com.sun.star.accessibilityAccessBridge"; XMultiServiceFactory serviceManager; java.util.Hashtable frameMap; public _AccessBridge(XMultiServiceFactory xMultiServiceFactory) { serviceManager = xMultiServiceFactory; frameMap = new java.util.Hashtable(); } /* * XInitialization */ public void initialize(java.lang.Object[] arguments) { try { // Currently there is no way to determine if key event forwarding is needed or not, // so we have to do it always .. XExtendedToolkit unoToolkit = (XExtendedToolkit) AnyConverter.toObject(new Type(XExtendedToolkit.class), arguments[0]); if(unoToolkit != null) { unoToolkit.addKeyHandler(new KeyHandler()); } else if( Build.DEBUG) { System.err.println("argument 0 is not of type XExtendedToolkit."); } } catch(com.sun.star.lang.IllegalArgumentException e) { // FIXME: output } } /* * XAccessibleNativeFrameMap */ public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){ try { // The office sometimes registers frames more than once, so check here if already done Integer handle = new Integer(AnyConverter.toInt(any)); if (! frameMap.containsKey(handle)) { if( Build.DEBUG ) { System.out.println("register native frame: " + handle); } java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible); if (w != null) { frameMap.put(handle, w); } } } catch (com.sun.star.lang.IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch (java.lang.Exception e) { System.err.println("Exception caught: " + e.getMessage()); } } public void revokeAccessibleNativeFrame(Object any) { try { Integer handle = new Integer(AnyConverter.toInt(any)); // Remember the accessible object associated to this frame java.awt.Window w = (java.awt.Window) frameMap.remove(handle); if (w != null) { if (Build.DEBUG) { System.out.println("revoke native frame: " + handle); } w.dispose(); } } catch (com.sun.star.lang.IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } } } static public class _WinAccessBridge extends _AccessBridge { Method registerVirtualFrame; Method revokeVirtualFrame; public _WinAccessBridge(XMultiServiceFactory xMultiServiceFactory) { super(xMultiServiceFactory); // java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); // tk.addAWTEventListener(new WindowsAccessBridgeAdapter(), java.awt.AWTEvent.WINDOW_EVENT_MASK); // On Windows all native frames must be registered to the access bridge. Therefor // the bridge exports two methods that we try to find here. try { Class bridge = Class.forName("com.sun.java.accessibility.AccessBridge"); Class[] parameterTypes = { javax.accessibility.Accessible.class, Integer.class }; if(bridge != null) { registerVirtualFrame = bridge.getMethod("registerVirtualFrame", parameterTypes); revokeVirtualFrame = bridge.getMethod("revokeVirtualFrame", parameterTypes); } } catch(NoSuchMethodException e) { System.err.println("ERROR: incompatible AccessBridge found: " + e.getMessage()); // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("incompatible AccessBridge class: " + e.getMessage()); } catch(java.lang.SecurityException e) { System.err.println("ERROR: no access to AccessBridge: " + e.getMessage()); // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("Security exception caught: " + e.getMessage()); } catch(ClassNotFoundException e) { // Forward this exception to UNO to indicate that the service will not work correctly. throw new com.sun.star.uno.RuntimeException("ClassNotFound exception caught: " + e.getMessage()); } } // Registers the native frame at the Windows access bridge protected void registerAccessibleNativeFrameImpl(Integer handle, Accessible a) { // register this frame to the access bridge Object[] args = { a, handle }; try { registerVirtualFrame.invoke(null, args); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException caught: " + e.getMessage()); } catch(IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch(InvocationTargetException e) { System.err.println("InvokationTargetException caught: " + e.getMessage()); } } // Revokes the native frame from the Windows access bridge protected void revokeAccessibleNativeFrameImpl(Integer handle, Accessible a) { Object[] args = { a, handle }; try { revokeVirtualFrame.invoke(null, args); } catch(IllegalAccessException e) { System.err.println("IllegalAccessException caught: " + e.getMessage()); } catch(IllegalArgumentException e) { System.err.println("IllegalArgumentException caught: " + e.getMessage()); } catch(InvocationTargetException e) { System.err.println("InvokationTargetException caught: " + e.getMessage()); } } /* * XAccessibleNativeFrameMap */ public void registerAccessibleNativeFrame(Object any, XAccessible xAccessible, XTopWindow xTopWindow ){ try { // The office sometimes registers frames more than once, so check here if already done Integer handle = new Integer(AnyConverter.toInt(any)); if (! frameMap.containsKey(handle)) { java.awt.Window w = AccessibleObjectFactory.getTopWindow(xAccessible); if (Build.DEBUG) { System.out.println("register native frame: " + handle); } if (w != null) { // Add the window proxy object to the frame list frameMap.put(handle, w); // Also register the frame with the access bridge object registerAccessibleNativeFrameImpl(handle,w); } } } catch(com.sun.star.lang.IllegalArgumentException exception) { System.err.println("IllegalArgumentException caught: " + exception.getMessage()); } } public void revokeAccessibleNativeFrame(Object any) { try { Integer handle = new Integer(AnyConverter.toInt(any)); // Remember the accessible object associated to this frame java.awt.Window w = (java.awt.Window) frameMap.remove(handle); if (w != null) { // Revoke the frame with the access bridge object revokeAccessibleNativeFrameImpl(handle, w); if (Build.DEBUG) { System.out.println("revoke native frame: " + handle); } // It seems that we have to do this synchronously, because otherwise on exit // the main thread of the office terminates before AWT has shut down and the // process will hang .. w.dispose(); /* class DisposeAction implements Runnable { java.awt.Window window; DisposeAction(java.awt.Window w) { window = w; } public void run() { window.dispose(); } } java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().invokeLater(new DisposeAction(w)); */ } } catch(com.sun.star.lang.IllegalArgumentException exception) { System.err.println("IllegalArgumentException caught: " + exception.getMessage()); } } } public static XSingleServiceFactory __getServiceFactory(String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey) { XSingleServiceFactory xSingleServiceFactory = null; if (implName.equals(AccessBridge.class.getName()) ) { // Initialize toolkit to register at Java <-> Windows access bridge java.awt.Toolkit tk = java.awt.Toolkit.getDefaultToolkit(); Class serviceClass; String os = (String) System.getProperty("os.name"); if(os.startsWith("Windows")) { serviceClass = _WinAccessBridge.class; } else { serviceClass = _AccessBridge.class; } xSingleServiceFactory = FactoryHelper.getServiceFactory( serviceClass, _AccessBridge._serviceName, multiFactory, regKey ); } return xSingleServiceFactory; } public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { return FactoryHelper.writeRegistryServiceInfo(AccessBridge.class.getName(), _AccessBridge._serviceName, regKey); } }
INTEGRATION: CWS beta2regression02 (1.14.2); FILE MERGED 2003/04/29 16:08:34 obr 1.14.2.1: #109204# transisiont from drafts to stable
accessibility/bridge/org/openoffice/accessibility/AccessBridge.java
INTEGRATION: CWS beta2regression02 (1.14.2); FILE MERGED 2003/04/29 16:08:34 obr 1.14.2.1: #109204# transisiont from drafts to stable
<ide><path>ccessibility/bridge/org/openoffice/accessibility/AccessBridge.java <ide> <ide> // <ide> static public class _AccessBridge implements XAccessibleTopWindowMap, XInitialization { <del> static final String _serviceName = "com.sun.star.accessibilityAccessBridge"; <add> static final String _serviceName = "com.sun.star.accessibility.AccessBridge"; <ide> <ide> XMultiServiceFactory serviceManager; <ide> java.util.Hashtable frameMap;
Java
apache-2.0
6b61db07c93dd163eac22baecef5b93eee05ce64
0
noemus/kotlin-eclipse,noemus/kotlin-eclipse
package org.jetbrains.kotlin.ui.editors.quickfix; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatchRequestor; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator2; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.IDocumentProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.core.log.KotlinLogger; import org.jetbrains.kotlin.ui.editors.AnnotationManager; import org.jetbrains.kotlin.ui.editors.DiagnosticAnnotation; import com.intellij.openapi.util.TextRange; public class KotlinMarkerResolutionGenerator implements IMarkerResolutionGenerator2 { private static SearchEngine searchEngine = new SearchEngine(); private static IMarkerResolution[] NO_RESOLUTIONS = new IMarkerResolution[] { }; @Override public IMarkerResolution[] getResolutions(@Nullable IMarker marker) { if (!hasResolutions(marker)) { return NO_RESOLUTIONS; } String markedText = null; if (marker != null) { markedText = marker.getAttribute(AnnotationManager.MARKED_TEXT, null); } if (markedText == null) { JavaEditor activeEditor = (JavaEditor) getActiveEditor(); if (activeEditor != null) { int caretOffset = activeEditor.getViewer().getTextWidget().getCaretOffset(); DiagnosticAnnotation annotation = getAnnotationByOffset(caretOffset); if (annotation != null) { markedText = annotation.getMarkedText(); } } } if (markedText == null) { return NO_RESOLUTIONS; } List<IType> typeResolutions = findAllTypes(markedText); List<AutoImportMarkerResolution> markerResolutions = new ArrayList<AutoImportMarkerResolution>(); for (IType type : typeResolutions) { markerResolutions.add(new AutoImportMarkerResolution(type)); } return markerResolutions.toArray(new IMarkerResolution[markerResolutions.size()]); } @NotNull private List<IType> findAllTypes(@NotNull String typeName) { IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); List<IType> searchCollector = new ArrayList<IType>(); TypeNameMatchRequestor requestor = new KotlinSearchTypeRequestor(searchCollector); try { searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH, typeName.toCharArray(), SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (CoreException e) { KotlinLogger.logAndThrow(e); } return searchCollector; } @Override public boolean hasResolutions(@Nullable IMarker marker) { JavaEditor activeEditor = (JavaEditor) getActiveEditor(); if (activeEditor == null) { return false; } int caretOffset = activeEditor.getViewer().getTextWidget().getCaretOffset(); Annotation annotation = getAnnotationByOffset(caretOffset); if (annotation != null) { if (annotation instanceof DiagnosticAnnotation) { return ((DiagnosticAnnotation) annotation).quickFixable(); } } if (marker != null) { return marker.getAttribute(AnnotationManager.IS_QUICK_FIXABLE, false); } return false; } @Nullable private DiagnosticAnnotation getAnnotationByOffset(int offset) { AbstractTextEditor editor = getActiveEditor(); if (editor == null) { return null; } IDocumentProvider documentProvider = editor.getDocumentProvider(); IAnnotationModel annotationModel = documentProvider.getAnnotationModel(editor.getEditorInput()); for (Iterator<?> i = annotationModel.getAnnotationIterator(); i.hasNext();) { Annotation annotation = (Annotation) i.next(); if (annotation instanceof DiagnosticAnnotation) { DiagnosticAnnotation diagnosticAnnotation = (DiagnosticAnnotation) annotation; TextRange range = diagnosticAnnotation.getRange(); if (range.getStartOffset() <= offset && range.getEndOffset() >= offset) { return diagnosticAnnotation; } } } return null; } @Nullable private AbstractTextEditor getActiveEditor() { IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow == null) { return null; } AbstractTextEditor editor = (AbstractTextEditor) workbenchWindow.getActivePage().getActiveEditor(); return editor; } }
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/quickfix/KotlinMarkerResolutionGenerator.java
package org.jetbrains.kotlin.ui.editors.quickfix; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatchRequestor; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator2; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.IDocumentProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.core.log.KotlinLogger; import org.jetbrains.kotlin.ui.editors.AnnotationManager; import org.jetbrains.kotlin.ui.editors.DiagnosticAnnotation; import com.intellij.openapi.util.TextRange; public class KotlinMarkerResolutionGenerator implements IMarkerResolutionGenerator2 { private static SearchEngine searchEngine = new SearchEngine(); private static IMarkerResolution[] NO_RESOLUTIONS = new IMarkerResolution[] { }; @Override public IMarkerResolution[] getResolutions(@Nullable IMarker marker) { if (!hasResolutions(marker)) { return NO_RESOLUTIONS; } String markedText = null; if (marker != null) { markedText = marker.getAttribute(AnnotationManager.MARKED_TEXT, null); } if (markedText == null) { int caretOffset = ((JavaEditor) getActiveEditor()).getViewer().getTextWidget().getCaretOffset(); DiagnosticAnnotation annotation = getAnnotationByOffset(caretOffset); if (annotation != null) { markedText = annotation.getMarkedText(); } } if (markedText == null) { return NO_RESOLUTIONS; } List<IType> typeResolutions = findAllTypes(markedText); List<AutoImportMarkerResolution> markerResolutions = new ArrayList<AutoImportMarkerResolution>(); for (IType type : typeResolutions) { markerResolutions.add(new AutoImportMarkerResolution(type)); } return markerResolutions.toArray(new IMarkerResolution[markerResolutions.size()]); } @NotNull private List<IType> findAllTypes(@NotNull String typeName) { IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); List<IType> searchCollector = new ArrayList<IType>(); TypeNameMatchRequestor requestor = new KotlinSearchTypeRequestor(searchCollector); try { searchEngine.searchAllTypeNames(null, SearchPattern.R_EXACT_MATCH, typeName.toCharArray(), SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.TYPE, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (CoreException e) { KotlinLogger.logAndThrow(e); } return searchCollector; } @Override public boolean hasResolutions(@Nullable IMarker marker) { int caretOffset = ((JavaEditor) getActiveEditor()).getViewer().getTextWidget().getCaretOffset(); Annotation annotation = getAnnotationByOffset(caretOffset); if (annotation != null) { if (annotation instanceof DiagnosticAnnotation) { return ((DiagnosticAnnotation) annotation).quickFixable(); } } if (marker != null) { return marker.getAttribute(AnnotationManager.IS_QUICK_FIXABLE, false); } return false; } @Nullable private DiagnosticAnnotation getAnnotationByOffset(int offset) { AbstractTextEditor editor = getActiveEditor(); if (editor == null) { return null; } IDocumentProvider documentProvider = editor.getDocumentProvider(); IAnnotationModel annotationModel = documentProvider.getAnnotationModel(editor.getEditorInput()); for (Iterator<?> i = annotationModel.getAnnotationIterator(); i.hasNext();) { Annotation annotation = (Annotation) i.next(); if (annotation instanceof DiagnosticAnnotation) { DiagnosticAnnotation diagnosticAnnotation = (DiagnosticAnnotation) annotation; TextRange range = diagnosticAnnotation.getRange(); if (range.getStartOffset() <= offset && range.getEndOffset() >= offset) { return diagnosticAnnotation; } } } return null; } @Nullable private AbstractTextEditor getActiveEditor() { IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (workbenchWindow == null) { return null; } AbstractTextEditor editor = (AbstractTextEditor) workbenchWindow.getActivePage().getActiveEditor(); return editor; } }
Remove null-errors
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/quickfix/KotlinMarkerResolutionGenerator.java
Remove null-errors
<ide><path>otlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/quickfix/KotlinMarkerResolutionGenerator.java <ide> } <ide> <ide> if (markedText == null) { <del> int caretOffset = ((JavaEditor) getActiveEditor()).getViewer().getTextWidget().getCaretOffset(); <del> DiagnosticAnnotation annotation = getAnnotationByOffset(caretOffset); <del> if (annotation != null) { <del> markedText = annotation.getMarkedText(); <add> JavaEditor activeEditor = (JavaEditor) getActiveEditor(); <add> <add> if (activeEditor != null) { <add> int caretOffset = activeEditor.getViewer().getTextWidget().getCaretOffset(); <add> DiagnosticAnnotation annotation = getAnnotationByOffset(caretOffset); <add> if (annotation != null) { <add> markedText = annotation.getMarkedText(); <add> } <ide> } <ide> } <ide> <ide> <ide> @Override <ide> public boolean hasResolutions(@Nullable IMarker marker) { <del> int caretOffset = ((JavaEditor) getActiveEditor()).getViewer().getTextWidget().getCaretOffset(); <add> JavaEditor activeEditor = (JavaEditor) getActiveEditor(); <add> <add> if (activeEditor == null) { <add> return false; <add> } <add> <add> int caretOffset = activeEditor.getViewer().getTextWidget().getCaretOffset(); <ide> Annotation annotation = getAnnotationByOffset(caretOffset); <ide> <ide> if (annotation != null) {
Java
epl-1.0
3b677f9f801744f5d7bda2fba8609b7510dde4dc
0
gnodet/wikitext
/******************************************************************************* * Copyright (c) 2003 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.bugzilla.ui.editor; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareUI; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.internal.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.internal.bugzilla.core.BugzillaReportElement; import org.eclipse.mylar.internal.bugzilla.core.BugzillaReportSubmitForm; import org.eclipse.mylar.internal.bugzilla.core.BugzillaRepositoryUtil; import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylar.internal.bugzilla.ui.BugzillaCompareInput; import org.eclipse.mylar.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylar.internal.bugzilla.ui.tasklist.BugzillaRepositoryConnector; import org.eclipse.mylar.internal.tasklist.Comment; import org.eclipse.mylar.internal.tasklist.RepositoryOperation; import org.eclipse.mylar.internal.tasklist.RepositoryTaskAttribute; import org.eclipse.mylar.internal.tasklist.RepositoryTaskData; import org.eclipse.mylar.internal.tasklist.ui.editors.AbstractBugEditorInput; import org.eclipse.mylar.internal.tasklist.ui.editors.AbstractRepositoryTaskEditor; import org.eclipse.mylar.internal.tasklist.ui.editors.ExistingBugEditorInput; import org.eclipse.mylar.internal.tasklist.ui.editors.RepositoryTaskOutlineNode; import org.eclipse.mylar.internal.tasklist.ui.editors.RepositoryTaskSelection; import org.eclipse.mylar.internal.tasklist.ui.views.DatePicker; import org.eclipse.mylar.internal.tasklist.ui.views.TaskRepositoriesView; import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryConnector; import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin; import org.eclipse.mylar.provisional.tasklist.TaskRepository; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; /** * An editor used to view a bug report that exists on a server. It uses a * <code>BugReport</code> object to store the data. * * @author Mik Kersten (hardening of prototype) * @author Rob Elves (adaption to Eclipse Forms) */ public class ExistingBugEditor extends AbstractRepositoryTaskEditor { private static final String LABEL_TIME_TRACKING = "Bugzilla Time Tracking"; private static final String REASSIGN_BUG_TO = "Reassign bug to"; private static final String LABEL_COMPARE_BUTTON = "Compare"; protected Set<String> removeCC = new HashSet<String>(); protected BugzillaCompareInput compareInput; protected Button compareButton; protected Button[] radios; protected Control[] radioOptions; protected List keyWordsList; protected Text keywordsText; protected List ccList; protected Text ccText; protected Text urlText; protected RepositoryTaskData taskData; protected AbstractRepositoryConnector connector; protected Text estimateText; protected Text actualText; protected Text remainingText; protected Text addTimeText; protected Text deadlineText; protected DatePicker deadlinePicker; /** * Creates a new <code>ExistingBugEditor</code>. */ public ExistingBugEditor() { super(); // Set up the input for comparing the bug report to the server CompareConfiguration config = new CompareConfiguration(); config.setLeftEditable(false); config.setRightEditable(false); config.setLeftLabel("Local Bug Report"); config.setRightLabel("Remote Bug Report"); config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); compareInput = new BugzillaCompareInput(config); } // @SuppressWarnings("deprecation") @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof ExistingBugEditorInput)) throw new PartInitException("Invalid Input: Must be ExistingBugEditorInput"); editorInput = (AbstractBugEditorInput) input; taskData = editorInput.getRepositoryTaskData(); repository = editorInput.getRepository(); connector = MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(repository.getKind()); setSite(site); setInput(input); taskOutlineModel = RepositoryTaskOutlineNode.parseBugReport(editorInput.getRepositoryTaskData()); // restoreBug(); isDirty = false; updateEditorTitle(); } @Override protected void addRadioButtons(Composite buttonComposite) { addSelfToCC(buttonComposite); FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); int i = 0; Button selected = null; radios = new Button[taskData.getOperations().size()]; radioOptions = new Control[taskData.getOperations().size()]; for (Iterator<RepositoryOperation> it = taskData.getOperations().iterator(); it.hasNext();) { RepositoryOperation o = it.next(); radios[i] = toolkit.createButton(buttonComposite, "", SWT.RADIO); radios[i].setFont(TEXT_FONT); GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); if (!o.hasOptions() && !o.isInput()) radioData.horizontalSpan = 4; else radioData.horizontalSpan = 3; radioData.heightHint = 20; String opName = o.getOperationName(); opName = opName.replaceAll("</.*>", ""); opName = opName.replaceAll("<.*>", ""); radios[i].setText(opName); radios[i].setLayoutData(radioData); // radios[i].setBackground(background); radios[i].addSelectionListener(new RadioButtonListener()); radios[i].addListener(SWT.FocusIn, new GenericListener()); if (o.hasOptions()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 1; radioData.heightHint = 20; radioData.widthHint = AbstractRepositoryTaskEditor.WRAP_LENGTH; // radioOptions[i] = new Combo(buttonComposite, SWT.NULL); radioOptions[i] = new CCombo(buttonComposite, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(radioOptions[i], true, true); // radioOptions[i] = new Combo(buttonComposite, SWT.MULTI | // SWT.V_SCROLL | SWT.READ_ONLY); // radioOptions[i].setData(FormToolkit.KEY_DRAW_BORDER, // FormToolkit.TEXT_BORDER); // radioOptions[i] = new Combo(buttonComposite, // SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL // | SWT.READ_ONLY); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); // radioOptions[i].setBackground(background); Object[] a = o.getOptionNames().toArray(); Arrays.sort(a); for (int j = 0; j < a.length; j++) { ((CCombo) radioOptions[i]).add((String) a[j]); } ((CCombo) radioOptions[i]).select(0); ((CCombo) radioOptions[i]).addSelectionListener(new RadioButtonListener()); } else if (o.isInput()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 1; radioData.widthHint = 120; // TODO: add condition for if opName = reassign to... String assignmentValue = ""; if (opName.equals(REASSIGN_BUG_TO)) { assignmentValue = repository.getUserName(); } radioOptions[i] = toolkit.createText(buttonComposite, assignmentValue);// , // SWT.SINGLE); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); // radioOptions[i].setBackground(background); ((Text) radioOptions[i]).setText(o.getInputValue()); ((Text) radioOptions[i]).addModifyListener(new RadioButtonListener()); } if (i == 0 || o.isChecked()) { if (selected != null) selected.setSelection(false); selected = radios[i]; radios[i].setSelection(true); if (o.hasOptions() && o.getOptionSelection() != null) { int j = 0; for (String s : ((CCombo) radioOptions[i]).getItems()) { if (s.compareTo(o.getOptionSelection()) == 0) { ((CCombo) radioOptions[i]).select(j); } j++; } } taskData.setSelectedOperation(o); } i++; } toolkit.paintBordersFor(buttonComposite); } private void addSelfToCC(Composite composite) { // if they aren't already on the cc list create an add self check box FormToolkit toolkit = new FormToolkit(composite.getDisplay()); RepositoryTaskAttribute owner = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); if (owner != null && owner.getValue().indexOf(repository.getUserName()) != -1) { return; } RepositoryTaskAttribute reporter = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER); if (reporter != null && reporter.getValue().indexOf(repository.getUserName()) != -1) { return; } // Don't add addselfcc if already there RepositoryTaskAttribute ccAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC); if (ccAttribute != null && ccAttribute.getValues().contains(repository.getUserName())) { return; } // taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), // "0"); final Button addSelfButton = toolkit.createButton(composite, "Add " + repository.getUserName() + " to CC list", SWT.CHECK); addSelfButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (addSelfButton.getSelection()) { taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), "1"); } else { taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), "0"); } changeDirtyStatus(true); } }); } @Override protected void addActionButtons(Composite buttonComposite) { FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); super.addActionButtons(buttonComposite); compareButton = toolkit.createButton(buttonComposite, LABEL_COMPARE_BUTTON, SWT.NONE); // compareButton.setFont(TEXT_FONT); GridData compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // compareButtonData.widthHint = 100; // compareButtonData.heightHint = 20; // // compareButton.setText("Compare"); compareButton.setLayoutData(compareButtonData); compareButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { OpenCompareEditorJob compareJob = new OpenCompareEditorJob("Comparing bug with remote server..."); compareJob.schedule(); } }); compareButton.addListener(SWT.FocusIn, new GenericListener()); // Button expandAll = toolkit.createButton(buttonComposite, // LABEL_EXPAND_ALL_BUTTON, SWT.NONE); // expandAll.setLayoutData(new // GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); // expandAll.addSelectionListener(new SelectionListener() { // // public void widgetDefaultSelected(SelectionEvent e) { // // ignore // // } // // public void widgetSelected(SelectionEvent e) { // revealAllComments(); // // } // }); // TODO used for spell checking. Add back when we want to support this // checkSpellingButton = new Button(buttonComposite, SWT.NONE); // checkSpellingButton.setFont(TEXT_FONT); // compareButtonData = new // GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // compareButtonData.widthHint = 100; // compareButtonData.heightHint = 20; // checkSpellingButton.setText("CheckSpelling"); // checkSpellingButton.setLayoutData(compareButtonData); // checkSpellingButton.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // checkSpelling(); // } // }); // checkSpellingButton.addListener(SWT.FocusIn, new GenericListener()); } /** * @return Returns the compareInput. */ public BugzillaCompareInput getCompareInput() { return compareInput; } // @Override // public RepositoryTaskData getBug() { // return taskData; // } @Override protected String getTitleString() { // Attribute summary = bug.getAttribute(ATTR_SUMMARY); // String summaryVal = ((null != summary) ? summary.getNewValue() : // null); return taskData.getLabel();// + ": " + checkText(summaryVal); } @Override public void submitBug() { if (isDirty()) { this.doSave(new NullProgressMonitor()); } updateBug(); submitButton.setEnabled(false); ExistingBugEditor.this.showBusy(true); BugzillaReportSubmitForm bugzillaReportSubmitForm; try { if (taskData.isLocallyCreated()) { boolean wrap = IBugzillaConstants.BugzillaServerVersion.SERVER_218.equals(repository.getVersion()); bugzillaReportSubmitForm = BugzillaReportSubmitForm.makeNewBugPost(repository.getUrl(), repository .getUserName(), repository.getPassword(), editorInput.getProxySettings(), repository .getCharacterEncoding(), taskData, wrap); } else { bugzillaReportSubmitForm = BugzillaReportSubmitForm.makeExistingBugPost(taskData, repository.getUrl(), repository.getUserName(), repository.getPassword(), editorInput.getProxySettings(), removeCC, repository.getCharacterEncoding()); } } catch (UnsupportedEncodingException e) { // should never get here but just in case... MessageDialog.openError(null, "Posting Error", "Ensure proper encoding selected in " + TaskRepositoriesView.NAME + "."); return; } final BugzillaRepositoryConnector bugzillaRepositoryClient = (BugzillaRepositoryConnector) MylarTaskListPlugin .getRepositoryManager().getRepositoryConnector(BugzillaPlugin.REPOSITORY_KIND); IJobChangeListener closeEditorListener = new IJobChangeListener() { public void done(final IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (event.getJob().getResult().equals(Status.OK_STATUS)) { close(); } else { submitButton.setEnabled(true); ExistingBugEditor.this.showBusy(false); } } }); } public void aboutToRun(IJobChangeEvent event) { // ignore } public void awake(IJobChangeEvent event) { // ignore } public void running(IJobChangeEvent event) { // ignore } public void scheduled(IJobChangeEvent event) { // ignore } public void sleeping(IJobChangeEvent event) { // ignore } }; bugzillaRepositoryClient.submitBugReport(taskData, bugzillaReportSubmitForm, closeEditorListener); } @Override protected void createCustomAttributeLayout(Composite composite) { FormToolkit toolkit = new FormToolkit(composite.getDisplay()); addCCList(toolkit, "", composite); try { addKeywordsList(toolkit, getRepositoryTaskData().getAttributeValue(RepositoryTaskAttribute.KEYWORDS), composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TaskRepositoriesView.NAME + "\n\nError reported: " + e.getMessage()); } if (getRepositoryTaskData().getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(toolkit, composite); } protected void addBugzillaTimeTracker(FormToolkit toolkit, Composite parent) { Section timeSection = toolkit.createSection(parent, ExpandableComposite.TREE_NODE); timeSection.setText(LABEL_TIME_TRACKING); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false); gd.horizontalSpan = 4; timeSection.setLayout(gl); timeSection.setLayoutData(gd); Composite timeComposite = toolkit.createComposite(timeSection); gl = new GridLayout(4, true); timeComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; timeComposite.setLayoutData(gd); RepositoryTaskData data = getRepositoryTaskData(); toolkit.createLabel(timeComposite, BugzillaReportElement.ESTIMATED_TIME.toString()); estimateText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ESTIMATED_TIME .getKeyString()), SWT.BORDER); estimateText.setFont(TEXT_FONT); estimateText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); estimateText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.ESTIMATED_TIME.getKeyString(), estimateText.getText()); } }); toolkit.createLabel(timeComposite, "Current Estimate:"); Text currentEstimate = toolkit.createText(timeComposite, "" + (Float.parseFloat(data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + Float .parseFloat(data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString())))); currentEstimate.setFont(TEXT_FONT); currentEstimate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); currentEstimate.setEditable(false); toolkit.createLabel(timeComposite, BugzillaReportElement.ACTUAL_TIME.toString()); actualText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME .getKeyString())); actualText.setFont(TEXT_FONT); actualText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); actualText.setEditable(false); data.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), "0"); toolkit.createLabel(timeComposite, BugzillaReportElement.WORK_TIME.toString()); addTimeText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.WORK_TIME .getKeyString()), SWT.BORDER); addTimeText.setFont(TEXT_FONT); addTimeText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); addTimeText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), addTimeText.getText()); } }); toolkit.createLabel(timeComposite, BugzillaReportElement.REMAINING_TIME.toString()); remainingText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.REMAINING_TIME .getKeyString()), SWT.BORDER); remainingText.setFont(TEXT_FONT); remainingText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); remainingText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData .setAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString(), remainingText.getText()); } }); toolkit.createLabel(timeComposite, BugzillaReportElement.DEADLINE.toString()); deadlinePicker = new DatePicker(timeComposite, /* SWT.NONE */SWT.BORDER, data .getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString())); deadlinePicker.setFont(TEXT_FONT); deadlinePicker.setDatePattern("yyyy-MM-dd"); deadlinePicker.addPickerSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { Calendar cal = deadlinePicker.getDate(); if (cal != null) { Date d = cal.getTime(); SimpleDateFormat f = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); f.applyPattern("yyyy-MM-dd"); taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), f.format(d)); changeDirtyStatus(true); // TODO goes dirty even if user // presses cancel } } }); timeSection.setClient(timeComposite); } protected void addKeywordsList(FormToolkit toolkit, String keywords, Composite attributesComposite) throws IOException { // newLayout(attributesComposite, 1, "Keywords:", PROPERTY); toolkit.createLabel(attributesComposite, "Keywords:"); keywordsText = toolkit.createText(attributesComposite, keywords); keywordsText.setFont(TEXT_FONT); keywordsText.setEditable(false); // keywordsText.setForeground(foreground); // keywordsText.setBackground(JFaceColors.getErrorBackground(display)); GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keywordsData.horizontalSpan = 2; keywordsData.widthHint = 200; keywordsText.setLayoutData(keywordsData); // keywordsText.setText(keywords); keywordsText.addListener(SWT.FocusIn, new GenericListener()); keyWordsList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL); keyWordsList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); keyWordsList.setFont(TEXT_FONT); GridData keyWordsTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keyWordsTextData.horizontalSpan = 1; keyWordsTextData.widthHint = 125; keyWordsTextData.heightHint = 40; keyWordsList.setLayoutData(keyWordsTextData); // initialize the keywords list with valid values java.util.List<String> validKeywords = new ArrayList<String>(); try { validKeywords = BugzillaPlugin.getRepositoryConfiguration(false, repository.getUrl(), MylarTaskListPlugin.getDefault().getProxySettings(), repository.getUserName(), repository.getPassword(), repository.getCharacterEncoding()).getKeywords(); } catch (Exception e) { // ignore } if (validKeywords != null) { for (Iterator<String> it = validKeywords.iterator(); it.hasNext();) { String keyword = it.next(); keyWordsList.add(keyword); } // get the selected keywords for the bug StringTokenizer st = new StringTokenizer(keywords, ",", false); ArrayList<Integer> indicies = new ArrayList<Integer>(); while (st.hasMoreTokens()) { String s = st.nextToken().trim(); int index = keyWordsList.indexOf(s); if (index != -1) indicies.add(new Integer(index)); } // select the keywords that were selected for the bug int length = indicies.size(); int[] sel = new int[length]; for (int i = 0; i < length; i++) { sel[i] = indicies.get(i).intValue(); } keyWordsList.select(sel); } keyWordsList.addSelectionListener(new KeywordListener()); keyWordsList.addListener(SWT.FocusIn, new GenericListener()); } protected void addCCList(FormToolkit toolkit, String ccValue, Composite attributesComposite) { newLayout(attributesComposite, 1, "Add CC:", PROPERTY); ccText = toolkit.createText(attributesComposite, ccValue); ccText.setFont(TEXT_FONT); ccText.setEditable(true); // ccText.setForeground(foreground); // ccText.setBackground(background); GridData ccData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); ccData.horizontalSpan = 1; ccData.widthHint = 200; ccText.setLayoutData(ccData); // ccText.setText(ccValue); ccText.addListener(SWT.FocusIn, new GenericListener()); ccText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.NEWCC.getKeyString(), ccText.getText()); } }); // newLayout(attributesComposite, 1, "CC: (Select to remove)", // PROPERTY); toolkit.createLabel(attributesComposite, "CC: (Select to remove)"); ccList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL);// SWT.BORDER ccList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); ccList.setFont(TEXT_FONT); GridData ccListData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); ccListData.horizontalSpan = 1; ccListData.widthHint = 125; ccListData.heightHint = 40; ccList.setLayoutData(ccListData); java.util.List<String> ccs = taskData.getCC(); if (ccs != null) { for (Iterator<String> it = ccs.iterator(); it.hasNext();) { String cc = it.next(); ccList.add(cc);// HtmlStreamTokenizer.unescape(cc)); } } ccList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { changeDirtyStatus(true); for (String cc : ccList.getItems()) { int index = ccList.indexOf(cc); if (ccList.isSelected(index)) { removeCC.add(cc); } else { removeCC.remove(cc); } } } public void widgetDefaultSelected(SelectionEvent e) { } }); ccList.addListener(SWT.FocusIn, new GenericListener()); } @Override protected void updateBug() { taskData.setHasLocalChanges(true); // go through all of the attributes and update the main values to the // new ones // for (Iterator<RepositoryTaskAttribute> it = // bug.getAttributes().iterator(); it.hasNext();) { // RepositoryTaskAttribute a = it.next(); // if (a.getNewValue() != null && // a.getNewValue().compareTo(a.getValue()) != 0) { // bug.setHasChanged(true); // } // a.setValue(a.getNewValue()); // // } // if (bug.getNewComment().compareTo(bug.getNewNewComment()) != 0) { // // TODO: Ask offline reports if this is true? // bug.setHasChanged(true); // } // Update some other fields as well. // bug.setNewComment(bug.getNewNewComment()); } // @Override // protected void restoreBug() { // // if (taskData == null) // return; // // // go through all of the attributes and restore the new values to the // // main ones // // for (Iterator<RepositoryTaskAttribute> it = // // bug.getAttributes().iterator(); it.hasNext();) { // // RepositoryTaskAttribute a = it.next(); // // a.setNewValue(a.getValue()); // // } // // // Restore some other fields as well. // // bug.setNewNewComment(bug.getNewComment()); // } /** * This job opens a compare editor to compare the current state of the bug * in the editor with the bug on the server. */ protected class OpenCompareEditorJob extends Job { public OpenCompareEditorJob(String name) { super(name); } @Override protected IStatus run(IProgressMonitor monitor) { final RepositoryTaskData serverBug; try { TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository( BugzillaPlugin.REPOSITORY_KIND, taskData.getRepositoryUrl()); serverBug = BugzillaRepositoryUtil.getBug(repository.getUrl(), repository.getUserName(), repository .getPassword(), editorInput.getProxySettings(), repository.getCharacterEncoding(), Integer .parseInt(taskData.getId())); // If no bug was found on the server, throw an exception so that // the // user gets the same message that appears when there is a // problem reading the server. if (serverBug == null) throw new Exception(); } catch (Exception e) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Could not open bug.", "Bug #" + taskData.getId() + " could not be read from the server."); } }); return new Status(IStatus.OK, BugzillaUiPlugin.PLUGIN_ID, IStatus.OK, "Could not get the bug report from the server.", null); } PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { compareInput.setTitle("Bug #" + taskData.getId()); compareInput.setLeft(taskData); compareInput.setRight(serverBug); CompareUI.openCompareEditor(compareInput); } }); return new Status(IStatus.OK, BugzillaUiPlugin.PLUGIN_ID, IStatus.OK, "", null); } } /** * Class to handle the selection change of the keywords. */ protected class KeywordListener implements SelectionListener { /* * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent arg0) { changeDirtyStatus(true); // get the selected keywords and create a string to submit StringBuffer keywords = new StringBuffer(); String[] sel = keyWordsList.getSelection(); // allow unselecting 1 keyword when it is the only one selected if (keyWordsList.getSelectionCount() == 1) { int index = keyWordsList.getSelectionIndex(); String keyword = keyWordsList.getItem(index); if (getRepositoryTaskData().getAttributeValue(BugzillaReportElement.KEYWORDS.getKeyString()).equals( keyword)) keyWordsList.deselectAll(); } for (int i = 0; i < keyWordsList.getSelectionCount(); i++) { keywords.append(sel[i]); if (i != keyWordsList.getSelectionCount() - 1) { keywords.append(","); } } taskData.setAttributeValue(BugzillaReportElement.KEYWORDS.getKeyString(), keywords.toString()); // update the keywords text field keywordsText.setText(keywords.toString()); } /* * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetDefaultSelected(SelectionEvent arg0) { // no need to listen to this } } /** * A listener for selection of a comment. */ protected class CommentListener implements Listener { /** The comment that this listener is for. */ private Comment comment; /** * Creates a new <code>CommentListener</code>. * * @param comment * The comment that this listener is for. */ public CommentListener(Comment comment) { this.comment = comment; } public void handleEvent(Event event) { fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection( new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(), comment.getCreated(), comment, taskData.getSummary())))); } } /** * Class to handle the selection change of the radio buttons. */ protected class RadioButtonListener implements SelectionListener, ModifyListener { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); ExistingBugEditor.this.changeDirtyStatus(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setOptionSelection(((CCombo) radioOptions[i]).getItem(((CCombo) radioOptions[i]) .getSelectionIndex())); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } ExistingBugEditor.this.changeDirtyStatus(true); } } validateInput(); } public void modifyText(ModifyEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); ExistingBugEditor.this.changeDirtyStatus(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setInputValue(((Text) radioOptions[i]).getText()); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } ExistingBugEditor.this.changeDirtyStatus(true); } } validateInput(); } } @Override protected void validateInput() { RepositoryOperation o = taskData.getSelectedOperation(); if (o != null && o.getKnobName().compareTo("resolve") == 0 && (addCommentsText.getText() == null || addCommentsText.getText().equals(""))) { // TODO: Highlight (change to light red?) New Comment area to // indicate need for message submitButton.setEnabled(false); } else { submitButton.setEnabled(true); } } /** * Adds a text field to display and edit the bug's URL attribute. * * @param url * The URL attribute of the bug. * @param attributesComposite * The composite to add the text field to. */ protected void addUrlText(String url, Composite attributesComposite) { FormToolkit toolkit = new FormToolkit(attributesComposite.getDisplay()); toolkit.createLabel(attributesComposite, "URL:"); urlText = toolkit.createText(attributesComposite, url); urlText.setFont(TEXT_FONT); GridData urlTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); urlTextData.horizontalSpan = 3; urlTextData.widthHint = 200; urlText.setLayoutData(urlTextData); // urlText.setText(url); urlText.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = urlText.getText(); RepositoryTaskAttribute a = getRepositoryTaskData().getAttribute( BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (!(a.getValue().equals(sel))) { a.setValue(sel); changeDirtyStatus(true); } } }); urlText.addListener(SWT.FocusIn, new GenericListener()); } @Override public void createCustomAttributeLayout() { // ignore } @Override public RepositoryTaskData getRepositoryTaskData() { return editorInput.getRepositoryTaskData(); } // @Override // public AbstractRepositoryTask getRepositoryTask() { // // ignore // return null; // } // @Override // public void handleSummaryEvent() { // String sel = summaryText.getText(); // RepositoryTaskAttribute a = // getReport().getAttribute(BugzillaReportElement.SHORT_DESC.getKeyString()); // if (!(a.getValue().equals(sel))) { // a.setValue(sel); // changeDirtyStatus(true); // } // } // TODO used for spell checking. Add back when we want to support this // protected Button checkSpellingButton; // // private void checkSpelling() { // SpellingContext context= new SpellingContext(); // context.setContentType(Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT)); // IDocument document = new Document(addCommentsTextBox.getText()); // ISpellingProblemCollector collector= new // SpellingProblemCollector(document); // EditorsUI.getSpellingService().check(document, context, collector, new // NullProgressMonitor()); // } // // private class SpellingProblemCollector implements // ISpellingProblemCollector { // // private IDocument document; // // private SpellingDialog spellingDialog; // // public SpellingProblemCollector(IDocument document){ // this.document = document; // spellingDialog = new // SpellingDialog(Display.getCurrent().getActiveShell(), "Spell Checking", // document); // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept(org.eclipse.ui.texteditor.spelling.SpellingProblem) // */ // public void accept(SpellingProblem problem) { // try { // int line= document.getLineOfOffset(problem.getOffset()) + 1; // String word= document.get(problem.getOffset(), problem.getLength()); // // spellingDialog.open(word, problem.getProposals()); // // } catch (BadLocationException x) { // // drop this SpellingProblem // } // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#beginCollecting() // */ // public void beginCollecting() { // // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#endCollecting() // */ // public void endCollecting() { // MessageDialog.openInformation(Display.getCurrent().getActiveShell(), // "Spell Checking Finished", "The spell check has finished"); // } // } }
org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/ExistingBugEditor.java
/******************************************************************************* * Copyright (c) 2003 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.bugzilla.ui.editor; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareUI; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.IJobChangeListener; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.internal.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.internal.bugzilla.core.BugzillaReportElement; import org.eclipse.mylar.internal.bugzilla.core.BugzillaReportSubmitForm; import org.eclipse.mylar.internal.bugzilla.core.BugzillaRepositoryUtil; import org.eclipse.mylar.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylar.internal.bugzilla.ui.BugzillaCompareInput; import org.eclipse.mylar.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylar.internal.bugzilla.ui.tasklist.BugzillaRepositoryConnector; import org.eclipse.mylar.internal.tasklist.Comment; import org.eclipse.mylar.internal.tasklist.RepositoryOperation; import org.eclipse.mylar.internal.tasklist.RepositoryTaskAttribute; import org.eclipse.mylar.internal.tasklist.RepositoryTaskData; import org.eclipse.mylar.internal.tasklist.ui.editors.AbstractBugEditorInput; import org.eclipse.mylar.internal.tasklist.ui.editors.AbstractRepositoryTaskEditor; import org.eclipse.mylar.internal.tasklist.ui.editors.ExistingBugEditorInput; import org.eclipse.mylar.internal.tasklist.ui.editors.RepositoryTaskOutlineNode; import org.eclipse.mylar.internal.tasklist.ui.editors.RepositoryTaskSelection; import org.eclipse.mylar.internal.tasklist.ui.views.DatePicker; import org.eclipse.mylar.internal.tasklist.ui.views.TaskRepositoriesView; import org.eclipse.mylar.provisional.tasklist.AbstractRepositoryConnector; import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin; import org.eclipse.mylar.provisional.tasklist.TaskRepository; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; /** * An editor used to view a bug report that exists on a server. It uses a * <code>BugReport</code> object to store the data. * * @author Mik Kersten (hardening of prototype) * @author Rob Elves (adaption to Eclipse Forms) */ public class ExistingBugEditor extends AbstractRepositoryTaskEditor { private static final String LABEL_TIME_TRACKING = "Bugzilla Time Tracking"; private static final String REASSIGN_BUG_TO = "Reassign bug to"; private static final String LABEL_COMPARE_BUTTON = "Compare"; protected Set<String> removeCC = new HashSet<String>(); protected BugzillaCompareInput compareInput; protected Button compareButton; protected Button[] radios; protected Control[] radioOptions; protected List keyWordsList; protected Text keywordsText; protected List ccList; protected Text ccText; protected Text urlText; protected RepositoryTaskData taskData; protected AbstractRepositoryConnector connector; protected Text estimateText; protected Text actualText; protected Text remainingText; protected Text addTimeText; protected Text deadlineText; protected DatePicker deadlinePicker; /** * Creates a new <code>ExistingBugEditor</code>. */ public ExistingBugEditor() { super(); // Set up the input for comparing the bug report to the server CompareConfiguration config = new CompareConfiguration(); config.setLeftEditable(false); config.setRightEditable(false); config.setLeftLabel("Local Bug Report"); config.setRightLabel("Remote Bug Report"); config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)); compareInput = new BugzillaCompareInput(config); } // @SuppressWarnings("deprecation") @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof ExistingBugEditorInput)) throw new PartInitException("Invalid Input: Must be ExistingBugEditorInput"); editorInput = (AbstractBugEditorInput) input; taskData = editorInput.getRepositoryTaskData(); repository = editorInput.getRepository(); connector = MylarTaskListPlugin.getRepositoryManager().getRepositoryConnector(repository.getKind()); setSite(site); setInput(input); taskOutlineModel = RepositoryTaskOutlineNode.parseBugReport(editorInput.getRepositoryTaskData()); // restoreBug(); isDirty = false; updateEditorTitle(); } @Override protected void addRadioButtons(Composite buttonComposite) { FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); int i = 0; Button selected = null; radios = new Button[taskData.getOperations().size()]; radioOptions = new Control[taskData.getOperations().size()]; for (Iterator<RepositoryOperation> it = taskData.getOperations().iterator(); it.hasNext();) { RepositoryOperation o = it.next(); radios[i] = toolkit.createButton(buttonComposite, "", SWT.RADIO); radios[i].setFont(TEXT_FONT); GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); if (!o.hasOptions() && !o.isInput()) radioData.horizontalSpan = 4; else radioData.horizontalSpan = 3; radioData.heightHint = 20; String opName = o.getOperationName(); opName = opName.replaceAll("</.*>", ""); opName = opName.replaceAll("<.*>", ""); radios[i].setText(opName); radios[i].setLayoutData(radioData); // radios[i].setBackground(background); radios[i].addSelectionListener(new RadioButtonListener()); radios[i].addListener(SWT.FocusIn, new GenericListener()); if (o.hasOptions()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 1; radioData.heightHint = 20; radioData.widthHint = AbstractRepositoryTaskEditor.WRAP_LENGTH; // radioOptions[i] = new Combo(buttonComposite, SWT.NULL); radioOptions[i] = new CCombo(buttonComposite, SWT.FLAT | SWT.READ_ONLY); toolkit.adapt(radioOptions[i], true, true); // radioOptions[i] = new Combo(buttonComposite, SWT.MULTI | // SWT.V_SCROLL | SWT.READ_ONLY); // radioOptions[i].setData(FormToolkit.KEY_DRAW_BORDER, // FormToolkit.TEXT_BORDER); // radioOptions[i] = new Combo(buttonComposite, // SWT.NO_BACKGROUND | SWT.MULTI | SWT.V_SCROLL // | SWT.READ_ONLY); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); // radioOptions[i].setBackground(background); Object[] a = o.getOptionNames().toArray(); Arrays.sort(a); for (int j = 0; j < a.length; j++) { ((CCombo) radioOptions[i]).add((String) a[j]); } ((CCombo) radioOptions[i]).select(0); ((CCombo) radioOptions[i]).addSelectionListener(new RadioButtonListener()); } else if (o.isInput()) { radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); radioData.horizontalSpan = 1; radioData.widthHint = 120; // TODO: add condition for if opName = reassign to... String assignmentValue = ""; if (opName.equals(REASSIGN_BUG_TO)) { assignmentValue = repository.getUserName(); } radioOptions[i] = toolkit.createText(buttonComposite, assignmentValue);// , // SWT.SINGLE); radioOptions[i].setFont(TEXT_FONT); radioOptions[i].setLayoutData(radioData); // radioOptions[i].setBackground(background); ((Text) radioOptions[i]).setText(o.getInputValue()); ((Text) radioOptions[i]).addModifyListener(new RadioButtonListener()); } if (i == 0 || o.isChecked()) { if (selected != null) selected.setSelection(false); selected = radios[i]; radios[i].setSelection(true); if (o.hasOptions() && o.getOptionSelection() != null) { int j = 0; for (String s : ((CCombo) radioOptions[i]).getItems()) { if (s.compareTo(o.getOptionSelection()) == 0) { ((CCombo) radioOptions[i]).select(j); } j++; } } taskData.setSelectedOperation(o); } i++; } toolkit.paintBordersFor(buttonComposite); } @Override protected void addActionButtons(Composite buttonComposite) { FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); super.addActionButtons(buttonComposite); compareButton = toolkit.createButton(buttonComposite, LABEL_COMPARE_BUTTON, SWT.NONE); // compareButton.setFont(TEXT_FONT); GridData compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // compareButtonData.widthHint = 100; // compareButtonData.heightHint = 20; // // compareButton.setText("Compare"); compareButton.setLayoutData(compareButtonData); compareButton.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { OpenCompareEditorJob compareJob = new OpenCompareEditorJob("Comparing bug with remote server..."); compareJob.schedule(); } }); compareButton.addListener(SWT.FocusIn, new GenericListener()); // Button expandAll = toolkit.createButton(buttonComposite, // LABEL_EXPAND_ALL_BUTTON, SWT.NONE); // expandAll.setLayoutData(new // GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); // expandAll.addSelectionListener(new SelectionListener() { // // public void widgetDefaultSelected(SelectionEvent e) { // // ignore // // } // // public void widgetSelected(SelectionEvent e) { // revealAllComments(); // // } // }); // TODO used for spell checking. Add back when we want to support this // checkSpellingButton = new Button(buttonComposite, SWT.NONE); // checkSpellingButton.setFont(TEXT_FONT); // compareButtonData = new // GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); // compareButtonData.widthHint = 100; // compareButtonData.heightHint = 20; // checkSpellingButton.setText("CheckSpelling"); // checkSpellingButton.setLayoutData(compareButtonData); // checkSpellingButton.addListener(SWT.Selection, new Listener() { // public void handleEvent(Event e) { // checkSpelling(); // } // }); // checkSpellingButton.addListener(SWT.FocusIn, new GenericListener()); } /** * @return Returns the compareInput. */ public BugzillaCompareInput getCompareInput() { return compareInput; } // @Override // public RepositoryTaskData getBug() { // return taskData; // } @Override protected String getTitleString() { // Attribute summary = bug.getAttribute(ATTR_SUMMARY); // String summaryVal = ((null != summary) ? summary.getNewValue() : // null); return taskData.getLabel();// + ": " + checkText(summaryVal); } @Override public void submitBug() { if (isDirty()) { this.doSave(new NullProgressMonitor()); } updateBug(); submitButton.setEnabled(false); ExistingBugEditor.this.showBusy(true); BugzillaReportSubmitForm bugzillaReportSubmitForm; try { if (taskData.isLocallyCreated()) { boolean wrap = IBugzillaConstants.BugzillaServerVersion.SERVER_218.equals(repository.getVersion()); bugzillaReportSubmitForm = BugzillaReportSubmitForm.makeNewBugPost(repository.getUrl(), repository .getUserName(), repository.getPassword(), editorInput.getProxySettings(), repository .getCharacterEncoding(), taskData, wrap); } else { bugzillaReportSubmitForm = BugzillaReportSubmitForm.makeExistingBugPost(taskData, repository.getUrl(), repository.getUserName(), repository.getPassword(), editorInput.getProxySettings(), removeCC, repository.getCharacterEncoding()); } } catch (UnsupportedEncodingException e) { // should never get here but just in case... MessageDialog.openError(null, "Posting Error", "Ensure proper encoding selected in " + TaskRepositoriesView.NAME + "."); return; } final BugzillaRepositoryConnector bugzillaRepositoryClient = (BugzillaRepositoryConnector) MylarTaskListPlugin .getRepositoryManager().getRepositoryConnector(BugzillaPlugin.REPOSITORY_KIND); IJobChangeListener closeEditorListener = new IJobChangeListener() { public void done(final IJobChangeEvent event) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { if (event.getJob().getResult().equals(Status.OK_STATUS)) { close(); } else { submitButton.setEnabled(true); ExistingBugEditor.this.showBusy(false); } } }); } public void aboutToRun(IJobChangeEvent event) { // ignore } public void awake(IJobChangeEvent event) { // ignore } public void running(IJobChangeEvent event) { // ignore } public void scheduled(IJobChangeEvent event) { // ignore } public void sleeping(IJobChangeEvent event) { // ignore } }; bugzillaRepositoryClient.submitBugReport(taskData, bugzillaReportSubmitForm, closeEditorListener); } @Override protected void createCustomAttributeLayout(Composite composite) { FormToolkit toolkit = new FormToolkit(composite.getDisplay()); addCCList(toolkit, "", composite); try { addKeywordsList(toolkit, getRepositoryTaskData().getAttributeValue(RepositoryTaskAttribute.KEYWORDS), composite); } catch (IOException e) { MessageDialog.openInformation(null, "Attribute Display Error", "Could not retrieve keyword list, ensure proper configuration in " + TaskRepositoriesView.NAME + "\n\nError reported: " + e.getMessage()); } if (getRepositoryTaskData().getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) addBugzillaTimeTracker(toolkit, composite); } protected void addBugzillaTimeTracker(FormToolkit toolkit, Composite parent) { Section timeSection = toolkit.createSection(parent, ExpandableComposite.TREE_NODE); timeSection.setText(LABEL_TIME_TRACKING); GridLayout gl = new GridLayout(); GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false); gd.horizontalSpan = 4; timeSection.setLayout(gl); timeSection.setLayoutData(gd); Composite timeComposite = toolkit.createComposite(timeSection); gl = new GridLayout(4, true); timeComposite.setLayout(gl); gd = new GridData(); gd.horizontalSpan = 5; timeComposite.setLayoutData(gd); RepositoryTaskData data = getRepositoryTaskData(); toolkit.createLabel(timeComposite, BugzillaReportElement.ESTIMATED_TIME.toString()); estimateText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ESTIMATED_TIME.getKeyString()), SWT.BORDER); estimateText.setFont(TEXT_FONT); estimateText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); estimateText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.ESTIMATED_TIME.getKeyString(), estimateText.getText()); } }); toolkit.createLabel(timeComposite, "Current Estimate:"); Text currentEstimate = toolkit.createText(timeComposite, "" + (Float.parseFloat(data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + Float.parseFloat(data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()))) ); currentEstimate.setFont(TEXT_FONT); currentEstimate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); currentEstimate.setEditable(false); toolkit.createLabel(timeComposite, BugzillaReportElement.ACTUAL_TIME.toString()); actualText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())); actualText.setFont(TEXT_FONT); actualText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); actualText.setEditable(false); data.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), "0"); toolkit.createLabel(timeComposite, BugzillaReportElement.WORK_TIME.toString()); addTimeText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString()), SWT.BORDER); addTimeText.setFont(TEXT_FONT); addTimeText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); addTimeText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), addTimeText.getText()); } }); toolkit.createLabel(timeComposite, BugzillaReportElement.REMAINING_TIME.toString()); remainingText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()), SWT.BORDER); remainingText.setFont(TEXT_FONT); remainingText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); remainingText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString(), remainingText.getText()); } }); toolkit.createLabel(timeComposite, BugzillaReportElement.DEADLINE.toString()); deadlinePicker = new DatePicker(timeComposite, /*SWT.NONE */ SWT.BORDER, data.getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString()) ); deadlinePicker.setFont(TEXT_FONT); deadlinePicker.setDatePattern("yyyy-MM-dd"); deadlinePicker.addPickerSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // ignore } public void widgetSelected(SelectionEvent e) { Calendar cal = deadlinePicker.getDate(); if (cal != null) { Date d = cal.getTime(); SimpleDateFormat f = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); f.applyPattern("yyyy-MM-dd"); taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), f.format(d)); changeDirtyStatus(true); // TODO goes dirty even if user presses cancel } } }); timeSection.setClient(timeComposite); } protected void addKeywordsList(FormToolkit toolkit, String keywords, Composite attributesComposite) throws IOException { // newLayout(attributesComposite, 1, "Keywords:", PROPERTY); toolkit.createLabel(attributesComposite, "Keywords:"); keywordsText = toolkit.createText(attributesComposite, keywords); keywordsText.setFont(TEXT_FONT); keywordsText.setEditable(false); // keywordsText.setForeground(foreground); // keywordsText.setBackground(JFaceColors.getErrorBackground(display)); GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keywordsData.horizontalSpan = 2; keywordsData.widthHint = 200; keywordsText.setLayoutData(keywordsData); // keywordsText.setText(keywords); keywordsText.addListener(SWT.FocusIn, new GenericListener()); keyWordsList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL); keyWordsList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); keyWordsList.setFont(TEXT_FONT); GridData keyWordsTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); keyWordsTextData.horizontalSpan = 1; keyWordsTextData.widthHint = 125; keyWordsTextData.heightHint = 40; keyWordsList.setLayoutData(keyWordsTextData); // initialize the keywords list with valid values java.util.List<String> validKeywords = new ArrayList<String>(); try { validKeywords = BugzillaPlugin.getRepositoryConfiguration(false, repository.getUrl(), MylarTaskListPlugin.getDefault().getProxySettings(), repository.getUserName(), repository.getPassword(), repository.getCharacterEncoding()).getKeywords(); } catch (Exception e) { // ignore } if (validKeywords != null) { for (Iterator<String> it = validKeywords.iterator(); it.hasNext();) { String keyword = it.next(); keyWordsList.add(keyword); } // get the selected keywords for the bug StringTokenizer st = new StringTokenizer(keywords, ",", false); ArrayList<Integer> indicies = new ArrayList<Integer>(); while (st.hasMoreTokens()) { String s = st.nextToken().trim(); int index = keyWordsList.indexOf(s); if (index != -1) indicies.add(new Integer(index)); } // select the keywords that were selected for the bug int length = indicies.size(); int[] sel = new int[length]; for (int i = 0; i < length; i++) { sel[i] = indicies.get(i).intValue(); } keyWordsList.select(sel); } keyWordsList.addSelectionListener(new KeywordListener()); keyWordsList.addListener(SWT.FocusIn, new GenericListener()); } protected void addCCList(FormToolkit toolkit, String ccValue, Composite attributesComposite) { newLayout(attributesComposite, 1, "Add CC:", PROPERTY); ccText = toolkit.createText(attributesComposite, ccValue); ccText.setFont(TEXT_FONT); ccText.setEditable(true); // ccText.setForeground(foreground); // ccText.setBackground(background); GridData ccData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); ccData.horizontalSpan = 1; ccData.widthHint = 200; ccText.setLayoutData(ccData); // ccText.setText(ccValue); ccText.addListener(SWT.FocusIn, new GenericListener()); ccText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { changeDirtyStatus(true); taskData.setAttributeValue(BugzillaReportElement.NEWCC.getKeyString(), ccText.getText()); } }); // newLayout(attributesComposite, 1, "CC: (Select to remove)", // PROPERTY); toolkit.createLabel(attributesComposite, "CC: (Select to remove)"); ccList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL);// SWT.BORDER ccList.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); ccList.setFont(TEXT_FONT); GridData ccListData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); ccListData.horizontalSpan = 1; ccListData.widthHint = 125; ccListData.heightHint = 40; ccList.setLayoutData(ccListData); java.util.List<String> ccs = taskData.getCC(); if (ccs != null) { for (Iterator<String> it = ccs.iterator(); it.hasNext();) { String cc = it.next(); ccList.add(cc);// HtmlStreamTokenizer.unescape(cc)); } } ccList.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { changeDirtyStatus(true); for (String cc : ccList.getItems()) { int index = ccList.indexOf(cc); if (ccList.isSelected(index)) { removeCC.add(cc); } else { removeCC.remove(cc); } } } public void widgetDefaultSelected(SelectionEvent e) { } }); ccList.addListener(SWT.FocusIn, new GenericListener()); } @Override protected void updateBug() { taskData.setHasLocalChanges(true); // go through all of the attributes and update the main values to the // new ones // for (Iterator<RepositoryTaskAttribute> it = // bug.getAttributes().iterator(); it.hasNext();) { // RepositoryTaskAttribute a = it.next(); // if (a.getNewValue() != null && // a.getNewValue().compareTo(a.getValue()) != 0) { // bug.setHasChanged(true); // } // a.setValue(a.getNewValue()); // // } // if (bug.getNewComment().compareTo(bug.getNewNewComment()) != 0) { // // TODO: Ask offline reports if this is true? // bug.setHasChanged(true); // } // Update some other fields as well. // bug.setNewComment(bug.getNewNewComment()); } // @Override // protected void restoreBug() { // // if (taskData == null) // return; // // // go through all of the attributes and restore the new values to the // // main ones // // for (Iterator<RepositoryTaskAttribute> it = // // bug.getAttributes().iterator(); it.hasNext();) { // // RepositoryTaskAttribute a = it.next(); // // a.setNewValue(a.getValue()); // // } // // // Restore some other fields as well. // // bug.setNewNewComment(bug.getNewComment()); // } /** * This job opens a compare editor to compare the current state of the bug * in the editor with the bug on the server. */ protected class OpenCompareEditorJob extends Job { public OpenCompareEditorJob(String name) { super(name); } @Override protected IStatus run(IProgressMonitor monitor) { final RepositoryTaskData serverBug; try { TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository( BugzillaPlugin.REPOSITORY_KIND, taskData.getRepositoryUrl()); serverBug = BugzillaRepositoryUtil.getBug(repository.getUrl(), repository.getUserName(), repository .getPassword(), editorInput.getProxySettings(), repository.getCharacterEncoding(), Integer.parseInt(taskData.getId())); // If no bug was found on the server, throw an exception so that // the // user gets the same message that appears when there is a // problem reading the server. if (serverBug == null) throw new Exception(); } catch (Exception e) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Could not open bug.", "Bug #" + taskData.getId() + " could not be read from the server."); } }); return new Status(IStatus.OK, BugzillaUiPlugin.PLUGIN_ID, IStatus.OK, "Could not get the bug report from the server.", null); } PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { compareInput.setTitle("Bug #" + taskData.getId()); compareInput.setLeft(taskData); compareInput.setRight(serverBug); CompareUI.openCompareEditor(compareInput); } }); return new Status(IStatus.OK, BugzillaUiPlugin.PLUGIN_ID, IStatus.OK, "", null); } } /** * Class to handle the selection change of the keywords. */ protected class KeywordListener implements SelectionListener { /* * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent arg0) { changeDirtyStatus(true); // get the selected keywords and create a string to submit StringBuffer keywords = new StringBuffer(); String[] sel = keyWordsList.getSelection(); // allow unselecting 1 keyword when it is the only one selected if (keyWordsList.getSelectionCount() == 1) { int index = keyWordsList.getSelectionIndex(); String keyword = keyWordsList.getItem(index); if (getRepositoryTaskData().getAttributeValue(BugzillaReportElement.KEYWORDS.getKeyString()).equals( keyword)) keyWordsList.deselectAll(); } for (int i = 0; i < keyWordsList.getSelectionCount(); i++) { keywords.append(sel[i]); if (i != keyWordsList.getSelectionCount() - 1) { keywords.append(","); } } taskData.setAttributeValue(BugzillaReportElement.KEYWORDS.getKeyString(), keywords.toString()); // update the keywords text field keywordsText.setText(keywords.toString()); } /* * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetDefaultSelected(SelectionEvent arg0) { // no need to listen to this } } /** * A listener for selection of a comment. */ protected class CommentListener implements Listener { /** The comment that this listener is for. */ private Comment comment; /** * Creates a new <code>CommentListener</code>. * * @param comment * The comment that this listener is for. */ public CommentListener(Comment comment) { this.comment = comment; } public void handleEvent(Event event) { fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection( new RepositoryTaskSelection(taskData.getId(), taskData.getRepositoryUrl(), comment.getCreated(), comment, taskData.getSummary())))); } } /** * Class to handle the selection change of the radio buttons. */ protected class RadioButtonListener implements SelectionListener, ModifyListener { public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } public void widgetSelected(SelectionEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); ExistingBugEditor.this.changeDirtyStatus(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setOptionSelection(((CCombo) radioOptions[i]).getItem(((CCombo) radioOptions[i]) .getSelectionIndex())); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } ExistingBugEditor.this.changeDirtyStatus(true); } } validateInput(); } public void modifyText(ModifyEvent e) { Button selected = null; for (int i = 0; i < radios.length; i++) { if (radios[i].getSelection()) selected = radios[i]; } // determine the operation to do to the bug for (int i = 0; i < radios.length; i++) { if (radios[i] != e.widget && radios[i] != selected) { radios[i].setSelection(false); } if (e.widget == radios[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); taskData.setSelectedOperation(o); ExistingBugEditor.this.changeDirtyStatus(true); } else if (e.widget == radioOptions[i]) { RepositoryOperation o = taskData.getOperation(radios[i].getText()); o.setInputValue(((Text) radioOptions[i]).getText()); if (taskData.getSelectedOperation() != null) taskData.getSelectedOperation().setChecked(false); o.setChecked(true); taskData.setSelectedOperation(o); radios[i].setSelection(true); if (selected != null && selected != radios[i]) { selected.setSelection(false); } ExistingBugEditor.this.changeDirtyStatus(true); } } validateInput(); } } @Override protected void validateInput() { RepositoryOperation o = taskData.getSelectedOperation(); if (o != null && o.getKnobName().compareTo("resolve") == 0 && (addCommentsText.getText() == null || addCommentsText.getText().equals(""))) { // TODO: Highlight (change to light red?) New Comment area to // indicate need for message submitButton.setEnabled(false); } else { submitButton.setEnabled(true); } } /** * Adds a text field to display and edit the bug's URL attribute. * * @param url * The URL attribute of the bug. * @param attributesComposite * The composite to add the text field to. */ protected void addUrlText(String url, Composite attributesComposite) { FormToolkit toolkit = new FormToolkit(attributesComposite.getDisplay()); toolkit.createLabel(attributesComposite, "URL:"); urlText = toolkit.createText(attributesComposite, url); urlText.setFont(TEXT_FONT); GridData urlTextData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); urlTextData.horizontalSpan = 3; urlTextData.widthHint = 200; urlText.setLayoutData(urlTextData); // urlText.setText(url); urlText.addListener(SWT.KeyUp, new Listener() { public void handleEvent(Event event) { String sel = urlText.getText(); RepositoryTaskAttribute a = getRepositoryTaskData().getAttribute( BugzillaReportElement.BUG_FILE_LOC.getKeyString()); if (!(a.getValue().equals(sel))) { a.setValue(sel); changeDirtyStatus(true); } } }); urlText.addListener(SWT.FocusIn, new GenericListener()); } @Override public void createCustomAttributeLayout() { // ignore } @Override public RepositoryTaskData getRepositoryTaskData() { return editorInput.getRepositoryTaskData(); } // @Override // public AbstractRepositoryTask getRepositoryTask() { // // ignore // return null; // } // @Override // public void handleSummaryEvent() { // String sel = summaryText.getText(); // RepositoryTaskAttribute a = // getReport().getAttribute(BugzillaReportElement.SHORT_DESC.getKeyString()); // if (!(a.getValue().equals(sel))) { // a.setValue(sel); // changeDirtyStatus(true); // } // } // TODO used for spell checking. Add back when we want to support this // protected Button checkSpellingButton; // // private void checkSpelling() { // SpellingContext context= new SpellingContext(); // context.setContentType(Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT)); // IDocument document = new Document(addCommentsTextBox.getText()); // ISpellingProblemCollector collector= new // SpellingProblemCollector(document); // EditorsUI.getSpellingService().check(document, context, collector, new // NullProgressMonitor()); // } // // private class SpellingProblemCollector implements // ISpellingProblemCollector { // // private IDocument document; // // private SpellingDialog spellingDialog; // // public SpellingProblemCollector(IDocument document){ // this.document = document; // spellingDialog = new // SpellingDialog(Display.getCurrent().getActiveShell(), "Spell Checking", // document); // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept(org.eclipse.ui.texteditor.spelling.SpellingProblem) // */ // public void accept(SpellingProblem problem) { // try { // int line= document.getLineOfOffset(problem.getOffset()) + 1; // String word= document.get(problem.getOffset(), problem.getLength()); // // spellingDialog.open(word, problem.getProposals()); // // } catch (BadLocationException x) { // // drop this SpellingProblem // } // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#beginCollecting() // */ // public void beginCollecting() { // // } // // /* // * @see // org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#endCollecting() // */ // public void endCollecting() { // MessageDialog.openInformation(Display.getCurrent().getActiveShell(), // "Spell Checking Finished", "The spell check has finished"); // } // } }
Progress on: 150026: Add self to cc field isn't available in editor when user not already on cc https://bugs.eclipse.org/bugs/show_bug.cgi?id=150026
org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/ExistingBugEditor.java
Progress on: 150026: Add self to cc field isn't available in editor when user not already on cc https://bugs.eclipse.org/bugs/show_bug.cgi?id=150026
<ide><path>rg.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/editor/ExistingBugEditor.java <ide> import org.eclipse.swt.custom.CCombo; <ide> import org.eclipse.swt.events.ModifyEvent; <ide> import org.eclipse.swt.events.ModifyListener; <add>import org.eclipse.swt.events.SelectionAdapter; <ide> import org.eclipse.swt.events.SelectionEvent; <ide> import org.eclipse.swt.events.SelectionListener; <ide> import org.eclipse.swt.layout.GridData; <ide> protected Text deadlineText; <ide> <ide> protected DatePicker deadlinePicker; <del> <add> <ide> /** <ide> * Creates a new <code>ExistingBugEditor</code>. <ide> */ <ide> <ide> @Override <ide> protected void addRadioButtons(Composite buttonComposite) { <add> addSelfToCC(buttonComposite); <ide> FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); <ide> int i = 0; <ide> Button selected = null; <ide> toolkit.paintBordersFor(buttonComposite); <ide> } <ide> <add> private void addSelfToCC(Composite composite) { <add> // if they aren't already on the cc list create an add self check box <add> FormToolkit toolkit = new FormToolkit(composite.getDisplay()); <add> RepositoryTaskAttribute owner = taskData.getAttribute(RepositoryTaskAttribute.USER_ASSIGNED); <add> <add> <add> if (owner != null && owner.getValue().indexOf(repository.getUserName()) != -1) { <add> return; <add> } <add> <add> RepositoryTaskAttribute reporter = taskData.getAttribute(RepositoryTaskAttribute.USER_REPORTER); <add> if (reporter != null && reporter.getValue().indexOf(repository.getUserName()) != -1) { <add> return; <add> } <add> // Don't add addselfcc if already there <add> RepositoryTaskAttribute ccAttribute = taskData.getAttribute(RepositoryTaskAttribute.USER_CC); <add> if (ccAttribute != null && ccAttribute.getValues().contains(repository.getUserName())) { <add> return; <add> } <add> <add> // taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), <add> // "0"); <add> <add> final Button addSelfButton = toolkit.createButton(composite, "Add " + repository.getUserName() + " to CC list", <add> SWT.CHECK); <add> <add> addSelfButton.addSelectionListener(new SelectionAdapter() { <add> <add> @Override <add> public void widgetSelected(SelectionEvent e) { <add> if (addSelfButton.getSelection()) { <add> taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), "1"); <add> } else { <add> taskData.setAttributeValue(BugzillaReportElement.ADDSELFCC.getKeyString(), "0"); <add> } <add> changeDirtyStatus(true); <add> } <add> }); <add> } <add> <ide> @Override <ide> protected void addActionButtons(Composite buttonComposite) { <ide> FormToolkit toolkit = new FormToolkit(buttonComposite.getDisplay()); <ide> protected void createCustomAttributeLayout(Composite composite) { <ide> FormToolkit toolkit = new FormToolkit(composite.getDisplay()); <ide> addCCList(toolkit, "", composite); <del> <add> <ide> try { <ide> addKeywordsList(toolkit, getRepositoryTaskData().getAttributeValue(RepositoryTaskAttribute.KEYWORDS), <ide> composite); <ide> "Could not retrieve keyword list, ensure proper configuration in " + TaskRepositoriesView.NAME <ide> + "\n\nError reported: " + e.getMessage()); <ide> } <del> <add> <ide> if (getRepositoryTaskData().getAttribute(BugzillaReportElement.ESTIMATED_TIME.getKeyString()) != null) <ide> addBugzillaTimeTracker(toolkit, composite); <ide> } <ide> <ide> protected void addBugzillaTimeTracker(FormToolkit toolkit, Composite parent) { <del> <add> <ide> Section timeSection = toolkit.createSection(parent, ExpandableComposite.TREE_NODE); <ide> timeSection.setText(LABEL_TIME_TRACKING); <ide> GridLayout gl = new GridLayout(); <ide> gd.horizontalSpan = 4; <ide> timeSection.setLayout(gl); <ide> timeSection.setLayoutData(gd); <del> <add> <ide> Composite timeComposite = toolkit.createComposite(timeSection); <ide> gl = new GridLayout(4, true); <ide> timeComposite.setLayout(gl); <ide> gd = new GridData(); <ide> gd.horizontalSpan = 5; <ide> timeComposite.setLayoutData(gd); <del> <del> RepositoryTaskData data = getRepositoryTaskData(); <del> <add> <add> RepositoryTaskData data = getRepositoryTaskData(); <add> <ide> toolkit.createLabel(timeComposite, BugzillaReportElement.ESTIMATED_TIME.toString()); <del> estimateText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ESTIMATED_TIME.getKeyString()), SWT.BORDER); <add> estimateText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ESTIMATED_TIME <add> .getKeyString()), SWT.BORDER); <ide> estimateText.setFont(TEXT_FONT); <ide> estimateText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); <ide> estimateText.addModifyListener(new ModifyListener() { <ide> taskData.setAttributeValue(BugzillaReportElement.ESTIMATED_TIME.getKeyString(), estimateText.getText()); <ide> } <ide> }); <del> <add> <ide> toolkit.createLabel(timeComposite, "Current Estimate:"); <del> Text currentEstimate = toolkit.createText(timeComposite, <del> "" + (Float.parseFloat(data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + <del> Float.parseFloat(data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()))) <del> ); <add> Text currentEstimate = toolkit.createText(timeComposite, "" <add> + (Float.parseFloat(data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())) + Float <add> .parseFloat(data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString())))); <ide> currentEstimate.setFont(TEXT_FONT); <ide> currentEstimate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); <ide> currentEstimate.setEditable(false); <del> <add> <ide> toolkit.createLabel(timeComposite, BugzillaReportElement.ACTUAL_TIME.toString()); <del> actualText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME.getKeyString())); <add> actualText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.ACTUAL_TIME <add> .getKeyString())); <ide> actualText.setFont(TEXT_FONT); <ide> actualText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); <ide> actualText.setEditable(false); <del> <add> <ide> data.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), "0"); <ide> toolkit.createLabel(timeComposite, BugzillaReportElement.WORK_TIME.toString()); <del> addTimeText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString()), SWT.BORDER); <add> addTimeText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.WORK_TIME <add> .getKeyString()), SWT.BORDER); <ide> addTimeText.setFont(TEXT_FONT); <ide> addTimeText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); <ide> addTimeText.addModifyListener(new ModifyListener() { <ide> taskData.setAttributeValue(BugzillaReportElement.WORK_TIME.getKeyString(), addTimeText.getText()); <ide> } <ide> }); <del> <add> <ide> toolkit.createLabel(timeComposite, BugzillaReportElement.REMAINING_TIME.toString()); <del> remainingText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString()), SWT.BORDER); <add> remainingText = toolkit.createText(timeComposite, data.getAttributeValue(BugzillaReportElement.REMAINING_TIME <add> .getKeyString()), SWT.BORDER); <ide> remainingText.setFont(TEXT_FONT); <ide> remainingText.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); <ide> remainingText.addModifyListener(new ModifyListener() { <ide> public void modifyText(ModifyEvent e) { <ide> changeDirtyStatus(true); <del> taskData.setAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString(), remainingText.getText()); <add> taskData <add> .setAttributeValue(BugzillaReportElement.REMAINING_TIME.getKeyString(), remainingText.getText()); <ide> } <ide> }); <del> <add> <ide> toolkit.createLabel(timeComposite, BugzillaReportElement.DEADLINE.toString()); <del> <del> deadlinePicker = new DatePicker(timeComposite, /*SWT.NONE */ SWT.BORDER, <del> data.getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString()) <del> ); <add> <add> deadlinePicker = new DatePicker(timeComposite, /* SWT.NONE */SWT.BORDER, data <add> .getAttributeValue(BugzillaReportElement.DEADLINE.getKeyString())); <ide> deadlinePicker.setFont(TEXT_FONT); <ide> deadlinePicker.setDatePattern("yyyy-MM-dd"); <ide> deadlinePicker.addPickerSelectionListener(new SelectionListener() { <ide> f.applyPattern("yyyy-MM-dd"); <ide> <ide> taskData.setAttributeValue(BugzillaReportElement.DEADLINE.getKeyString(), f.format(d)); <del> changeDirtyStatus(true); // TODO goes dirty even if user presses cancel <add> changeDirtyStatus(true); // TODO goes dirty even if user <add> // presses cancel <ide> } <ide> } <ide> }); <ide> TaskRepository repository = MylarTaskListPlugin.getRepositoryManager().getRepository( <ide> BugzillaPlugin.REPOSITORY_KIND, taskData.getRepositoryUrl()); <ide> serverBug = BugzillaRepositoryUtil.getBug(repository.getUrl(), repository.getUserName(), repository <del> .getPassword(), editorInput.getProxySettings(), repository.getCharacterEncoding(), <del> Integer.parseInt(taskData.getId())); <add> .getPassword(), editorInput.getProxySettings(), repository.getCharacterEncoding(), Integer <add> .parseInt(taskData.getId())); <ide> // If no bug was found on the server, throw an exception so that <ide> // the <ide> // user gets the same message that appears when there is a
Java
bsd-3-clause
8682c405569efd646dab0739181e869e3e4c67ec
0
MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2
package org.carrot2.workbench.core.ui.views; import org.carrot2.core.Cluster; import org.carrot2.workbench.core.ui.DocumentListBrowser; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.ViewPart; public class DocumentListView extends ViewPart { public static final String ID = "org.carrot2.workbench.core.documents"; private DocumentListBrowser browserPart; @Override public void createPartControl(Composite parent) { browserPart = new DocumentListBrowser(); browserPart.init(this.getSite(), parent); browserPart.populateToolbar(getViewSite().getActionBars().getToolBarManager()); ISelection selection = getSite().getPage().getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection selected = (IStructuredSelection) selection; if (selected.size() == 1 && selected.getFirstElement() instanceof Cluster) { browserPart.updateBrowserText((Cluster) selected.getFirstElement()); } } } @Override public void setFocus() { } @Override public void dispose() { browserPart.dispose(); super.dispose(); } }
workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/views/DocumentListView.java
package org.carrot2.workbench.core.ui.views; import org.carrot2.core.Cluster; import org.carrot2.workbench.core.ui.DocumentListBrowser; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.part.ViewPart; public class DocumentListView extends ViewPart { public static final String ID = "org.carrot2.workbench.core.documents"; private DocumentListBrowser browserPart; @Override public void createPartControl(Composite parent) { browserPart = new DocumentListBrowser(); browserPart.init(this.getSite(), parent); browserPart.populateToolbar(getViewSite().getActionBars().getToolBarManager()); } @Override public void setFocus() { ISelection selection = getSite().getPage().getSelection(); if (selection != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { IStructuredSelection selected = (IStructuredSelection) selection; if (selected.size() == 1 && selected.getFirstElement() instanceof Cluster) { browserPart.updateBrowserText((Cluster) selected.getFirstElement()); } } } @Override public void dispose() { browserPart.dispose(); super.dispose(); } }
little bug with documents view fixed git-svn-id: f05d591df75ba7f0993a7f82cc16d06976130918@2633 7ff1d41c-760d-0410-a7ff-a3a56f310b35
workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/views/DocumentListView.java
little bug with documents view fixed
<ide><path>orkbench/org.carrot2.workbench.core/src/org/carrot2/workbench/core/ui/views/DocumentListView.java <ide> browserPart = new DocumentListBrowser(); <ide> browserPart.init(this.getSite(), parent); <ide> browserPart.populateToolbar(getViewSite().getActionBars().getToolBarManager()); <del> } <del> <del> @Override <del> public void setFocus() <del> { <ide> ISelection selection = getSite().getPage().getSelection(); <ide> if (selection != null && !selection.isEmpty() <ide> && selection instanceof IStructuredSelection) <ide> } <ide> <ide> @Override <add> public void setFocus() <add> { <add> } <add> <add> @Override <ide> public void dispose() <ide> { <ide> browserPart.dispose();
Java
apache-2.0
7a6a8c2c07b223d5857dc6a953fb73ecd8d3ac67
0
hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services
package org.sagebionetworks.repo.model.dbo.dao.discussion; import static org.junit.Assert.*; import static org.sagebionetworks.repo.model.dbo.dao.discussion.DBODiscussionReplyDAOImpl.MAX_LIMIT; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.ids.IdGenerator; import org.sagebionetworks.ids.IdGenerator.TYPE; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.Node; import org.sagebionetworks.repo.model.NodeDAO; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionReplyDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionThreadDAO; import org.sagebionetworks.repo.model.dao.discussion.ForumDAO; import org.sagebionetworks.repo.model.discussion.DiscussionReplyBundle; import org.sagebionetworks.repo.model.discussion.DiscussionReplyOrder; import org.sagebionetworks.repo.model.discussion.DiscussionThreadAuthorStat; import org.sagebionetworks.repo.model.discussion.DiscussionThreadReplyStat; import org.sagebionetworks.repo.model.discussion.Forum; import org.sagebionetworks.repo.model.jdo.NodeTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" }) public class DBODiscussionReplyDAOImplTest { @Autowired private ForumDAO forumDao; @Autowired private UserGroupDAO userGroupDAO; @Autowired private NodeDAO nodeDao; @Autowired private DiscussionThreadDAO threadDao; @Autowired private DiscussionReplyDAO replyDao; @Autowired private IdGenerator idGenerator; private Long userId = null; private String projectId = null; private String forumId; private String threadId; private Long threadIdLong; private List<Long> usersToDelete = new ArrayList<Long>(); @Before public void before() { // create a user to create a project UserGroup user = new UserGroup(); user.setIsIndividual(true); userId = userGroupDAO.create(user); usersToDelete.add(userId); // create a project Node project = NodeTestUtils.createNew("projectName" + "-" + new Random().nextInt(), userId); project.setParentId(StackConfiguration.getRootFolderEntityIdStatic()); projectId = nodeDao.createNew(project); // create a forum Forum dto = forumDao.createForum(projectId); forumId = dto.getId(); // create a thread threadIdLong = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID); threadId = threadIdLong.toString(); threadDao.createThread(forumId, threadId, "title", "messageKey", userId); } @After public void after() { if (projectId != null) nodeDao.delete(projectId); for (Long userId: usersToDelete) { if (userId != null) { userGroupDAO.delete(userId.toString()); } } } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullThreadId() { replyDao.createReply(null, "messageKey", userId); } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullMessageKey() { replyDao.createReply(threadId, null, userId); } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullUserId() { replyDao.createReply(threadId, "messageKey", null); } @Test public void testCreate() { String messageKey = "messageKey"; DiscussionReplyBundle dto = replyDao.createReply(threadId, messageKey, userId); assertNotNull(dto); assertEquals(threadId, dto.getThreadId()); assertEquals(forumId, dto.getForumId()); assertEquals(projectId, dto.getProjectId()); assertEquals(messageKey, dto.getMessageKey()); assertEquals(userId.toString(), dto.getCreatedBy()); assertFalse(dto.getIsEdited()); assertFalse(dto.getIsDeleted()); assertNotNull(dto.getId()); assertNotNull(dto.getEtag()); Long replyId = Long.parseLong(dto.getId()); assertEquals(dto, replyDao.getReply(replyId)); } @Test public void testGetReplyCount() { assertEquals(0L, replyDao.getReplyCount(threadIdLong)); replyDao.createReply(threadId, "messageKey", userId); assertEquals(1L, replyDao.getReplyCount(threadIdLong)); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullThreadId() { replyDao.getRepliesForThread(null, 1L, 0L, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullLimit() { replyDao.getRepliesForThread(threadIdLong, null, 0L, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullOffset() { replyDao.getRepliesForThread(threadIdLong, 1L, null, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNegativeLimit() { replyDao.getRepliesForThread(threadIdLong, -1L, 0l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNegativeOffset() { replyDao.getRepliesForThread(threadIdLong, 1L, -1l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithLimitOverMax() { replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT+1, 0l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullOrderNotNullAscending() { replyDao.getRepliesForThread(threadIdLong, 1L, 0l, null, true); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNotNullOrderNullAscending() { replyDao.getRepliesForThread(threadIdLong, 1L, 0l, DiscussionReplyOrder.CREATED_ON, null); } @Test public void testGetRepliesForThreadWithZeroExistingReplies() { PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, null, null); assertNotNull(results); assertEquals(0L, results.getTotalNumberOfResults()); assertTrue(results.getResults().isEmpty()); } @Test public void getRepliesForThreadLimitAndOffsetTest() throws InterruptedException { int numberOfReplies = 3; List<DiscussionReplyBundle> createdReplies = createReplies(numberOfReplies, threadId); PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, null, null); assertNotNull(results); assertEquals("unordered replies", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("unordered replies", new HashSet<DiscussionReplyBundle>(results.getResults()), new HashSet<DiscussionReplyBundle>(createdReplies)); results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("ordered replies", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("ordered replies", createdReplies, results.getResults()); results = replyDao.getRepliesForThread(threadIdLong, 1L, 1L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("middle element", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("middle element", createdReplies.get(1), results.getResults().get(0)); results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 3L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("out of range", numberOfReplies, results.getTotalNumberOfResults()); assertTrue("out of range", results.getResults().isEmpty()); } @Test public void getRepliesForThreadDescendingTest() throws InterruptedException { int numberOfReplies = 3; List<DiscussionReplyBundle> createdReplies = createReplies(numberOfReplies, threadId); PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, DiscussionReplyOrder.CREATED_ON, false); assertEquals("ordered desc replies", numberOfReplies, results.getTotalNumberOfResults()); Collections.reverse(createdReplies); assertEquals("ordered desc replies", createdReplies, results.getResults()); } private List<DiscussionReplyBundle> createReplies(int numberOfReplies, String threadId) throws InterruptedException { List<DiscussionReplyBundle> list = new ArrayList<DiscussionReplyBundle>(); for (int i = 0; i < numberOfReplies; i++) { Thread.sleep(1000); list.add(replyDao.createReply(threadId, UUID.randomUUID().toString(), userId)); } return list; } @Test public void testGetEtag(){ DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); String etag = replyDao.getEtagForUpdate(replyId); assertNotNull(etag); assertEquals(dto.getEtag(), etag); } @Test public void testDelete(){ DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); dto.setIsDeleted(true); replyDao.markReplyAsDeleted(replyId); DiscussionReplyBundle returnedDto = replyDao.getReply(replyId); assertFalse("after marking reply as deleted, etag should be different", dto.getEtag().equals(returnedDto.getEtag())); dto.setModifiedOn(returnedDto.getModifiedOn()); dto.setEtag(returnedDto.getEtag()); assertEquals(dto, returnedDto); } @Test public void testUpdateMessageKey() throws InterruptedException { DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); Thread.sleep(1000); dto.setIsEdited(true); String newMessageKey = UUID.randomUUID().toString(); dto.setMessageKey(newMessageKey); replyDao.updateMessageKey(replyId, newMessageKey); DiscussionReplyBundle returnedDto = replyDao.getReply(replyId); assertFalse("after updating message key, modifiedOn should be different", dto.getModifiedOn().equals(returnedDto.getModifiedOn())); assertFalse("after updating message key, etag should be different", dto.getEtag().equals(returnedDto.getEtag())); dto.setModifiedOn(returnedDto.getModifiedOn()); dto.setEtag(returnedDto.getEtag()); assertEquals(dto, returnedDto); } @Test public void testGetThreadReplyStats() throws InterruptedException { // create another thread Long threadIdLong2 = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID); String threadId2 = threadIdLong2.toString(); threadDao.createThread(forumId, threadId2, "title", "messageKey2", userId); int numberOfReplies = 2; // create 2 replies for each thread createReplies(numberOfReplies, threadId); createReplies(numberOfReplies, threadId2); List<DiscussionThreadReplyStat> stats = replyDao.getThreadReplyStat(10L, 0L); assertNotNull(stats); assertEquals(stats.size(), 2); DiscussionThreadReplyStat stat1 = stats.get(0); DiscussionThreadReplyStat stat2 = stats.get(1); assertEquals(stat1.getThreadId(), threadIdLong); assertEquals(stat2.getThreadId(), threadIdLong2); assertEquals(stat1.getNumberOfReplies(), (Long) 2L); assertEquals(stat2.getNumberOfReplies(), (Long) 2L); assertNotNull(stat1.getLastActivity()); assertNotNull(stat2.getLastActivity()); } @Test public void testGetThreadAuthorStats() throws InterruptedException { DiscussionThreadAuthorStat stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertNotNull(stat); assertEquals(stat.getThreadId(), threadIdLong); assertTrue(stat.getActiveAuthors().isEmpty()); List<Long> users = createUsers(6); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(0)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(0)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(1)); stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertEquals(stat.getActiveAuthors(), Arrays.asList(users.get(0).toString(), users.get(1).toString())); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(1)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(2)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(2)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(3)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(3)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(4)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(4)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(5)); stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertEquals(stat.getActiveAuthors(), Arrays.asList(users.get(0).toString(), users.get(1).toString(), users.get(2).toString(), users.get(3).toString(), users.get(4).toString())); usersToDelete.addAll(users); } private List<Long> createUsers(int numberOfUsers) { List<Long> createdUsers = new ArrayList<Long>(); UserGroup user = new UserGroup(); user.setIsIndividual(true); for (int i = 0; i < numberOfUsers; i++) { createdUsers.add(userGroupDAO.create(user)); } return createdUsers; } }
lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/dbo/dao/discussion/DBODiscussionReplyDAOImplTest.java
package org.sagebionetworks.repo.model.dbo.dao.discussion; import static org.junit.Assert.*; import static org.sagebionetworks.repo.model.dbo.dao.discussion.DBODiscussionReplyDAOImpl.MAX_LIMIT; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.sagebionetworks.StackConfiguration; import org.sagebionetworks.ids.IdGenerator; import org.sagebionetworks.ids.IdGenerator.TYPE; import org.sagebionetworks.reflection.model.PaginatedResults; import org.sagebionetworks.repo.model.Node; import org.sagebionetworks.repo.model.NodeDAO; import org.sagebionetworks.repo.model.UserGroup; import org.sagebionetworks.repo.model.UserGroupDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionReplyDAO; import org.sagebionetworks.repo.model.dao.discussion.DiscussionThreadDAO; import org.sagebionetworks.repo.model.dao.discussion.ForumDAO; import org.sagebionetworks.repo.model.discussion.DiscussionReplyBundle; import org.sagebionetworks.repo.model.discussion.DiscussionReplyOrder; import org.sagebionetworks.repo.model.discussion.DiscussionThreadAuthorStat; import org.sagebionetworks.repo.model.discussion.DiscussionThreadReplyStat; import org.sagebionetworks.repo.model.discussion.Forum; import org.sagebionetworks.repo.model.jdo.NodeTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" }) public class DBODiscussionReplyDAOImplTest { @Autowired private ForumDAO forumDao; @Autowired private UserGroupDAO userGroupDAO; @Autowired private NodeDAO nodeDao; @Autowired private DiscussionThreadDAO threadDao; @Autowired private DiscussionReplyDAO replyDao; @Autowired private IdGenerator idGenerator; private Long userId = null; private String projectId = null; private String forumId; private String threadId; private Long threadIdLong; private List<Long> usersToDelete = new ArrayList<Long>(); @Before public void before() { // create a user to create a project UserGroup user = new UserGroup(); user.setIsIndividual(true); userId = userGroupDAO.create(user); usersToDelete.add(userId); // create a project Node project = NodeTestUtils.createNew("projectName" + "-" + new Random().nextInt(), userId); project.setParentId(StackConfiguration.getRootFolderEntityIdStatic()); projectId = nodeDao.createNew(project); // create a forum Forum dto = forumDao.createForum(projectId); forumId = dto.getId(); // create a thread threadIdLong = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID); threadId = threadIdLong.toString(); threadDao.createThread(forumId, threadId, "title", "messageKey", userId); } @After public void after() { if (projectId != null) nodeDao.delete(projectId); for (Long userId: usersToDelete) { if (userId != null) { userGroupDAO.delete(userId.toString()); } } } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullThreadId() { replyDao.createReply(null, "messageKey", userId); } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullMessageKey() { replyDao.createReply(threadId, null, userId); } @Test (expected = IllegalArgumentException.class) public void testCreateReplyWithNullUserId() { replyDao.createReply(threadId, "messageKey", null); } @Test public void testCreate() { String messageKey = "messageKey"; DiscussionReplyBundle dto = replyDao.createReply(threadId, messageKey, userId); assertNotNull(dto); assertEquals(threadId, dto.getThreadId()); assertEquals(forumId, dto.getForumId()); assertEquals(projectId, dto.getProjectId()); assertEquals(messageKey, dto.getMessageKey()); assertEquals(userId.toString(), dto.getCreatedBy()); assertFalse(dto.getIsEdited()); assertFalse(dto.getIsDeleted()); assertNotNull(dto.getId()); assertNotNull(dto.getEtag()); Long replyId = Long.parseLong(dto.getId()); assertEquals(dto, replyDao.getReply(replyId)); } @Test public void testGetReplyCount() { assertEquals(0L, replyDao.getReplyCount(threadIdLong)); replyDao.createReply(threadId, "messageKey", userId); assertEquals(1L, replyDao.getReplyCount(threadIdLong)); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullThreadId() { replyDao.getRepliesForThread(null, 1L, 0L, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullLimit() { replyDao.getRepliesForThread(threadIdLong, null, 0L, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullOffset() { replyDao.getRepliesForThread(threadIdLong, 1L, null, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNegativeLimit() { replyDao.getRepliesForThread(threadIdLong, -1L, 0l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNegativeOffset() { replyDao.getRepliesForThread(threadIdLong, 1L, -1l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithLimitOverMax() { replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT+1, 0l, null, null); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNullOrderNotNullAscending() { replyDao.getRepliesForThread(threadIdLong, 1L, 0l, null, true); } @Test (expected = IllegalArgumentException.class) public void testGetRepliesForThreadWithNotNullOrderNullAscending() { replyDao.getRepliesForThread(threadIdLong, 1L, 0l, DiscussionReplyOrder.CREATED_ON, null); } @Test public void testGetRepliesForThreadWithZeroExistingReplies() { PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, null, null); assertNotNull(results); assertEquals(0L, results.getTotalNumberOfResults()); assertTrue(results.getResults().isEmpty()); } @Test public void getRepliesForThreadLimitAndOffsetTest() throws InterruptedException { int numberOfReplies = 3; List<DiscussionReplyBundle> createdReplies = createReplies(numberOfReplies, threadId); PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, null, null); assertNotNull(results); assertEquals("unordered replies", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("unordered replies", new HashSet<DiscussionReplyBundle>(results.getResults()), new HashSet<DiscussionReplyBundle>(createdReplies)); results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("ordered replies", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("ordered replies", createdReplies, results.getResults()); results = replyDao.getRepliesForThread(threadIdLong, 1L, 1L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("middle element", numberOfReplies, results.getTotalNumberOfResults()); assertEquals("middle element", createdReplies.get(1), results.getResults().get(0)); results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 3L, DiscussionReplyOrder.CREATED_ON, true); assertEquals("out of range", numberOfReplies, results.getTotalNumberOfResults()); assertTrue("out of range", results.getResults().isEmpty()); } @Test public void getRepliesForThreadDescendingTest() throws InterruptedException { int numberOfReplies = 3; List<DiscussionReplyBundle> createdReplies = createReplies(numberOfReplies, threadId); PaginatedResults<DiscussionReplyBundle> results = replyDao.getRepliesForThread(threadIdLong, MAX_LIMIT, 0L, DiscussionReplyOrder.CREATED_ON, false); assertEquals("ordered desc replies", numberOfReplies, results.getTotalNumberOfResults()); Collections.reverse(createdReplies); assertEquals("ordered desc replies", createdReplies, results.getResults()); } private List<DiscussionReplyBundle> createReplies(int numberOfReplies, String threadId) throws InterruptedException { List<DiscussionReplyBundle> list = new ArrayList<DiscussionReplyBundle>(); for (int i = 0; i < numberOfReplies; i++) { Thread.sleep(1000); list.add(replyDao.createReply(threadId, UUID.randomUUID().toString(), userId)); } return list; } @Test public void testGetEtag(){ DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); String etag = replyDao.getEtagForUpdate(replyId); assertNotNull(etag); assertEquals(dto.getEtag(), etag); } @Test public void testDelete(){ DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); dto.setIsDeleted(true); replyDao.markReplyAsDeleted(replyId); DiscussionReplyBundle returnedDto = replyDao.getReply(replyId); assertFalse("after marking reply as deleted, etag should be different", dto.getEtag().equals(returnedDto.getEtag())); dto.setModifiedOn(returnedDto.getModifiedOn()); dto.setEtag(returnedDto.getEtag()); assertEquals(dto, returnedDto); } @Test public void testUpdateMessageKey() throws InterruptedException { DiscussionReplyBundle dto = replyDao.createReply(threadId, "messageKey", userId); long replyId = Long.parseLong(dto.getId()); Thread.sleep(1000); dto.setIsEdited(true); String newMessageKey = UUID.randomUUID().toString(); dto.setMessageKey(newMessageKey); replyDao.updateMessageKey(replyId, newMessageKey); DiscussionReplyBundle returnedDto = replyDao.getReply(replyId); assertFalse("after updating message key, modifiedOn should be different", dto.getModifiedOn().equals(returnedDto.getModifiedOn())); assertFalse("after updating message key, etag should be different", dto.getEtag().equals(returnedDto.getEtag())); dto.setModifiedOn(returnedDto.getModifiedOn()); dto.setEtag(returnedDto.getEtag()); assertEquals(dto, returnedDto); } @Test public void testGetThreadReplyStats() throws InterruptedException { // create another thread Long threadIdLong2 = idGenerator.generateNewId(TYPE.DISCUSSION_THREAD_ID); String threadId2 = threadIdLong2.toString(); threadDao.createThread(forumId, threadId2, "title", "messageKey2", userId); int numberOfReplies = 2; // create 2 replies for each thread createReplies(numberOfReplies, threadId); createReplies(numberOfReplies, threadId2); List<DiscussionThreadReplyStat> stats = replyDao.getThreadReplyStat(10L, 0L); assertNotNull(stats); assertEquals(stats.size(), 2); DiscussionThreadReplyStat stat1 = stats.get(0); DiscussionThreadReplyStat stat2 = stats.get(1); assertEquals(stat1.getThreadId(), threadIdLong); assertEquals(stat2.getThreadId(), threadIdLong2); assertEquals(stat1.getNumberOfReplies(), (Long) 2L); assertEquals(stat2.getNumberOfReplies(), (Long) 2L); assertNotNull(stat1.getLastActivity()); assertNotNull(stat2.getLastActivity()); } @Ignore // see PLFM-3700 @Test public void testGetThreadAuthorStats() throws InterruptedException { DiscussionThreadAuthorStat stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertNotNull(stat); assertEquals(stat.getThreadId(), threadIdLong); assertTrue(stat.getActiveAuthors().isEmpty()); List<Long> users = createUsers(6); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(0)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(0)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(1)); stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertEquals(stat.getActiveAuthors(), Arrays.asList(users.get(0).toString(), users.get(1).toString())); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(1)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(2)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(2)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(3)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(3)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(4)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(4)); replyDao.createReply(threadId, UUID.randomUUID().toString(), users.get(5)); stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong); assertEquals(stat.getActiveAuthors(), Arrays.asList(users.get(0).toString(), users.get(1).toString(), users.get(2).toString(), users.get(3).toString(), users.get(4).toString())); usersToDelete.addAll(users); } private List<Long> createUsers(int numberOfUsers) { List<Long> createdUsers = new ArrayList<Long>(); UserGroup user = new UserGroup(); user.setIsIndividual(true); for (int i = 0; i < numberOfUsers; i++) { createdUsers.add(userGroupDAO.create(user)); } return createdUsers; } }
test was fixed
lib/jdomodels/src/test/java/org/sagebionetworks/repo/model/dbo/dao/discussion/DBODiscussionReplyDAOImplTest.java
test was fixed
<ide><path>ib/jdomodels/src/test/java/org/sagebionetworks/repo/model/dbo/dao/discussion/DBODiscussionReplyDAOImplTest.java <ide> assertNotNull(stat2.getLastActivity()); <ide> } <ide> <del> @Ignore // see PLFM-3700 <ide> @Test <ide> public void testGetThreadAuthorStats() throws InterruptedException { <ide> DiscussionThreadAuthorStat stat = replyDao.getDiscussionThreadAuthorStat(threadIdLong);
Java
apache-2.0
bcdfb269800bda195c8d5f8e07181bbc3f33d15b
0
Esri/arcgis-runtime-samples-android,Esri/arcgis-runtime-samples-android,Esri/arcgis-runtime-samples-android,Esri/arcgis-runtime-samples-android
/* Copyright 2016 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.esri.arcgisruntime.sample.findroute; import android.app.ProgressDialog; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.esri.arcgisruntime.concurrent.ListenableFuture; import com.esri.arcgisruntime.geometry.Geometry; import com.esri.arcgisruntime.geometry.Point; import com.esri.arcgisruntime.geometry.SpatialReference; import com.esri.arcgisruntime.geometry.SpatialReferences; import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer; import com.esri.arcgisruntime.mapping.ArcGISMap; import com.esri.arcgisruntime.mapping.Basemap; import com.esri.arcgisruntime.mapping.Viewpoint; import com.esri.arcgisruntime.mapping.view.Graphic; import com.esri.arcgisruntime.mapping.view.GraphicsOverlay; import com.esri.arcgisruntime.mapping.view.MapView; import com.esri.arcgisruntime.symbology.PictureMarkerSymbol; import com.esri.arcgisruntime.symbology.SimpleLineSymbol; import com.esri.arcgisruntime.tasks.route.DirectionManeuver; import com.esri.arcgisruntime.tasks.route.Route; import com.esri.arcgisruntime.tasks.route.RouteParameters; import com.esri.arcgisruntime.tasks.route.RouteResult; import com.esri.arcgisruntime.tasks.route.RouteTask; import com.esri.arcgisruntime.tasks.route.Stop; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "FindRouteSample"; private ArcGISVectorTiledLayer mVectorTiledLayer; private FloatingActionButton mDirectionFab; private ProgressDialog mProgressDialog; private MapView mMapView; private RouteTask mRouteTask; private RouteParameters mRouteParams; private Point mSourcePoint; private Point mDestinationPoint; private Route mRoute; private SimpleLineSymbol mRouteSymbol; private GraphicsOverlay mGraphicsOverlay; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drawer); // inflate MapView from layout mMapView = (MapView) findViewById(R.id.mapView); // create new Vector Tiled Layer from service url mVectorTiledLayer = new ArcGISVectorTiledLayer( getResources().getString(R.string.navigation_vector)); // set tiled layer as basemap Basemap basemap = new Basemap(mVectorTiledLayer); // create a map with the basemap ArcGISMap mMap = new ArcGISMap(basemap); // create a viewpoint from lat, long, scale Viewpoint sanDiegoPoint = new Viewpoint(32.7157, -117.1611, 200000); // set initial map extent mMap.setInitialViewpoint(sanDiegoPoint); // set the map to be displayed in this view mMapView.setMap(mMap); // inflate navigation drawer mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDirectionFab = (FloatingActionButton) findViewById(R.id.fab); setupDrawer(); setupSymbols(); mProgressDialog = new ProgressDialog(this); mProgressDialog.setTitle(getString(R.string.progress_title)); mProgressDialog.setMessage(getString(R.string.progress_message)); mDirectionFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mProgressDialog.show(); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); setTitle(getString(R.string.app_name)); } mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); // create RouteTask instance mRouteTask = new RouteTask(getString(R.string.routing_service)); final ListenableFuture<RouteParameters> listenableFuture = mRouteTask.generateDefaultParametersAsync(); listenableFuture.addDoneListener(new Runnable() { @Override public void run() { try { if (listenableFuture.isDone()) { int i = 0; mRouteParams = listenableFuture.get(); // get List of Stops List<Stop> routeStops = mRouteParams.getStops(); // set return directions as true to return turn-by-turn directions in the result of getDirectionManeuvers(). mRouteParams.setReturnDirections(true); // add your stops to it 32.7254716,-117.1508181 32.7076359,-117.1592837 -117.15557279683529 //-13041171, 3860988, SpatialReference(3857) -13041693, 3856006, SpatialReference(3857) routeStops.add(new Stop(new Point(-117.15083257944445, 32.741123367963446, SpatialReferences.getWgs84()))); routeStops.add(new Stop(new Point(-117.15557279683529, 32.703360305883045, SpatialReferences.getWgs84()))); // solve RouteResult result = mRouteTask.solveAsync(mRouteParams).get(); final List routes = result.getRoutes(); mRoute = (Route) routes.get(0); // create a mRouteSymbol graphic Graphic routeGraphic = new Graphic(mRoute.getRouteGeometry(), mRouteSymbol); // add mRouteSymbol graphic to the map mGraphicsOverlay.getGraphics().add(routeGraphic); // get directions // NOTE: to get turn-by-turn directions Route Parameters should set returnDirection flag as true final List<DirectionManeuver> directions = mRoute.getDirectionManeuvers(); String[] directionsArray = new String[directions.size()]; for (DirectionManeuver dm : directions) { directionsArray[i++] = dm.getDirectionText(); } Log.d(TAG,directions.get(0).getGeometry().getExtent().getXMin() + ""); Log.d(TAG,directions.get(0).getGeometry().getExtent().getYMin() + ""); // Set the adapter for the list view mDrawerList.setAdapter(new ArrayAdapter<>(getApplicationContext(), R.layout.drawer_layout_text, directionsArray)); if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(mGraphicsOverlay.getGraphics().size() > 3) { mGraphicsOverlay.getGraphics().remove(mGraphicsOverlay.getGraphics().size() - 1); } mDrawerLayout.closeDrawers(); DirectionManeuver dm = directions.get(position); Geometry gm = dm.getGeometry(); Viewpoint vp = new Viewpoint(gm.getExtent(),20); mMapView.setViewpointWithDurationAsync(vp,3); SimpleLineSymbol selectedRouteSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.GREEN, 5); Graphic selectedRouteGraphic = new Graphic(directions.get(position).getGeometry(), selectedRouteSymbol); mGraphicsOverlay.getGraphics().add(selectedRouteGraphic); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } }); } }); } /** * Set up the Source, Destination and mRouteSymbol graphics symbol */ private void setupSymbols() { mGraphicsOverlay = new GraphicsOverlay(); //add the overlay to the map view mMapView.getGraphicsOverlays().add(mGraphicsOverlay); //[DocRef: Name=Picture Marker Symbol Drawable-android, Category=Fundamentals, Topic=Symbols and Renderers] //Create a picture marker symbol from an app resource BitmapDrawable startDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_source); final PictureMarkerSymbol pinSourceSymbol = new PictureMarkerSymbol(startDrawable); pinSourceSymbol.loadAsync(); //[DocRef: END] pinSourceSymbol.addDoneLoadingListener(new Runnable() { @Override public void run() { //add a new graphic as start point mSourcePoint = new Point(-117.15083257944445, 32.741123367963446, SpatialReferences.getWgs84()); Graphic pinSourceGraphic = new Graphic(mSourcePoint, pinSourceSymbol); mGraphicsOverlay.getGraphics().add(pinSourceGraphic); } }); pinSourceSymbol.setOffsetY(20); BitmapDrawable endDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_destination); final PictureMarkerSymbol pinDestinationSymbol = new PictureMarkerSymbol(endDrawable); pinDestinationSymbol.loadAsync(); //[DocRef: END] pinDestinationSymbol.addDoneLoadingListener(new Runnable() { @Override public void run() { //add a new graphic as end point mDestinationPoint = new Point(-117.15557279683529, 32.703360305883045, SpatialReferences.getWgs84()); Graphic destinationGraphic = new Graphic(mDestinationPoint, pinDestinationSymbol); mGraphicsOverlay.getGraphics().add(destinationGraphic); } }); pinDestinationSymbol.setOffsetY(20); mRouteSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5); } @Override protected void onPause() { super.onPause(); mMapView.pause(); } @Override protected void onResume() { super.onResume(); mMapView.resume(); } /** * set up the drawer */ private void setupDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.addDrawerListener(mDrawerToggle); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. // Activate the navigation drawer toggle return (mDrawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item); } }
find-route/src/main/java/com/esri/arcgisruntime/sample/findroute/MainActivity.java
/* Copyright 2016 Esri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.esri.arcgisruntime.sample.findroute; import android.app.ProgressDialog; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.esri.arcgisruntime.concurrent.ListenableFuture; import com.esri.arcgisruntime.geometry.Geometry; import com.esri.arcgisruntime.geometry.Point; import com.esri.arcgisruntime.geometry.SpatialReferences; import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer; import com.esri.arcgisruntime.mapping.ArcGISMap; import com.esri.arcgisruntime.mapping.Basemap; import com.esri.arcgisruntime.mapping.Viewpoint; import com.esri.arcgisruntime.mapping.view.Graphic; import com.esri.arcgisruntime.mapping.view.GraphicsOverlay; import com.esri.arcgisruntime.mapping.view.MapView; import com.esri.arcgisruntime.symbology.PictureMarkerSymbol; import com.esri.arcgisruntime.symbology.SimpleLineSymbol; import com.esri.arcgisruntime.tasks.route.DirectionManeuver; import com.esri.arcgisruntime.tasks.route.Route; import com.esri.arcgisruntime.tasks.route.RouteParameters; import com.esri.arcgisruntime.tasks.route.RouteResult; import com.esri.arcgisruntime.tasks.route.RouteTask; import com.esri.arcgisruntime.tasks.route.Stop; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "FindRouteSample"; private ArcGISVectorTiledLayer mVectorTiledLayer; private FloatingActionButton mDirectionFab; private ProgressDialog mProgressDialog; private MapView mMapView; private RouteTask mRouteTask; private RouteParameters mRouteParams; private Point mSourcePoint; private Point mDestinationPoint; private Route mRoute; private SimpleLineSymbol mRouteSymbol; private GraphicsOverlay mGraphicsOverlay; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drawer); // inflate MapView from layout mMapView = (MapView) findViewById(R.id.mapView); // create new Vector Tiled Layer from service url mVectorTiledLayer = new ArcGISVectorTiledLayer( getResources().getString(R.string.navigation_vector)); // set tiled layer as basemap Basemap basemap = new Basemap(mVectorTiledLayer); // create a map with the basemap ArcGISMap mMap = new ArcGISMap(basemap); // create a viewpoint from lat, long, scale Viewpoint sanDiegoPoint = new Viewpoint(32.7157, -117.1611, 200000); // set initial map extent mMap.setInitialViewpoint(sanDiegoPoint); // set the map to be displayed in this view mMapView.setMap(mMap); // inflate navigation drawer mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDirectionFab = (FloatingActionButton) findViewById(R.id.fab); setupDrawer(); setupSymbols(); mProgressDialog = new ProgressDialog(this); mProgressDialog.setTitle(getString(R.string.progress_title)); mProgressDialog.setMessage(getString(R.string.progress_message)); mDirectionFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mProgressDialog.show(); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); setTitle(getString(R.string.app_name)); } mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); // create RouteTask instance mRouteTask = new RouteTask(getString(R.string.routing_service)); final ListenableFuture<RouteParameters> listenableFuture = mRouteTask.generateDefaultParametersAsync(); listenableFuture.addDoneListener(new Runnable() { @Override public void run() { try { if (listenableFuture.isDone()) { int i = 0; mRouteParams = listenableFuture.get(); // get List of Stops List<Stop> routeStops = mRouteParams.getStops(); // set return directions as true to return turn-by-turn directions in the result of getDirectionManeuvers(). mRouteParams.setReturnDirections(true); // add your stops to it routeStops.add(new Stop(new Point(-13041171.537945, 3860988.271378, SpatialReferences.getWebMercator()))); routeStops.add(new Stop(new Point(-13041693.562570, 3856006.859684, SpatialReferences.getWebMercator()))); // solve RouteResult result = mRouteTask.solveAsync(mRouteParams).get(); final List routes = result.getRoutes(); mRoute = (Route) routes.get(0); // create a mRouteSymbol graphic Graphic routeGraphic = new Graphic(mRoute.getRouteGeometry(), mRouteSymbol); // add mRouteSymbol graphic to the map mGraphicsOverlay.getGraphics().add(routeGraphic); // get directions // NOTE: to get turn-by-turn directions Route Parameters should set returnDirection flag as true final List<DirectionManeuver> directions = mRoute.getDirectionManeuvers(); String[] directionsArray = new String[directions.size()]; for (DirectionManeuver dm : directions) { directionsArray[i++] = dm.getDirectionText(); } // Set the adapter for the list view mDrawerList.setAdapter(new ArrayAdapter<>(getApplicationContext(), R.layout.drawer_layout_text, directionsArray)); if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(mGraphicsOverlay.getGraphics().size() > 3) { mGraphicsOverlay.getGraphics().remove(mGraphicsOverlay.getGraphics().size() - 1); } mDrawerLayout.closeDrawers(); DirectionManeuver dm = directions.get(position); Geometry gm = dm.getGeometry(); Viewpoint vp = new Viewpoint(gm.getExtent(),20); mMapView.setViewpointWithDurationAsync(vp,3); SimpleLineSymbol selectedRouteSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.GREEN, 5); Graphic selectedRouteGraphic = new Graphic(directions.get(position).getGeometry(), selectedRouteSymbol); mGraphicsOverlay.getGraphics().add(selectedRouteGraphic); } }); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } }); } }); } /** * Set up the Source, Destination and mRouteSymbol graphics symbol */ private void setupSymbols() { mGraphicsOverlay = new GraphicsOverlay(); //add the overlay to the map view mMapView.getGraphicsOverlays().add(mGraphicsOverlay); //[DocRef: Name=Picture Marker Symbol Drawable-android, Category=Fundamentals, Topic=Symbols and Renderers] //Create a picture marker symbol from an app resource BitmapDrawable startDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_source); final PictureMarkerSymbol pinSourceSymbol = new PictureMarkerSymbol(startDrawable); pinSourceSymbol.loadAsync(); //[DocRef: END] pinSourceSymbol.addDoneLoadingListener(new Runnable() { @Override public void run() { //add a new graphic as start point mSourcePoint = new Point(-13041171.537945, 3860988.271378, SpatialReferences.getWebMercator()); Graphic pinSourceGraphic = new Graphic(mSourcePoint, pinSourceSymbol); mGraphicsOverlay.getGraphics().add(pinSourceGraphic); } }); BitmapDrawable endDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_destination); final PictureMarkerSymbol pinDestinationSymbol = new PictureMarkerSymbol(endDrawable); pinDestinationSymbol.loadAsync(); //[DocRef: END] pinDestinationSymbol.addDoneLoadingListener(new Runnable() { @Override public void run() { //add a new graphic as end point mDestinationPoint = new Point(-13041693.562570, 3856006.859684, SpatialReferences.getWebMercator()); Graphic destinationGraphic = new Graphic(mDestinationPoint, pinDestinationSymbol); mGraphicsOverlay.getGraphics().add(destinationGraphic); } }); mRouteSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5); } @Override protected void onPause() { super.onPause(); mMapView.pause(); } @Override protected void onResume() { super.onResume(); mMapView.resume(); } /** * set up the drawer */ private void setupDrawer() { mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.addDrawerListener(mDrawerToggle); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. // Activate the navigation drawer toggle return (mDrawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item); } }
- refactored to set offset on start and end PictureMarkerSymbols
find-route/src/main/java/com/esri/arcgisruntime/sample/findroute/MainActivity.java
- refactored to set offset on start and end PictureMarkerSymbols
<ide><path>ind-route/src/main/java/com/esri/arcgisruntime/sample/findroute/MainActivity.java <ide> package com.esri.arcgisruntime.sample.findroute; <ide> <ide> import android.app.ProgressDialog; <add>import android.content.pm.ActivityInfo; <ide> import android.content.res.Configuration; <ide> import android.graphics.Color; <ide> import android.graphics.drawable.BitmapDrawable; <ide> import com.esri.arcgisruntime.concurrent.ListenableFuture; <ide> import com.esri.arcgisruntime.geometry.Geometry; <ide> import com.esri.arcgisruntime.geometry.Point; <add>import com.esri.arcgisruntime.geometry.SpatialReference; <ide> import com.esri.arcgisruntime.geometry.SpatialReferences; <ide> import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer; <ide> import com.esri.arcgisruntime.mapping.ArcGISMap; <ide> // set return directions as true to return turn-by-turn directions in the result of getDirectionManeuvers(). <ide> mRouteParams.setReturnDirections(true); <ide> <del> // add your stops to it <del> routeStops.add(new Stop(new Point(-13041171.537945, 3860988.271378, SpatialReferences.getWebMercator()))); <del> routeStops.add(new Stop(new Point(-13041693.562570, 3856006.859684, SpatialReferences.getWebMercator()))); <add> // add your stops to it 32.7254716,-117.1508181 32.7076359,-117.1592837 -117.15557279683529 <add> //-13041171, 3860988, SpatialReference(3857) -13041693, 3856006, SpatialReference(3857) <add> routeStops.add(new Stop(new Point(-117.15083257944445, 32.741123367963446, SpatialReferences.getWgs84()))); <add> routeStops.add(new Stop(new Point(-117.15557279683529, 32.703360305883045, SpatialReferences.getWgs84()))); <ide> <ide> // solve <ide> RouteResult result = mRouteTask.solveAsync(mRouteParams).get(); <ide> for (DirectionManeuver dm : directions) { <ide> directionsArray[i++] = dm.getDirectionText(); <ide> } <add> Log.d(TAG,directions.get(0).getGeometry().getExtent().getXMin() + ""); <add> Log.d(TAG,directions.get(0).getGeometry().getExtent().getYMin() + ""); <ide> <ide> // Set the adapter for the list view <ide> mDrawerList.setAdapter(new ArrayAdapter<>(getApplicationContext(), <ide> @Override <ide> public void run() { <ide> //add a new graphic as start point <del> mSourcePoint = new Point(-13041171.537945, 3860988.271378, SpatialReferences.getWebMercator()); <add> mSourcePoint = new Point(-117.15083257944445, 32.741123367963446, SpatialReferences.getWgs84()); <ide> Graphic pinSourceGraphic = new Graphic(mSourcePoint, pinSourceSymbol); <ide> mGraphicsOverlay.getGraphics().add(pinSourceGraphic); <ide> } <ide> }); <add> pinSourceSymbol.setOffsetY(20); <ide> BitmapDrawable endDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_destination); <ide> final PictureMarkerSymbol pinDestinationSymbol = new PictureMarkerSymbol(endDrawable); <ide> pinDestinationSymbol.loadAsync(); <ide> @Override <ide> public void run() { <ide> //add a new graphic as end point <del> mDestinationPoint = new Point(-13041693.562570, 3856006.859684, SpatialReferences.getWebMercator()); <add> mDestinationPoint = new Point(-117.15557279683529, 32.703360305883045, SpatialReferences.getWgs84()); <ide> Graphic destinationGraphic = new Graphic(mDestinationPoint, pinDestinationSymbol); <ide> mGraphicsOverlay.getGraphics().add(destinationGraphic); <ide> } <ide> }); <add> pinDestinationSymbol.setOffsetY(20); <ide> <ide> mRouteSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLUE, 5); <ide> } <ide> <ide> @Override <ide> public void onConfigurationChanged(Configuration newConfig) { <add> setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); <ide> super.onConfigurationChanged(newConfig); <add> <ide> mDrawerToggle.onConfigurationChanged(newConfig); <ide> } <ide>
Java
epl-1.0
884e4412243d6c09a1127c60eb0448cf90799eb2
0
stalep/forge-core,pplatek/core,jerr/jbossforge-core,ivannov/core,oscerd/core,oscerd/core,ivannov/core,oscerd/core,ivannov/core,pplatek/core,pplatek/core,forge/core,D9110/core,D9110/core,D9110/core,ivannov/core,D9110/core,forge/core,oscerd/core,forge/core,agoncal/core,oscerd/core,oscerd/core,ivannov/core,agoncal/core,D9110/core,agoncal/core,agoncal/core,D9110/core,jerr/jbossforge-core,forge/core,pplatek/core,jerr/jbossforge-core,ivannov/core,jerr/jbossforge-core,oscerd/core,pplatek/core,D9110/core,pplatek/core,jerr/jbossforge-core,agoncal/core,pplatek/core,jerr/jbossforge-core,ivannov/core,oscerd/core,D9110/core,ivannov/core,pplatek/core,D9110/core,jerr/jbossforge-core,agoncal/core,agoncal/core,stalep/forge-core,jerr/jbossforge-core,agoncal/core,ivannov/core,forge/core,agoncal/core,pplatek/core,agoncal/core,pplatek/core,jerr/jbossforge-core,forge/core,forge/core,jerr/jbossforge-core,oscerd/core,oscerd/core,ivannov/core,forge/core,forge/core,forge/core,D9110/core
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.ui.impl; import java.util.concurrent.Callable; import javax.enterprise.inject.Vetoed; import org.jboss.forge.addon.convert.Converter; import org.jboss.forge.addon.facets.AbstractFaceted; import org.jboss.forge.addon.ui.UIValidator; import org.jboss.forge.addon.ui.context.UIValidationContext; import org.jboss.forge.addon.ui.facets.HintsFacet; import org.jboss.forge.addon.ui.input.InputComponent; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.util.InputComponents; import org.jboss.forge.furnace.util.Callables; /** * Implementation of a {@link UIInput} object * * @author <a href="mailto:[email protected]">George Gastaldi</a> * * @param <VALUETYPE> */ @Vetoed @SuppressWarnings("unchecked") public abstract class AbstractInputComponent<IMPLTYPE extends InputComponent<IMPLTYPE, VALUETYPE>, VALUETYPE> extends AbstractFaceted<HintsFacet> implements InputComponent<IMPLTYPE, VALUETYPE> { private final String name; private final char shortName; private final Class<VALUETYPE> type; private String label; private String description; private Callable<Boolean> enabled = Callables.returning(Boolean.TRUE); private Callable<Boolean> required = Callables.returning(Boolean.FALSE); private String requiredMessage; private Converter<String, VALUETYPE> valueConverter; private UIValidator validator; public AbstractInputComponent(String name, char shortName, Class<VALUETYPE> type) { this.name = name; this.shortName = shortName; this.type = type; } @Override public String getLabel() { return label; } @Override public String getName() { return name; } @Override public char getShortName() { return shortName; } @Override public String getDescription() { return description; } @Override public Class<VALUETYPE> getValueType() { return type; } @Override public boolean isEnabled() { return Callables.call(enabled); } @Override public boolean isRequired() { return Callables.call(required); } @Override public IMPLTYPE setEnabled(boolean enabled) { this.enabled = Callables.returning(enabled); return (IMPLTYPE) this; } @Override public IMPLTYPE setEnabled(Callable<Boolean> callback) { enabled = callback; return (IMPLTYPE) this; } @Override public IMPLTYPE setLabel(String label) { this.label = label; return (IMPLTYPE) this; } @Override public IMPLTYPE setDescription(String description) { this.description = description; return (IMPLTYPE) this; } @Override public IMPLTYPE setRequired(boolean required) { this.required = Callables.returning(required); return (IMPLTYPE) this; } @Override public IMPLTYPE setRequired(Callable<Boolean> required) { this.required = required; return (IMPLTYPE) this; } @Override public boolean supports(HintsFacet type) { return true; } @Override public String getRequiredMessage() { return requiredMessage; } @Override public IMPLTYPE setRequiredMessage(String requiredMessage) { this.requiredMessage = requiredMessage; return (IMPLTYPE) this; } @Override public Converter<String, VALUETYPE> getValueConverter() { return valueConverter; } @Override public IMPLTYPE setValueConverter(Converter<String, VALUETYPE> converter) { this.valueConverter = converter; return (IMPLTYPE) this; } @Override public IMPLTYPE setValidator(UIValidator validator) { this.validator = validator; return (IMPLTYPE) this; } @Override public UIValidator getValidator() { return this.validator; } @Override public void validate(UIValidationContext context) { String msg = InputComponents.validateRequired(this); if (msg != null && !msg.isEmpty()) { context.addValidationError(this, msg); } if (this.validator != null) { this.validator.validate(context); } } }
ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/AbstractInputComponent.java
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.ui.impl; import java.util.concurrent.Callable; import javax.enterprise.inject.Vetoed; import org.jboss.forge.addon.convert.Converter; import org.jboss.forge.addon.facets.AbstractFaceted; import org.jboss.forge.addon.ui.UIValidator; import org.jboss.forge.addon.ui.context.UIValidationContext; import org.jboss.forge.addon.ui.facets.HintsFacet; import org.jboss.forge.addon.ui.input.InputComponent; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.util.InputComponents; import org.jboss.forge.furnace.util.Callables; /** * Implementation of a {@link UIInput} object * * @author <a href="mailto:[email protected]">George Gastaldi</a> * * @param <VALUETYPE> */ @Vetoed @SuppressWarnings("unchecked") public abstract class AbstractInputComponent<IMPLTYPE extends InputComponent<IMPLTYPE, VALUETYPE>, VALUETYPE> extends AbstractFaceted<HintsFacet> implements InputComponent<IMPLTYPE, VALUETYPE> { private final String name; private final char shortName; private final Class<VALUETYPE> type; private String label; private String description; private Callable<Boolean> enabled = Callables.returning(Boolean.TRUE); private Callable<Boolean> required = Callables.returning(Boolean.FALSE); private String requiredMessage; private Converter<String, VALUETYPE> valueConverter; private UIValidator validator; public AbstractInputComponent(String name, char shortName, Class<VALUETYPE> type) { this.name = name; this.shortName = shortName; this.type = type; } @Override public String getLabel() { return label; } @Override public String getName() { return name; } @Override public char getShortName() { return shortName; } @Override public String getDescription() { return description; } @Override public Class<VALUETYPE> getValueType() { return type; } @Override public boolean isEnabled() { return Callables.call(enabled); } @Override public boolean isRequired() { return Callables.call(required); } @Override public IMPLTYPE setEnabled(boolean enabled) { this.enabled = Callables.returning(enabled); return (IMPLTYPE) this; } @Override public IMPLTYPE setEnabled(Callable<Boolean> callback) { enabled = callback; return (IMPLTYPE) this; } @Override public IMPLTYPE setLabel(String label) { this.label = label; return (IMPLTYPE) this; } @Override public IMPLTYPE setDescription(String description) { this.description = description; return (IMPLTYPE) this; } @Override public IMPLTYPE setRequired(boolean required) { this.required = Callables.returning(required); return (IMPLTYPE) this; } @Override public IMPLTYPE setRequired(Callable<Boolean> required) { this.required = required; return (IMPLTYPE) this; } @Override public boolean supports(HintsFacet type) { return true; } @Override public String getRequiredMessage() { return requiredMessage; } @Override public IMPLTYPE setRequiredMessage(String requiredMessage) { this.requiredMessage = requiredMessage; return (IMPLTYPE) this; } @Override public Converter<String, VALUETYPE> getValueConverter() { return valueConverter; } @Override public IMPLTYPE setValueConverter(Converter<String, VALUETYPE> converter) { this.valueConverter = converter; return (IMPLTYPE) this; } @Override public IMPLTYPE setValidator(UIValidator validator) { this.validator = validator; return (IMPLTYPE) this; } @Override public UIValidator getValidator() { return this.validator; } @Override public void validate(UIValidationContext validator) { String msg = InputComponents.validateRequired(this); if (msg != null && !msg.isEmpty()) { validator.addValidationError(this, msg); } if (this.validator != null) { this.validator.validate(validator); } } }
More meaningful variable name
ui/impl/src/main/java/org/jboss/forge/addon/ui/impl/AbstractInputComponent.java
More meaningful variable name
<ide><path>i/impl/src/main/java/org/jboss/forge/addon/ui/impl/AbstractInputComponent.java <ide> } <ide> <ide> @Override <del> public void validate(UIValidationContext validator) <add> public void validate(UIValidationContext context) <ide> { <ide> String msg = InputComponents.validateRequired(this); <ide> if (msg != null && !msg.isEmpty()) <ide> { <del> validator.addValidationError(this, msg); <add> context.addValidationError(this, msg); <ide> } <ide> if (this.validator != null) <ide> { <del> this.validator.validate(validator); <add> this.validator.validate(context); <ide> } <ide> } <ide> }
Java
apache-2.0
2742b300a82271db64bbf67ab1439f25bdc9f6d8
0
idea4bsd/idea4bsd,apixandru/intellij-community,da1z/intellij-community,signed/intellij-community,xfournet/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,signed/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,xfournet/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,fitermay/intellij-community,ibinti/intellij-community,semonte/intellij-community,signed/intellij-community,allotria/intellij-community,ibinti/intellij-community,xfournet/intellij-community,apixandru/intellij-community,allotria/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,FHannes/intellij-community,semonte/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,semonte/intellij-community,da1z/intellij-community,fitermay/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,da1z/intellij-community,allotria/intellij-community,semonte/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fitermay/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,da1z/intellij-community,signed/intellij-community,semonte/intellij-community,signed/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,apixandru/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,signed/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,xfournet/intellij-community,da1z/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fitermay/intellij-community,xfournet/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,signed/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.editor.textarea; import javax.swing.*; import javax.swing.text.BadLocationException; /** * @author yole */ public class TextAreaDocument extends TextComponentDocument { private final JTextArea myTextArea; public TextAreaDocument(final JTextArea textComponent) { super(textComponent); myTextArea = textComponent; } @Override public int getLineCount() { return myTextArea.getLineCount(); } @Override public int getLineNumber(final int offset) { try { return myTextArea.getLineOfOffset(offset); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineStartOffset(final int line) { try { return myTextArea.getLineStartOffset(line); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineEndOffset(final int line) { try { return myTextArea.getLineEndOffset(line) - getLineSeparatorLength(line); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineSeparatorLength(final int line) { if (line == myTextArea.getLineCount()-1) { return 0; } try { int l = 0; String text = getText(); for (int pos = myTextArea.getLineEndOffset(line) - 1; pos >= myTextArea.getLineStartOffset(line); pos--) { if (text.charAt(pos) != '\r' && text.charAt(pos) != '\n') break; l++; } return l; } catch (BadLocationException e) { throw new RuntimeException(e); } } }
platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextAreaDocument.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.editor.textarea; import javax.swing.*; import javax.swing.text.BadLocationException; /** * @author yole */ public class TextAreaDocument extends TextComponentDocument { private final JTextArea myTextArea; public TextAreaDocument(final JTextArea textComponent) { super(textComponent); myTextArea = textComponent; } @Override public int getLineCount() { return myTextArea.getLineCount(); } @Override public int getLineNumber(final int offset) { try { return myTextArea.getLineOfOffset(offset); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineStartOffset(final int line) { try { return myTextArea.getLineStartOffset(line); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineEndOffset(final int line) { try { return myTextArea.getLineEndOffset(line) - getLineSeparatorLength(line); } catch (BadLocationException e) { throw new RuntimeException(e); } } @Override public int getLineSeparatorLength(final int line) { if (line == myTextArea.getLineCount()-1) { return 0; } try { int endOffset = myTextArea.getLineEndOffset(line) - 1; int startOffset = myTextArea.getLineStartOffset(line); int l = 0; String text = getText(); while(l < endOffset - startOffset && (text.charAt(endOffset - l) == '\r' || text.charAt(endOffset - l) == '\n')) { l++; } return l; } catch (BadLocationException e) { throw new RuntimeException(e); } } }
IDEA-160926 Backspace doesn't join empty lines in JTextArea
platform/platform-impl/src/com/intellij/openapi/editor/textarea/TextAreaDocument.java
IDEA-160926 Backspace doesn't join empty lines in JTextArea
<ide><path>latform/platform-impl/src/com/intellij/openapi/editor/textarea/TextAreaDocument.java <ide> return 0; <ide> } <ide> try { <del> int endOffset = myTextArea.getLineEndOffset(line) - 1; <del> int startOffset = myTextArea.getLineStartOffset(line); <ide> int l = 0; <ide> String text = getText(); <del> while(l < endOffset - startOffset && (text.charAt(endOffset - l) == '\r' || text.charAt(endOffset - l) == '\n')) { <add> for (int pos = myTextArea.getLineEndOffset(line) - 1; pos >= myTextArea.getLineStartOffset(line); pos--) { <add> if (text.charAt(pos) != '\r' && text.charAt(pos) != '\n') break; <ide> l++; <ide> } <ide> return l;
Java
lgpl-2.1
c4bc7eaea135bd2b290f1fbbbea42f420cf1c87b
0
RockManJoe64/swingx,RockManJoe64/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * Find panel to incorporate search capability into the users application. * The most intended usage is to adding this panel to the dialogs. * * * @author ?? * @author Jeanette Winzenburg */ public class JXFindPanel extends AbstractPatternPanel { public static final String FIND_NEXT_ACTION_COMMAND = "findNext"; public static final String FIND_PREVIOUS_ACTION_COMMAND = "findPrevious"; protected Searchable searchable; protected JCheckBox wrapCheck; protected JCheckBox backCheck; private boolean initialized; /* * Default constructor for the find panel. Constructs panel not targeted to * any component. */ public JXFindPanel() { this(null); } /* * Construct search panel targeted to specific <code>Searchable</code> component. * * @param searchible Component where search widget will try to locate and select * information using methods of the <code>Searchible</code> interface. */ public JXFindPanel(Searchable searchable) { setSearchable(searchable); initActions(); } /** * Sets the Searchable targeted of this find widget. * Triggers a search with null pattern to release the old * searchable, if any. * * @param searchable Component where search widget will try to locate and select * information using methods of the {@link Searchable Searchable} interface. */ public void setSearchable(Searchable searchable) { if ((this.searchable != null) && this.searchable.equals(searchable)) return; Searchable old = this.searchable; if (old != null) { old.search((Pattern) null); } this.searchable = searchable; getPatternModel().setFoundIndex(-1); firePropertyChange("searchable", old, this.searchable); } /** * Notifies this component that it now has a parent component. * When this method is invoked, the chain of parent components is * set up with <code>KeyboardAction</code> event listeners. */ public void addNotify() { init(); super.addNotify(); } /** * Initializes component and its listeners and models. */ protected void init() { if (initialized) return; initialized = true; initComponents(); build(); bind(); setName(getUIString(SEARCH_TITLE)); } //------------------ support synch the model <--> components /** * Configure and bind components to/from PatternModel. */ @Override protected void bind() { super.bind(); getActionContainerFactory().configureButton(wrapCheck, getAction(PatternModel.MATCH_WRAP_ACTION_COMMAND), null); getActionContainerFactory().configureButton(backCheck, getAction(PatternModel.MATCH_BACKWARDS_ACTION_COMMAND), null); } /** * called from listening to empty property of PatternModel. * * this implementation calls super and additionally synchs the * enabled state of FIND_NEXT_ACTION_COMMAND, FIND_PREVIOUS_ACTION_COMMAND * to !empty. */ @Override protected void refreshEmptyFromModel() { super.refreshEmptyFromModel(); boolean enabled = !getPatternModel().isEmpty(); getAction(FIND_NEXT_ACTION_COMMAND).setEnabled(enabled); getAction(FIND_PREVIOUS_ACTION_COMMAND).setEnabled(enabled); } //--------------------- action callbacks /** * Action callback for Find action. * Find next/previous match using current setting of direction flag. * */ public void match() { doFind(); } /** * Action callback for FindNext action. * Sets direction flag to forward and calls find. */ public void findNext() { getPatternModel().setBackwards(false); doFind(); } /** * Action callback for FindPrevious action. * Sets direction flag to previous and calls find. */ public void findPrevious() { getPatternModel().setBackwards(true); doFind(); } /** * Common standalone method to perform search. Used by the action callback methods * for Find/FindNext/FindPrevious actions. Finds next/previous match using current * setting of direction flag. Result is being reporred using showFoundMessage and * showNotFoundMessage methods respectively. * * @see #match * @see #findNext * @see #findPrevious */ protected void doFind() { if (searchable == null) return; int foundIndex = doSearch(); boolean notFound = (foundIndex == -1) && !getPatternModel().isEmpty(); if (notFound) { if (getPatternModel().isWrapping()) { notFound = doSearch() == -1; } } if (notFound) { showNotFoundMessage(); } else { showFoundMessage(); } } /** * Proforms search and returns index of the next match. * * @return Index of the next match in document. */ protected int doSearch() { int foundIndex = searchable.search(getPatternModel().getPattern(), getPatternModel().getFoundIndex(), getPatternModel().isBackwards()); getPatternModel().setFoundIndex(foundIndex); return getPatternModel().getFoundIndex(); // first try on #236-swingx - foundIndex wrong in backwards search. // re-think: autoIncrement in PatternModel? // return foundIndex; } /** * Report that suitable match is found. */ protected void showFoundMessage() { } /** * Report that no match is found. */ protected void showNotFoundMessage() { JOptionPane.showMessageDialog(this, "Value not found"); } //-------------------------- initial /** * creates and registers all "executable" actions. * Meaning: the actions bound to a callback method on this. */ @Override protected void initExecutables() { getActionMap().put(FIND_NEXT_ACTION_COMMAND, createBoundAction(FIND_NEXT_ACTION_COMMAND, "findNext")); getActionMap().put(FIND_PREVIOUS_ACTION_COMMAND, createBoundAction(FIND_PREVIOUS_ACTION_COMMAND, "findPrevious")); super.initExecutables(); } //----------------------------- init ui /** * Create and initialize components. */ protected void initComponents() { super.initComponents(); wrapCheck = new JCheckBox(); backCheck = new JCheckBox(); } /** * Compose and layout all the subcomponents. */ protected void build() { Box lBox = new Box(BoxLayout.LINE_AXIS); lBox.add(searchLabel); lBox.add(new JLabel(":")); lBox.add(new JLabel(" ")); lBox.setAlignmentY(Component.TOP_ALIGNMENT); Box rBox = new Box(BoxLayout.PAGE_AXIS); rBox.add(searchField); rBox.add(matchCheck); rBox.add(wrapCheck); rBox.add(backCheck); rBox.setAlignmentY(Component.TOP_ALIGNMENT); setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); add(lBox); add(rBox); } }
src/java/org/jdesktop/swingx/JXFindPanel.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx; import java.awt.Component; import java.util.regex.Pattern; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * Find panel to incorporate search capability into the users application. * The most intended usage is to adding this panel to the dialogs. * * * @author ?? * @author Jeanette Winzenburg */ public class JXFindPanel extends AbstractPatternPanel { public static final String FIND_NEXT_ACTION_COMMAND = "findNext"; public static final String FIND_PREVIOUS_ACTION_COMMAND = "findPrevious"; protected Searchable searchable; protected JCheckBox wrapCheck; protected JCheckBox backCheck; private boolean initialized; /* * Default constructor for the find panel. Constructs panel not targeted to * any component. */ public JXFindPanel() { this(null); } /* * Construct search panel targeted to specific <code>Searchable</code> component. * * @param searchible Component where search widget will try to locate and select * information using methods of the <code>Searchible</code> interface. */ public JXFindPanel(Searchable searchable) { setSearchable(searchable); initActions(); } /** * Sets the Searchable targeted of this find widget. * Triggers a search with null pattern to release the old * searchable, if any. * * @param searchable Component where search widget will try to locate and select * information using methods of the {@link Searchable Searchable} interface. */ public void setSearchable(Searchable searchable) { if ((this.searchable != null) && this.searchable.equals(searchable)) return; Searchable old = this.searchable; if (old != null) { old.search((Pattern) null); } this.searchable = searchable; getPatternModel().setFoundIndex(-1); firePropertyChange("searchable", old, this.searchable); } /** * Notifies this component that it now has a parent component. * When this method is invoked, the chain of parent components is * set up with <code>KeyboardAction</code> event listeners. */ public void addNotify() { init(); super.addNotify(); } /** * Initializes component and its listeners and models. */ protected void init() { if (initialized) return; initialized = true; initComponents(); build(); bind(); setName(getUIString(SEARCH_TITLE)); } //------------------ support synch the model <--> components /** * Configure and bind components to/from PatternModel. */ @Override protected void bind() { super.bind(); getActionContainerFactory().configureButton(wrapCheck, getAction(PatternModel.MATCH_WRAP_ACTION_COMMAND), null); getActionContainerFactory().configureButton(backCheck, getAction(PatternModel.MATCH_BACKWARDS_ACTION_COMMAND), null); } /** * called from listening to empty property of PatternModel. * * this implementation calls super and additionally synchs the * enabled state of FIND_NEXT_ACTION_COMMAND, FIND_PREVIOUS_ACTION_COMMAND * to !empty. */ @Override protected void refreshEmptyFromModel() { super.refreshEmptyFromModel(); boolean enabled = !getPatternModel().isEmpty(); getAction(FIND_NEXT_ACTION_COMMAND).setEnabled(enabled); getAction(FIND_PREVIOUS_ACTION_COMMAND).setEnabled(enabled); } //--------------------- action callbacks /** * Action callback for Find action. * Find next/previous match using current setting of direction flag. * */ public void match() { doFind(); } /** * Action callback for FindNext action. * Sets direction flag to forward and calls find. */ public void findNext() { getPatternModel().setBackwards(false); doFind(); } /** * Action callback for FindPrevious action. * Sets direction flag to previous and calls find. */ public void findPrevious() { getPatternModel().setBackwards(true); doFind(); } /** * Common standalone method to perform search. Used by the action callback methods * for Find/FindNext/FindPrevious actions. Finds next/previous match using current * setting of direction flag. Result is being reporred using showFoundMessage and * showNotFoundMessage methods respectively. * * @see #match * @see #findNext * @see #findPrevious */ protected void doFind() { if (searchable == null) return; int foundIndex = doSearch(); boolean notFound = (foundIndex == -1) && !getPatternModel().isEmpty(); if (notFound) { if (getPatternModel().isWrapping()) { notFound = doSearch() == -1; } } if (notFound) { showNotFoundMessage(); } else { showFoundMessage(); } } /** * Proforms search and returns index of the next match. * * @return Index of the next match in document. */ protected int doSearch() { int foundIndex = searchable.search(getPatternModel().getPattern(), getPatternModel().getFoundIndex(), getPatternModel().isBackwards()); getPatternModel().setFoundIndex(foundIndex); return getPatternModel().getFoundIndex(); } /** * Report that suitable match is found. */ protected void showFoundMessage() { } /** * Report that no match is found. */ protected void showNotFoundMessage() { JOptionPane.showMessageDialog(this, "Value not found"); } //-------------------------- initial /** * creates and registers all "executable" actions. * Meaning: the actions bound to a callback method on this. */ @Override protected void initExecutables() { getActionMap().put(FIND_NEXT_ACTION_COMMAND, createBoundAction(FIND_NEXT_ACTION_COMMAND, "findNext")); getActionMap().put(FIND_PREVIOUS_ACTION_COMMAND, createBoundAction(FIND_PREVIOUS_ACTION_COMMAND, "findPrevious")); super.initExecutables(); } //----------------------------- init ui /** * Create and initialize components. */ protected void initComponents() { super.initComponents(); wrapCheck = new JCheckBox(); backCheck = new JCheckBox(); } /** * Compose and layout all the subcomponents. */ protected void build() { Box lBox = new Box(BoxLayout.LINE_AXIS); lBox.add(searchLabel); lBox.add(new JLabel(":")); lBox.add(new JLabel(" ")); lBox.setAlignmentY(Component.TOP_ALIGNMENT); Box rBox = new Box(BoxLayout.PAGE_AXIS); rBox.add(searchField); rBox.add(matchCheck); rBox.add(wrapCheck); rBox.add(backCheck); rBox.setAlignmentY(Component.TOP_ALIGNMENT); setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); add(lBox); add(rBox); } }
Issue number: #236-swingx added comment to JXFindPanel (part of the reason)
src/java/org/jdesktop/swingx/JXFindPanel.java
Issue number: #236-swingx
<ide><path>rc/java/org/jdesktop/swingx/JXFindPanel.java <ide> getPatternModel().getFoundIndex(), getPatternModel().isBackwards()); <ide> getPatternModel().setFoundIndex(foundIndex); <ide> return getPatternModel().getFoundIndex(); <add>// first try on #236-swingx - foundIndex wrong in backwards search. <add>// re-think: autoIncrement in PatternModel? <add>// return foundIndex; <ide> } <ide> <ide> /**
Java
agpl-3.0
ca4f2ccb428a5562240e143239c8336f7dacce21
0
servernge/holocore,servernge/holocore,servernge/holocore
package services.objects; import intents.GalacticPacketIntent; import intents.swgobject_events.SWGObjectEventIntent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import main.ProjectSWG; import network.packets.swg.zone.HeartBeatMessage; import network.packets.swg.zone.ParametersMessage; import network.packets.swg.zone.UpdatePvpStatusMessage; import network.packets.swg.zone.chat.ChatOnConnectAvatar; import network.packets.swg.zone.chat.VoiceChatStatus; import network.packets.swg.zone.insertion.ChatServerStatus; import network.packets.swg.zone.insertion.CmdStartScene; import network.packets.swg.zone.insertion.SelectCharacter; import network.packets.swg.zone.object_controller.DataTransform; import network.packets.swg.zone.object_controller.ObjectController; import resources.Location; import resources.Race; import resources.Terrain; import resources.client_info.ClientFactory; import resources.client_info.visitors.ObjectData; import resources.client_info.visitors.SlotArrangementData; import resources.client_info.visitors.SlotDescriptorData; import resources.control.Intent; import resources.control.Manager; import resources.objects.SWGObject; import resources.objects.creature.CreatureObject; import resources.objects.intangible.IntangibleObject; import resources.objects.player.PlayerObject; import resources.objects.quadtree.QuadTree; import resources.objects.tangible.TangibleObject; import resources.objects.waypoint.WaypointObject; import resources.objects.weapon.WeaponObject; import resources.player.Player; import resources.server_info.ObjectDatabase; import resources.server_info.ObjectDatabase.Traverser; import services.player.PlayerManager; public class ObjectManager extends Manager { private static final double AWARE_RANGE = 200; private ClientFactory clientFac; private ObjectDatabase<SWGObject> objects; private Map <Terrain, QuadTree <SWGObject>> quadTree; private long maxObjectId; public ObjectManager() { objects = new ObjectDatabase<SWGObject>("odb/objects.db"); quadTree = new HashMap<Terrain, QuadTree<SWGObject>>(); maxObjectId = 1; } @Override public boolean initialize() { registerForIntent(SWGObjectEventIntent.TYPE); registerForIntent(GalacticPacketIntent.TYPE); for (Terrain t : Terrain.values()) { quadTree.put(t, new QuadTree<SWGObject>(-5000, -5000, 5000, 5000)); } objects.loadToCache(); long startLoad = System.nanoTime(); System.out.println("ObjectManager: Loading " + objects.size() + " objects from ObjectDatabase..."); objects.traverse(new Traverser<SWGObject>() { @Override public void process(SWGObject obj) { obj.setOwner(null); Location l = obj.getLocation(); if (l.getTerrain() != null) { QuadTree <SWGObject> tree = quadTree.get(l.getTerrain()); if (tree != null) { tree.put(l.getX(), l.getZ(), obj); } else { System.err.println("ObjectManager: Unable to load QuadTree for object " + obj.getObjectId() + " and terrain: " + l.getTerrain()); } } if (obj.getObjectId() >= maxObjectId) { maxObjectId = obj.getObjectId() + 1; } } }); double loadTime = (System.nanoTime() - startLoad) / 1E6; System.out.printf("ObjectManager: Finished loading %d objects. Time: %fms%n", objects.size(), loadTime); clientFac = new ClientFactory(); return super.initialize(); } @Override public boolean terminate() { objects.traverse(new Traverser<SWGObject>() { @Override public void process(SWGObject obj) { obj.setOwner(null); } }); objects.save(); return super.terminate(); } @Override public void onIntentReceived(Intent i) { if (i instanceof GalacticPacketIntent) { GalacticPacketIntent gpi = (GalacticPacketIntent) i; if (gpi.getPacket() instanceof SelectCharacter) { zoneInCharacter(gpi.getPlayerManager(), gpi.getNetworkId(), ((SelectCharacter)gpi.getPacket()).getCharacterId()); } else if (gpi.getPacket() instanceof ObjectController) { ObjectController controller = (ObjectController) gpi.getPacket(); if (controller.getControllerData() instanceof DataTransform) { DataTransform trans = (DataTransform) controller.getControllerData(); SWGObject obj = getObject(controller.getObjectId()); Location oldLocation = obj.getLocation(); Location newLocation = trans.getLocation(); newLocation.setTerrain(oldLocation.getTerrain()); moveObject(trans, obj, oldLocation, newLocation); } } } } public SWGObject getObject(long objectId) { synchronized (objects) { return objects.get(objectId); } } public SWGObject createObject(String template) { return createObject(template, null); } public SWGObject createObject(String template, Location l) { synchronized (objects) { long objectId = getNextObjectId(); SWGObject obj = createObjectFromTemplate(objectId, template); if (obj == null) { System.err.println("ObjectManager: Unable to create object with template " + template); return null; } addObjectAttributes(obj, template); obj.setTemplate(template); obj.setLocation(l); // addToQuadtree(obj, l); moveObject(null, obj, null, l); objects.put(objectId, obj); return obj; } } private void moveObject(DataTransform transform, SWGObject obj, Location oldLocation, Location newLocation) { if (oldLocation != null && oldLocation.getTerrain() != null) { // Remove from QuadTree double x = oldLocation.getX(); double y = oldLocation.getZ(); quadTree.get(oldLocation.getTerrain()).remove(x, y, obj); } if (newLocation != null && newLocation.getTerrain() != null) { // Add to QuadTree, update awareness obj.setLocation(newLocation); updateAwarenessForObject(obj); quadTree.get(newLocation.getTerrain()).put(newLocation.getX(), newLocation.getZ(), obj); } if (transform != null) obj.sendDataTransforms(transform); } private void updateAwarenessForObject(SWGObject obj) { Location location = obj.getLocation(); List <Player> updatedAware = new ArrayList<Player>(); double x = location.getX(); double y = location.getZ(); QuadTree<SWGObject> tree = quadTree.get(location.getTerrain()); for (SWGObject inRange : tree.getWithinRange(x, y, AWARE_RANGE)) { if (inRange.getOwner() != null && inRange.getObjectId() != obj.getObjectId()) { updatedAware.add(inRange.getOwner()); } } obj.updateAwareness(updatedAware); } private void addObjectAttributes(SWGObject obj, String template) { ObjectData attributes = (ObjectData) clientFac.getInfoFromFile(ClientFactory.formatToSharedFile(template)); obj.setStf((String) attributes.getAttribute(ObjectData.OBJ_STF)); obj.setDetailStf((String) attributes.getAttribute(ObjectData.DETAIL_STF)); obj.setVolume((Integer) attributes.getAttribute(ObjectData.VOLUME_LIMIT)); addSlotsToObject(obj, attributes); } private void addSlotsToObject(SWGObject obj, ObjectData attributes) { if ((String) attributes.getAttribute(ObjectData.SLOT_DESCRIPTOR) != null) { // These are the slots that the object *HAS* SlotDescriptorData descriptor = (SlotDescriptorData) clientFac.getInfoFromFile((String) attributes.getAttribute(ObjectData.SLOT_DESCRIPTOR)); for (String slotName : descriptor.getSlots()) { obj.addObjectSlot(slotName, null); } } if ((String) attributes.getAttribute(ObjectData.ARRANGEMENT_FILE) != null) { // This is what slots the object *USES* SlotArrangementData arrangementData = (SlotArrangementData) clientFac.getInfoFromFile((String) attributes.getAttribute(ObjectData.ARRANGEMENT_FILE)); obj.setArrangment(arrangementData.getArrangement()); } } private void zoneInCharacter(PlayerManager playerManager, long netId, long characterId) { Player player = playerManager.getPlayerFromNetworkId(netId); if (player != null) { verifyPlayerObjectsSet(player, characterId); long objId = player.getCreatureObject().getObjectId(); Race race = ((CreatureObject) player.getCreatureObject()).getRace(); Location l = player.getCreatureObject().getLocation(); long time = (long)(ProjectSWG.getCoreTime()/1E3); sendPacket(player, new HeartBeatMessage()); sendPacket(player, new ChatServerStatus(true)); sendPacket(player, new VoiceChatStatus()); sendPacket(player, new ParametersMessage()); sendPacket(player, new ChatOnConnectAvatar()); sendPacket(player, new CmdStartScene(false, objId, race, l, time)); // player.getCreatureObject().createObject(player); CreatureObject creature = (CreatureObject) player.getCreatureObject(); player.sendPacket(new UpdatePvpStatusMessage(creature.getPvpType(), creature.getPvpFactionId(), creature.getObjectId())); creature.createObject(player); creature.clearAware(); moveObject(null, creature, creature.getLocation(), creature.getLocation()); updateAwarenessForObject(creature); } } private void verifyPlayerObjectsSet(Player player, long characterId) { if (player.getCreatureObject() != null && player.getPlayerObject() != null) return; SWGObject creature = objects.get(characterId); if (creature == null) { System.err.println("ObjectManager: Failed to start zone - CreatureObject could not be fetched from database"); throw new NullPointerException("CreatureObject for ID: " + characterId + " cannot be null!"); } player.setCreatureObject(creature); // CreatureObject contains the player object! creature.setOwner(player); if (player.getPlayerObject() == null) { System.err.println("FATAL: " + player.getUsername() + "'s CreatureObject has a null ghost!"); } } private long getNextObjectId() { synchronized (objects) { return maxObjectId++; } } private String getFirstTemplatePart(String template) { int ind = template.indexOf('/'); if (ind == -1) return ""; return template.substring(0, ind); } private SWGObject createObjectFromTemplate(long objectId, String template) { if (!template.startsWith("object/")) return null; if (!template.endsWith(".iff")) return null; template = template.substring(7, template.length()-7-4); switch (getFirstTemplatePart(template)) { case "creature": return createCreatureObject(objectId, template); case "player": return createPlayerObject(objectId, template); case "tangible": return createTangibleObject(objectId, template); case "intangible": return createIntangibleObject(objectId, template); case "waypoint": return createWaypointObject(objectId, template); case "weapon": return createWeaponObject(objectId, template); case "building": break; case "cell": break; } return null; } private CreatureObject createCreatureObject(long objectId, String template) { return new CreatureObject(objectId); } private PlayerObject createPlayerObject(long objectId, String template) { return new PlayerObject(objectId); } private TangibleObject createTangibleObject(long objectId, String template) { return new TangibleObject(objectId); } private IntangibleObject createIntangibleObject(long objectId, String template) { return new IntangibleObject(objectId); } private WaypointObject createWaypointObject(long objectId, String template) { return new WaypointObject(objectId); } private WeaponObject createWeaponObject(long objectId, String template) { return new WeaponObject(objectId); } public SWGObject getObjectById(long id) { return objects.get(id); } }
src/services/objects/ObjectManager.java
package services.objects; import intents.GalacticPacketIntent; import intents.swgobject_events.SWGObjectEventIntent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import main.ProjectSWG; import network.packets.swg.zone.HeartBeatMessage; import network.packets.swg.zone.ParametersMessage; import network.packets.swg.zone.UpdatePvpStatusMessage; import network.packets.swg.zone.chat.ChatOnConnectAvatar; import network.packets.swg.zone.chat.VoiceChatStatus; import network.packets.swg.zone.insertion.ChatServerStatus; import network.packets.swg.zone.insertion.CmdStartScene; import network.packets.swg.zone.insertion.SelectCharacter; import network.packets.swg.zone.object_controller.DataTransform; import network.packets.swg.zone.object_controller.ObjectController; import resources.Location; import resources.Race; import resources.Terrain; import resources.client_info.ClientFactory; import resources.client_info.visitors.ObjectData; import resources.client_info.visitors.SlotArrangementData; import resources.client_info.visitors.SlotDescriptorData; import resources.control.Intent; import resources.control.Manager; import resources.objects.SWGObject; import resources.objects.creature.CreatureObject; import resources.objects.intangible.IntangibleObject; import resources.objects.player.PlayerObject; import resources.objects.quadtree.QuadTree; import resources.objects.tangible.TangibleObject; import resources.objects.waypoint.WaypointObject; import resources.objects.weapon.WeaponObject; import resources.player.Player; import resources.server_info.ObjectDatabase; import resources.server_info.ObjectDatabase.Traverser; import services.player.PlayerManager; public class ObjectManager extends Manager { private static final double AWARE_RANGE = 200; private ClientFactory clientFac; private ObjectDatabase<SWGObject> objects; private Map <Terrain, QuadTree <SWGObject>> quadTree; private long maxObjectId; public ObjectManager() { objects = new ObjectDatabase<SWGObject>("odb/objects.db"); quadTree = new HashMap<Terrain, QuadTree<SWGObject>>(); maxObjectId = 1; } @Override public boolean initialize() { registerForIntent(SWGObjectEventIntent.TYPE); registerForIntent(GalacticPacketIntent.TYPE); for (Terrain t : Terrain.values()) { quadTree.put(t, new QuadTree<SWGObject>(-5000, -5000, 5000, 5000)); } objects.loadToCache(); long startLoad = System.nanoTime(); System.out.println("ObjectManager: Loading " + objects.size() + " objects from ObjectDatabase..."); objects.traverse(new Traverser<SWGObject>() { @Override public void process(SWGObject obj) { obj.setOwner(null); Location l = obj.getLocation(); if (l.getTerrain() != null) { QuadTree <SWGObject> tree = quadTree.get(l.getTerrain()); if (tree != null) { tree.put(l.getX(), l.getZ(), obj); } else { System.err.println("ObjectManager: Unable to load QuadTree for object " + obj.getObjectId() + " and terrain: " + l.getTerrain()); } } if (obj.getObjectId() >= maxObjectId) { maxObjectId = obj.getObjectId() + 1; } } }); double loadTime = (System.nanoTime() - startLoad) / 1E6; System.out.printf("ObjectManager: Finished loading %d objects. Time: %fms%n", objects.size(), loadTime); clientFac = new ClientFactory(); return super.initialize(); } @Override public boolean terminate() { objects.traverse(new Traverser<SWGObject>() { @Override public void process(SWGObject obj) { obj.setOwner(null); } }); objects.save(); return super.terminate(); } @Override public void onIntentReceived(Intent i) { if (i instanceof GalacticPacketIntent) { GalacticPacketIntent gpi = (GalacticPacketIntent) i; if (gpi.getPacket() instanceof SelectCharacter) { zoneInCharacter(gpi.getPlayerManager(), gpi.getNetworkId(), ((SelectCharacter)gpi.getPacket()).getCharacterId()); } else if (gpi.getPacket() instanceof ObjectController) { ObjectController controller = (ObjectController) gpi.getPacket(); if (controller.getControllerData() instanceof DataTransform) { DataTransform trans = (DataTransform) controller.getControllerData(); SWGObject obj = getObject(controller.getObjectId()); Location oldLocation = obj.getLocation(); Location newLocation = trans.getLocation(); newLocation.setTerrain(oldLocation.getTerrain()); moveObject(obj, oldLocation, newLocation); } } } } public SWGObject getObject(long objectId) { synchronized (objects) { return objects.get(objectId); } } public SWGObject createObject(String template) { return createObject(template, null); } public SWGObject createObject(String template, Location l) { synchronized (objects) { long objectId = getNextObjectId(); SWGObject obj = createObjectFromTemplate(objectId, template); if (obj == null) { System.err.println("ObjectManager: Unable to create object with template " + template); return null; } addObjectAttributes(obj, template); obj.setTemplate(template); obj.setLocation(l); // addToQuadtree(obj, l); moveObject(obj, null, l); objects.put(objectId, obj); return obj; } } private void moveObject(SWGObject obj, Location oldLocation, Location newLocation) { if (oldLocation != null && oldLocation.getTerrain() != null) { // Remove from QuadTree double x = oldLocation.getX(); double y = oldLocation.getZ(); quadTree.get(oldLocation.getTerrain()).remove(x, y, obj); } if (newLocation != null && newLocation.getTerrain() != null) { // Add to QuadTree, update awareness obj.setLocation(newLocation); updateAwarenessForObject(obj); quadTree.get(newLocation.getTerrain()).put(newLocation.getX(), newLocation.getZ(), obj); } } private void updateAwarenessForObject(SWGObject obj) { Location location = obj.getLocation(); List <Player> updatedAware = new ArrayList<Player>(); double x = location.getX(); double y = location.getZ(); QuadTree<SWGObject> tree = quadTree.get(location.getTerrain()); for (SWGObject inRange : tree.getWithinRange(x, y, AWARE_RANGE)) { if (inRange.getOwner() != null && inRange.getObjectId() != obj.getObjectId()) { updatedAware.add(inRange.getOwner()); } } obj.updateAwareness(updatedAware); obj.sendDataTransforms(); } private void addObjectAttributes(SWGObject obj, String template) { ObjectData attributes = (ObjectData) clientFac.getInfoFromFile(ClientFactory.formatToSharedFile(template)); obj.setStf((String) attributes.getAttribute(ObjectData.OBJ_STF)); obj.setDetailStf((String) attributes.getAttribute(ObjectData.DETAIL_STF)); obj.setVolume((Integer) attributes.getAttribute(ObjectData.VOLUME_LIMIT)); addSlotsToObject(obj, attributes); } private void addSlotsToObject(SWGObject obj, ObjectData attributes) { if ((String) attributes.getAttribute(ObjectData.SLOT_DESCRIPTOR) != null) { // These are the slots that the object *HAS* SlotDescriptorData descriptor = (SlotDescriptorData) clientFac.getInfoFromFile((String) attributes.getAttribute(ObjectData.SLOT_DESCRIPTOR)); for (String slotName : descriptor.getSlots()) { obj.addObjectSlot(slotName, null); } } if ((String) attributes.getAttribute(ObjectData.ARRANGEMENT_FILE) != null) { // This is what slots the object *USES* SlotArrangementData arrangementData = (SlotArrangementData) clientFac.getInfoFromFile((String) attributes.getAttribute(ObjectData.ARRANGEMENT_FILE)); obj.setArrangment(arrangementData.getArrangement()); } } private void zoneInCharacter(PlayerManager playerManager, long netId, long characterId) { Player player = playerManager.getPlayerFromNetworkId(netId); if (player != null) { verifyPlayerObjectsSet(player, characterId); long objId = player.getCreatureObject().getObjectId(); Race race = ((CreatureObject) player.getCreatureObject()).getRace(); Location l = player.getCreatureObject().getLocation(); long time = (long)(ProjectSWG.getCoreTime()/1E3); sendPacket(player, new HeartBeatMessage()); sendPacket(player, new ChatServerStatus(true)); sendPacket(player, new VoiceChatStatus()); sendPacket(player, new ParametersMessage()); sendPacket(player, new ChatOnConnectAvatar()); sendPacket(player, new CmdStartScene(false, objId, race, l, time)); // player.getCreatureObject().createObject(player); CreatureObject creature = (CreatureObject) player.getCreatureObject(); player.sendPacket(new UpdatePvpStatusMessage(creature.getPvpType(), creature.getPvpFactionId(), creature.getObjectId())); creature.createObject(player); creature.clearAware(); moveObject(creature, creature.getLocation(), creature.getLocation()); updateAwarenessForObject(creature); } } private void verifyPlayerObjectsSet(Player player, long characterId) { if (player.getCreatureObject() != null && player.getPlayerObject() != null) return; SWGObject creature = objects.get(characterId); if (creature == null) { System.err.println("ObjectManager: Failed to start zone - CreatureObject could not be fetched from database"); throw new NullPointerException("CreatureObject for ID: " + characterId + " cannot be null!"); } player.setCreatureObject(creature); // CreatureObject contains the player object! creature.setOwner(player); if (player.getPlayerObject() == null) { System.err.println("FATAL: " + player.getUsername() + "'s CreatureObject has a null ghost!"); } } private long getNextObjectId() { synchronized (objects) { return maxObjectId++; } } private String getFirstTemplatePart(String template) { int ind = template.indexOf('/'); if (ind == -1) return ""; return template.substring(0, ind); } private SWGObject createObjectFromTemplate(long objectId, String template) { if (!template.startsWith("object/")) return null; if (!template.endsWith(".iff")) return null; template = template.substring(7, template.length()-7-4); switch (getFirstTemplatePart(template)) { case "creature": return createCreatureObject(objectId, template); case "player": return createPlayerObject(objectId, template); case "tangible": return createTangibleObject(objectId, template); case "intangible": return createIntangibleObject(objectId, template); case "waypoint": return createWaypointObject(objectId, template); case "weapon": return createWeaponObject(objectId, template); case "building": break; case "cell": break; } return null; } private CreatureObject createCreatureObject(long objectId, String template) { return new CreatureObject(objectId); } private PlayerObject createPlayerObject(long objectId, String template) { return new PlayerObject(objectId); } private TangibleObject createTangibleObject(long objectId, String template) { return new TangibleObject(objectId); } private IntangibleObject createIntangibleObject(long objectId, String template) { return new IntangibleObject(objectId); } private WaypointObject createWaypointObject(long objectId, String template) { return new WaypointObject(objectId); } private WeaponObject createWeaponObject(long objectId, String template) { return new WeaponObject(objectId); } public SWGObject getObjectById(long id) { return objects.get(id); } }
Completely fixed awareness by adding UpdateTransform
src/services/objects/ObjectManager.java
Completely fixed awareness by adding UpdateTransform
<ide><path>rc/services/objects/ObjectManager.java <ide> Location oldLocation = obj.getLocation(); <ide> Location newLocation = trans.getLocation(); <ide> newLocation.setTerrain(oldLocation.getTerrain()); <del> moveObject(obj, oldLocation, newLocation); <add> moveObject(trans, obj, oldLocation, newLocation); <ide> } <ide> } <ide> } <ide> obj.setTemplate(template); <ide> obj.setLocation(l); <ide> // addToQuadtree(obj, l); <del> moveObject(obj, null, l); <add> moveObject(null, obj, null, l); <ide> objects.put(objectId, obj); <ide> return obj; <ide> } <ide> } <ide> <del> private void moveObject(SWGObject obj, Location oldLocation, Location newLocation) { <add> private void moveObject(DataTransform transform, SWGObject obj, Location oldLocation, Location newLocation) { <ide> if (oldLocation != null && oldLocation.getTerrain() != null) { // Remove from QuadTree <ide> double x = oldLocation.getX(); <ide> double y = oldLocation.getZ(); <ide> updateAwarenessForObject(obj); <ide> quadTree.get(newLocation.getTerrain()).put(newLocation.getX(), newLocation.getZ(), obj); <ide> } <add> if (transform != null) <add> obj.sendDataTransforms(transform); <ide> } <ide> <ide> private void updateAwarenessForObject(SWGObject obj) { <ide> } <ide> } <ide> obj.updateAwareness(updatedAware); <del> obj.sendDataTransforms(); <ide> } <ide> <ide> private void addObjectAttributes(SWGObject obj, String template) { <ide> player.sendPacket(new UpdatePvpStatusMessage(creature.getPvpType(), creature.getPvpFactionId(), creature.getObjectId())); <ide> creature.createObject(player); <ide> creature.clearAware(); <del> moveObject(creature, creature.getLocation(), creature.getLocation()); <add> moveObject(null, creature, creature.getLocation(), creature.getLocation()); <ide> updateAwarenessForObject(creature); <ide> } <ide> }
Java
apache-2.0
9eb3f22c9c1daa72d5c0892cdd049a6fa51c4317
0
mglukhikh/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,vladmm/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,izonder/intellij-community,samthor/intellij-community,ryano144/intellij-community,retomerz/intellij-community,supersven/intellij-community,amith01994/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,kdwink/intellij-community,robovm/robovm-studio,robovm/robovm-studio,samthor/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,slisson/intellij-community,supersven/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,ernestp/consulo,FHannes/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,amith01994/intellij-community,allotria/intellij-community,da1z/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,hurricup/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,signed/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,orekyuu/intellij-community,signed/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,ernestp/consulo,semonte/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,caot/intellij-community,izonder/intellij-community,samthor/intellij-community,robovm/robovm-studio,diorcety/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,dslomov/intellij-community,slisson/intellij-community,fitermay/intellij-community,izonder/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,consulo/consulo,TangHao1987/intellij-community,akosyakov/intellij-community,da1z/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,allotria/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,semonte/intellij-community,jagguli/intellij-community,clumsy/intellij-community,samthor/intellij-community,clumsy/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,slisson/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,da1z/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,asedunov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,apixandru/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,kool79/intellij-community,apixandru/intellij-community,ernestp/consulo,blademainer/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ahb0327/intellij-community,samthor/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,allotria/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,kool79/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,slisson/intellij-community,fnouama/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,wreckJ/intellij-community,izonder/intellij-community,amith01994/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,nicolargo/intellij-community,samthor/intellij-community,consulo/consulo,kdwink/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,caot/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,supersven/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,fitermay/intellij-community,asedunov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,allotria/intellij-community,allotria/intellij-community,dslomov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,kool79/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,diorcety/intellij-community,signed/intellij-community,semonte/intellij-community,kdwink/intellij-community,amith01994/intellij-community,kool79/intellij-community,ryano144/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,consulo/consulo,apixandru/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,samthor/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,xfournet/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,caot/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,holmes/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,holmes/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ernestp/consulo,dslomov/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,clumsy/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,caot/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,diorcety/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ernestp/consulo,wreckJ/intellij-community,nicolargo/intellij-community,signed/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,petteyg/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,asedunov/intellij-community,semonte/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,FHannes/intellij-community,apixandru/intellij-community,supersven/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,diorcety/intellij-community,fnouama/intellij-community,blademainer/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ibinti/intellij-community,FHannes/intellij-community,signed/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,kool79/intellij-community,blademainer/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,robovm/robovm-studio,kdwink/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,slisson/intellij-community,signed/intellij-community,slisson/intellij-community,allotria/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,dslomov/intellij-community,caot/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,semonte/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ernestp/consulo,idea4bsd/idea4bsd,ahb0327/intellij-community,Distrotech/intellij-community,izonder/intellij-community,signed/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,consulo/consulo,apixandru/intellij-community,holmes/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,jagguli/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,signed/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,robovm/robovm-studio,robovm/robovm-studio,retomerz/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,da1z/intellij-community,caot/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,consulo/consulo,suncycheng/intellij-community,kdwink/intellij-community,holmes/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,adedayo/intellij-community,supersven/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,fnouama/intellij-community,kool79/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,da1z/intellij-community,consulo/consulo,youdonghai/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,da1z/intellij-community,signed/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,signed/intellij-community,Distrotech/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,caot/intellij-community,retomerz/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,hurricup/intellij-community,samthor/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,signed/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,da1z/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,da1z/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,slisson/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,asedunov/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,izonder/intellij-community,apixandru/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,caot/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,amith01994/intellij-community,semonte/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,hurricup/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,xfournet/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,caot/intellij-community,semonte/intellij-community,da1z/intellij-community,amith01994/intellij-community,izonder/intellij-community,semonte/intellij-community,kool79/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,holmes/intellij-community,asedunov/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,izonder/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,retomerz/intellij-community,FHannes/intellij-community,supersven/intellij-community,allotria/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,dslomov/intellij-community
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.find.impl.livePreview; import com.intellij.find.FindManager; import com.intellij.find.FindModel; import com.intellij.find.FindResult; import com.intellij.find.FindUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.concurrency.FutureResult; import com.intellij.util.containers.HashSet; import com.intellij.util.containers.Stack; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.regex.PatternSyntaxException; public class SearchResults implements DocumentListener { public int getStamp() { return ++myStamp; } @Override public void beforeDocumentChange(DocumentEvent event) { myCursorPositions.clear(); } @Override public void documentChanged(DocumentEvent event) { } public enum Direction {UP, DOWN} private List<SearchResultsListener> myListeners = new ArrayList<SearchResultsListener>(); private @Nullable LiveOccurrence myCursor; private List<LiveOccurrence> myOccurrences = new ArrayList<LiveOccurrence>(); private Set<RangeMarker> myExcluded = new HashSet<RangeMarker>(); private Editor myEditor; private Project myProject; private FindModel myFindModel; private int myMatchesLimit = 100; private boolean myNotFoundState = false; private boolean myDisposed = false; private int myStamp = 0; private int myLastUpdatedStamp = -1; private Stack<Pair<FindModel, LiveOccurrence>> myCursorPositions = new Stack<Pair<FindModel, LiveOccurrence>>(); public SearchResults(Editor editor, Project project) { myEditor = editor; myProject = project; myEditor.getDocument().addDocumentListener(this); } public void setNotFoundState(boolean isForward) { myNotFoundState = true; FindModel findModel = new FindModel(); findModel.copyFrom(myFindModel); findModel.setForward(isForward); FindUtil.processNotFound(myEditor, findModel.getStringToFind(), findModel, getProject()); } public int getMatchesCount() { return myOccurrences.size(); } public boolean hasMatches() { return !getOccurrences().isEmpty(); } public FindModel getFindModel() { return myFindModel; } public boolean isExcluded(LiveOccurrence occurrence) { for (RangeMarker rangeMarker : myExcluded) { if (TextRange.areSegmentsEqual(rangeMarker, occurrence.getPrimaryRange())) { return true; } } return false; } public void exclude(LiveOccurrence occurrence) { boolean include = false; final TextRange r = occurrence.getPrimaryRange(); for (RangeMarker rangeMarker : myExcluded) { if (TextRange.areSegmentsEqual(rangeMarker, r)) { myExcluded.remove(rangeMarker); rangeMarker.dispose(); include = true; break; } } if (!include) { myExcluded.add(myEditor.getDocument().createRangeMarker(r.getStartOffset(), r.getEndOffset(), true)); } notifyChanged(); } public Set<RangeMarker> getExcluded() { return myExcluded; } public interface SearchResultsListener { void searchResultsUpdated(SearchResults sr); void editorChanged(SearchResults sr, Editor oldEditor); void cursorMoved(boolean toChangeSelection); } public void addListener(SearchResultsListener srl) { myListeners.add(srl); } public void removeListener(SearchResultsListener srl) { myListeners.remove(srl); } public int getMatchesLimit() { return myMatchesLimit; } public void setMatchesLimit(int matchesLimit) { myMatchesLimit = matchesLimit; } @Nullable public LiveOccurrence getCursor() { return myCursor; } public List<LiveOccurrence> getOccurrences() { return myOccurrences; } @Nullable public Project getProject() { return myProject; } public synchronized void setEditor(Editor editor) { Editor oldOne = myEditor; myEditor = editor; notifyEditorChanged(oldOne); } private void notifyEditorChanged(Editor oldOne) { for (SearchResultsListener listener : myListeners) { listener.editorChanged(this, oldOne); } } public synchronized Editor getEditor() { return myEditor; } private static void findResultsToOccurrences(ArrayList<FindResult> results, Collection<LiveOccurrence> occurrences) { for (FindResult r : results) { LiveOccurrence occurrence = new LiveOccurrence(); occurrence.setPrimaryRange(r); occurrences.add(occurrence); } } public void clear() { searchCompleted(new ArrayList<LiveOccurrence>(), getEditor(), null, false, null, getStamp()); } public void updateThreadSafe(final FindModel findModel, final boolean toChangeSelection, @Nullable final TextRange next, final int stamp) { if (myDisposed) return; final ArrayList<LiveOccurrence> occurrences = new ArrayList<LiveOccurrence>(); final Editor editor = getEditor(); final ArrayList<FindResult> results = new ArrayList<FindResult>(); if (findModel != null) { updatePreviousFindModel(findModel); final FutureResult<int[]> startsRef = new FutureResult<int[]>(); final FutureResult<int[]> endsRef = new FutureResult<int[]>(); getSelection(editor, startsRef, endsRef); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { int[] starts = new int[0]; int[] ends = new int[0]; try { starts = startsRef.get(); ends = endsRef.get(); } catch (InterruptedException ignore) { } catch (ExecutionException ignore) { } if (starts.length == 0 || findModel.isGlobal()) { findInRange(new TextRange(0, Integer.MAX_VALUE), editor, findModel, results); } else { for (int i = 0; i < starts.length; ++i) { findInRange(new TextRange(starts[i], ends[i]), editor, findModel, results); } } findResultsToOccurrences(results, occurrences); final Runnable searchCompletedRunnable = new Runnable() { @Override public void run() { searchCompleted(occurrences, editor, findModel, toChangeSelection, next, stamp); } }; if (!ApplicationManager.getApplication().isUnitTestMode()) { UIUtil.invokeLaterIfNeeded(searchCompletedRunnable); } else { searchCompletedRunnable.run(); } } }); } } private void updatePreviousFindModel(FindModel model) { FindModel prev = FindManager.getInstance(getProject()).getPreviousFindModel(); if (prev == null) { prev = new FindModel(); } if (!model.getStringToFind().isEmpty()) { prev.copyFrom(model); FindManager.getInstance(getProject()).setPreviousFindModel(prev); } } private static void getSelection(final Editor editor, final FutureResult<int[]> starts, final FutureResult<int[]> ends) { if (ApplicationManager.getApplication().isDispatchThread()) { SelectionModel selection = editor.getSelectionModel(); starts.set(selection.getBlockSelectionStarts()); ends.set(selection.getBlockSelectionEnds()); } else { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { SelectionModel selection = editor.getSelectionModel(); starts.set(selection.getBlockSelectionStarts()); ends.set(selection.getBlockSelectionEnds()); } }); } catch (InterruptedException ignore) { } catch (InvocationTargetException ignore) { } } } private void findInRange(TextRange r, Editor editor, FindModel findModel, ArrayList<FindResult> results) { VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); int offset = r.getStartOffset(); while (true) { FindManager findManager = FindManager.getInstance(getProject()); FindResult result; try { CharSequence bombedCharSequence = StringUtil.newBombedCharSequence(editor.getDocument().getCharsSequence(), 3000); result = findManager.findString(bombedCharSequence, offset, findModel, virtualFile); } catch(PatternSyntaxException e) { result = null; } catch (ProcessCanceledException e) { result = null; } if (result == null || !result.isStringFound()) break; int newOffset = result.getEndOffset(); if (offset == newOffset || result.getEndOffset() > r.getEndOffset()) break; offset = newOffset; results.add(result); } } public void dispose() { myDisposed = true; myEditor.getDocument().removeDocumentListener(this); } private void searchCompleted(List<LiveOccurrence> occurrences, Editor editor, @Nullable FindModel findModel, boolean toChangeSelection, @Nullable TextRange next, int stamp) { if (stamp < myLastUpdatedStamp){ return; } myLastUpdatedStamp = stamp; if (editor != getEditor() || myDisposed) { return; } myOccurrences = occurrences; final TextRange oldCursorRange = myCursor != null ? myCursor.getPrimaryRange() : null; Collections.sort(myOccurrences, new Comparator<LiveOccurrence>() { @Override public int compare(LiveOccurrence liveOccurrence, LiveOccurrence liveOccurrence1) { return liveOccurrence.getPrimaryRange().getStartOffset() - liveOccurrence1.getPrimaryRange().getStartOffset(); } }); myFindModel = findModel; updateCursor(oldCursorRange, next); updateExcluded(); notifyChanged(); if (oldCursorRange == null || myCursor == null || !myCursor.getPrimaryRange().equals(oldCursorRange)) { notifyCursorMoved(toChangeSelection); } } private void updateExcluded() { Set<RangeMarker> invalid = new HashSet<RangeMarker>(); for (RangeMarker marker : myExcluded) { if (!marker.isValid()) { invalid.add(marker); marker.dispose(); } } myExcluded.removeAll(invalid); } private void updateCursor(@Nullable TextRange oldCursorRange, @Nullable TextRange next) { boolean justReplaced = next != null; boolean toPush = true; if (justReplaced || (toPush = !repairCursorFromStack())) { if (justReplaced || !tryToRepairOldCursor(oldCursorRange)) { if (myFindModel != null) { if(oldCursorRange != null && !myFindModel.isGlobal()) { myCursor = firstOccurrenceAfterOffset(oldCursorRange.getEndOffset()); } else { if (justReplaced) { nextOccurrence(false, next, false, justReplaced); } else { LiveOccurrence afterCaret = oldCursorRange == null ? firstOccurrenceAtOrAfterCaret() : firstOccurrenceAfterCaret(); if (afterCaret != null) { myCursor = afterCaret; } else { myCursor = null; } } } } else { myCursor = null; } } } if (!justReplaced && myCursor == null && hasMatches()) { nextOccurrence(true, oldCursorRange, false, false); } if (toPush && myCursor != null){ push(); } } private boolean repairCursorFromStack() { if (myCursorPositions.size() >= 2) { final Pair<FindModel, LiveOccurrence> oldPosition = myCursorPositions.get(myCursorPositions.size() - 2); if (oldPosition.first.equals(myFindModel)) { LiveOccurrence newCursor; if ((newCursor = findOccurrenceEqualTo(oldPosition.second)) != null) { myCursorPositions.pop(); myCursor = newCursor; return true; } } } return false; } @Nullable private LiveOccurrence findOccurrenceEqualTo(LiveOccurrence occurrence) { for (LiveOccurrence liveOccurrence : myOccurrences) { if (liveOccurrence.getPrimaryRange().equals(occurrence.getPrimaryRange())) { return liveOccurrence; } } return null; } @Nullable private LiveOccurrence firstOccurrenceAtOrAfterCaret() { int offset = getEditor().getCaretModel().getOffset(); for (LiveOccurrence occurrence : myOccurrences) { if (offset <= occurrence.getPrimaryRange().getEndOffset() && offset >= occurrence.getPrimaryRange().getStartOffset()) { return occurrence; } } return firstOccurrenceAfterCaret(); } private void notifyChanged() { for (SearchResultsListener listener : myListeners) { listener.searchResultsUpdated(this); } } static boolean insideVisibleArea(Editor e, TextRange r) { Rectangle visibleArea = e.getScrollingModel().getVisibleArea(); Point point = e.logicalPositionToXY(e.offsetToLogicalPosition(r.getStartOffset())); return visibleArea.contains(point); } @Nullable private LiveOccurrence firstVisibleOccurrence() { int offset = Integer.MAX_VALUE; LiveOccurrence firstOccurrence = null; LiveOccurrence firstVisibleOccurrence = null; for (LiveOccurrence o : getOccurrences()) { if (insideVisibleArea(myEditor, o.getPrimaryRange())) { if (firstVisibleOccurrence == null || o.getPrimaryRange().getStartOffset() < firstVisibleOccurrence.getPrimaryRange().getStartOffset()) { firstVisibleOccurrence = o; } } if (o.getPrimaryRange().getStartOffset() < offset) { offset = o.getPrimaryRange().getStartOffset(); firstOccurrence = o; } } return firstVisibleOccurrence != null ? firstVisibleOccurrence : firstOccurrence; } @Nullable private LiveOccurrence firstOccurrenceBeforeCaret() { int offset = getEditor().getCaretModel().getOffset(); return firstOccurrenceBeforeOffset(offset); } @Nullable private LiveOccurrence firstOccurrenceBeforeOffset(int offset) { for (int i = getOccurrences().size()-1; i >= 0; --i) { if (getOccurrences().get(i).getPrimaryRange().getEndOffset() < offset) { return getOccurrences().get(i); } } return null; } @Nullable private LiveOccurrence firstOccurrenceAfterCaret() { int caret = myEditor.getCaretModel().getOffset(); return firstOccurrenceAfterOffset(caret); } @Nullable private LiveOccurrence firstOccurrenceAfterOffset(int offset) { LiveOccurrence afterCaret = null; for (LiveOccurrence occurrence : getOccurrences()) { if (occurrence.getPrimaryRange().getStartOffset() >= offset) { if (afterCaret == null || occurrence.getPrimaryRange().getStartOffset() < afterCaret.getPrimaryRange().getStartOffset() ) { afterCaret = occurrence; } } } return afterCaret; } private boolean tryToRepairOldCursor(@Nullable TextRange oldCursorRange) { if (oldCursorRange == null) return false; LiveOccurrence mayBeOldCursor = null; for (LiveOccurrence searchResult : getOccurrences()) { if (searchResult.getPrimaryRange().intersects(oldCursorRange)) { mayBeOldCursor = searchResult; } if (searchResult.getPrimaryRange().getStartOffset() == oldCursorRange.getStartOffset()) { break; } } if (mayBeOldCursor != null) { myCursor = mayBeOldCursor; return true; } return false; } @Nullable private LiveOccurrence prevOccurrence(TextRange range) { for (int i = getOccurrences().size() - 1; i >= 0; --i) { final LiveOccurrence occurrence = getOccurrences().get(i); if (occurrence.getPrimaryRange().getEndOffset() <= range.getStartOffset()) { return occurrence; } } return null; } @Nullable private LiveOccurrence nextOccurrence(TextRange range) { for (LiveOccurrence occurrence : getOccurrences()) { if (occurrence.getPrimaryRange().getStartOffset() >= range.getEndOffset()) { return occurrence; } } return null; } public void prevOccurrence() { LiveOccurrence next = null; if (myFindModel == null) return; boolean processFromTheBeginning = false; if (myNotFoundState) { myNotFoundState = false; processFromTheBeginning = true; } if (!myFindModel.isGlobal()) { if (myCursor != null) { next = prevOccurrence(myCursor.getPrimaryRange()); } } else { next = firstOccurrenceBeforeCaret(); } if (next == null) { if (processFromTheBeginning) { if (hasMatches()) { next = getOccurrences().get(getOccurrences().size()-1); } } else { setNotFoundState(false); } } moveCursorTo(next); push(); } private void push() { myCursorPositions.push(new Pair<FindModel, LiveOccurrence>(myFindModel, myCursor)); } public void nextOccurrence() { if (myFindModel == null) return; nextOccurrence(false, myCursor != null ? myCursor.getPrimaryRange() : null, true, false); push(); } private void nextOccurrence(boolean processFromTheBeginning, TextRange cursor, boolean toNotify, boolean justReplaced) { LiveOccurrence next; if (myNotFoundState) { myNotFoundState = false; processFromTheBeginning = true; } if ((!myFindModel.isGlobal() || justReplaced) && cursor != null) { next = nextOccurrence(cursor); } else { next = firstOccurrenceAfterCaret(); } if (next == null) { if (processFromTheBeginning) { if (hasMatches()) { next = getOccurrences().get(0); } } else { setNotFoundState(true); } } if (toNotify) { moveCursorTo(next); } else { myCursor = next; } } public void moveCursorTo(LiveOccurrence next) { if (next != null) { myCursor = next; notifyCursorMoved(true); } } private void notifyCursorMoved(boolean toChangeSelection) { for (SearchResultsListener listener : myListeners) { listener.cursorMoved(toChangeSelection); } } }
platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.find.impl.livePreview; import com.intellij.find.FindManager; import com.intellij.find.FindModel; import com.intellij.find.FindResult; import com.intellij.find.FindUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.concurrency.FutureResult; import com.intellij.util.containers.HashSet; import com.intellij.util.containers.Stack; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.regex.PatternSyntaxException; public class SearchResults implements DocumentListener { public int getStamp() { return ++myStamp; } @Override public void beforeDocumentChange(DocumentEvent event) { myCursorPositions.clear(); } @Override public void documentChanged(DocumentEvent event) { } public enum Direction {UP, DOWN} private List<SearchResultsListener> myListeners = new ArrayList<SearchResultsListener>(); private @Nullable LiveOccurrence myCursor; private List<LiveOccurrence> myOccurrences = new ArrayList<LiveOccurrence>(); private Set<RangeMarker> myExcluded = new HashSet<RangeMarker>(); private Editor myEditor; private Project myProject; private FindModel myFindModel; private int myMatchesLimit = 100; private boolean myNotFoundState = false; private boolean myDisposed = false; private int myStamp = 0; private int myLastUpdatedStamp = -1; private Stack<Pair<FindModel, LiveOccurrence>> myCursorPositions = new Stack<Pair<FindModel, LiveOccurrence>>(); public SearchResults(Editor editor, Project project) { myEditor = editor; myProject = project; myEditor.getDocument().addDocumentListener(this); } public void setNotFoundState(boolean isForward) { myNotFoundState = true; FindModel findModel = new FindModel(); findModel.copyFrom(myFindModel); findModel.setForward(isForward); FindUtil.processNotFound(myEditor, findModel.getStringToFind(), findModel, getProject()); } public int getMatchesCount() { return myOccurrences.size(); } public boolean hasMatches() { return !getOccurrences().isEmpty(); } public FindModel getFindModel() { return myFindModel; } public boolean isExcluded(LiveOccurrence occurrence) { for (RangeMarker rangeMarker : myExcluded) { if (TextRange.areSegmentsEqual(rangeMarker, occurrence.getPrimaryRange())) { return true; } } return false; } public void exclude(LiveOccurrence occurrence) { boolean include = false; final TextRange r = occurrence.getPrimaryRange(); for (RangeMarker rangeMarker : myExcluded) { if (TextRange.areSegmentsEqual(rangeMarker, r)) { myExcluded.remove(rangeMarker); rangeMarker.dispose(); include = true; break; } } if (!include) { myExcluded.add(myEditor.getDocument().createRangeMarker(r.getStartOffset(), r.getEndOffset(), true)); } notifyChanged(); } public Set<RangeMarker> getExcluded() { return myExcluded; } public interface SearchResultsListener { void searchResultsUpdated(SearchResults sr); void editorChanged(SearchResults sr, Editor oldEditor); void cursorMoved(boolean toChangeSelection); } public void addListener(SearchResultsListener srl) { myListeners.add(srl); } public void removeListener(SearchResultsListener srl) { myListeners.remove(srl); } public int getMatchesLimit() { return myMatchesLimit; } public void setMatchesLimit(int matchesLimit) { myMatchesLimit = matchesLimit; } @Nullable public LiveOccurrence getCursor() { return myCursor; } public List<LiveOccurrence> getOccurrences() { return myOccurrences; } @Nullable public Project getProject() { return myProject; } public synchronized void setEditor(Editor editor) { Editor oldOne = myEditor; myEditor = editor; notifyEditorChanged(oldOne); } private void notifyEditorChanged(Editor oldOne) { for (SearchResultsListener listener : myListeners) { listener.editorChanged(this, oldOne); } } public synchronized Editor getEditor() { return myEditor; } private static void findResultsToOccurrences(ArrayList<FindResult> results, Collection<LiveOccurrence> occurrences) { for (FindResult r : results) { LiveOccurrence occurrence = new LiveOccurrence(); occurrence.setPrimaryRange(r); occurrences.add(occurrence); } } public void clear() { searchCompleted(new ArrayList<LiveOccurrence>(), getEditor(), null, false, null, getStamp()); } public void updateThreadSafe(final FindModel findModel, final boolean toChangeSelection, @Nullable final TextRange next, final int stamp) { if (myDisposed) return; final ArrayList<LiveOccurrence> occurrences = new ArrayList<LiveOccurrence>(); final Editor editor = getEditor(); final ArrayList<FindResult> results = new ArrayList<FindResult>(); if (findModel != null) { updatePreviousFindModel(findModel); final FutureResult<int[]> startsRef = new FutureResult<int[]>(); final FutureResult<int[]> endsRef = new FutureResult<int[]>(); getSelection(editor, startsRef, endsRef); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { int[] starts = new int[0]; int[] ends = new int[0]; try { starts = startsRef.get(); ends = endsRef.get(); } catch (InterruptedException ignore) { } catch (ExecutionException ignore) { } if (starts.length == 0 || findModel.isGlobal()) { findInRange(new TextRange(0, Integer.MAX_VALUE), editor, findModel, results); } else { for (int i = 0; i < starts.length; ++i) { findInRange(new TextRange(starts[i], ends[i]), editor, findModel, results); } } findResultsToOccurrences(results, occurrences); final Runnable searchCompletedRunnable = new Runnable() { @Override public void run() { searchCompleted(occurrences, editor, findModel, toChangeSelection, next, stamp); } }; if (!ApplicationManager.getApplication().isUnitTestMode()) { SwingUtilities.invokeLater(searchCompletedRunnable); } else { searchCompletedRunnable.run(); } } }); } } private void updatePreviousFindModel(FindModel model) { FindModel prev = FindManager.getInstance(getProject()).getPreviousFindModel(); if (prev == null) { prev = new FindModel(); } if (!model.getStringToFind().isEmpty()) { prev.copyFrom(model); FindManager.getInstance(getProject()).setPreviousFindModel(prev); } } private static void getSelection(final Editor editor, final FutureResult<int[]> starts, final FutureResult<int[]> ends) { if (ApplicationManager.getApplication().isDispatchThread()) { SelectionModel selection = editor.getSelectionModel(); starts.set(selection.getBlockSelectionStarts()); ends.set(selection.getBlockSelectionEnds()); } else { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { SelectionModel selection = editor.getSelectionModel(); starts.set(selection.getBlockSelectionStarts()); ends.set(selection.getBlockSelectionEnds()); } }); } catch (InterruptedException ignore) { } catch (InvocationTargetException ignore) { } } } private void findInRange(TextRange r, Editor editor, FindModel findModel, ArrayList<FindResult> results) { VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(editor.getDocument()); int offset = r.getStartOffset(); while (true) { FindManager findManager = FindManager.getInstance(getProject()); FindResult result; try { CharSequence bombedCharSequence = StringUtil.newBombedCharSequence(editor.getDocument().getCharsSequence(), 3000); result = findManager.findString(bombedCharSequence, offset, findModel, virtualFile); } catch(PatternSyntaxException e) { result = null; } catch (ProcessCanceledException e) { result = null; } if (result == null || !result.isStringFound()) break; int newOffset = result.getEndOffset(); if (offset == newOffset || result.getEndOffset() > r.getEndOffset()) break; offset = newOffset; results.add(result); } } public void dispose() { myDisposed = true; myEditor.getDocument().removeDocumentListener(this); } private void searchCompleted(List<LiveOccurrence> occurrences, Editor editor, @Nullable FindModel findModel, boolean toChangeSelection, @Nullable TextRange next, int stamp) { if (stamp < myLastUpdatedStamp){ return; } myLastUpdatedStamp = stamp; if (editor != getEditor() || myDisposed) { return; } myOccurrences = occurrences; final TextRange oldCursorRange = myCursor != null ? myCursor.getPrimaryRange() : null; Collections.sort(myOccurrences, new Comparator<LiveOccurrence>() { @Override public int compare(LiveOccurrence liveOccurrence, LiveOccurrence liveOccurrence1) { return liveOccurrence.getPrimaryRange().getStartOffset() - liveOccurrence1.getPrimaryRange().getStartOffset(); } }); myFindModel = findModel; updateCursor(oldCursorRange, next); updateExcluded(); notifyChanged(); if (oldCursorRange == null || myCursor == null || !myCursor.getPrimaryRange().equals(oldCursorRange)) { notifyCursorMoved(toChangeSelection); } } private void updateExcluded() { Set<RangeMarker> invalid = new HashSet<RangeMarker>(); for (RangeMarker marker : myExcluded) { if (!marker.isValid()) { invalid.add(marker); marker.dispose(); } } myExcluded.removeAll(invalid); } private void updateCursor(@Nullable TextRange oldCursorRange, @Nullable TextRange next) { boolean justReplaced = next != null; boolean toPush = true; if (justReplaced || (toPush = !repairCursorFromStack())) { if (justReplaced || !tryToRepairOldCursor(oldCursorRange)) { if (myFindModel != null) { if(oldCursorRange != null && !myFindModel.isGlobal()) { myCursor = firstOccurrenceAfterOffset(oldCursorRange.getEndOffset()); } else { if (justReplaced) { nextOccurrence(false, next, false, justReplaced); } else { LiveOccurrence afterCaret = oldCursorRange == null ? firstOccurrenceAtOrAfterCaret() : firstOccurrenceAfterCaret(); if (afterCaret != null) { myCursor = afterCaret; } else { myCursor = null; } } } } else { myCursor = null; } } } if (!justReplaced && myCursor == null && hasMatches()) { nextOccurrence(true, oldCursorRange, false, false); } if (toPush && myCursor != null){ push(); } } private boolean repairCursorFromStack() { if (myCursorPositions.size() >= 2) { final Pair<FindModel, LiveOccurrence> oldPosition = myCursorPositions.get(myCursorPositions.size() - 2); if (oldPosition.first.equals(myFindModel)) { LiveOccurrence newCursor; if ((newCursor = findOccurrenceEqualTo(oldPosition.second)) != null) { myCursorPositions.pop(); myCursor = newCursor; return true; } } } return false; } @Nullable private LiveOccurrence findOccurrenceEqualTo(LiveOccurrence occurrence) { for (LiveOccurrence liveOccurrence : myOccurrences) { if (liveOccurrence.getPrimaryRange().equals(occurrence.getPrimaryRange())) { return liveOccurrence; } } return null; } @Nullable private LiveOccurrence firstOccurrenceAtOrAfterCaret() { int offset = getEditor().getCaretModel().getOffset(); for (LiveOccurrence occurrence : myOccurrences) { if (offset <= occurrence.getPrimaryRange().getEndOffset() && offset >= occurrence.getPrimaryRange().getStartOffset()) { return occurrence; } } return firstOccurrenceAfterCaret(); } private void notifyChanged() { for (SearchResultsListener listener : myListeners) { listener.searchResultsUpdated(this); } } static boolean insideVisibleArea(Editor e, TextRange r) { Rectangle visibleArea = e.getScrollingModel().getVisibleArea(); Point point = e.logicalPositionToXY(e.offsetToLogicalPosition(r.getStartOffset())); return visibleArea.contains(point); } @Nullable private LiveOccurrence firstVisibleOccurrence() { int offset = Integer.MAX_VALUE; LiveOccurrence firstOccurrence = null; LiveOccurrence firstVisibleOccurrence = null; for (LiveOccurrence o : getOccurrences()) { if (insideVisibleArea(myEditor, o.getPrimaryRange())) { if (firstVisibleOccurrence == null || o.getPrimaryRange().getStartOffset() < firstVisibleOccurrence.getPrimaryRange().getStartOffset()) { firstVisibleOccurrence = o; } } if (o.getPrimaryRange().getStartOffset() < offset) { offset = o.getPrimaryRange().getStartOffset(); firstOccurrence = o; } } return firstVisibleOccurrence != null ? firstVisibleOccurrence : firstOccurrence; } @Nullable private LiveOccurrence firstOccurrenceBeforeCaret() { int offset = getEditor().getCaretModel().getOffset(); return firstOccurrenceBeforeOffset(offset); } @Nullable private LiveOccurrence firstOccurrenceBeforeOffset(int offset) { for (int i = getOccurrences().size()-1; i >= 0; --i) { if (getOccurrences().get(i).getPrimaryRange().getEndOffset() < offset) { return getOccurrences().get(i); } } return null; } @Nullable private LiveOccurrence firstOccurrenceAfterCaret() { int caret = myEditor.getCaretModel().getOffset(); return firstOccurrenceAfterOffset(caret); } @Nullable private LiveOccurrence firstOccurrenceAfterOffset(int offset) { LiveOccurrence afterCaret = null; for (LiveOccurrence occurrence : getOccurrences()) { if (occurrence.getPrimaryRange().getStartOffset() >= offset) { if (afterCaret == null || occurrence.getPrimaryRange().getStartOffset() < afterCaret.getPrimaryRange().getStartOffset() ) { afterCaret = occurrence; } } } return afterCaret; } private boolean tryToRepairOldCursor(@Nullable TextRange oldCursorRange) { if (oldCursorRange == null) return false; LiveOccurrence mayBeOldCursor = null; for (LiveOccurrence searchResult : getOccurrences()) { if (searchResult.getPrimaryRange().intersects(oldCursorRange)) { mayBeOldCursor = searchResult; } if (searchResult.getPrimaryRange().getStartOffset() == oldCursorRange.getStartOffset()) { break; } } if (mayBeOldCursor != null) { myCursor = mayBeOldCursor; return true; } return false; } @Nullable private LiveOccurrence prevOccurrence(TextRange range) { for (int i = getOccurrences().size() - 1; i >= 0; --i) { final LiveOccurrence occurrence = getOccurrences().get(i); if (occurrence.getPrimaryRange().getEndOffset() <= range.getStartOffset()) { return occurrence; } } return null; } @Nullable private LiveOccurrence nextOccurrence(TextRange range) { for (LiveOccurrence occurrence : getOccurrences()) { if (occurrence.getPrimaryRange().getStartOffset() >= range.getEndOffset()) { return occurrence; } } return null; } public void prevOccurrence() { LiveOccurrence next = null; if (myFindModel == null) return; boolean processFromTheBeginning = false; if (myNotFoundState) { myNotFoundState = false; processFromTheBeginning = true; } if (!myFindModel.isGlobal()) { if (myCursor != null) { next = prevOccurrence(myCursor.getPrimaryRange()); } } else { next = firstOccurrenceBeforeCaret(); } if (next == null) { if (processFromTheBeginning) { if (hasMatches()) { next = getOccurrences().get(getOccurrences().size()-1); } } else { setNotFoundState(false); } } moveCursorTo(next); push(); } private void push() { myCursorPositions.push(new Pair<FindModel, LiveOccurrence>(myFindModel, myCursor)); } public void nextOccurrence() { if (myFindModel == null) return; nextOccurrence(false, myCursor != null ? myCursor.getPrimaryRange() : null, true, false); push(); } private void nextOccurrence(boolean processFromTheBeginning, TextRange cursor, boolean toNotify, boolean justReplaced) { LiveOccurrence next; if (myNotFoundState) { myNotFoundState = false; processFromTheBeginning = true; } if ((!myFindModel.isGlobal() || justReplaced) && cursor != null) { next = nextOccurrence(cursor); } else { next = firstOccurrenceAfterCaret(); } if (next == null) { if (processFromTheBeginning) { if (hasMatches()) { next = getOccurrences().get(0); } } else { setNotFoundState(true); } } if (toNotify) { moveCursorTo(next); } else { myCursor = next; } } public void moveCursorTo(LiveOccurrence next) { if (next != null) { myCursor = next; notifyCursorMoved(true); } } private void notifyCursorMoved(boolean toChangeSelection) { for (SearchResultsListener listener : myListeners) { listener.cursorMoved(toChangeSelection); } } }
IDEA-98318 Text Replace replaces wrong text if IntelliJ has a high CPU load
platform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java
IDEA-98318 Text Replace replaces wrong text if IntelliJ has a high CPU load
<ide><path>latform/lang-impl/src/com/intellij/find/impl/livePreview/SearchResults.java <ide> import com.intellij.util.concurrency.FutureResult; <ide> import com.intellij.util.containers.HashSet; <ide> import com.intellij.util.containers.Stack; <add>import com.intellij.util.ui.UIUtil; <ide> import org.jetbrains.annotations.Nullable; <ide> <ide> import javax.swing.*; <ide> }; <ide> <ide> if (!ApplicationManager.getApplication().isUnitTestMode()) { <del> SwingUtilities.invokeLater(searchCompletedRunnable); <add> UIUtil.invokeLaterIfNeeded(searchCompletedRunnable); <ide> } <ide> else { <ide> searchCompletedRunnable.run();
Java
bsd-2-clause
6c743e278afc2178f4e5d7c74c9c3f4da0694444
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
package com.jme.scene.model.XMLparser.Converters.TDSChunkingFiles; import com.jme.scene.Node; import com.jme.scene.TriMesh; import com.jme.scene.Spatial; import com.jme.scene.state.LightState; import com.jme.math.*; import com.jme.light.Light; import com.jme.light.SpotLight; import com.jme.light.PointLight; import com.jme.renderer.ColorRGBA; import com.jme.system.DisplaySystem; import com.jme.system.JmeException; import com.jme.animation.SpatialTransformer; import java.io.IOException; import java.io.DataInput; import java.util.ArrayList; import java.util.Iterator; /** * Started Date: Jul 2, 2004<br><br> * * type=4d4d=MAIN_3DS * parent=nothing * @author Jack Lindamood */ public class TDSFile extends ChunkerClass{ EditableObjectChunk objects=null; KeyframeChunk keyframes=null; ArrayList spatialNodes; ArrayList spatialNodesNames; private SpatialTransformer st; public TDSFile(DataInput myIn) throws IOException { super(myIn); ChunkHeader c=new ChunkHeader(myIn); if (c.type!=MAIN_3DS) throw new IOException("Header doesn't match 0x4D4D; Header=" + Integer.toHexString(c.type)); c.length-=6; setHeader(c); chunk(); } protected boolean processChildChunk(ChunkHeader i) throws IOException { switch(i.type){ case TDS_VERSION: readVersion(); return true; case EDIT_3DS: objects=new EditableObjectChunk(myIn,i); return true; case KEYFRAMES: keyframes=new KeyframeChunk(myIn,i); return true; default: return false; } } private void readVersion() throws IOException{ int version=myIn.readInt(); if (DEBUG || DEBUG_LIGHT) System.out.println("Version:" + version); } public Node buildScene() throws IOException { buildObject(); putTranslations(); Node uberNode=new Node("TDS Scene"); LightState ls=null; for (int i=0;i<spatialNodes.size();i++){ if (spatialNodes.get(i) instanceof Spatial){ Spatial toAttach=(Spatial)spatialNodes.get(i); uberNode.attachChild(toAttach); } else if (spatialNodes.get(i) instanceof Light){ if (ls==null){ ls=DisplaySystem.getDisplaySystem().getRenderer().getLightState(); ls.setEnabled(true); } ls.attach((Light) spatialNodes.get(i)); } } if (ls!=null) uberNode.setRenderState(ls); if (st.keyframes.size()==1) st.setTimeFrame(0); else uberNode.addController(st); st.setActive(true); return uberNode; } private void putTranslations() { int spatialCount=0; for (int i=0;i<spatialNodes.size();i++) if (spatialNodes.get(i) instanceof Spatial) spatialCount++; st=new SpatialTransformer(spatialCount); spatialCount=0; for (int i=0;i<spatialNodes.size();i++){ if (spatialNodes.get(i) instanceof Spatial){ st.setObject(spatialNodes.get(i),spatialCount++,getParentIndex(i)); } } Object[] keysetKeyframe=keyframes.objKeyframes.keySet().toArray(); for (int i=0;i<keysetKeyframe.length;i++){ KeyframeInfoChunk thisOne=(KeyframeInfoChunk) keyframes.objKeyframes.get(keysetKeyframe[i]); int indexInST=findIndex(thisOne.name); for (int j=0;j<thisOne.track.size();j++){ KeyframeInfoChunk.KeyPointInTime thisTime=(KeyframeInfoChunk.KeyPointInTime) thisOne.track.get(j); if (thisTime.rot!=null) st.setRotation(indexInST,thisTime.frame,thisTime.rot); if (thisTime.position!=null) st.setPosition(indexInST,thisTime.frame,thisTime.position); if (thisTime.scale!=null) st.setScale(indexInST,thisTime.frame,thisTime.scale); } } st.setSpeed(10); } private int findIndex(String name) { int j=0; for (int i=0;i<spatialNodesNames.size();i++){ if (spatialNodesNames.get(i).equals(name)) return j; if (spatialNodes.get(i) instanceof Spatial) j++; } throw new JmeException("Logic error. Unknown keyframe name " + name); } private int getParentIndex(int objectIndex) { int b=3; if (((KeyframeInfoChunk)keyframes.objKeyframes.get(spatialNodesNames.get(objectIndex)))==null) return -2; short parentID=((KeyframeInfoChunk)keyframes.objKeyframes.get(spatialNodesNames.get(objectIndex))).parent; if (parentID==-1) return -1; Object[] objs=keyframes.objKeyframes.keySet().toArray(); for (int i=0;i<objs.length;i++){ if (((KeyframeInfoChunk)keyframes.objKeyframes.get(objs[i])).myID==parentID) return i; } throw new JmeException("Logic error. Unknown parent ID for " + objectIndex); } private void buildObject() throws IOException { spatialNodes=new ArrayList(); // An ArrayList of Nodes spatialNodesNames=new ArrayList(); // Their names Iterator i=objects.namedObjects.keySet().iterator(); while (i.hasNext()){ String objectKey=(String) i.next(); NamedObjectChunk noc=(NamedObjectChunk) objects.namedObjects.get(objectKey); spatialNodesNames.add(noc.name); if (noc.whatIAm instanceof TriMeshChunk){ Node parentNode=new Node(objectKey); putChildMeshes(parentNode,(TriMeshChunk) noc.whatIAm,((KeyframeInfoChunk)keyframes.objKeyframes.get(objectKey)).pivot); if (parentNode.getQuantity()==1){ spatialNodes.add(parentNode.getChild(0)); ((Spatial)parentNode.getChild(0)).setName(parentNode.getName()); } else spatialNodes.add(parentNode); } else if (noc.whatIAm instanceof LightChunk){ spatialNodes.add(createChildLight((LightChunk)noc.whatIAm)); } else{ spatialNodes.add(null); } } } private Light createChildLight(LightChunk lightChunk) { // Light attenuation does not work right. if (lightChunk.spotInfo!=null){ SpotLight toReturn=new SpotLight(); toReturn.setLocation(lightChunk.myLoc); toReturn.setDiffuse(lightChunk.lightColor); toReturn.setAmbient(ColorRGBA.black); toReturn.setSpecular(ColorRGBA.white); Vector3f tempDir=lightChunk.myLoc.subtract(lightChunk.spotInfo.target).multLocal(-1); tempDir.normalizeLocal(); toReturn.setDirection(tempDir); // toReturn.setAngle(lightChunk.spotInfo.fallOff); // Get this working correctly toReturn.setAngle(180); // TODO: Get this working correctly, it's just a hack toReturn.setEnabled(true); return toReturn; } else{ PointLight toReturn=new PointLight(); toReturn.setLocation(lightChunk.myLoc); toReturn.setDiffuse(lightChunk.lightColor); toReturn.setAmbient(ColorRGBA.black); toReturn.setSpecular(ColorRGBA.white); toReturn.setEnabled(true); return toReturn; } } private void putChildMeshes(Node parentNode, TriMeshChunk whatIAm,Vector3f pivotLoc) throws IOException { FacesChunk myFace=whatIAm.face; boolean[] faceHasMaterial=new boolean[myFace.nFaces]; int noMaterialCount=myFace.nFaces; ArrayList normals=new ArrayList(myFace.nFaces); ArrayList vertexes=new ArrayList(myFace.nFaces); Vector3f tempNormal=new Vector3f(); ArrayList texCoords=new ArrayList(myFace.nFaces); whatIAm.coordSystem.inverse(); for (int i=0;i<whatIAm.vertexes.length;i++){ whatIAm.coordSystem.multPoint(whatIAm.vertexes[i]); whatIAm.vertexes[i].subtractLocal(pivotLoc); } Vector3f[] faceNormals=new Vector3f[myFace.nFaces]; calculateFaceNormals(faceNormals,whatIAm.vertexes,whatIAm.face.faces); // Precalculate nextTo[vertex][0...i] <---> // whatIAm.vertexes[vertex] is next to face nextTo[vertex][0] & nextTo[vertex][i] if (DEBUG || DEBUG_LIGHT) System.out.println("Precaching"); int[] vertexCount=new int[whatIAm.vertexes.length]; int vertexIndex; for (int i=0;i<myFace.nFaces;i++){ for (int j=0;j<3;j++){ vertexCount[myFace.faces[i][j]]++; } } int[][] realNextFaces=new int[whatIAm.vertexes.length][]; for (int i=0;i<realNextFaces.length;i++) realNextFaces[i]=new int[vertexCount[i]]; for (int i=0;i<myFace.nFaces;i++){ for (int j=0;j<3;j++){ vertexIndex=myFace.faces[i][j]; realNextFaces[vertexIndex][--vertexCount[vertexIndex]]=i; } } if (DEBUG || DEBUG_LIGHT) System.out.println("Precaching done"); int[] indexes=new int[myFace.nFaces*3]; int curPosition; for (int i=0;i<myFace.materialIndexes.size();i++){ // For every original material String matName=(String) myFace.materialNames.get(i); int[] appliedFacesIndexes=(int[])myFace.materialIndexes.get(i); if (DEBUG_LIGHT || DEBUG) System.out.println("On material " + matName + " with " + appliedFacesIndexes.length + " faces."); if (appliedFacesIndexes.length!=0){ // If it's got something make a new trimesh for it TriMesh part=new TriMesh(parentNode.getName()+i); normals.clear(); curPosition=0; vertexes.clear(); texCoords.clear(); for (int j=0;j<appliedFacesIndexes.length;j++){ // Look thru every face in that new TriMesh if (DEBUG) if (j%500==0) System.out.println("Face:" + j); int actuallFace=appliedFacesIndexes[j]; if (faceHasMaterial[actuallFace]==false){ faceHasMaterial[actuallFace]=true; noMaterialCount--; } for (int k=0;k<3;k++){ // and every vertex in that face // what faces contain this vertex index? If they do and are in the same SG, average vertexIndex=myFace.faces[actuallFace][k]; tempNormal.set(faceNormals[actuallFace]); calcFacesWithVertexAndSmoothGroup(realNextFaces[vertexIndex],faceNormals,myFace,tempNormal,actuallFace); // Now can I just index this Vertex/tempNormal combination? int l=0; Vector3f vertexValue=whatIAm.vertexes[vertexIndex]; for (l=0;l<normals.size();l++) if (normals.get(l).equals(tempNormal) && vertexes.get(l).equals(vertexValue)) break; if (l==normals.size()){ // if new normals.add(new Vector3f(tempNormal)); vertexes.add(whatIAm.vertexes[vertexIndex]); if (whatIAm.texCoords!=null) texCoords.add(whatIAm.texCoords[vertexIndex]); indexes[curPosition++]=l; } else { // if old indexes[curPosition++]=l; } } } Vector3f[] newVerts=new Vector3f[vertexes.size()]; for (int indexV=0;indexV<newVerts.length;indexV++) newVerts[indexV]=(Vector3f) vertexes.get(indexV); part.setVertices(newVerts); part.setNormals((Vector3f[]) normals.toArray(new Vector3f[]{})); if (whatIAm.texCoords!=null) part.setTextures((Vector2f[]) texCoords.toArray(new Vector2f[]{})); int[] intIndexes=new int[curPosition]; System.arraycopy(indexes,0,intIndexes,0,curPosition); part.setIndices(intIndexes); MaterialBlock myMaterials=(MaterialBlock) objects.materialBlocks.get(matName); if (matName==null) throw new IOException("Couldn't find the correct name of " + myMaterials); if (myMaterials.myMatState.isEnabled()) part.setRenderState(myMaterials.myMatState); if (myMaterials.myTexState.isEnabled()) part.setRenderState(myMaterials.myTexState); if (myMaterials.myWireState.isEnabled()) part.setRenderState(myMaterials.myWireState); parentNode.attachChild(part); } } if (noMaterialCount!=0){ // attach materialless parts int[] noMaterialIndexes=new int[noMaterialCount*3]; int partCount=0; for (int i=0;i<whatIAm.face.nFaces;i++){ if (!faceHasMaterial[i]){ noMaterialIndexes[partCount++]=myFace.faces[i][0]; noMaterialIndexes[partCount++]=myFace.faces[i][1]; noMaterialIndexes[partCount++]=myFace.faces[i][2]; } } TriMesh noMaterials=new TriMesh(parentNode.getName()+"-1"); noMaterials.setVertices(whatIAm.vertexes); noMaterials.setIndices(noMaterialIndexes); parentNode.attachChild(noMaterials); } } private void calculateFaceNormals(Vector3f[] faceNormals,Vector3f[] vertexes,int[][] faces) { Vector3f tempa=new Vector3f(),tempb=new Vector3f(); // Face normals for (int i=0;i<faceNormals.length;i++){ tempa.set(vertexes[faces[i][0]]); // tempa=a tempa.subtractLocal(vertexes[faces[i][1]]); // tempa-=b (tempa=a-b) tempb.set(vertexes[faces[i][0]]); // tempb=a tempb.subtractLocal(vertexes[faces[i][2]]); // tempb-=c (tempb=a-c) faceNormals[i]=tempa.cross(tempb).normalizeLocal(); } } // Find all face normals for faces that contain that vertex AND are in that smoothing group. private void calcFacesWithVertexAndSmoothGroup(int[] thisVertexTable,Vector3f[] faceNormals,FacesChunk myFace, Vector3f tempNormal, int faceIndex) { // tempNormal starts out with the face normal value int smoothingGroupValue=myFace.smoothingGroups[faceIndex]; if (smoothingGroupValue==0) return; // 0 smoothing group values don't have smooth edges anywhere int arrayFace; for (int i=0;i<thisVertexTable.length;i++){ arrayFace=thisVertexTable[i]; if (arrayFace==faceIndex) continue; if ((myFace.smoothingGroups[arrayFace] & smoothingGroupValue)!=0 ) tempNormal.addLocal(faceNormals[arrayFace]); } tempNormal.normalizeLocal(); } }
src/com/jme/scene/model/XMLparser/Converters/TDSChunkingFiles/TDSFile.java
package com.jme.scene.model.XMLparser.Converters.TDSChunkingFiles; import com.jme.scene.Node; import com.jme.scene.TriMesh; import com.jme.scene.Spatial; import com.jme.scene.state.LightState; import com.jme.math.*; import com.jme.light.Light; import com.jme.light.SpotLight; import com.jme.light.PointLight; import com.jme.renderer.ColorRGBA; import com.jme.system.DisplaySystem; import com.jme.system.JmeException; import com.jme.animation.SpatialTransformer; import java.io.IOException; import java.io.DataInput; import java.util.ArrayList; import java.util.Iterator; /** * Started Date: Jul 2, 2004<br><br> * * type=4d4d=MAIN_3DS * parent=nothing * @author Jack Lindamood */ public class TDSFile extends ChunkerClass{ EditableObjectChunk objects=null; KeyframeChunk keyframes=null; ArrayList spatialNodes; ArrayList spatialNodesNames; private SpatialTransformer st; public TDSFile(DataInput myIn) throws IOException { super(myIn); ChunkHeader c=new ChunkHeader(myIn); if (c.type!=MAIN_3DS) throw new IOException("Header doesn't match 0x4D4D; Header=" + Integer.toHexString(c.type)); c.length-=6; setHeader(c); chunk(); } protected boolean processChildChunk(ChunkHeader i) throws IOException { switch(i.type){ case TDS_VERSION: readVersion(); return true; case EDIT_3DS: objects=new EditableObjectChunk(myIn,i); return true; case KEYFRAMES: keyframes=new KeyframeChunk(myIn,i); return true; default: return false; } } private void readVersion() throws IOException{ int version=myIn.readInt(); if (DEBUG || DEBUG_LIGHT) System.out.println("Version:" + version); } public Node buildScene() throws IOException { buildObject(); putTranslations(); Node uberNode=new Node("TDS Scene"); LightState ls=null; for (int i=0;i<spatialNodes.size();i++){ if (spatialNodes.get(i) instanceof Spatial){ Spatial toAttach=(Spatial)spatialNodes.get(i); uberNode.attachChild(toAttach); } else if (spatialNodes.get(i) instanceof Light){ if (ls==null){ ls=DisplaySystem.getDisplaySystem().getRenderer().getLightState(); ls.setEnabled(true); } ls.attach((Light) spatialNodes.get(i)); } } if (ls!=null) uberNode.setRenderState(ls); if (st.keyframes.size()==1) st.setTimeFrame(0); else uberNode.addController(st); st.setActive(true); return uberNode; } private void putTranslations() { int spatialCount=0; for (int i=0;i<spatialNodes.size();i++) if (spatialNodes.get(i) instanceof Spatial) spatialCount++; st=new SpatialTransformer(spatialCount); spatialCount=0; for (int i=0;i<spatialNodes.size();i++){ if (spatialNodes.get(i) instanceof Spatial){ st.setObject(spatialNodes.get(i),spatialCount++,getParentIndex(i)); } } Object[] keysetKeyframe=keyframes.objKeyframes.keySet().toArray(); for (int i=0;i<keysetKeyframe.length;i++){ KeyframeInfoChunk thisOne=(KeyframeInfoChunk) keyframes.objKeyframes.get(keysetKeyframe[i]); int indexInST=findIndex(thisOne.name); for (int j=0;j<thisOne.track.size();j++){ KeyframeInfoChunk.KeyPointInTime thisTime=(KeyframeInfoChunk.KeyPointInTime) thisOne.track.get(j); if (thisTime.rot!=null) st.setRotation(indexInST,thisTime.frame,thisTime.rot); if (thisTime.position!=null) st.setPosition(indexInST,thisTime.frame,thisTime.position); if (thisTime.scale!=null) st.setScale(indexInST,thisTime.frame,thisTime.scale); } } st.setSpeed(10); } private int findIndex(String name) { int j=0; for (int i=0;i<spatialNodesNames.size();i++){ if (spatialNodesNames.get(i).equals(name)) return j; if (spatialNodes.get(i) instanceof Spatial) j++; } throw new JmeException("Logic error. Unknown keyframe name " + name); } private int getParentIndex(int objectIndex) { int b=3; if (((KeyframeInfoChunk)keyframes.objKeyframes.get(spatialNodesNames.get(objectIndex)))==null) return -2; short parentID=((KeyframeInfoChunk)keyframes.objKeyframes.get(spatialNodesNames.get(objectIndex))).parent; if (parentID==-1) return -1; Object[] objs=keyframes.objKeyframes.keySet().toArray(); for (int i=0;i<objs.length;i++){ if (((KeyframeInfoChunk)keyframes.objKeyframes.get(objs[i])).myID==parentID) return i; } throw new JmeException("Logic error. Unknown parent ID for " + objectIndex); } private void buildObject() throws IOException { spatialNodes=new ArrayList(); // An ArrayList of Nodes spatialNodesNames=new ArrayList(); // Their names Iterator i=objects.namedObjects.keySet().iterator(); while (i.hasNext()){ String objectKey=(String) i.next(); NamedObjectChunk noc=(NamedObjectChunk) objects.namedObjects.get(objectKey); spatialNodesNames.add(noc.name); if (noc.whatIAm instanceof TriMeshChunk){ Node parentNode=new Node(objectKey); putChildMeshes(parentNode,(TriMeshChunk) noc.whatIAm,((KeyframeInfoChunk)keyframes.objKeyframes.get(objectKey)).pivot); if (parentNode.getQuantity()==1){ spatialNodes.add(parentNode.getChild(0)); ((Spatial)parentNode.getChild(0)).setName(parentNode.getName()); } else spatialNodes.add(parentNode); } else if (noc.whatIAm instanceof LightChunk){ spatialNodes.add(createChildLight((LightChunk)noc.whatIAm)); } else{ spatialNodes.add(null); } } } private Light createChildLight(LightChunk lightChunk) { // Light attenuation does not work right. if (lightChunk.spotInfo!=null){ SpotLight toReturn=new SpotLight(); toReturn.setLocation(lightChunk.myLoc); toReturn.setDiffuse(lightChunk.lightColor); toReturn.setAmbient(ColorRGBA.black); toReturn.setSpecular(ColorRGBA.white); Vector3f tempDir=lightChunk.myLoc.subtract(lightChunk.spotInfo.target).multLocal(-1); tempDir.normalizeLocal(); toReturn.setDirection(tempDir); // toReturn.setAngle(lightChunk.spotInfo.fallOff); // Get this working correctly toReturn.setAngle(180); // TODO: Get this working correctly, it's just a hack toReturn.setEnabled(true); return toReturn; } else{ PointLight toReturn=new PointLight(); toReturn.setLocation(lightChunk.myLoc); toReturn.setDiffuse(lightChunk.lightColor); toReturn.setAmbient(ColorRGBA.black); toReturn.setSpecular(ColorRGBA.white); toReturn.setEnabled(true); return toReturn; } } private void putChildMeshes(Node parentNode, TriMeshChunk whatIAm,Vector3f pivotLoc) throws IOException { FacesChunk myFace=whatIAm.face; boolean[] faceHasMaterial=new boolean[myFace.nFaces]; int noMaterialCount=myFace.nFaces; ArrayList normals=new ArrayList(myFace.nFaces); ArrayList vertexes=new ArrayList(myFace.nFaces); Vector3f tempNormal=new Vector3f(); ArrayList texCoords=new ArrayList(myFace.nFaces); whatIAm.coordSystem.inverse(); for (int i=0;i<whatIAm.vertexes.length;i++){ whatIAm.coordSystem.multPoint(whatIAm.vertexes[i]); whatIAm.vertexes[i].subtractLocal(pivotLoc); } Vector3f[] faceNormals=new Vector3f[myFace.nFaces]; calculateFaceNormals(faceNormals,whatIAm.vertexes,whatIAm.face.faces); // Precalculate nextTo[vertex][0...i] <---> // whatIAm.vertexes[vertex] is next to face nextTo[vertex][0] & nextTo[vertex][i] if (DEBUG || DEBUG_LIGHT) System.out.println("Precaching"); int[] vertexCount=new int[whatIAm.vertexes.length]; int vertexIndex; for (int i=0;i<myFace.nFaces;i++){ for (int j=0;j<3;j++){ vertexCount[myFace.faces[i][j]]++; } } int[][] realNextFaces=new int[whatIAm.vertexes.length][]; for (int i=0;i<realNextFaces.length;i++) realNextFaces[i]=new int[vertexCount[i]]; for (int i=0;i<myFace.nFaces;i++){ for (int j=0;j<3;j++){ vertexIndex=myFace.faces[i][j]; realNextFaces[vertexIndex][--vertexCount[vertexIndex]]=i; } } if (DEBUG || DEBUG_LIGHT) System.out.println("Precaching done"); int[] indexes=new int[myFace.nFaces*3]; int curPosition; for (int i=0;i<myFace.materialIndexes.size();i++){ // For every original material String matName=(String) myFace.materialNames.get(i); int[] appliedFacesIndexes=(int[])myFace.materialIndexes.get(i); if (DEBUG_LIGHT || DEBUG) System.out.println("On material " + matName + " with " + appliedFacesIndexes.length + " faces."); if (appliedFacesIndexes.length!=0){ // If it's got something make a new trimesh for it TriMesh part=new TriMesh(parentNode.getName()+i); normals.clear(); curPosition=0; vertexes.clear(); texCoords.clear(); for (int j=0;j<appliedFacesIndexes.length;j++){ // Look thru every face in that new TriMesh if (DEBUG) if (j%500==0) System.out.println("Face:" + j); int actuallFace=appliedFacesIndexes[j]; if (faceHasMaterial[actuallFace]==false){ faceHasMaterial[actuallFace]=true; noMaterialCount--; } for (int k=0;k<3;k++){ // and every vertex in that face // what faces contain this vertex index? If they do and are in the same SG, average vertexIndex=myFace.faces[actuallFace][k]; tempNormal.set(faceNormals[actuallFace]); calcFacesWithVertexAndSmoothGroup(realNextFaces[vertexIndex],faceNormals,myFace,tempNormal,actuallFace); // Now can I just index this Vertex/tempNormal combination? int l=0; Vector3f vertexValue=whatIAm.vertexes[vertexIndex]; for (l=0;l<normals.size();l++) if (normals.get(l).equals(tempNormal) && vertexes.get(l).equals(vertexValue)) break; if (l==normals.size()){ // if new normals.add(new Vector3f(tempNormal)); vertexes.add(whatIAm.vertexes[vertexIndex]); if (whatIAm.texCoords!=null) texCoords.add(whatIAm.texCoords[vertexIndex]); indexes[curPosition++]=l; } else { // if old indexes[curPosition++]=l; } } } Vector3f[] newVerts=new Vector3f[vertexes.size()]; for (int indexV=0;indexV<newVerts.length;indexV++) newVerts[indexV]=(Vector3f) vertexes.get(indexV); part.setVertices(newVerts); part.setNormals((Vector3f[]) normals.toArray(new Vector3f[]{})); if (whatIAm.texCoords!=null) part.setTextures((Vector2f[]) texCoords.toArray(new Vector2f[]{})); int[] intIndexes=new int[curPosition]; System.arraycopy(indexes,0,intIndexes,0,curPosition); part.setIndices(intIndexes); // TODO: remove in final product if (parentNode.getName().equals("red")){ part.setSolidColor(ColorRGBA.red); } else if (parentNode.getName().equals("blue")){ part.setSolidColor(ColorRGBA.blue); }else part.setSolidColor(ColorRGBA.randomColor()); MaterialBlock myMaterials=(MaterialBlock) objects.materialBlocks.get(matName); if (matName==null) throw new IOException("Couldn't find the correct name of " + myMaterials); if (myMaterials.myMatState.isEnabled()) part.setRenderState(myMaterials.myMatState); if (myMaterials.myTexState.isEnabled()) part.setRenderState(myMaterials.myTexState); if (myMaterials.myWireState.isEnabled()) part.setRenderState(myMaterials.myWireState); parentNode.attachChild(part); } } if (noMaterialCount!=0){ // attach materialless parts int[] noMaterialIndexes=new int[noMaterialCount*3]; int partCount=0; for (int i=0;i<whatIAm.face.nFaces;i++){ if (!faceHasMaterial[i]){ noMaterialIndexes[partCount++]=myFace.faces[i][0]; noMaterialIndexes[partCount++]=myFace.faces[i][1]; noMaterialIndexes[partCount++]=myFace.faces[i][2]; } } TriMesh noMaterials=new TriMesh(parentNode.getName()+"-1"); noMaterials.setVertices(whatIAm.vertexes); noMaterials.setIndices(noMaterialIndexes); noMaterials.setSolidColor(ColorRGBA.randomColor()); parentNode.attachChild(noMaterials); } } private void calculateFaceNormals(Vector3f[] faceNormals,Vector3f[] vertexes,int[][] faces) { Vector3f tempa=new Vector3f(),tempb=new Vector3f(); // Face normals for (int i=0;i<faceNormals.length;i++){ tempa.set(vertexes[faces[i][0]]); // tempa=a tempa.subtractLocal(vertexes[faces[i][1]]); // tempa-=b (tempa=a-b) tempb.set(vertexes[faces[i][0]]); // tempb=a tempb.subtractLocal(vertexes[faces[i][2]]); // tempb-=c (tempb=a-c) faceNormals[i]=tempa.cross(tempb).normalizeLocal(); } } // Find all face normals for faces that contain that vertex AND are in that smoothing group. private void calcFacesWithVertexAndSmoothGroup(int[] thisVertexTable,Vector3f[] faceNormals,FacesChunk myFace, Vector3f tempNormal, int faceIndex) { // tempNormal starts out with the face normal value int smoothingGroupValue=myFace.smoothingGroups[faceIndex]; if (smoothingGroupValue==0) return; // 0 smoothing group values don't have smooth edges anywhere int arrayFace; for (int i=0;i<thisVertexTable.length;i++){ arrayFace=thisVertexTable[i]; if (arrayFace==faceIndex) continue; if ((myFace.smoothingGroups[arrayFace] & smoothingGroupValue)!=0 ) tempNormal.addLocal(faceNormals[arrayFace]); } tempNormal.normalizeLocal(); } }
Removed solid color addition git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@1464 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jme/scene/model/XMLparser/Converters/TDSChunkingFiles/TDSFile.java
Removed solid color addition
<ide><path>rc/com/jme/scene/model/XMLparser/Converters/TDSChunkingFiles/TDSFile.java <ide> System.arraycopy(indexes,0,intIndexes,0,curPosition); <ide> part.setIndices(intIndexes); <ide> <del> // TODO: remove in final product <del> if (parentNode.getName().equals("red")){ <del> part.setSolidColor(ColorRGBA.red); <del> } else if (parentNode.getName().equals("blue")){ <del> part.setSolidColor(ColorRGBA.blue); <del> }else <del> part.setSolidColor(ColorRGBA.randomColor()); <del> <ide> MaterialBlock myMaterials=(MaterialBlock) objects.materialBlocks.get(matName); <ide> if (matName==null) <ide> throw new IOException("Couldn't find the correct name of " + myMaterials); <ide> TriMesh noMaterials=new TriMesh(parentNode.getName()+"-1"); <ide> noMaterials.setVertices(whatIAm.vertexes); <ide> noMaterials.setIndices(noMaterialIndexes); <del> noMaterials.setSolidColor(ColorRGBA.randomColor()); <ide> parentNode.attachChild(noMaterials); <ide> } <ide> }
Java
mit
c0e4c1467109755a0b060097047caca6090c32f4
0
TechReborn/RebornStorage
package RebornStorage.multiblocks; import RebornStorage.blocks.BlockMultiCrafter; import RebornStorage.tiles.TileMultiCrafter; import com.raoulvdberge.refinedstorage.api.autocrafting.ICraftingPattern; import com.raoulvdberge.refinedstorage.api.autocrafting.ICraftingPatternProvider; import com.raoulvdberge.refinedstorage.api.network.INetworkMaster; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import reborncore.common.multiblock.IMultiblockPart; import reborncore.common.multiblock.MultiblockControllerBase; import reborncore.common.multiblock.rectangular.RectangularMultiblockControllerBase; import reborncore.common.util.Inventory; import java.util.*; /** * Created by Mark on 03/01/2017. */ public class MultiBlockCrafter extends RectangularMultiblockControllerBase { public Map<Integer, Inventory> invs = new TreeMap<>(); public int powerUsage = 0; public int speed = 0; public int pages = 0; public MultiBlockCrafter(World world) { super(world); } @Override public void onAttachedPartWithMultiblockData(IMultiblockPart iMultiblockPart, NBTTagCompound nbtTagCompound) { } @Override protected void onBlockAdded(IMultiblockPart iMultiblockPart) { } @Override protected void onBlockRemoved(IMultiblockPart iMultiblockPart) { } @Override protected void onMachineAssembled() { invs.clear(); updateInfo(); } public void updateInfo(){ powerUsage = 0; speed = 0; pages = 0; invs.clear(); for(IMultiblockPart part : connectedParts){ if(part.getBlockState().getValue(BlockMultiCrafter.VARIANTS).equals("storage")){ pages ++; powerUsage += 5; if(part instanceof TileMultiCrafter){ TileMultiCrafter tile = (TileMultiCrafter) part; int id = 0; boolean genId = false; if(tile.page.isPresent()){ if(!invs.containsKey(tile.page.get())){ id = tile.page.get(); } else { genId = true; } } else { genId = true; } if(genId){ id = invs.size() + 1; //Does this need +1? tile.page = Optional.of(id); } invs.put(id, tile.inv); } } if(part.getBlockState().getValue(BlockMultiCrafter.VARIANTS).equals("cpu")){ powerUsage += 10; speed++; } } } public Inventory getInvForPage(int page){ return invs.get(page); } @Override protected void onMachineRestored() { } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { System.out.println("Invalid"); } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { return (9 * 3); } @Override protected int getMaximumXSize() { return 16; } @Override protected int getMaximumZSize() { return 16; } @Override protected int getMaximumYSize() { return 16; } @Override protected int getMinimumXSize() { return 3; } @Override protected int getMinimumYSize() { return 3; } @Override protected int getMinimumZSize() { return 3; } @Override protected void onAssimilate(MultiblockControllerBase multiblockControllerBase) { } @Override protected void onAssimilated(MultiblockControllerBase multiblockControllerBase) { } @Override protected boolean updateServer() { tick(); return true; } @Override protected void updateClient() { } @Override public void writeToNBT(NBTTagCompound nbtTagCompound) { } @Override public void readFromNBT(NBTTagCompound nbtTagCompound) { } @Override public void formatDescriptionPacket(NBTTagCompound nbtTagCompound) { writeToNBT(nbtTagCompound); } @Override public void decodeDescriptionPacket(NBTTagCompound nbtTagCompound) { readFromNBT(nbtTagCompound); } //RS things: public void tick(){ } public List<ICraftingPattern> actualPatterns = new ArrayList(); public INetworkMaster network; public void rebuildPatterns() { try { this.actualPatterns.clear(); if (!isAssembled()) { return; } updateInfo(); for (HashMap.Entry<Integer, Inventory> entry : invs.entrySet()) { for (int i = 0; i < entry.getValue().getSizeInventory(); ++i) { ItemStack patternStack = entry.getValue().getStackInSlot(i); if (patternStack != null && patternStack.getItem() instanceof ICraftingPatternProvider) { ICraftingPattern pattern = ((ICraftingPatternProvider) patternStack.getItem()).create(worldObj, patternStack, getReferenceTile()); if (pattern.isValid()) { this.actualPatterns.add(pattern); } } } } if (network != null) { network.rebuildPatterns(); } } catch (Exception e){} } public void onConnectionChange(INetworkMaster network, boolean state, BlockPos pos) { if (!state) { network.getCraftingTasks().stream().filter((task) -> task.getPattern().getContainer().getPosition().equals(pos)).forEach(network::cancelCraftingTask); } rebuildPatterns(); this.network = network; } private TileMultiCrafter getReferenceTile(){ return (TileMultiCrafter) worldObj.getTileEntity(getReferenceCoord().toBlockPos()); } }
src/main/java/RebornStorage/multiblocks/MultiBlockCrafter.java
package RebornStorage.multiblocks; import RebornStorage.blocks.BlockMultiCrafter; import RebornStorage.tiles.TileMultiCrafter; import com.raoulvdberge.refinedstorage.api.autocrafting.ICraftingPattern; import com.raoulvdberge.refinedstorage.api.autocrafting.ICraftingPatternProvider; import com.raoulvdberge.refinedstorage.api.network.INetworkMaster; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import reborncore.common.multiblock.IMultiblockPart; import reborncore.common.multiblock.MultiblockControllerBase; import reborncore.common.multiblock.rectangular.RectangularMultiblockControllerBase; import reborncore.common.util.Inventory; import java.util.*; /** * Created by Mark on 03/01/2017. */ public class MultiBlockCrafter extends RectangularMultiblockControllerBase { public Map<Integer, Inventory> invs = new TreeMap<>(); public int powerUsage = 0; public int speed = 0; public int pages = 0; public MultiBlockCrafter(World world) { super(world); } @Override public void onAttachedPartWithMultiblockData(IMultiblockPart iMultiblockPart, NBTTagCompound nbtTagCompound) { } @Override protected void onBlockAdded(IMultiblockPart iMultiblockPart) { } @Override protected void onBlockRemoved(IMultiblockPart iMultiblockPart) { } @Override protected void onMachineAssembled() { invs.clear(); updateInfo(); } public void updateInfo(){ powerUsage = 0; speed = 0; pages = 0; invs.clear(); for(IMultiblockPart part : connectedParts){ if(part.getBlockState().getValue(BlockMultiCrafter.VARIANTS).equals("storage")){ pages ++; powerUsage += 5; if(part instanceof TileMultiCrafter){ TileMultiCrafter tile = (TileMultiCrafter) part; int id = 0; boolean genId = false; if(tile.page.isPresent()){ if(!invs.containsKey(tile.page.get())){ id = tile.page.get(); } else { genId = true; } } else { genId = true; } if(genId){ id = invs.size() + 1; //Does this need +1? tile.page = Optional.of(id); } invs.put(id, tile.inv); } } if(part.getBlockState().getValue(BlockMultiCrafter.VARIANTS).equals("cpu")){ powerUsage += 10; speed++; } } } public Inventory getInvForPage(int page){ return invs.get(page); } @Override protected void onMachineRestored() { } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { System.out.println("Invalid"); } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { return (9 * 3); } @Override protected int getMaximumXSize() { return 16; } @Override protected int getMaximumZSize() { return 16; } @Override protected int getMaximumYSize() { return 16; } @Override protected int getMinimumXSize() { return 3; } @Override protected int getMinimumYSize() { return 3; } @Override protected int getMinimumZSize() { return 3; } @Override protected void onAssimilate(MultiblockControllerBase multiblockControllerBase) { } @Override protected void onAssimilated(MultiblockControllerBase multiblockControllerBase) { } @Override protected boolean updateServer() { tick(); return true; } @Override protected void updateClient() { } @Override public void writeToNBT(NBTTagCompound nbtTagCompound) { } @Override public void readFromNBT(NBTTagCompound nbtTagCompound) { } @Override public void formatDescriptionPacket(NBTTagCompound nbtTagCompound) { writeToNBT(nbtTagCompound); } @Override public void decodeDescriptionPacket(NBTTagCompound nbtTagCompound) { readFromNBT(nbtTagCompound); } //RS things: public void tick(){ } public List<ICraftingPattern> actualPatterns = new ArrayList(); public INetworkMaster network; public void rebuildPatterns() { this.actualPatterns.clear(); if(!isAssembled()){ return; } updateInfo(); for(HashMap.Entry<Integer, Inventory> entry : invs.entrySet()){ for (int i = 0; i < entry.getValue().getSizeInventory(); ++i) { ItemStack patternStack = entry.getValue().getStackInSlot(i); if (patternStack != null && patternStack.getItem() instanceof ICraftingPatternProvider) { ICraftingPattern pattern = ((ICraftingPatternProvider) patternStack.getItem()).create(worldObj, patternStack, getReferenceTile()); if (pattern.isValid()) { this.actualPatterns.add(pattern); } } } } if(network != null){ network.rebuildPatterns(); } } public void onConnectionChange(INetworkMaster network, boolean state, BlockPos pos) { if (!state) { network.getCraftingTasks().stream().filter((task) -> task.getPattern().getContainer().getPosition().equals(pos)).forEach(network::cancelCraftingTask); } rebuildPatterns(); this.network = network; } private TileMultiCrafter getReferenceTile(){ return (TileMultiCrafter) worldObj.getTileEntity(getReferenceCoord().toBlockPos()); } }
Added try catch for now closes #8
src/main/java/RebornStorage/multiblocks/MultiBlockCrafter.java
Added try catch for now closes #8
<ide><path>rc/main/java/RebornStorage/multiblocks/MultiBlockCrafter.java <ide> public INetworkMaster network; <ide> <ide> public void rebuildPatterns() { <del> this.actualPatterns.clear(); <del> if(!isAssembled()){ <del> return; <del> } <del> updateInfo(); <del> for(HashMap.Entry<Integer, Inventory> entry : invs.entrySet()){ <del> for (int i = 0; i < entry.getValue().getSizeInventory(); ++i) { <del> ItemStack patternStack = entry.getValue().getStackInSlot(i); <del> if (patternStack != null && patternStack.getItem() instanceof ICraftingPatternProvider) { <del> ICraftingPattern pattern = ((ICraftingPatternProvider) patternStack.getItem()).create(worldObj, patternStack, getReferenceTile()); <del> if (pattern.isValid()) { <del> this.actualPatterns.add(pattern); <add> try <add> { <add> this.actualPatterns.clear(); <add> if (!isAssembled()) <add> { <add> return; <add> } <add> updateInfo(); <add> for (HashMap.Entry<Integer, Inventory> entry : invs.entrySet()) <add> { <add> for (int i = 0; i < entry.getValue().getSizeInventory(); ++i) <add> { <add> ItemStack patternStack = entry.getValue().getStackInSlot(i); <add> if (patternStack != null && patternStack.getItem() instanceof ICraftingPatternProvider) <add> { <add> ICraftingPattern pattern = ((ICraftingPatternProvider) patternStack.getItem()).create(worldObj, patternStack, getReferenceTile()); <add> if (pattern.isValid()) <add> { <add> this.actualPatterns.add(pattern); <add> } <ide> } <ide> } <ide> } <add> if (network != null) <add> { <add> network.rebuildPatterns(); <add> } <ide> } <del> if(network != null){ <del> network.rebuildPatterns(); <del> } <add> catch (Exception e){} <ide> } <ide> <ide> public void onConnectionChange(INetworkMaster network, boolean state, BlockPos pos) {
Java
bsd-3-clause
1a16dbf2959a633cd1e2a8441272e3fd068f9c6a
0
crr0004/k-9,farmboy0/k-9,huhu/k-9,cliniome/pki,cketti/k-9,deepworks/k-9,439teamwork/k-9,torte71/k-9,CodingRmy/k-9,ndew623/k-9,deepworks/k-9,vatsalsura/k-9,vasyl-khomko/k-9,roscrazy/k-9,herpiko/k-9,cooperpellaton/k-9,indus1/k-9,moparisthebest/k-9,sebkur/k-9,sedrubal/k-9,dpereira411/k-9,nilsbraden/k-9,gnebsy/k-9,gaionim/k-9,dgger/k-9,gnebsy/k-9,tsunli/k-9,jberkel/k-9,jca02266/k-9,WenduanMou1/k-9,Eagles2F/k-9,G00fY2/k-9_material_design,philipwhiuk/k-9,cketti/k-9,thuanpq/k-9,XiveZ/k-9,sanderbaas/k-9,cketti/k-9,konfer/k-9,KitAway/k-9,439teamwork/k-9,konfer/k-9,tonytamsf/k-9,huhu/k-9,k9mail/k-9,nilsbraden/k-9,jberkel/k-9,gilbertw1/k-9,philipwhiuk/q-mail,cooperpellaton/k-9,dpereira411/k-9,suzp1984/k-9,thuanpq/k-9,leixinstar/k-9,cliniome/pki,cooperpellaton/k-9,thuanpq/k-9,jca02266/k-9,rtreffer/openpgp-k-9,cketti/k-9,CodingRmy/k-9,KitAway/k-9,deepworks/k-9,439teamwork/k-9,huhu/k-9,WenduanMou1/k-9,torte71/k-9,XiveZ/k-9,gilbertw1/k-9,herpiko/k-9,philipwhiuk/k-9,github201407/k-9,rollbrettler/k-9,dgger/k-9,mawiegand/k-9,denim2x/k-9,icedman21/k-9,vatsalsura/k-9,jca02266/k-9,GuillaumeSmaha/k-9,mawiegand/k-9,github201407/k-9,dhootha/k-9,konfer/k-9,rollbrettler/k-9,gilbertw1/k-9,suzp1984/k-9,WenduanMou1/k-9,tonytamsf/k-9,icedman21/k-9,github201407/k-9,dhootha/k-9,vasyl-khomko/k-9,torte71/k-9,msdgwzhy6/k-9,herpiko/k-9,icedman21/k-9,GuillaumeSmaha/k-9,dpereira411/k-9,gnebsy/k-9,sonork/k-9,vt0r/k-9,k9mail/k-9,roscrazy/k-9,denim2x/k-9,Eagles2F/k-9,farmboy0/k-9,sonork/k-9,crr0004/k-9,denim2x/k-9,rishabhbitsg/k-9,bashrc/k-9,cliniome/pki,bashrc/k-9,Eagles2F/k-9,moparisthebest/k-9,rishabhbitsg/k-9,vt0r/k-9,msdgwzhy6/k-9,rtreffer/openpgp-k-9,sebkur/k-9,suzp1984/k-9,bashrc/k-9,gaionim/k-9,sebkur/k-9,farmboy0/k-9,ndew623/k-9,G00fY2/k-9_material_design,tsunli/k-9,dhootha/k-9,indus1/k-9,KitAway/k-9,mawiegand/k-9,Valodim/k-9,sanderbaas/k-9,rollbrettler/k-9,sedrubal/k-9,leixinstar/k-9,moparisthebest/k-9,philipwhiuk/q-mail,nilsbraden/k-9,leixinstar/k-9,sonork/k-9,dgger/k-9,ndew623/k-9,sanderbaas/k-9,GuillaumeSmaha/k-9,k9mail/k-9,tsunli/k-9,crr0004/k-9,XiveZ/k-9,gaionim/k-9,tonytamsf/k-9,msdgwzhy6/k-9,vasyl-khomko/k-9,philipwhiuk/q-mail
package com.fsck.k9.activity; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.text.TextWatcher; import android.text.util.Rfc822Tokenizer; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.view.ContextThemeWrapper; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AutoCompleteTextView.Validator; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.EmailAddressAdapter; import com.fsck.k9.EmailAddressValidator; import com.fsck.k9.FontSizes; import com.fsck.k9.Identity; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.loader.AttachmentContentLoader; import com.fsck.k9.activity.loader.AttachmentInfoLoader; import com.fsck.k9.activity.misc.Attachment; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.crypto.CryptoProvider; import com.fsck.k9.crypto.PgpData; import com.fsck.k9.fragment.ProgressDialogFragment; import com.fsck.k9.helper.ContactItem; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.HtmlConverter; import com.fsck.k9.helper.StringUtils; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Multipart; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody; import com.fsck.k9.mail.store.LocalStore.TempFileBody; import com.fsck.k9.mail.store.LocalStore.TempFileMessageBody; import com.fsck.k9.view.MessageWebView; import org.apache.james.mime4j.codec.EncoderUtil; import org.apache.james.mime4j.util.MimeUtil; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.SimpleHtmlSerializer; import org.htmlcleaner.TagNode; import java.text.DateFormat; 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.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MessageCompose extends K9Activity implements OnClickListener, ProgressDialogFragment.CancelListener { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final int DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED = 2; private static final int DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY = 3; private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 4; private static final int DIALOG_CHOOSE_IDENTITY = 5; private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID; private static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE"; private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL"; private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD"; private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT"; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MESSAGE_BODY = "messageBody"; private static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; private static final String STATE_KEY_ATTACHMENTS = "com.fsck.k9.activity.MessageCompose.attachments"; private static final String STATE_KEY_CC_SHOWN = "com.fsck.k9.activity.MessageCompose.ccShown"; private static final String STATE_KEY_BCC_SHOWN = "com.fsck.k9.activity.MessageCompose.bccShown"; private static final String STATE_KEY_QUOTED_TEXT_MODE = "com.fsck.k9.activity.MessageCompose.QuotedTextShown"; private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = "com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced"; private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId"; private static final String STATE_KEY_HTML_QUOTE = "com.fsck.k9.activity.MessageCompose.HTMLQuote"; private static final String STATE_IDENTITY_CHANGED = "com.fsck.k9.activity.MessageCompose.identityChanged"; private static final String STATE_IDENTITY = "com.fsck.k9.activity.MessageCompose.identity"; private static final String STATE_PGP_DATA = "pgpData"; private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo"; private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references"; private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt"; private static final String STATE_KEY_DRAFT_NEEDS_SAVING = "com.fsck.k9.activity.MessageCompose.mDraftNeedsSaving"; private static final String STATE_KEY_FORCE_PLAIN_TEXT = "com.fsck.k9.activity.MessageCompose.forcePlainText"; private static final String STATE_KEY_QUOTED_TEXT_FORMAT = "com.fsck.k9.activity.MessageCompose.quotedTextFormat"; private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading"; private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments"; private static final String LOADER_ARG_ATTACHMENT = "attachment"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; private static final int MSG_PROGRESS_ON = 1; private static final int MSG_PROGRESS_OFF = 2; private static final int MSG_SKIPPED_ATTACHMENTS = 3; private static final int MSG_SAVED_DRAFT = 4; private static final int MSG_DISCARDED_DRAFT = 5; private static final int MSG_PERFORM_STALLED_ACTION = 6; private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1; private static final int CONTACT_PICKER_TO = 4; private static final int CONTACT_PICKER_CC = 5; private static final int CONTACT_PICKER_BCC = 6; private static final int CONTACT_PICKER_TO2 = 7; private static final int CONTACT_PICKER_CC2 = 8; private static final int CONTACT_PICKER_BCC2 = 9; private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[0]; /** * Regular expression to remove the first localized "Re:" prefix in subjects. * * Currently: * - "Aw:" (german: abbreviation for "Antwort") */ private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE); /** * The account used for message composition. */ private Account mAccount; private Contacts mContacts; /** * This identity's settings are used for message composition. * Note: This has to be an identity of the account {@link #mAccount}. */ private Identity mIdentity; private boolean mIdentityChanged = false; private boolean mSignatureChanged = false; /** * Reference to the source message (in case of reply, forward, or edit * draft actions). */ private MessageReference mMessageReference; private Message mSourceMessage; /** * "Original" message body * * <p> * The contents of this string will be used instead of the body of a referenced message when * replying to or forwarding a message.<br> * Right now this is only used when replying to a signed or encrypted message. It then contains * the stripped/decrypted body of that message. * </p> * <p><strong>Note:</strong> * When this field is not {@code null} we assume that the message we are composing right now * should be encrypted. * </p> */ private String mSourceMessageBody; /** * Indicates that the source message has been processed at least once and should not * be processed on any subsequent loads. This protects us from adding attachments that * have already been added from the restore of the view state. */ private boolean mSourceMessageProcessed = false; private int mMaxLoaderId = 0; enum Action { COMPOSE, REPLY, REPLY_ALL, FORWARD, EDIT_DRAFT } /** * Contains the action we're currently performing (e.g. replying to a message) */ private Action mAction; private enum QuotedTextMode { NONE, SHOW, HIDE } private boolean mReadReceipt = false; private QuotedTextMode mQuotedTextMode = QuotedTextMode.NONE; /** * Contains the format of the quoted text (text vs. HTML). */ private SimpleMessageFormat mQuotedTextFormat; /** * When this it {@code true} the message format setting is ignored and we're always sending * a text/plain message. */ private boolean mForcePlainText = false; private Button mChooseIdentityButton; private LinearLayout mCcWrapper; private LinearLayout mBccWrapper; private MultiAutoCompleteTextView mToView; private MultiAutoCompleteTextView mCcView; private MultiAutoCompleteTextView mBccView; private EditText mSubjectView; private EolConvertingEditText mSignatureView; private EolConvertingEditText mMessageContentView; private LinearLayout mAttachments; private Button mQuotedTextShow; private View mQuotedTextBar; private ImageButton mQuotedTextEdit; private ImageButton mQuotedTextDelete; private EolConvertingEditText mQuotedText; private MessageWebView mQuotedHTML; private InsertableHtmlContent mQuotedHtmlContent; // Container for HTML reply as it's being built. private View mEncryptLayout; private CheckBox mCryptoSignatureCheckbox; private CheckBox mEncryptCheckbox; private TextView mCryptoSignatureUserId; private TextView mCryptoSignatureUserIdRest; private ImageButton mAddToFromContacts; private ImageButton mAddCcFromContacts; private ImageButton mAddBccFromContacts; private PgpData mPgpData = null; private boolean mAutoEncrypt = false; private boolean mContinueWithoutPublicKey = false; private String mReferences; private String mInReplyTo; private Menu mMenu; private boolean mSourceProcessed = false; enum SimpleMessageFormat { TEXT, HTML } /** * The currently used message format. * * <p> * <strong>Note:</strong> * Don't modify this field directly. Use {@link #updateMessageFormat()}. * </p> */ private SimpleMessageFormat mMessageFormat; private QuoteStyle mQuoteStyle; private boolean mDraftNeedsSaving = false; private boolean mPreventDraftSaving = false; /** * If this is {@code true} we don't save the message as a draft in {@link #onPause()}. */ private boolean mIgnoreOnPause = false; /** * The database ID of this message's draft. This is used when saving drafts so the message in * the database is updated instead of being created anew. This property is INVALID_DRAFT_ID * until the first save. */ private long mDraftId = INVALID_DRAFT_ID; /** * Number of attachments currently being fetched. */ private int mNumAttachmentsLoading = 0; private enum WaitingAction { NONE, SEND, SAVE } /** * Specifies what action to perform once attachments have been fetched. */ private WaitingAction mWaitingForAttachments = WaitingAction.NONE; private Handler mHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS_ON: setSupportProgressBarIndeterminateVisibility(true); break; case MSG_PROGRESS_OFF: setSupportProgressBarIndeterminateVisibility(false); break; case MSG_SKIPPED_ATTACHMENTS: Toast.makeText( MessageCompose.this, getString(R.string.message_compose_attachments_skipped_toast), Toast.LENGTH_LONG).show(); break; case MSG_SAVED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_saved_toast), Toast.LENGTH_LONG).show(); break; case MSG_DISCARDED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); break; case MSG_PERFORM_STALLED_ACTION: performStalledAction(); break; default: super.handleMessage(msg); break; } } }; private Listener mListener = new Listener(); private EmailAddressAdapter mAddressAdapter; private Validator mAddressValidator; private FontSizes mFontSizes = K9.getFontSizes(); private ContextThemeWrapper mThemeContext; /** * Compose a new message using the given account. If account is null the default account * will be used. * @param context * @param account */ public static void actionCompose(Context context, Account account) { String accountUuid = (account == null) ? Preferences.getPreferences(context).getDefaultAccount().getUuid() : account.getUuid(); Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_ACCOUNT, accountUuid); i.setAction(ACTION_COMPOSE); context.startActivity(i); } /** * Get intent for composing a new message as a reply to the given message. If replyAll is true * the function is reply all instead of simply reply. * @param context * @param account * @param message * @param replyAll * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static Intent getActionReplyIntent( Context context, Account account, Message message, boolean replyAll, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); if (replyAll) { i.setAction(ACTION_REPLY_ALL); } else { i.setAction(ACTION_REPLY); } return i; } /** * Compose a new message as a reply to the given message. If replyAll is true the function * is reply all instead of simply reply. * @param context * @param account * @param message * @param replyAll * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionReply( Context context, Account account, Message message, boolean replyAll, String messageBody) { context.startActivity(getActionReplyIntent(context, account, message, replyAll, messageBody)); } /** * Compose a new message as a forward of the given message. * @param context * @param account * @param message * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionForward( Context context, Account account, Message message, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); i.setAction(ACTION_FORWARD); context.startActivity(i); } /** * Continue composition of the given message. This action modifies the way this Activity * handles certain actions. * Save will attempt to replace the message in the given folder with the updated version. * Discard will delete the message from the given folder. * @param context * @param message */ public static void actionEditDraft(Context context, MessageReference messageReference) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference); i.setAction(ACTION_EDIT_DRAFT); context.startActivity(i); } /* * This is a workaround for an annoying ( temporarly? ) issue: * https://github.com/JakeWharton/ActionBarSherlock/issues/449 */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setSupportProgressBarIndeterminateVisibility(false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) { // theme the whole content according to the theme (except the action bar) mThemeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9ComposerTheme())); View v = ((LayoutInflater) mThemeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)). inflate(R.layout.message_compose, null); TypedValue outValue = new TypedValue(); // background color needs to be forced mThemeContext.getTheme().resolveAttribute(R.attr.messageViewHeaderBackgroundColor, outValue, true); v.setBackgroundColor(outValue.data); setContentView(v); } else { setContentView(R.layout.message_compose); mThemeContext = this; } final Intent intent = getIntent(); mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY); if (K9.DEBUG && mSourceMessageBody != null) Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body."); final String accountUuid = (mMessageReference != null) ? mMessageReference.accountUuid : intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); if (mAccount == null) { mAccount = Preferences.getPreferences(this).getDefaultAccount(); } if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } mContacts = Contacts.getInstance(MessageCompose.this); mAddressAdapter = new EmailAddressAdapter(mThemeContext); mAddressValidator = new EmailAddressValidator(); mChooseIdentityButton = (Button) findViewById(R.id.identity); mChooseIdentityButton.setOnClickListener(this); if (mAccount.getIdentities().size() == 1 && Preferences.getPreferences(this).getAvailableAccounts().size() == 1) { mChooseIdentityButton.setVisibility(View.GONE); } mToView = (MultiAutoCompleteTextView) findViewById(R.id.to); mCcView = (MultiAutoCompleteTextView) findViewById(R.id.cc); mBccView = (MultiAutoCompleteTextView) findViewById(R.id.bcc); mSubjectView = (EditText) findViewById(R.id.subject); mSubjectView.getInputExtras(true).putBoolean("allowEmoji", true); mAddToFromContacts = (ImageButton) findViewById(R.id.add_to); mAddCcFromContacts = (ImageButton) findViewById(R.id.add_cc); mAddBccFromContacts = (ImageButton) findViewById(R.id.add_bcc); mCcWrapper = (LinearLayout) findViewById(R.id.cc_wrapper); mBccWrapper = (LinearLayout) findViewById(R.id.bcc_wrapper); if (mAccount.isAlwaysShowCcBcc()) { onAddCcBcc(); } EolConvertingEditText upperSignature = (EolConvertingEditText)findViewById(R.id.upper_signature); EolConvertingEditText lowerSignature = (EolConvertingEditText)findViewById(R.id.lower_signature); mMessageContentView = (EolConvertingEditText)findViewById(R.id.message_content); mMessageContentView.getInputExtras(true).putBoolean("allowEmoji", true); mAttachments = (LinearLayout)findViewById(R.id.attachments); mQuotedTextShow = (Button)findViewById(R.id.quoted_text_show); mQuotedTextBar = findViewById(R.id.quoted_text_bar); mQuotedTextEdit = (ImageButton)findViewById(R.id.quoted_text_edit); mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete); mQuotedText = (EolConvertingEditText)findViewById(R.id.quoted_text); mQuotedText.getInputExtras(true).putBoolean("allowEmoji", true); mQuotedHTML = (MessageWebView) findViewById(R.id.quoted_html); mQuotedHTML.configure(); // Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone // feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130 mQuotedHTML.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } }); TextWatcher watcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } @Override public void afterTextChanged(android.text.Editable s) { /* do nothing */ } }; // For watching changes to the To:, Cc:, and Bcc: fields for auto-encryption on a matching // address. TextWatcher recipientWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } @Override public void afterTextChanged(android.text.Editable s) { final CryptoProvider crypto = mAccount.getCryptoProvider(); if (mAutoEncrypt && crypto.isAvailable(getApplicationContext())) { for (Address address : getRecipientAddresses()) { if (crypto.hasPublicKeyForEmail(getApplicationContext(), address.getAddress())) { mEncryptCheckbox.setChecked(true); mContinueWithoutPublicKey = false; break; } } } } }; TextWatcher sigwatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; mSignatureChanged = true; } @Override public void afterTextChanged(android.text.Editable s) { /* do nothing */ } }; mToView.addTextChangedListener(recipientWatcher); mCcView.addTextChangedListener(recipientWatcher); mBccView.addTextChangedListener(recipientWatcher); mSubjectView.addTextChangedListener(watcher); mMessageContentView.addTextChangedListener(watcher); mQuotedText.addTextChangedListener(watcher); /* Yes, there really are poeple who ship versions of android without a contact picker */ if (mContacts.hasContactPicker()) { mAddToFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_TO); } }); mAddCcFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_CC); } }); mAddBccFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_BCC); } }); } else { mAddToFromContacts.setVisibility(View.GONE); mAddCcFromContacts.setVisibility(View.GONE); mAddBccFromContacts.setVisibility(View.GONE); } /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ showOrHideQuotedText(QuotedTextMode.NONE); mQuotedTextShow.setOnClickListener(this); mQuotedTextEdit.setOnClickListener(this); mQuotedTextDelete.setOnClickListener(this); mToView.setAdapter(mAddressAdapter); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(mAddressValidator); mCcView.setAdapter(mAddressAdapter); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(mAddressValidator); mBccView.setAdapter(mAddressAdapter); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(mAddressValidator); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } if (initFromIntent(intent)) { mAction = Action.COMPOSE; mDraftNeedsSaving = true; } else { String action = intent.getAction(); if (ACTION_COMPOSE.equals(action)) { mAction = Action.COMPOSE; } else if (ACTION_REPLY.equals(action)) { mAction = Action.REPLY; } else if (ACTION_REPLY_ALL.equals(action)) { mAction = Action.REPLY_ALL; } else if (ACTION_FORWARD.equals(action)) { mAction = Action.FORWARD; } else if (ACTION_EDIT_DRAFT.equals(action)) { mAction = Action.EDIT_DRAFT; } else { // This shouldn't happen Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action"); mAction = Action.COMPOSE; } } if (mIdentity == null) { mIdentity = mAccount.getIdentity(0); } if (mAccount.isSignatureBeforeQuotedText()) { mSignatureView = upperSignature; lowerSignature.setVisibility(View.GONE); } else { mSignatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } mSignatureView.addTextChangedListener(sigwatcher); if (!mIdentity.getSignatureUse()) { mSignatureView.setVisibility(View.GONE); } mReadReceipt = mAccount.isMessageReadReceiptAlways(); mQuoteStyle = mAccount.getQuoteStyle(); updateFrom(); if (!mSourceMessageProcessed) { updateSignature(); if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.FORWARD || mAction == Action.EDIT_DRAFT) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't * want to reload the message every time the activity is resumed. * There is no harm in adding twice. */ MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } if (mAction != Action.EDIT_DRAFT) { addAddresses(mBccView, mAccount.getAlwaysBcc()); } } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { mMessageReference.flag = Flag.ANSWERED; } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.EDIT_DRAFT) { //change focus to message body. mMessageContentView.requestFocus(); } else { // Explicitly set focus to "To:" input field (see issue 2998) mToView.requestFocus(); } if (mAction == Action.FORWARD) { mMessageReference.flag = Flag.FORWARDED; } mEncryptLayout = findViewById(R.id.layout_encrypt); mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature); mCryptoSignatureUserId = (TextView)findViewById(R.id.userId); mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest); mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt); mEncryptCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateMessageFormat(); } }); if (mSourceMessageBody != null) { // mSourceMessageBody is set to something when replying to and forwarding decrypted // messages, so the sender probably wants the message to be encrypted. mEncryptCheckbox.setChecked(true); } initializeCrypto(); final CryptoProvider crypto = mAccount.getCryptoProvider(); if (crypto.isAvailable(this)) { mEncryptLayout.setVisibility(View.VISIBLE); mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { mPreventDraftSaving = true; if (!crypto.selectSecretKey(MessageCompose.this, mPgpData)) { mPreventDraftSaving = false; } checkBox.setChecked(false); } else { mPgpData.setSignatureKeyId(0); updateEncryptLayout(); } } }); if (mAccount.getCryptoAutoSignature()) { long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail()); if (ids != null && ids.length > 0) { mPgpData.setSignatureKeyId(ids[0]); mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0])); } else { mPgpData.setSignatureKeyId(0); mPgpData.setSignatureUserId(null); } } updateEncryptLayout(); mAutoEncrypt = mAccount.isCryptoAutoEncrypt(); } else { mEncryptLayout.setVisibility(View.GONE); } // Set font size of input controls int fontSize = mFontSizes.getMessageComposeInput(); mFontSizes.setViewTextSize(mToView, fontSize); mFontSizes.setViewTextSize(mCcView, fontSize); mFontSizes.setViewTextSize(mBccView, fontSize); mFontSizes.setViewTextSize(mSubjectView, fontSize); mFontSizes.setViewTextSize(mMessageContentView, fontSize); mFontSizes.setViewTextSize(mQuotedText, fontSize); mFontSizes.setViewTextSize(mSignatureView, fontSize); updateMessageFormat(); setTitle(); } /** * Handle external intents that trigger the message compose activity. * * <p> * Supported external intents: * <ul> * <li>{@link Intent#ACTION_VIEW}</li> * <li>{@link Intent#ACTION_SENDTO}</li> * <li>{@link Intent#ACTION_SEND}</li> * <li>{@link Intent#ACTION_SEND_MULTIPLE}</li> * </ul> * </p> * * @param intent * The (external) intent that started the activity. * * @return {@code true}, if this activity was started by an external intent. {@code false}, * otherwise. */ private boolean initFromIntent(final Intent intent) { boolean startedByExternalIntent = false; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { startedByExternalIntent = true; /* * Someone has clicked a mailto: link. The address is in the URI. */ if (intent.getData() != null) { Uri uri = intent.getData(); if ("mailto".equals(uri.getScheme())) { initializeFromMailto(uri); } } /* * Note: According to the documenation ACTION_VIEW and ACTION_SENDTO don't accept * EXTRA_* parameters. * And previously we didn't process these EXTRAs. But it looks like nobody bothers to * read the official documentation and just copies wrong sample code that happens to * work with the AOSP Email application. And because even big players get this wrong, * we're now finally giving in and read the EXTRAs for ACTION_SENDTO (below). */ } if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) || Intent.ACTION_SENDTO.equals(action)) { startedByExternalIntent = true; /* * Note: Here we allow a slight deviation from the documentated behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME * type of the intent. In addition one or multiple attachments can be added * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI if (text != null && mMessageContentView.getText().length() == 0) { mMessageContentView.setCharacters(text); } String type = intent.getType(); if (Intent.ACTION_SEND.equals(action)) { Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null) { addAttachment(stream, type); } } else { ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; if (stream != null) { addAttachment(stream, type); } } } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); // Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI if (subject != null && mSubjectView.getText().length() == 0) { mSubjectView.setText(subject); } String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC); String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC); if (extraEmail != null) { addRecipients(mToView, Arrays.asList(extraEmail)); } boolean ccOrBcc = false; if (extraCc != null) { ccOrBcc |= addRecipients(mCcView, Arrays.asList(extraCc)); } if (extraBcc != null) { ccOrBcc |= addRecipients(mBccView, Arrays.asList(extraBcc)); } if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } } return startedByExternalIntent; } private boolean addRecipients(TextView view, List<String> recipients) { if (recipients == null || recipients.size() == 0) { return false; } StringBuilder addressList = new StringBuilder(); // Read current contents of the TextView String text = view.getText().toString(); addressList.append(text); // Add comma if necessary if (text.length() != 0 && !(text.endsWith(", ") || text.endsWith(","))) { addressList.append(", "); } // Add recipients for (String recipient : recipients) { addressList.append(recipient); addressList.append(", "); } view.setText(addressList); return true; } private void initializeCrypto() { if (mPgpData != null) { return; } mPgpData = new PgpData(); } /** * Fill the encrypt layout with the latest data about signature key and encryption keys. */ public void updateEncryptLayout() { if (!mPgpData.hasSignatureKey()) { mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign); mCryptoSignatureCheckbox.setChecked(false); mCryptoSignatureUserId.setVisibility(View.INVISIBLE); mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE); } else { // if a signature key is selected, then the checkbox itself has no text mCryptoSignatureCheckbox.setText(""); mCryptoSignatureCheckbox.setChecked(true); mCryptoSignatureUserId.setVisibility(View.VISIBLE); mCryptoSignatureUserIdRest.setVisibility(View.VISIBLE); mCryptoSignatureUserId.setText(R.string.unknown_crypto_signature_user_id); mCryptoSignatureUserIdRest.setText(""); String userId = mPgpData.getSignatureUserId(); if (userId == null) { userId = mAccount.getCryptoProvider().getUserId(this, mPgpData.getSignatureKeyId()); mPgpData.setSignatureUserId(userId); } if (userId != null) { String chunks[] = mPgpData.getSignatureUserId().split(" <", 2); mCryptoSignatureUserId.setText(chunks[0]); if (chunks.length > 1) { mCryptoSignatureUserIdRest.setText("<" + chunks[1]); } } } updateMessageFormat(); } @Override public void onResume() { super.onResume(); mIgnoreOnPause = false; MessagingController.getInstance(getApplication()).addListener(mListener); } @Override public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mListener); // Save email as draft when activity is changed (go to home screen, call received) or screen locked // don't do this if only changing orientations if (!mIgnoreOnPause && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) { saveIfNeeded(); } } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Attachment list, * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); ArrayList<Attachment> attachments = new ArrayList<Attachment>(); for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { View view = mAttachments.getChildAt(i); Attachment attachment = (Attachment) view.getTag(); attachments.add(attachment); } outState.putInt(STATE_KEY_NUM_ATTACHMENTS_LOADING, mNumAttachmentsLoading); outState.putString(STATE_KEY_WAITING_FOR_ATTACHMENTS, mWaitingForAttachments.name()); outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, attachments); outState.putBoolean(STATE_KEY_CC_SHOWN, mCcWrapper.getVisibility() == View.VISIBLE); outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccWrapper.getVisibility() == View.VISIBLE); outState.putSerializable(STATE_KEY_QUOTED_TEXT_MODE, mQuotedTextMode); outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed); outState.putLong(STATE_KEY_DRAFT_ID, mDraftId); outState.putSerializable(STATE_IDENTITY, mIdentity); outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged); outState.putSerializable(STATE_PGP_DATA, mPgpData); outState.putString(STATE_IN_REPLY_TO, mInReplyTo); outState.putString(STATE_REFERENCES, mReferences); outState.putSerializable(STATE_KEY_HTML_QUOTE, mQuotedHtmlContent); outState.putBoolean(STATE_KEY_READ_RECEIPT, mReadReceipt); outState.putBoolean(STATE_KEY_DRAFT_NEEDS_SAVING, mDraftNeedsSaving); outState.putBoolean(STATE_KEY_FORCE_PLAIN_TEXT, mForcePlainText); outState.putSerializable(STATE_KEY_QUOTED_TEXT_FORMAT, mQuotedTextFormat); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mAttachments.removeAllViews(); mMaxLoaderId = 0; mNumAttachmentsLoading = savedInstanceState.getInt(STATE_KEY_NUM_ATTACHMENTS_LOADING); mWaitingForAttachments = WaitingAction.NONE; try { String waitingFor = savedInstanceState.getString(STATE_KEY_WAITING_FOR_ATTACHMENTS); mWaitingForAttachments = WaitingAction.valueOf(waitingFor); } catch (Exception e) { Log.w(K9.LOG_TAG, "Couldn't read value \" + STATE_KEY_WAITING_FOR_ATTACHMENTS +" + "\" from saved instance state", e); } ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS); for (Attachment attachment : attachments) { addAttachmentView(attachment); if (attachment.loaderId > mMaxLoaderId) { mMaxLoaderId = attachment.loaderId; } if (attachment.state == Attachment.LoadingState.URI_ONLY) { initAttachmentInfoLoader(attachment); } else if (attachment.state == Attachment.LoadingState.METADATA) { initAttachmentContentLoader(attachment); } } mReadReceipt = savedInstanceState .getBoolean(STATE_KEY_READ_RECEIPT); mCcWrapper.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE : View.GONE); mBccWrapper.setVisibility(savedInstanceState .getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE); // This method is called after the action bar menu has already been created and prepared. // So compute the visibility of the "Add Cc/Bcc" menu item again. computeAddCcBccVisibility(); mQuotedHtmlContent = (InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE); if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) { mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } mDraftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID); mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY); mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED); mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA); mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO); mReferences = savedInstanceState.getString(STATE_REFERENCES); mDraftNeedsSaving = savedInstanceState.getBoolean(STATE_KEY_DRAFT_NEEDS_SAVING); mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT); mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable( STATE_KEY_QUOTED_TEXT_FORMAT); showOrHideQuotedText( (QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE)); initializeCrypto(); updateFrom(); updateSignature(); updateEncryptLayout(); updateMessageFormat(); } private void setTitle() { switch (mAction) { case REPLY: { setTitle(R.string.compose_title_reply); break; } case REPLY_ALL: { setTitle(R.string.compose_title_reply_all); break; } case FORWARD: { setTitle(R.string.compose_title_forward); break; } case COMPOSE: default: { setTitle(R.string.compose_title_compose); break; } } } private void addAddresses(MultiAutoCompleteTextView view, String addresses) { if (StringUtils.isNullOrEmpty(addresses)) { return; } for (String address : addresses.split(",")) { addAddress(view, new Address(address, "")); } } private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) { if (addresses == null) { return; } for (Address address : addresses) { addAddress(view, address); } } private void addAddress(MultiAutoCompleteTextView view, Address address) { view.append(address + ", "); } private Address[] getAddresses(MultiAutoCompleteTextView view) { return Address.parseUnencoded(view.getText().toString().trim()); } /* * Returns an Address array of recipients this email will be sent to. * @return Address array of recipients this email will be sent to. */ private Address[] getRecipientAddresses() { String addresses = mToView.getText().toString() + mCcView.getText().toString() + mBccView.getText().toString(); return Address.parseUnencoded(addresses.trim()); } /* * Build the Body that will contain the text of the message. We'll decide where to * include it later. Draft messages are treated somewhat differently in that signatures are not * appended and HTML separators between composed text and quoted text are not added. * @param isDraft If we should build a message that will be saved as a draft (as opposed to sent). */ private TextBody buildText(boolean isDraft) { return buildText(isDraft, mMessageFormat); } /** * Build the {@link Body} that will contain the text of the message. * * <p> * Draft messages are treated somewhat differently in that signatures are not appended and HTML * separators between composed text and quoted text are not added. * </p> * * @param isDraft * If {@code true} we build a message that will be saved as a draft (as opposed to * sent). * @param messageFormat * Specifies what type of message to build ({@code text/plain} vs. {@code text/html}). * * @return {@link TextBody} instance that contains the entered text and possibly the quoted * original message. */ private TextBody buildText(boolean isDraft, SimpleMessageFormat messageFormat) { // The length of the formatted version of the user-supplied text/reply int composedMessageLength; // The offset of the user-supplied text/reply in the final text body int composedMessageOffset; /* * Find out if we need to include the original message as quoted text. * * We include the quoted text in the body if the user didn't choose to hide it. We always * include the quoted text when we're saving a draft. That's so the user is able to * "un-hide" the quoted text if (s)he opens a saved draft. */ boolean includeQuotedText = (mQuotedTextMode.equals(QuotedTextMode.SHOW) || isDraft); // Reply after quote makes no sense for HEADER style replies boolean replyAfterQuote = (mQuoteStyle == QuoteStyle.HEADER) ? false : mAccount.isReplyAfterQuote(); boolean signatureBeforeQuotedText = mAccount.isSignatureBeforeQuotedText(); // Get the user-supplied text String text = mMessageContentView.getCharacters(); // Handle HTML separate from the rest of the text content if (messageFormat == SimpleMessageFormat.HTML) { // Do we have to modify an existing message to include our reply? if (includeQuotedText && mQuotedHtmlContent != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "insertable: " + mQuotedHtmlContent.toDebugString()); } if (!isDraft) { // Append signature to the reply if (replyAfterQuote || signatureBeforeQuotedText) { text = appendSignature(text); } } // Convert the text to HTML text = HtmlConverter.textToHtmlFragment(text); /* * Set the insertion location based upon our reply after quote setting. * Additionally, add some extra separators between the composed message and quoted * message depending on the quote location. We only add the extra separators when * we're sending, that way when we load a draft, we don't have to know the length * of the separators to remove them before editing. */ if (replyAfterQuote) { mQuotedHtmlContent.setInsertionLocation( InsertableHtmlContent.InsertionLocation.AFTER_QUOTE); if (!isDraft) { text = "<br clear=\"all\">" + text; } } else { mQuotedHtmlContent.setInsertionLocation( InsertableHtmlContent.InsertionLocation.BEFORE_QUOTE); if (!isDraft) { text += "<br><br>"; } } if (!isDraft) { // Place signature immediately after the quoted text if (!(replyAfterQuote || signatureBeforeQuotedText)) { mQuotedHtmlContent.insertIntoQuotedFooter(getSignatureHtml()); } } mQuotedHtmlContent.setUserContent(text); // Save length of the body and its offset. This is used when thawing drafts. composedMessageLength = text.length(); composedMessageOffset = mQuotedHtmlContent.getInsertionPoint(); text = mQuotedHtmlContent.toString(); } else { // There is no text to quote so simply append the signature if available if (!isDraft) { text = appendSignature(text); } // Convert the text to HTML text = HtmlConverter.textToHtmlFragment(text); //TODO: Wrap this in proper HTML tags composedMessageLength = text.length(); composedMessageOffset = 0; } } else { // Capture composed message length before we start attaching quoted parts and signatures. composedMessageLength = text.length(); composedMessageOffset = 0; if (!isDraft) { // Append signature to the text/reply if (replyAfterQuote || signatureBeforeQuotedText) { text = appendSignature(text); } } String quotedText = mQuotedText.getCharacters(); if (includeQuotedText && quotedText.length() > 0) { if (replyAfterQuote) { composedMessageOffset = quotedText.length() + "\r\n".length(); text = quotedText + "\r\n" + text; } else { text += "\r\n\r\n" + quotedText.toString(); } } if (!isDraft) { // Place signature immediately after the quoted text if (!(replyAfterQuote || signatureBeforeQuotedText)) { text = appendSignature(text); } } } TextBody body = new TextBody(text); body.setComposedMessageLength(composedMessageLength); body.setComposedMessageOffset(composedMessageOffset); return body; } /** * Build the final message to be sent (or saved). If there is another message quoted in this one, it will be baked * into the final message here. * @param isDraft Indicates if this message is a draft or not. Drafts do not have signatures * appended and have some extra metadata baked into their header for use during thawing. * @return Message to be sent. * @throws MessagingException */ private MimeMessage createMessage(boolean isDraft) throws MessagingException { MimeMessage message = new MimeMessage(); message.addSentDate(new Date()); Address from = new Address(mIdentity.getEmail(), mIdentity.getName()); message.setFrom(from); message.setRecipients(RecipientType.TO, getAddresses(mToView)); message.setRecipients(RecipientType.CC, getAddresses(mCcView)); message.setRecipients(RecipientType.BCC, getAddresses(mBccView)); message.setSubject(mSubjectView.getText().toString()); if (mReadReceipt) { message.setHeader("Disposition-Notification-To", from.toEncodedString()); message.setHeader("X-Confirm-Reading-To", from.toEncodedString()); message.setHeader("Return-Receipt-To", from.toEncodedString()); } message.setHeader("User-Agent", getString(R.string.message_header_mua)); final String replyTo = mIdentity.getReplyTo(); if (replyTo != null) { message.setReplyTo(new Address[] { new Address(replyTo) }); } if (mInReplyTo != null) { message.setInReplyTo(mInReplyTo); } if (mReferences != null) { message.setReferences(mReferences); } // Build the body. // TODO FIXME - body can be either an HTML or Text part, depending on whether we're in // HTML mode or not. Should probably fix this so we don't mix up html and text parts. TextBody body = null; if (mPgpData.getEncryptedData() != null) { String text = mPgpData.getEncryptedData(); body = new TextBody(text); } else { body = buildText(isDraft); } // text/plain part when mMessageFormat == MessageFormat.HTML TextBody bodyPlain = null; final boolean hasAttachments = mAttachments.getChildCount() > 0; if (mMessageFormat == SimpleMessageFormat.HTML) { // HTML message (with alternative text part) // This is the compiled MIME part for an HTML message. MimeMultipart composedMimeMessage = new MimeMultipart(); composedMimeMessage.setSubType("alternative"); // Let the receiver select either the text or the HTML part. composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html")); bodyPlain = buildText(isDraft, SimpleMessageFormat.TEXT); composedMimeMessage.addBodyPart(new MimeBodyPart(bodyPlain, "text/plain")); if (hasAttachments) { // If we're HTML and have attachments, we have a MimeMultipart container to hold the // whole message (mp here), of which one part is a MimeMultipart container // (composedMimeMessage) with the user's composed messages, and subsequent parts for // the attachments. MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(composedMimeMessage)); addAttachmentsToMessage(mp); message.setBody(mp); } else { // If no attachments, our multipart/alternative part is the only one we need. message.setBody(composedMimeMessage); } } else if (mMessageFormat == SimpleMessageFormat.TEXT) { // Text-only message. if (hasAttachments) { MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(body, "text/plain")); addAttachmentsToMessage(mp); message.setBody(mp); } else { // No attachments to include, just stick the text body in the message and call it good. message.setBody(body); } } // If this is a draft, add metadata for thawing. if (isDraft) { // Add the identity to the message. message.addHeader(K9.IDENTITY_HEADER, buildIdentityHeader(body, bodyPlain)); } return message; } /** * Add attachments as parts into a MimeMultipart container. * @param mp MimeMultipart container in which to insert parts. * @throws MessagingException */ private void addAttachmentsToMessage(final MimeMultipart mp) throws MessagingException { Body body; for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag(); if (attachment.state != Attachment.LoadingState.COMPLETE) { continue; } String contentType = attachment.contentType; if (MimeUtil.isMessage(contentType)) { body = new TempFileMessageBody(attachment.filename); } else { body = new TempFileBody(attachment.filename); } MimeBodyPart bp = new MimeBodyPart(body); /* * Correctly encode the filename here. Otherwise the whole * header value (all parameters at once) will be encoded by * MimeHeader.writeTo(). */ bp.addHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\r\n name=\"%s\"", contentType, EncoderUtil.encodeIfNecessary(attachment.name, EncoderUtil.Usage.WORD_ENTITY, 7))); bp.setEncoding(MimeUtility.getEncodingforType(contentType)); /* * TODO: Oh the joys of MIME... * * From RFC 2183 (The Content-Disposition Header Field): * "Parameter values longer than 78 characters, or which * contain non-ASCII characters, MUST be encoded as specified * in [RFC 2184]." * * Example: * * Content-Type: application/x-stuff * title*1*=us-ascii'en'This%20is%20even%20more%20 * title*2*=%2A%2A%2Afun%2A%2A%2A%20 * title*3="isn't it!" */ bp.addHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format( "attachment;\r\n filename=\"%s\";\r\n size=%d", attachment.name, attachment.size)); mp.addBodyPart(bp); } } // FYI, there's nothing in the code that requires these variables to one letter. They're one // letter simply to save space. This name sucks. It's too similar to Account.Identity. private enum IdentityField { LENGTH("l"), OFFSET("o"), FOOTER_OFFSET("fo"), PLAIN_LENGTH("pl"), PLAIN_OFFSET("po"), MESSAGE_FORMAT("f"), MESSAGE_READ_RECEIPT("r"), SIGNATURE("s"), NAME("n"), EMAIL("e"), // TODO - store a reference to the message being replied so we can mark it at the time of send. ORIGINAL_MESSAGE("m"), CURSOR_POSITION("p"), // Where in the message your cursor was when you saved. QUOTED_TEXT_MODE("q"), QUOTE_STYLE("qs"); private final String value; IdentityField(String value) { this.value = value; } public String value() { return value; } /** * Get the list of IdentityFields that should be integer values. * * <p> * These values are sanity checked for integer-ness during decoding. * </p> * * @return The list of integer {@link IdentityField}s. */ public static IdentityField[] getIntegerFields() { return new IdentityField[] { LENGTH, OFFSET, FOOTER_OFFSET, PLAIN_LENGTH, PLAIN_OFFSET }; } } // Version identifier for "new style" identity. ! is an impossible value in base64 encoding, so we // use that to determine which version we're in. private static final String IDENTITY_VERSION_1 = "!"; /** * Build the identity header string. This string contains metadata about a draft message to be * used upon loading a draft for composition. This should be generated at the time of saving a * draft.<br> * <br> * This is a URL-encoded key/value pair string. The list of possible values are in {@link IdentityField}. * @param body {@link TextBody} to analyze for body length and offset. * @param bodyPlain {@link TextBody} to analyze for body length and offset. May be null. * @return Identity string. */ private String buildIdentityHeader(final TextBody body, final TextBody bodyPlain) { Uri.Builder uri = new Uri.Builder(); if (body.getComposedMessageLength() != null && body.getComposedMessageOffset() != null) { // See if the message body length is already in the TextBody. uri.appendQueryParameter(IdentityField.LENGTH.value(), body.getComposedMessageLength().toString()); uri.appendQueryParameter(IdentityField.OFFSET.value(), body.getComposedMessageOffset().toString()); } else { // If not, calculate it now. uri.appendQueryParameter(IdentityField.LENGTH.value(), Integer.toString(body.getText().length())); uri.appendQueryParameter(IdentityField.OFFSET.value(), Integer.toString(0)); } if (mQuotedHtmlContent != null) { uri.appendQueryParameter(IdentityField.FOOTER_OFFSET.value(), Integer.toString(mQuotedHtmlContent.getFooterInsertionPoint())); } if (bodyPlain != null) { if (bodyPlain.getComposedMessageLength() != null && bodyPlain.getComposedMessageOffset() != null) { // See if the message body length is already in the TextBody. uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), bodyPlain.getComposedMessageLength().toString()); uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), bodyPlain.getComposedMessageOffset().toString()); } else { // If not, calculate it now. uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), Integer.toString(body.getText().length())); uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), Integer.toString(0)); } } // Save the quote style (useful for forwards). uri.appendQueryParameter(IdentityField.QUOTE_STYLE.value(), mQuoteStyle.name()); // Save the message format for this offset. uri.appendQueryParameter(IdentityField.MESSAGE_FORMAT.value(), mMessageFormat.name()); // If we're not using the standard identity of signature, append it on to the identity blob. if (mIdentity.getSignatureUse() && mSignatureChanged) { uri.appendQueryParameter(IdentityField.SIGNATURE.value(), mSignatureView.getCharacters()); } if (mIdentityChanged) { uri.appendQueryParameter(IdentityField.NAME.value(), mIdentity.getName()); uri.appendQueryParameter(IdentityField.EMAIL.value(), mIdentity.getEmail()); } if (mMessageReference != null) { uri.appendQueryParameter(IdentityField.ORIGINAL_MESSAGE.value(), mMessageReference.toIdentityString()); } uri.appendQueryParameter(IdentityField.CURSOR_POSITION.value(), Integer.toString(mMessageContentView.getSelectionStart())); uri.appendQueryParameter(IdentityField.QUOTED_TEXT_MODE.value(), mQuotedTextMode.name()); String k9identity = IDENTITY_VERSION_1 + uri.build().getEncodedQuery(); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Generated identity: " + k9identity); } return k9identity; } /** * Parse an identity string. Handles both legacy and new (!) style identities. * * @param identityString * The encoded identity string that was saved in a drafts header. * * @return A map containing the value for each {@link IdentityField} in the identity string. */ private Map<IdentityField, String> parseIdentityHeader(final String identityString) { Map<IdentityField, String> identity = new HashMap<IdentityField, String>(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Decoding identity: " + identityString); if (identityString == null || identityString.length() < 1) { return identity; } // Check to see if this is a "next gen" identity. if (identityString.charAt(0) == IDENTITY_VERSION_1.charAt(0) && identityString.length() > 2) { Uri.Builder builder = new Uri.Builder(); builder.encodedQuery(identityString.substring(1)); // Need to cut off the ! at the beginning. Uri uri = builder.build(); for (IdentityField key : IdentityField.values()) { String value = uri.getQueryParameter(key.value()); if (value != null) { identity.put(key, value); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Decoded identity: " + identity.toString()); // Sanity check our Integers so that recipients of this result don't have to. for (IdentityField key : IdentityField.getIntegerFields()) { if (identity.get(key) != null) { try { Integer.parseInt(identity.get(key)); } catch (NumberFormatException e) { Log.e(K9.LOG_TAG, "Invalid " + key.name() + " field in identity: " + identity.get(key)); } } } } else { // Legacy identity if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got a saved legacy identity: " + identityString); StringTokenizer tokens = new StringTokenizer(identityString, ":", false); // First item is the body length. We use this to separate the composed reply from the quoted text. if (tokens.hasMoreTokens()) { String bodyLengthS = Utility.base64Decode(tokens.nextToken()); try { identity.put(IdentityField.LENGTH, Integer.valueOf(bodyLengthS).toString()); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'"); } } if (tokens.hasMoreTokens()) { identity.put(IdentityField.SIGNATURE, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.NAME, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.EMAIL, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.QUOTED_TEXT_MODE, Utility.base64Decode(tokens.nextToken())); } } return identity; } private String appendSignature(String originalText) { String text = originalText; if (mIdentity.getSignatureUse()) { String signature = mSignatureView.getCharacters(); if (signature != null && !signature.contentEquals("")) { text += "\r\n" + signature; } } return text; } /** * Get an HTML version of the signature in the #mSignatureView, if any. * @return HTML version of signature. */ private String getSignatureHtml() { String signature = ""; if (mIdentity.getSignatureUse()) { signature = mSignatureView.getCharacters(); if(!StringUtils.isNullOrEmpty(signature)) { signature = HtmlConverter.textToHtmlFragment("\r\n" + signature); } } return signature; } private void sendMessage() { new SendMessageTask().execute(); } private void saveMessage() { new SaveMessageTask().execute(); } private void saveIfNeeded() { if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys() || mEncryptCheckbox.isChecked() || !mAccount.hasDraftsFolder()) { return; } mDraftNeedsSaving = false; saveMessage(); } public void onEncryptionKeySelectionDone() { if (mPgpData.hasEncryptionKeys()) { onSend(); } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } public void onEncryptDone() { if (mPgpData.getEncryptedData() != null) { onSend(); } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } private void onSend() { if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) { mToView.setError(getString(R.string.message_compose_error_no_recipients)); Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show(); return; } if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SEND; showWaitingForAttachmentDialog(); } else { performSend(); } } private void performSend() { final CryptoProvider crypto = mAccount.getCryptoProvider(); if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) { // key selection before encryption StringBuilder emails = new StringBuilder(); for (Address address : getRecipientAddresses()) { if (emails.length() != 0) { emails.append(','); } emails.append(address.getAddress()); if (!mContinueWithoutPublicKey && !crypto.hasPublicKeyForEmail(this, address.getAddress())) { showDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); return; } } if (emails.length() != 0) { emails.append(','); } emails.append(mIdentity.getEmail()); mPreventDraftSaving = true; if (!crypto.selectEncryptionKeys(MessageCompose.this, emails.toString(), mPgpData)) { mPreventDraftSaving = false; } return; } if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) { if (mPgpData.getEncryptedData() == null) { String text = buildText(false).getText(); mPreventDraftSaving = true; if (!crypto.encrypt(this, text, mPgpData)) { mPreventDraftSaving = false; } return; } } sendMessage(); if (mMessageReference != null && mMessageReference.flag != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Setting referenced message (" + mMessageReference.folderName + ", " + mMessageReference.uid + ") flag to " + mMessageReference.flag); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).setFlag(account, folderName, sourceMessageUid, mMessageReference.flag, true); } mDraftNeedsSaving = false; finish(); } private void onDiscard() { if (mDraftId != INVALID_DRAFT_ID) { MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftId); mDraftId = INVALID_DRAFT_ID; } mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT); mDraftNeedsSaving = false; finish(); } private void onSave() { if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SAVE; showWaitingForAttachmentDialog(); } else { performSave(); } } private void performSave() { saveIfNeeded(); finish(); } private void onAddCcBcc() { mCcWrapper.setVisibility(View.VISIBLE); mBccWrapper.setVisibility(View.VISIBLE); computeAddCcBccVisibility(); } /** * Hide the 'Add Cc/Bcc' menu item when both fields are visible. */ private void computeAddCcBccVisibility() { if (mMenu != null && mCcWrapper.getVisibility() == View.VISIBLE && mBccWrapper.getVisibility() == View.VISIBLE) { mMenu.findItem(R.id.add_cc_bcc).setVisible(false); } } private void onReadReceipt() { CharSequence txt; if (mReadReceipt == false) { txt = getString(R.string.read_receipt_enabled); mReadReceipt = true; } else { txt = getString(R.string.read_receipt_disabled); mReadReceipt = false; } Context context = getApplicationContext(); Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } /** * Kick off a picker for whatever kind of MIME types we'll accept and let Android take over. */ private void onAddAttachment() { if (K9.isGalleryBuggy()) { if (K9.useGalleryBugWorkaround()) { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_use_workaround), Toast.LENGTH_LONG).show(); } else { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_buggy_gallery), Toast.LENGTH_LONG).show(); } } onAddAttachment2("*/*"); } /** * Kick off a picker for the specified MIME type and let Android take over. * * @param mime_type * The MIME type we want our attachment to have. */ private void onAddAttachment2(final String mime_type) { if (mAccount.getCryptoProvider().isAvailable(this)) { Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show(); } Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(mime_type); mIgnoreOnPause = true; startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT); } private void addAttachment(Uri uri) { addAttachment(uri, null); } private void addAttachment(Uri uri, String contentType) { Attachment attachment = new Attachment(); attachment.state = Attachment.LoadingState.URI_ONLY; attachment.uri = uri; attachment.contentType = contentType; attachment.loaderId = ++mMaxLoaderId; addAttachmentView(attachment); initAttachmentInfoLoader(attachment); } private void initAttachmentInfoLoader(Attachment attachment) { LoaderManager loaderManager = getSupportLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentInfoLoaderCallback); } private void initAttachmentContentLoader(Attachment attachment) { LoaderManager loaderManager = getSupportLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentContentLoaderCallback); } private void addAttachmentView(Attachment attachment) { boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY); boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE); View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachments, false); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); View progressBar = view.findViewById(R.id.progressBar); if (hasMetadata) { nameView.setText(attachment.name); } else { nameView.setText(R.string.loading_attachment); } progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE); ImageButton delete = (ImageButton) view.findViewById(R.id.attachment_delete); delete.setOnClickListener(MessageCompose.this); delete.setTag(view); view.setTag(attachment); mAttachments.addView(view); } private View getAttachmentView(int loaderId) { for (int i = 0, childCount = mAttachments.getChildCount(); i < childCount; i++) { View view = mAttachments.getChildAt(i); Attachment tag = (Attachment) view.getTag(); if (tag != null && tag.loaderId == loaderId) { return view; } } return null; } private LoaderManager.LoaderCallbacks<Attachment> mAttachmentInfoLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { onFetchAttachmentStarted(); Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentInfoLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { view.setTag(attachment); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); nameView.setText(attachment.name); attachment.loaderId = ++mMaxLoaderId; initAttachmentContentLoader(attachment); } else { onFetchAttachmentFinished(); } getSupportLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; private LoaderManager.LoaderCallbacks<Attachment> mAttachmentContentLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentContentLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { if (attachment.state == Attachment.LoadingState.COMPLETE) { view.setTag(attachment); View progressBar = view.findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); } else { mAttachments.removeView(view); } } onFetchAttachmentFinished(); getSupportLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; private void onFetchAttachmentStarted() { mNumAttachmentsLoading += 1; } private void onFetchAttachmentFinished() { // We're not allowed to perform fragment transactions when called from onLoadFinished(). // So we use the Handler to call performStalledAction(). mHandler.sendEmptyMessage(MSG_PERFORM_STALLED_ACTION); } private void performStalledAction() { mNumAttachmentsLoading -= 1; WaitingAction waitingFor = mWaitingForAttachments; mWaitingForAttachments = WaitingAction.NONE; if (waitingFor != WaitingAction.NONE) { dismissWaitingForAttachmentDialog(); } switch (waitingFor) { case SEND: { performSend(); break; } case SAVE: { performSave(); break; } case NONE: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true mPreventDraftSaving = false; if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) { return; } if (resultCode != RESULT_OK) return; if (data == null) { return; } switch (requestCode) { case ACTIVITY_REQUEST_PICK_ATTACHMENT: addAttachment(data.getData()); mDraftNeedsSaving = true; break; case CONTACT_PICKER_TO: case CONTACT_PICKER_CC: case CONTACT_PICKER_BCC: ContactItem contact = mContacts.extractInfoFromContactPickerIntent(data); if (contact == null) { Toast.makeText(this, getString(R.string.error_contact_address_not_found), Toast.LENGTH_LONG).show(); return; } if (contact.emailAddresses.size() > 1) { Intent i = new Intent(this, EmailAddressList.class); i.putExtra(EmailAddressList.EXTRA_CONTACT_ITEM, contact); if (requestCode == CONTACT_PICKER_TO) { startActivityForResult(i, CONTACT_PICKER_TO2); } else if (requestCode == CONTACT_PICKER_CC) { startActivityForResult(i, CONTACT_PICKER_CC2); } else if (requestCode == CONTACT_PICKER_BCC) { startActivityForResult(i, CONTACT_PICKER_BCC2); } return; } if (K9.DEBUG) { List<String> emails = contact.emailAddresses; for (int i = 0; i < emails.size(); i++) { Log.v(K9.LOG_TAG, "email[" + i + "]: " + emails.get(i)); } } String email = contact.emailAddresses.get(0); if (requestCode == CONTACT_PICKER_TO) { addAddress(mToView, new Address(email, "")); } else if (requestCode == CONTACT_PICKER_CC) { addAddress(mCcView, new Address(email, "")); } else if (requestCode == CONTACT_PICKER_BCC) { addAddress(mBccView, new Address(email, "")); } else { return; } break; case CONTACT_PICKER_TO2: case CONTACT_PICKER_CC2: case CONTACT_PICKER_BCC2: String emailAddr = data.getStringExtra(EmailAddressList.EXTRA_EMAIL_ADDRESS); if (requestCode == CONTACT_PICKER_TO2) { addAddress(mToView, new Address(emailAddr, "")); } else if (requestCode == CONTACT_PICKER_CC2) { addAddress(mCcView, new Address(emailAddr, "")); } else if (requestCode == CONTACT_PICKER_BCC2) { addAddress(mBccView, new Address(emailAddr, "")); } break; } } public void doLaunchContactPicker(int resultId) { mIgnoreOnPause = true; startActivityForResult(mContacts.contactPickerIntent(), resultId); } private void onAccountChosen(Account account, Identity identity) { if (!mAccount.equals(account)) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account); } // on draft edit, make sure we don't keep previous message UID if (mAction == Action.EDIT_DRAFT) { mMessageReference = null; } // test whether there is something to save if (mDraftNeedsSaving || (mDraftId != INVALID_DRAFT_ID)) { final long previousDraftId = mDraftId; final Account previousAccount = mAccount; // make current message appear as new mDraftId = INVALID_DRAFT_ID; // actual account switch mAccount = account; if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); } saveMessage(); if (previousDraftId != INVALID_DRAFT_ID) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftId); } MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } } else { mAccount = account; } // Show CC/BCC text input field when switching to an account that always wants them // displayed. // Please note that we're not hiding the fields if the user switches back to an account // that doesn't have this setting checked. if (mAccount.isAlwaysShowCcBcc()) { onAddCcBcc(); } // not sure how to handle mFolder, mSourceMessage? } switchToIdentity(identity); } private void switchToIdentity(Identity identity) { mIdentity = identity; mIdentityChanged = true; mDraftNeedsSaving = true; updateFrom(); updateBcc(); updateSignature(); updateMessageFormat(); } private void updateFrom() { mChooseIdentityButton.setText(mIdentity.getEmail()); } private void updateBcc() { if (mIdentityChanged) { mBccWrapper.setVisibility(View.VISIBLE); } mBccView.setText(""); addAddresses(mBccView, mAccount.getAlwaysBcc()); } private void updateSignature() { if (mIdentity.getSignatureUse()) { mSignatureView.setCharacters(mIdentity.getSignature()); mSignatureView.setVisibility(View.VISIBLE); } else { mSignatureView.setVisibility(View.GONE); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.attachment_delete: /* * The view is the delete button, and we have previously set the tag of * the delete button to the view that owns it. We don't use parent because the * view is very complex and could change in the future. */ mAttachments.removeView((View) view.getTag()); mDraftNeedsSaving = true; break; case R.id.quoted_text_show: showOrHideQuotedText(QuotedTextMode.SHOW); updateMessageFormat(); mDraftNeedsSaving = true; break; case R.id.quoted_text_delete: showOrHideQuotedText(QuotedTextMode.HIDE); updateMessageFormat(); mDraftNeedsSaving = true; break; case R.id.quoted_text_edit: mForcePlainText = true; if (mMessageReference != null) { // shouldn't happen... // TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call? MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } break; case R.id.identity: showDialog(DIALOG_CHOOSE_IDENTITY); break; } } /** * Show or hide the quoted text. * * @param mode * The value to set {@link #mQuotedTextMode} to. */ private void showOrHideQuotedText(QuotedTextMode mode) { mQuotedTextMode = mode; switch (mode) { case NONE: case HIDE: { if (mode == QuotedTextMode.NONE) { mQuotedTextShow.setVisibility(View.GONE); } else { mQuotedTextShow.setVisibility(View.VISIBLE); } mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); break; } case SHOW: { mQuotedTextShow.setVisibility(View.GONE); mQuotedTextBar.setVisibility(View.VISIBLE); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.VISIBLE); mQuotedTextEdit.setVisibility(View.VISIBLE); } else { mQuotedText.setVisibility(View.VISIBLE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); } break; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send: mPgpData.setEncryptionKeys(null); onSend(); break; case R.id.save: if (mEncryptCheckbox.isChecked()) { showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } else { onSave(); } break; case R.id.discard: onDiscard(); break; case R.id.add_cc_bcc: onAddCcBcc(); break; case R.id.add_attachment: onAddAttachment(); break; case R.id.add_attachment_image: onAddAttachment2("image/*"); break; case R.id.add_attachment_video: onAddAttachment2("video/*"); break; case R.id.read_receipt: onReadReceipt(); default: return super.onOptionsItemSelected(item); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.message_compose_option, menu); mMenu = menu; // Disable the 'Save' menu option if Drafts folder is set to -NONE- if (!mAccount.hasDraftsFolder()) { menu.findItem(R.id.save).setEnabled(false); } /* * Show the menu items "Add attachment (Image)" and "Add attachment (Video)" * if the work-around for the Gallery bug is enabled (see Issue 1186). */ menu.findItem(R.id.add_attachment_image).setVisible(K9.useGalleryBugWorkaround()); menu.findItem(R.id.add_attachment_video).setVisible(K9.useGalleryBugWorkaround()); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); computeAddCcBccVisibility(); return true; } @Override public void onBackPressed() { if (mDraftNeedsSaving) { if (mEncryptCheckbox.isChecked()) { showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } else if (!mAccount.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } else { // Check if editing an existing draft. if (mDraftId == INVALID_DRAFT_ID) { onDiscard(); } else { super.onBackPressed(); } } } private void showWaitingForAttachmentDialog() { String title; switch (mWaitingForAttachments) { case SEND: { title = getString(R.string.fetching_attachment_dialog_title_send); break; } case SAVE: { title = getString(R.string.fetching_attachment_dialog_title_save); break; } default: { return; } } ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title, getString(R.string.fetching_attachment_dialog_message)); fragment.show(getSupportFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT); } public void onCancel(ProgressDialogFragment fragment) { attachmentProgressDialogCancelled(); } void attachmentProgressDialogCancelled() { mWaitingForAttachments = WaitingAction.NONE; } private void dismissWaitingForAttachmentDialog() { ProgressDialogFragment fragment = (ProgressDialogFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT); if (fragment != null) { fragment.dismiss(); } } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.save_or_discard_draft_message_dlg_title) .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onSave(); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onDiscard(); } }) .create(); case DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED: return new AlertDialog.Builder(this) .setTitle(R.string.refuse_to_save_draft_marked_encrypted_dlg_title) .setMessage(R.string.refuse_to_save_draft_marked_encrypted_instructions_fmt) .setNeutralButton(R.string.okay_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } }) .create(); case DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY: return new AlertDialog.Builder(this) .setTitle(R.string.continue_without_public_key_dlg_title) .setMessage(R.string.continue_without_public_key_instructions_fmt) .setPositiveButton(R.string.continue_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); mContinueWithoutPublicKey = true; onSend(); } }) .setNegativeButton(R.string.back_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); mContinueWithoutPublicKey = false; } }) .create(); case DIALOG_CONFIRM_DISCARD_ON_BACK: return new AlertDialog.Builder(this) .setTitle(R.string.confirm_discard_draft_message_title) .setMessage(R.string.confirm_discard_draft_message) .setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); Toast.makeText(MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); onDiscard(); } }) .create(); case DIALOG_CHOOSE_IDENTITY: Context context = new ContextThemeWrapper(this, (K9.getK9Theme() == K9.Theme.LIGHT) ? R.style.Theme_K9_Dialog_Light : R.style.Theme_K9_Dialog_Dark); Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.send_as); final IdentityAdapter adapter = new IdentityAdapter(context); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IdentityContainer container = (IdentityContainer) adapter.getItem(which); onAccountChosen(container.account, container.identity); } }); return builder.create(); } return super.onCreateDialog(id); } /** * Add all attachments of an existing message as if they were added by hand. * * @param part * The message part to check for being an attachment. This method will recurse if it's * a multipart part. * @param depth * The recursion depth. Currently unused. * * @return {@code true} if all attachments were able to be attached, {@code false} otherwise. * * @throws MessagingException * In case of an error */ private boolean loadAttachments(Part part, int depth) throws MessagingException { if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); boolean ret = true; for (int i = 0, count = mp.getCount(); i < count; i++) { if (!loadAttachments(mp.getBodyPart(i), depth + 1)) { ret = false; } } return ret; } String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String name = MimeUtility.getHeaderParameter(contentType, "name"); if (name != null) { Body body = part.getBody(); if (body != null && body instanceof LocalAttachmentBody) { final Uri uri = ((LocalAttachmentBody) body).getContentUri(); mHandler.post(new Runnable() { @Override public void run() { addAttachment(uri); } }); } else { return false; } } return true; } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * * @param message * The source message used to populate the various text fields. */ private void processSourceMessage(Message message) { try { switch (mAction) { case REPLY: case REPLY_ALL: { processMessageToReplyTo(message); break; } case FORWARD: { processMessageToForward(message); break; } case EDIT_DRAFT: { processDraftMessage(message); break; } default: { Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action"); break; } } } catch (MessagingException me) { /** * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ Log.e(K9.LOG_TAG, "Error while processing source message: ", me); } finally { mSourceMessageProcessed = true; mDraftNeedsSaving = false; } updateMessageFormat(); } private void processMessageToReplyTo(Message message) throws MessagingException { if (message.getSubject() != null) { final String subject = PREFIX.matcher(message.getSubject()).replaceFirst(""); if (!subject.toLowerCase(Locale.US).startsWith("re:")) { mSubjectView.setText("Re: " + subject); } else { mSubjectView.setText(subject); } } else { mSubjectView.setText(""); } /* * If a reply-to was included with the message use that, otherwise use the from * or sender address. */ Address[] replyToAddresses; if (message.getReplyTo().length > 0) { replyToAddresses = message.getReplyTo(); } else { replyToAddresses = message.getFrom(); } // if we're replying to a message we sent, we probably meant // to reply to the recipient of that message if (mAccount.isAnIdentity(replyToAddresses)) { replyToAddresses = message.getRecipients(RecipientType.TO); } addAddresses(mToView, replyToAddresses); if (message.getMessageId() != null && message.getMessageId().length() > 0) { mInReplyTo = message.getMessageId(); if (message.getReferences() != null && message.getReferences().length > 0) { StringBuilder buffy = new StringBuilder(); for (int i = 0; i < message.getReferences().length; i++) buffy.append(message.getReferences()[i]); mReferences = buffy.toString() + " " + mInReplyTo; } else { mReferences = mInReplyTo; } } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "could not get Message-ID."); } // Quote the message and setup the UI. populateUIWithQuotedMessage(mAccount.isDefaultQuotedTextShown()); if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { Identity useIdentity = null; for (Address address : message.getRecipients(RecipientType.TO)) { Identity identity = mAccount.findIdentity(address); if (identity != null) { useIdentity = identity; break; } } if (useIdentity == null) { if (message.getRecipients(RecipientType.CC).length > 0) { for (Address address : message.getRecipients(RecipientType.CC)) { Identity identity = mAccount.findIdentity(address); if (identity != null) { useIdentity = identity; break; } } } } if (useIdentity != null) { Identity defaultIdentity = mAccount.getIdentity(0); if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } if (mAction == Action.REPLY_ALL) { if (message.getReplyTo().length > 0) { for (Address address : message.getFrom()) { if (!mAccount.isAnIdentity(address)) { addAddress(mToView, address); } } } for (Address address : message.getRecipients(RecipientType.TO)) { if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) { addAddress(mToView, address); } } if (message.getRecipients(RecipientType.CC).length > 0) { for (Address address : message.getRecipients(RecipientType.CC)) { if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) { addAddress(mCcView, address); } } mCcWrapper.setVisibility(View.VISIBLE); } } } private void processMessageToForward(Message message) throws MessagingException { String subject = message.getSubject(); if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) { mSubjectView.setText("Fwd: " + subject); } else { mSubjectView.setText(subject); } mQuoteStyle = QuoteStyle.HEADER; // "Be Like Thunderbird" - on forwarded messages, set the message ID // of the forwarded message in the references and the reply to. TB // only includes ID of the message being forwarded in the reference, // even if there are multiple references. if (!StringUtils.isNullOrEmpty(message.getMessageId())) { mInReplyTo = message.getMessageId(); mReferences = mInReplyTo; } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. populateUIWithQuotedMessage(true); if (!mSourceMessageProcessed) { if (!loadAttachments(message, 0)) { mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS); } } } private void processDraftMessage(Message message) throws MessagingException { String showQuotedTextMode = "NONE"; mDraftId = MessagingController.getInstance(getApplication()).getId(message); mSubjectView.setText(message.getSubject()); addAddresses(mToView, message.getRecipients(RecipientType.TO)); if (message.getRecipients(RecipientType.CC).length > 0) { addAddresses(mCcView, message.getRecipients(RecipientType.CC)); mCcWrapper.setVisibility(View.VISIBLE); } Address[] bccRecipients = message.getRecipients(RecipientType.BCC); if (bccRecipients.length > 0) { addAddresses(mBccView, bccRecipients); String bccAddress = mAccount.getAlwaysBcc(); if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) { // If the auto-bcc is the only entry in the BCC list, don't show the Bcc fields. mBccWrapper.setVisibility(View.GONE); } else { mBccWrapper.setVisibility(View.VISIBLE); } } // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); if ((inReplyTo != null) && (inReplyTo.length >= 1)) { mInReplyTo = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); if ((references != null) && (references.length >= 1)) { mReferences = references[0]; } if (!mSourceMessageProcessed) { loadAttachments(message, 0); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map<IdentityField, String> k9identity = new HashMap<IdentityField, String>(); if (message.getHeader(K9.IDENTITY_HEADER) != null && message.getHeader(K9.IDENTITY_HEADER).length > 0 && message.getHeader(K9.IDENTITY_HEADER)[0] != null) { k9identity = parseIdentityHeader(message.getHeader(K9.IDENTITY_HEADER)[0]); } Identity newIdentity = new Identity(); if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); mSignatureChanged = true; } else { newIdentity.setSignatureUse(message.getFolder().getAccount().getSignatureUse()); newIdentity.setSignature(mIdentity.getSignature()); } if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); mIdentityChanged = true; } else { newIdentity.setName(mIdentity.getName()); } if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); mIdentityChanged = true; } else { newIdentity.setEmail(mIdentity.getEmail()); } if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { mMessageReference = null; try { String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE); MessageReference messageReference = new MessageReference(originalMessage); // Check if this is a valid account in our database Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.accountUuid); if (account != null) { mMessageReference = messageReference; } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e); } } int cursorPosition = 0; if (k9identity.containsKey(IdentityField.CURSOR_POSITION)) { try { cursorPosition = Integer.valueOf(k9identity.get(IdentityField.CURSOR_POSITION)).intValue(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e); } } if (k9identity.containsKey(IdentityField.QUOTED_TEXT_MODE)) { showQuotedTextMode = k9identity.get(IdentityField.QUOTED_TEXT_MODE); } mIdentity = newIdentity; updateSignature(); updateFrom(); Integer bodyLength = k9identity.get(IdentityField.LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.LENGTH)) : 0; Integer bodyOffset = k9identity.get(IdentityField.OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.OFFSET)) : 0; Integer bodyFooterOffset = k9identity.get(IdentityField.FOOTER_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.FOOTER_OFFSET)) : null; Integer bodyPlainLength = k9identity.get(IdentityField.PLAIN_LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_LENGTH)) : null; Integer bodyPlainOffset = k9identity.get(IdentityField.PLAIN_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_OFFSET)) : null; mQuoteStyle = k9identity.get(IdentityField.QUOTE_STYLE) != null ? QuoteStyle.valueOf(k9identity.get(IdentityField.QUOTE_STYLE)) : mAccount.getQuoteStyle(); QuotedTextMode quotedMode; try { quotedMode = QuotedTextMode.valueOf(showQuotedTextMode); } catch (Exception e) { quotedMode = QuotedTextMode.NONE; } // Always respect the user's current composition format preference, even if the // draft was saved in a different format. // TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail. String messageFormatString = k9identity.get(IdentityField.MESSAGE_FORMAT); MessageFormat messageFormat = null; if (messageFormatString != null) { try { messageFormat = MessageFormat.valueOf(messageFormatString); } catch (Exception e) { /* do nothing */ } } if (messageFormat == null) { // This message probably wasn't created by us. The exception is legacy // drafts created before the advent of HTML composition. In those cases, // we'll display the whole message (including the quoted part) in the // composition window. If that's the case, try and convert it to text to // match the behavior in text mode. mMessageContentView.setCharacters(getBodyTextFromMessage(message, SimpleMessageFormat.TEXT)); mForcePlainText = true; showOrHideQuotedText(quotedMode); return; } if (messageFormat == MessageFormat.HTML) { Part part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { // Shouldn't happen if we were the one who saved it. mQuotedTextFormat = SimpleMessageFormat.HTML; String text = MimeUtility.getTextFromPart(part); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } if (bodyOffset + bodyLength > text.length()) { // The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid LENGTH/OFFSET"); bodyOffset = 0; bodyLength = 0; } // Grab our reply text. String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); mMessageContentView.setCharacters(HtmlConverter.htmlToText(bodyText)); // Regenerate the quoted html without our user content in it. StringBuilder quotedHTML = new StringBuilder(); quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply quotedHTML.append(text.substring(bodyOffset + bodyLength)); if (quotedHTML.length() > 0) { mQuotedHtmlContent = new InsertableHtmlContent(); mQuotedHtmlContent.setQuotedContent(quotedHTML); // We don't know if bodyOffset refers to the header or to the footer mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset); if (bodyFooterOffset != null) { mQuotedHtmlContent.setFooterInsertionPoint(bodyFooterOffset); } else { mQuotedHtmlContent.setFooterInsertionPoint(bodyOffset); } mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } } if (bodyPlainOffset != null && bodyPlainLength != null) { processSourceMessageText(message, bodyPlainOffset, bodyPlainLength, false); } } else if (messageFormat == MessageFormat.TEXT) { mQuotedTextFormat = SimpleMessageFormat.TEXT; processSourceMessageText(message, bodyOffset, bodyLength, true); } else { Log.e(K9.LOG_TAG, "Unhandled message format."); } // Set the cursor position if we have it. try { mMessageContentView.setSelection(cursorPosition); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e); } showOrHideQuotedText(quotedMode); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * @param message Source message * @param bodyOffset Insertion point for reply. * @param bodyLength Length of reply. * @param viewMessageContent Update mMessageContentView or not. * @throws MessagingException */ private void processSourceMessageText(Message message, Integer bodyOffset, Integer bodyLength, boolean viewMessageContent) throws MessagingException { Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (textPart != null) { String text = MimeUtility.getTextFromPart(textPart); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } // If we had a body length (and it was valid), separate the composition from the quoted text // and put them in their respective places in the UI. if (bodyLength > 0) { try { String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); // Regenerate the quoted text without our user content in it nor added newlines. StringBuilder quotedText = new StringBuilder(); if (bodyOffset == 0 && text.substring(bodyLength, bodyLength + 4).equals("\r\n\r\n")) { // top-posting: ignore two newlines at start of quote quotedText.append(text.substring(bodyLength + 4)); } else if (bodyOffset + bodyLength == text.length() && text.substring(bodyOffset - 2, bodyOffset).equals("\r\n")) { // bottom-posting: ignore newline at end of quote quotedText.append(text.substring(0, bodyOffset - 2)); } else { quotedText.append(text.substring(0, bodyOffset)); // stuff before the reply quotedText.append(text.substring(bodyOffset + bodyLength)); } if (viewMessageContent) { mMessageContentView.setCharacters(bodyText); } mQuotedText.setCharacters(quotedText); } catch (IndexOutOfBoundsException e) { // Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid bodyOffset/bodyLength"); if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } else { if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } } // Regexes to check for signature. private static final Pattern DASH_SIGNATURE_PLAIN = Pattern.compile("\r\n-- \r\n.*", Pattern.DOTALL); private static final Pattern DASH_SIGNATURE_HTML = Pattern.compile("(<br( /)?>|\r?\n)-- <br( /)?>", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_START = Pattern.compile("<blockquote", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_END = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); /** * Build and populate the UI with the quoted message. * * @param showQuotedText * {@code true} if the quoted text should be shown, {@code false} otherwise. * * @throws MessagingException */ private void populateUIWithQuotedMessage(boolean showQuotedText) throws MessagingException { MessageFormat origMessageFormat = mAccount.getMessageFormat(); if (mForcePlainText || origMessageFormat == MessageFormat.TEXT) { // Use plain text for the quoted message mQuotedTextFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { // Figure out which message format to use for the quoted text by looking if the source // message contains a text/html part. If it does, we use that. mQuotedTextFormat = (MimeUtility.findFirstPartByMimeType(mSourceMessage, "text/html") == null) ? SimpleMessageFormat.TEXT : SimpleMessageFormat.HTML; } else { mQuotedTextFormat = SimpleMessageFormat.HTML; } // TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption? // Handle the original message in the reply // If we already have mSourceMessageBody, use that. It's pre-populated if we've got crypto going on. String content = (mSourceMessageBody != null) ? mSourceMessageBody : getBodyTextFromMessage(mSourceMessage, mQuotedTextFormat); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { // Strip signature. // closing tags such as </div>, </span>, </table>, </pre> will be cut off. if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { Matcher dashSignatureHtml = DASH_SIGNATURE_HTML.matcher(content); if (dashSignatureHtml.find()) { Matcher blockquoteStart = BLOCKQUOTE_START.matcher(content); Matcher blockquoteEnd = BLOCKQUOTE_END.matcher(content); List<Integer> start = new ArrayList<Integer>(); List<Integer> end = new ArrayList<Integer>(); while(blockquoteStart.find()) { start.add(blockquoteStart.start()); } while(blockquoteEnd.find()) { end.add(blockquoteEnd.start()); } if (start.size() != end.size()) { Log.d(K9.LOG_TAG, "There are " + start.size() + " <blockquote> tags, but " + end.size() + " </blockquote> tags. Refusing to strip."); } else if (start.size() > 0) { // Ignore quoted signatures in blockquotes. dashSignatureHtml.region(0, start.get(0)); if (dashSignatureHtml.find()) { // before first <blockquote>. content = content.substring(0, dashSignatureHtml.start()); } else { for (int i = 0; i < start.size() - 1; i++) { // within blockquotes. if (end.get(i) < start.get(i+1)) { dashSignatureHtml.region(end.get(i), start.get(i+1)); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); break; } } } if (end.get(end.size() - 1) < content.length()) { // after last </blockquote>. dashSignatureHtml.region(end.get(end.size() - 1), content.length()); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); } } } } else { // No blockquotes found. content = content.substring(0, dashSignatureHtml.start()); } } // Fix the stripping off of closing tags if a signature was stripped, // as well as clean up the HTML of the quoted message. HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); // see http://htmlcleaner.sourceforge.net/parameters.php for descriptions properties.setNamespacesAware(false); properties.setAdvancedXmlEscape(false); properties.setOmitXmlDeclaration(true); properties.setOmitDoctypeDeclaration(false); properties.setTranslateSpecialEntities(false); properties.setRecognizeUnicodeChars(false); TagNode node = cleaner.clean(content); SimpleHtmlSerializer htmlSerialized = new SimpleHtmlSerializer(properties); try { content = htmlSerialized.getAsString(node, "UTF8"); } catch (java.io.IOException ioe) { // Can't imagine this happening. Log.e(K9.LOG_TAG, "Problem cleaning quoted message.", ioe); } } // Add the HTML reply header to the top of the content. mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mQuoteStyle); // Load the message with the reply header. mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); // TODO: Also strip the signature from the text/plain part mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, getBodyTextFromMessage(mSourceMessage, SimpleMessageFormat.TEXT), mQuoteStyle)); } else if (mQuotedTextFormat == SimpleMessageFormat.TEXT) { if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { if (DASH_SIGNATURE_PLAIN.matcher(content).find()) { content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n"); } } mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, content, mQuoteStyle)); } if (showQuotedText) { showOrHideQuotedText(QuotedTextMode.SHOW); } else { showOrHideQuotedText(QuotedTextMode.HIDE); } } /** * Fetch the body text from a message in the desired message format. This method handles * conversions between formats (html to text and vice versa) if necessary. * @param message Message to analyze for body part. * @param format Desired format. * @return Text in desired format. * @throws MessagingException */ private String getBodyTextFromMessage(final Message message, final SimpleMessageFormat format) throws MessagingException { Part part; if (format == SimpleMessageFormat.HTML) { // HTML takes precedence, then text. part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found."); return HtmlConverter.textToHtml(MimeUtility.getTextFromPart(part)); } } else if (format == SimpleMessageFormat.TEXT) { // Text takes precedence, then html. part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found."); return HtmlConverter.htmlToText(MimeUtility.getTextFromPart(part)); } } // If we had nothing interesting, return an empty string. return ""; } // Regular expressions to look for various HTML tags. This is no HTML::Parser, but hopefully it's good enough for // our purposes. private static final Pattern FIND_INSERTION_POINT_HTML = Pattern.compile("(?si:.*?(<html(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HEAD = Pattern.compile("(?si:.*?(<head(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_BODY = Pattern.compile("(?si:.*?(<body(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HTML_END = Pattern.compile("(?si:.*(</html>).*?)"); private static final Pattern FIND_INSERTION_POINT_BODY_END = Pattern.compile("(?si:.*(</body>).*?)"); // The first group in a Matcher contains the first capture group. We capture the tag found in the above REs so that // we can locate the *end* of that tag. private static final int FIND_INSERTION_POINT_FIRST_GROUP = 1; // HTML bits to insert as appropriate // TODO is it safe to assume utf-8 here? private static final String FIND_INSERTION_POINT_HTML_CONTENT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>"; private static final String FIND_INSERTION_POINT_HTML_END_CONTENT = "</html>"; private static final String FIND_INSERTION_POINT_HEAD_CONTENT = "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>"; // Index of the start of the beginning of a String. private static final int FIND_INSERTION_POINT_START_OF_STRING = 0; /** * <p>Find the start and end positions of the HTML in the string. This should be the very top * and bottom of the displayable message. It returns a {@link InsertableHtmlContent}, which * contains both the insertion points and potentially modified HTML. The modified HTML should be * used in place of the HTML in the original message.</p> * * <p>This method loosely mimics the HTML forward/reply behavior of BlackBerry OS 4.5/BIS 2.5, which in turn mimics * Outlook 2003 (as best I can tell).</p> * * @param content Content to examine for HTML insertion points * @return Insertion points and HTML to use for insertion. */ private InsertableHtmlContent findInsertionPoints(final String content) { InsertableHtmlContent insertable = new InsertableHtmlContent(); // If there is no content, don't bother doing any of the regex dancing. if (content == null || content.equals("")) { return insertable; } // Search for opening tags. boolean hasHtmlTag = false; boolean hasHeadTag = false; boolean hasBodyTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content); if (htmlMatcher.matches()) { hasHtmlTag = true; } // Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content. Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content); if (headMatcher.matches()) { hasHeadTag = true; } // Look for a BODY tag. This is the ideal place for us to start our content. Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content); if (bodyMatcher.matches()) { hasBodyTag = true; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag); // Given our inspections, let's figure out where to start our content. // This is the ideal case -- there's a BODY tag and we insert ourselves just after it. if (hasBodyTag) { insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHeadTag) { // Now search for a HEAD tag. We can insert after there. // If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't // try to add BODY, either. Right or wrong, it seems to work fine. insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlTag) { // Lastly, check for an HTML tag. // In this case, it will add a HEAD, but no BODY. StringBuilder newContent = new StringBuilder(content); // Insert the HEAD content just after the HTML tag. newContent.insert(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP), FIND_INSERTION_POINT_HEAD_CONTENT); insertable.setQuotedContent(newContent); // The new insertion point is the end of the HTML tag, plus the length of the HEAD content. insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } else { // If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this. // Again, we add a HEAD, but not BODY. StringBuilder newContent = new StringBuilder(content); // Add the HTML and HEAD tags. newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HEAD_CONTENT); newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HTML_CONTENT); // Append the </HTML> tag. newContent.append(FIND_INSERTION_POINT_HTML_END_CONTENT); insertable.setQuotedContent(newContent); insertable.setHeaderInsertionPoint(FIND_INSERTION_POINT_HTML_CONTENT.length() + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } // Search for closing tags. We have to do this after we deal with opening tags since it may // have modified the message. boolean hasHtmlEndTag = false; boolean hasBodyEndTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent()); if (htmlEndMatcher.matches()) { hasHtmlEndTag = true; } // Look for a BODY tag. This is the ideal place for us to place our footer. Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent()); if (bodyEndMatcher.matches()) { hasBodyEndTag = true; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag); // Now figure out where to put our footer. // This is the ideal case -- there's a BODY tag and we insert ourselves just before it. if (hasBodyEndTag) { insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlEndTag) { // Check for an HTML tag. Add ourselves just before it. insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else { // If we have none of the above, we probably have a fragment of HTML. // Set our footer insertion point as the end of the string. insertable.setFooterInsertionPoint(insertable.getQuotedContent().length()); } return insertable; } class Listener extends MessagingListener { @Override public void loadMessageForViewStarted(Account account, String folder, String uid) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_ON); } @Override public void loadMessageForViewFinished(Account account, String folder, String uid, Message message) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); } @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mSourceMessage = message; runOnUiThread(new Runnable() { @Override public void run() { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). if (mSourceProcessed) { try { populateUIWithQuotedMessage(true); } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? showOrHideQuotedText(QuotedTextMode.HIDE); Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); } updateMessageFormat(); } else { processSourceMessage(message); mSourceProcessed = true; } } }); } @Override public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); // TODO show network error } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { // Track UID changes of the source message if (mMessageReference != null) { final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.accountUuid); final String sourceFolder = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) { if (oldUid.equals(sourceMessageUid)) { mMessageReference.uid = newUid; } if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) { mSourceMessage.setUid(newUid); } } } } } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailtoUri * The mailto: URI we use to initialize the message fields. */ private void initializeFromMailto(Uri mailtoUri) { String schemaSpecific = mailtoUri.getSchemeSpecificPart(); int end = schemaSpecific.indexOf('?'); if (end == -1) { end = schemaSpecific.length(); } // Extract the recipient's email address from the mailto URI if there's one. String recipient = Uri.decode(schemaSpecific.substring(0, end)); /* * mailto URIs are not hierarchical. So calling getQueryParameters() * will throw an UnsupportedOperationException. We avoid this by * creating a new hierarchical dummy Uri object with the query * parameters of the original URI. */ CaseInsensitiveParamWrapper uri = new CaseInsensitiveParamWrapper( Uri.parse("foo://bar?" + mailtoUri.getEncodedQuery())); // Read additional recipients from the "to" parameter. List<String> to = uri.getQueryParameters("to"); if (recipient.length() != 0) { to = new ArrayList<String>(to); to.add(0, recipient); } addRecipients(mToView, to); // Read carbon copy recipients from the "cc" parameter. boolean ccOrBcc = addRecipients(mCcView, uri.getQueryParameters("cc")); // Read blind carbon copy recipients from the "bcc" parameter. ccOrBcc |= addRecipients(mBccView, uri.getQueryParameters("bcc")); if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } // Read subject from the "subject" parameter. List<String> subject = uri.getQueryParameters("subject"); if (!subject.isEmpty()) { mSubjectView.setText(subject.get(0)); } // Read message body from the "body" parameter. List<String> body = uri.getQueryParameters("body"); if (!body.isEmpty()) { mMessageContentView.setCharacters(body.get(0)); } } private static class CaseInsensitiveParamWrapper { private final Uri uri; private Set<String> mParamNames; public CaseInsensitiveParamWrapper(Uri uri) { this.uri = uri; } public List<String> getQueryParameters(String key) { final List<String> params = new ArrayList<String>(); for (String paramName : getQueryParameterNames()) { if (paramName.equalsIgnoreCase(key)) { params.addAll(uri.getQueryParameters(paramName)); } } return params; } @TargetApi(11) private Set<String> getQueryParameterNames() { if (Build.VERSION.SDK_INT >= 11) { return uri.getQueryParameterNames(); } return getQueryParameterNamesPreSdk11(); } private Set<String> getQueryParameterNamesPreSdk11() { if (mParamNames == null) { String query = uri.getQuery(); Set<String> paramNames = new HashSet<String>(); Collections.addAll(paramNames, query.split("(=[^&]*(&|$))|&")); mParamNames = paramNames; } return mParamNames; } } private class SendMessageTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; try { message = createMessage(false); // isDraft = true } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } try { mContacts.markAsContacted(message.getRecipients(RecipientType.TO)); mContacts.markAsContacted(message.getRecipients(RecipientType.CC)); mContacts.markAsContacted(message.getRecipients(RecipientType.BCC)); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); } MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null); long draftId = mDraftId; if (draftId != INVALID_DRAFT_ID) { mDraftId = INVALID_DRAFT_ID; MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId); } return null; } } private class SaveMessageTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; try { message = createMessage(true); // isDraft = true } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } /* * Save a draft */ if (mAction == Action.EDIT_DRAFT) { /* * We're saving a previously saved draft, so update the new message's uid * to the old message's uid. */ if (mMessageReference != null) { message.setUid(mMessageReference.uid); } } final MessagingController messagingController = MessagingController.getInstance(getApplication()); Message draftMessage = messagingController.saveDraft(mAccount, message, mDraftId); mDraftId = messagingController.getId(draftMessage); mHandler.sendEmptyMessage(MSG_SAVED_DRAFT); return null; } } private static final int REPLY_WRAP_LINE_WIDTH = 72; private static final int QUOTE_BUFFER_LENGTH = 512; // amount of extra buffer to allocate to accommodate quoting headers or prefixes /** * Add quoting markup to a text message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Quoted text. * @throws MessagingException */ private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { String body = messageBody == null ? "" : messageBody; String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); if (sentDate.length() != 0) { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt_with_date) + "\r\n", sentDate, Address.toString(originalMessage.getFrom()))); } else { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt) + "\r\n", Address.toString(originalMessage.getFrom())) ); } final String prefix = mAccount.getQuotePrefix(); final String wrappedText = Utility.wrap(body, REPLY_WRAP_LINE_WIDTH - prefix.length()); // "$" and "\" in the quote prefix have to be escaped for // the replaceAll() invocation. final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1"); quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix)); return quotedText.toString().replaceAll("\\\r", ""); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); quotedText.append("\r\n"); quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\r\n"); if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\r\n"); } if (sentDate.length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(sentDate).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\r\n"); } if (originalMessage.getSubject() != null) { quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\r\n"); } quotedText.append("\r\n"); quotedText.append(body); return quotedText.toString(); } else { // Shouldn't ever happen. return body; } } /** * Add quoting markup to a HTML message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Modified insertable message. * @throws MessagingException */ private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { InsertableHtmlContent insertable = findInsertionPoints(messageBody); String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH); header.append("<div class=\"gmail_quote\">"); if (sentDate.length() != 0) { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt_with_date), sentDate, Address.toString(originalMessage.getFrom())) )); } else { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt), Address.toString(originalMessage.getFrom())) )); } header.append("<blockquote class=\"gmail_quote\" " + "style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\">\r\n"); String footer = "</blockquote></div>"; insertable.insertIntoQuotedHeader(header.toString()); insertable.insertIntoQuotedFooter(footer); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder header = new StringBuilder(); header.append("<div style='font-size:10.0pt;font-family:\"Tahoma\",\"sans-serif\";padding:3.0pt 0in 0in 0in'>\r\n"); header.append("<hr style='border:none;border-top:solid #E1E1E1 1.0pt'>\r\n"); // This gets converted into a horizontal line during html to text conversion. if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_from)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getFrom()))) .append("<br>\r\n"); } if (sentDate.length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_send_date)).append("</b> ") .append(sentDate) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_to)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.TO)))) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_cc)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.CC)))) .append("<br>\r\n"); } if (originalMessage.getSubject() != null) { header.append("<b>").append(getString(R.string.message_compose_quote_header_subject)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(originalMessage.getSubject())) .append("<br>\r\n"); } header.append("</div>\r\n"); header.append("<br>\r\n"); insertable.insertIntoQuotedHeader(header.toString()); } return insertable; } /** * Used to store an {@link Identity} instance together with the {@link Account} it belongs to. * * @see IdentityAdapter */ static class IdentityContainer { public final Identity identity; public final Account account; IdentityContainer(Identity identity, Account account) { this.identity = identity; this.account = account; } } /** * Adapter for the <em>Choose identity</em> list view. * * <p> * Account names are displayed as section headers, identities as selectable list items. * </p> */ static class IdentityAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater; private List<Object> mItems; public IdentityAdapter(Context context) { mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); List<Object> items = new ArrayList<Object>(); Preferences prefs = Preferences.getPreferences(context.getApplicationContext()); Account[] accounts = prefs.getAvailableAccounts().toArray(EMPTY_ACCOUNT_ARRAY); for (Account account : accounts) { items.add(account); List<Identity> identities = account.getIdentities(); for (Identity identity : identities) { items.add(new IdentityContainer(identity, account)); } } mItems = items; } @Override public int getCount() { return mItems.size(); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return (mItems.get(position) instanceof Account) ? 0 : 1; } @Override public boolean isEnabled(int position) { return (mItems.get(position) instanceof IdentityContainer); } @Override public Object getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int position, View convertView, ViewGroup parent) { Object item = mItems.get(position); View view = null; if (item instanceof Account) { if (convertView != null && convertView.getTag() instanceof AccountHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_account_item, parent, false); AccountHolder holder = new AccountHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.chip = view.findViewById(R.id.chip); view.setTag(holder); } Account account = (Account) item; AccountHolder holder = (AccountHolder) view.getTag(); holder.name.setText(account.getDescription()); holder.chip.setBackgroundColor(account.getChipColor()); } else if (item instanceof IdentityContainer) { if (convertView != null && convertView.getTag() instanceof IdentityHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_identity_item, parent, false); IdentityHolder holder = new IdentityHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.description = (TextView) view.findViewById(R.id.description); view.setTag(holder); } IdentityContainer identityContainer = (IdentityContainer) item; Identity identity = identityContainer.identity; IdentityHolder holder = (IdentityHolder) view.getTag(); holder.name.setText(identity.getDescription()); holder.description.setText(getIdentityDescription(identity)); } return view; } static class AccountHolder { public TextView name; public View chip; } static class IdentityHolder { public TextView name; public TextView description; } } private static String getIdentityDescription(Identity identity) { return String.format("%s <%s>", identity.getName(), identity.getEmail()); } private void setMessageFormat(SimpleMessageFormat format) { // This method will later be used to enable/disable the rich text editing mode. mMessageFormat = format; } private void updateMessageFormat() { MessageFormat origMessageFormat = mAccount.getMessageFormat(); SimpleMessageFormat messageFormat; if (origMessageFormat == MessageFormat.TEXT) { // The user wants to send text/plain messages. We don't override that choice under // any circumstances. messageFormat = SimpleMessageFormat.TEXT; } else if (mForcePlainText && includeQuotedText()) { // Right now we send a text/plain-only message when the quoted text was edited, no // matter what the user selected for the message format. messageFormat = SimpleMessageFormat.TEXT; } else if (mEncryptCheckbox.isChecked() || mCryptoSignatureCheckbox.isChecked()) { // Right now we only support PGP inline which doesn't play well with HTML. So force // plain text in those cases. messageFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { if (mAction == Action.COMPOSE || mQuotedTextFormat == SimpleMessageFormat.TEXT || !includeQuotedText()) { // If the message format is set to "AUTO" we use text/plain whenever possible. That // is, when composing new messages and replying to or forwarding text/plain // messages. messageFormat = SimpleMessageFormat.TEXT; } else { messageFormat = SimpleMessageFormat.HTML; } } else { // In all other cases use HTML messageFormat = SimpleMessageFormat.HTML; } setMessageFormat(messageFormat); } private boolean includeQuotedText() { return (mQuotedTextMode == QuotedTextMode.SHOW); } /** * Extract the date from a message and convert it into a locale-specific * date string suitable for use in a header for a quoted message. * * @param message * @return A string with the formatted date/time */ private String getSentDateText(Message message) { try { final int dateStyle = DateFormat.LONG; final int timeStyle = DateFormat.LONG; Date date = message.getSentDate(); Locale locale = getResources().getConfiguration().locale; return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale) .format(date); } catch (Exception e) { return ""; } } /** * An {@link EditText} extension with methods that convert line endings from * {@code \r\n} to {@code \n} and back again when setting and getting text. * */ private static class EolConvertingEditText extends EditText { public EolConvertingEditText(Context context, AttributeSet attrs) { super(context, attrs); } /** * Return the text the EolConvertingEditText is displaying. * * @return A string with any line endings converted to {@code \r\n}. */ public String getCharacters() { return getText().toString().replace("\n", "\r\n"); } /** * Sets the string value of the EolConvertingEditText. Any line endings * in the string will be converted to {@code \n}. * * @param text */ public void setCharacters(CharSequence text) { setText(text.toString().replace("\r\n", "\n")); } } }
src/com/fsck/k9/activity/MessageCompose.java
package com.fsck.k9.activity; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.text.TextWatcher; import android.text.util.Rfc822Tokenizer; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.view.ContextThemeWrapper; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.AutoCompleteTextView.Validator; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.MessageFormat; import com.fsck.k9.Account.QuoteStyle; import com.fsck.k9.EmailAddressAdapter; import com.fsck.k9.EmailAddressValidator; import com.fsck.k9.FontSizes; import com.fsck.k9.Identity; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.loader.AttachmentContentLoader; import com.fsck.k9.activity.loader.AttachmentInfoLoader; import com.fsck.k9.activity.misc.Attachment; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.crypto.CryptoProvider; import com.fsck.k9.crypto.PgpData; import com.fsck.k9.fragment.ProgressDialogFragment; import com.fsck.k9.helper.ContactItem; import com.fsck.k9.helper.Contacts; import com.fsck.k9.helper.HtmlConverter; import com.fsck.k9.helper.StringUtils; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Body; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.Multipart; import com.fsck.k9.mail.Part; import com.fsck.k9.mail.internet.MimeBodyPart; import com.fsck.k9.mail.internet.MimeHeader; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.internet.MimeMultipart; import com.fsck.k9.mail.internet.MimeUtility; import com.fsck.k9.mail.internet.TextBody; import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody; import com.fsck.k9.mail.store.LocalStore.TempFileBody; import com.fsck.k9.mail.store.LocalStore.TempFileMessageBody; import com.fsck.k9.view.MessageWebView; import org.apache.james.mime4j.codec.EncoderUtil; import org.apache.james.mime4j.util.MimeUtil; import org.htmlcleaner.CleanerProperties; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.SimpleHtmlSerializer; import org.htmlcleaner.TagNode; import java.text.DateFormat; 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.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MessageCompose extends K9Activity implements OnClickListener, ProgressDialogFragment.CancelListener { private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1; private static final int DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED = 2; private static final int DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY = 3; private static final int DIALOG_CONFIRM_DISCARD_ON_BACK = 4; private static final int DIALOG_CHOOSE_IDENTITY = 5; private static final long INVALID_DRAFT_ID = MessagingController.INVALID_MESSAGE_ID; private static final String ACTION_COMPOSE = "com.fsck.k9.intent.action.COMPOSE"; private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY"; private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL"; private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD"; private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT"; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_MESSAGE_BODY = "messageBody"; private static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; private static final String STATE_KEY_ATTACHMENTS = "com.fsck.k9.activity.MessageCompose.attachments"; private static final String STATE_KEY_CC_SHOWN = "com.fsck.k9.activity.MessageCompose.ccShown"; private static final String STATE_KEY_BCC_SHOWN = "com.fsck.k9.activity.MessageCompose.bccShown"; private static final String STATE_KEY_QUOTED_TEXT_MODE = "com.fsck.k9.activity.MessageCompose.QuotedTextShown"; private static final String STATE_KEY_SOURCE_MESSAGE_PROCED = "com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced"; private static final String STATE_KEY_DRAFT_ID = "com.fsck.k9.activity.MessageCompose.draftId"; private static final String STATE_KEY_HTML_QUOTE = "com.fsck.k9.activity.MessageCompose.HTMLQuote"; private static final String STATE_IDENTITY_CHANGED = "com.fsck.k9.activity.MessageCompose.identityChanged"; private static final String STATE_IDENTITY = "com.fsck.k9.activity.MessageCompose.identity"; private static final String STATE_PGP_DATA = "pgpData"; private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo"; private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references"; private static final String STATE_KEY_READ_RECEIPT = "com.fsck.k9.activity.MessageCompose.messageReadReceipt"; private static final String STATE_KEY_DRAFT_NEEDS_SAVING = "com.fsck.k9.activity.MessageCompose.mDraftNeedsSaving"; private static final String STATE_KEY_FORCE_PLAIN_TEXT = "com.fsck.k9.activity.MessageCompose.forcePlainText"; private static final String STATE_KEY_QUOTED_TEXT_FORMAT = "com.fsck.k9.activity.MessageCompose.quotedTextFormat"; private static final String STATE_KEY_NUM_ATTACHMENTS_LOADING = "numAttachmentsLoading"; private static final String STATE_KEY_WAITING_FOR_ATTACHMENTS = "waitingForAttachments"; private static final String LOADER_ARG_ATTACHMENT = "attachment"; private static final String FRAGMENT_WAITING_FOR_ATTACHMENT = "waitingForAttachment"; private static final int MSG_PROGRESS_ON = 1; private static final int MSG_PROGRESS_OFF = 2; private static final int MSG_SKIPPED_ATTACHMENTS = 3; private static final int MSG_SAVED_DRAFT = 4; private static final int MSG_DISCARDED_DRAFT = 5; private static final int MSG_PERFORM_STALLED_ACTION = 6; private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1; private static final int CONTACT_PICKER_TO = 4; private static final int CONTACT_PICKER_CC = 5; private static final int CONTACT_PICKER_BCC = 6; private static final int CONTACT_PICKER_TO2 = 7; private static final int CONTACT_PICKER_CC2 = 8; private static final int CONTACT_PICKER_BCC2 = 9; private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[0]; /** * Regular expression to remove the first localized "Re:" prefix in subjects. * * Currently: * - "Aw:" (german: abbreviation for "Antwort") */ private static final Pattern PREFIX = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE); /** * The account used for message composition. */ private Account mAccount; private Contacts mContacts; /** * This identity's settings are used for message composition. * Note: This has to be an identity of the account {@link #mAccount}. */ private Identity mIdentity; private boolean mIdentityChanged = false; private boolean mSignatureChanged = false; /** * Reference to the source message (in case of reply, forward, or edit * draft actions). */ private MessageReference mMessageReference; private Message mSourceMessage; /** * "Original" message body * * <p> * The contents of this string will be used instead of the body of a referenced message when * replying to or forwarding a message.<br> * Right now this is only used when replying to a signed or encrypted message. It then contains * the stripped/decrypted body of that message. * </p> * <p><strong>Note:</strong> * When this field is not {@code null} we assume that the message we are composing right now * should be encrypted. * </p> */ private String mSourceMessageBody; /** * Indicates that the source message has been processed at least once and should not * be processed on any subsequent loads. This protects us from adding attachments that * have already been added from the restore of the view state. */ private boolean mSourceMessageProcessed = false; private int mMaxLoaderId = 0; enum Action { COMPOSE, REPLY, REPLY_ALL, FORWARD, EDIT_DRAFT } /** * Contains the action we're currently performing (e.g. replying to a message) */ private Action mAction; private enum QuotedTextMode { NONE, SHOW, HIDE } private boolean mReadReceipt = false; private QuotedTextMode mQuotedTextMode = QuotedTextMode.NONE; /** * Contains the format of the quoted text (text vs. HTML). */ private SimpleMessageFormat mQuotedTextFormat; /** * When this it {@code true} the message format setting is ignored and we're always sending * a text/plain message. */ private boolean mForcePlainText = false; private Button mChooseIdentityButton; private LinearLayout mCcWrapper; private LinearLayout mBccWrapper; private MultiAutoCompleteTextView mToView; private MultiAutoCompleteTextView mCcView; private MultiAutoCompleteTextView mBccView; private EditText mSubjectView; private EolConvertingEditText mSignatureView; private EolConvertingEditText mMessageContentView; private LinearLayout mAttachments; private Button mQuotedTextShow; private View mQuotedTextBar; private ImageButton mQuotedTextEdit; private ImageButton mQuotedTextDelete; private EolConvertingEditText mQuotedText; private MessageWebView mQuotedHTML; private InsertableHtmlContent mQuotedHtmlContent; // Container for HTML reply as it's being built. private View mEncryptLayout; private CheckBox mCryptoSignatureCheckbox; private CheckBox mEncryptCheckbox; private TextView mCryptoSignatureUserId; private TextView mCryptoSignatureUserIdRest; private ImageButton mAddToFromContacts; private ImageButton mAddCcFromContacts; private ImageButton mAddBccFromContacts; private PgpData mPgpData = null; private boolean mAutoEncrypt = false; private boolean mContinueWithoutPublicKey = false; private String mReferences; private String mInReplyTo; private Menu mMenu; private boolean mSourceProcessed = false; enum SimpleMessageFormat { TEXT, HTML } /** * The currently used message format. * * <p> * <strong>Note:</strong> * Don't modify this field directly. Use {@link #updateMessageFormat()}. * </p> */ private SimpleMessageFormat mMessageFormat; private QuoteStyle mQuoteStyle; private boolean mDraftNeedsSaving = false; private boolean mPreventDraftSaving = false; /** * If this is {@code true} we don't save the message as a draft in {@link #onPause()}. */ private boolean mIgnoreOnPause = false; /** * The database ID of this message's draft. This is used when saving drafts so the message in * the database is updated instead of being created anew. This property is INVALID_DRAFT_ID * until the first save. */ private long mDraftId = INVALID_DRAFT_ID; /** * Number of attachments currently being fetched. */ private int mNumAttachmentsLoading = 0; private enum WaitingAction { NONE, SEND, SAVE } /** * Specifies what action to perform once attachments have been fetched. */ private WaitingAction mWaitingForAttachments = WaitingAction.NONE; private Handler mHandler = new Handler() { @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case MSG_PROGRESS_ON: setSupportProgressBarIndeterminateVisibility(true); break; case MSG_PROGRESS_OFF: setSupportProgressBarIndeterminateVisibility(false); break; case MSG_SKIPPED_ATTACHMENTS: Toast.makeText( MessageCompose.this, getString(R.string.message_compose_attachments_skipped_toast), Toast.LENGTH_LONG).show(); break; case MSG_SAVED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_saved_toast), Toast.LENGTH_LONG).show(); break; case MSG_DISCARDED_DRAFT: Toast.makeText( MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); break; case MSG_PERFORM_STALLED_ACTION: performStalledAction(); break; default: super.handleMessage(msg); break; } } }; private Listener mListener = new Listener(); private EmailAddressAdapter mAddressAdapter; private Validator mAddressValidator; private FontSizes mFontSizes = K9.getFontSizes(); private ContextThemeWrapper mThemeContext; /** * Compose a new message using the given account. If account is null the default account * will be used. * @param context * @param account */ public static void actionCompose(Context context, Account account) { String accountUuid = (account == null) ? Preferences.getPreferences(context).getDefaultAccount().getUuid() : account.getUuid(); Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_ACCOUNT, accountUuid); i.setAction(ACTION_COMPOSE); context.startActivity(i); } /** * Get intent for composing a new message as a reply to the given message. If replyAll is true * the function is reply all instead of simply reply. * @param context * @param account * @param message * @param replyAll * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static Intent getActionReplyIntent( Context context, Account account, Message message, boolean replyAll, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); if (replyAll) { i.setAction(ACTION_REPLY_ALL); } else { i.setAction(ACTION_REPLY); } return i; } /** * Compose a new message as a reply to the given message. If replyAll is true the function * is reply all instead of simply reply. * @param context * @param account * @param message * @param replyAll * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionReply( Context context, Account account, Message message, boolean replyAll, String messageBody) { context.startActivity(getActionReplyIntent(context, account, message, replyAll, messageBody)); } /** * Compose a new message as a forward of the given message. * @param context * @param account * @param message * @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message */ public static void actionForward( Context context, Account account, Message message, String messageBody) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_BODY, messageBody); i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference()); i.setAction(ACTION_FORWARD); context.startActivity(i); } /** * Continue composition of the given message. This action modifies the way this Activity * handles certain actions. * Save will attempt to replace the message in the given folder with the updated version. * Discard will delete the message from the given folder. * @param context * @param message */ public static void actionEditDraft(Context context, MessageReference messageReference) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference); i.setAction(ACTION_EDIT_DRAFT); context.startActivity(i); } /* * This is a workaround for an annoying ( temporarly? ) issue: * https://github.com/JakeWharton/ActionBarSherlock/issues/449 */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setSupportProgressBarIndeterminateVisibility(false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); if (K9.getK9ComposerThemeSetting() != K9.Theme.USE_GLOBAL) { // theme the whole content according to the theme (except the action bar) mThemeContext = new ContextThemeWrapper(this, K9.getK9ThemeResourceId(K9.getK9ComposerTheme())); View v = ((LayoutInflater) mThemeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)). inflate(R.layout.message_compose, null); TypedValue outValue = new TypedValue(); // background color needs to be forced mThemeContext.getTheme().resolveAttribute(R.attr.messageViewHeaderBackgroundColor, outValue, true); v.setBackgroundColor(outValue.data); setContentView(v); } else { setContentView(R.layout.message_compose); mThemeContext = this; } final Intent intent = getIntent(); mMessageReference = intent.getParcelableExtra(EXTRA_MESSAGE_REFERENCE); mSourceMessageBody = intent.getStringExtra(EXTRA_MESSAGE_BODY); if (K9.DEBUG && mSourceMessageBody != null) Log.d(K9.LOG_TAG, "Composing message with explicitly specified message body."); final String accountUuid = (mMessageReference != null) ? mMessageReference.accountUuid : intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); if (mAccount == null) { mAccount = Preferences.getPreferences(this).getDefaultAccount(); } if (mAccount == null) { /* * There are no accounts set up. This should not have happened. Prompt the * user to set up an account as an acceptable bailout. */ startActivity(new Intent(this, Accounts.class)); mDraftNeedsSaving = false; finish(); return; } mContacts = Contacts.getInstance(MessageCompose.this); mAddressAdapter = new EmailAddressAdapter(mThemeContext); mAddressValidator = new EmailAddressValidator(); mChooseIdentityButton = (Button) findViewById(R.id.identity); mChooseIdentityButton.setOnClickListener(this); if (mAccount.getIdentities().size() == 1 && Preferences.getPreferences(this).getAvailableAccounts().size() == 1) { mChooseIdentityButton.setVisibility(View.GONE); } mToView = (MultiAutoCompleteTextView) findViewById(R.id.to); mCcView = (MultiAutoCompleteTextView) findViewById(R.id.cc); mBccView = (MultiAutoCompleteTextView) findViewById(R.id.bcc); mSubjectView = (EditText) findViewById(R.id.subject); mSubjectView.getInputExtras(true).putBoolean("allowEmoji", true); mAddToFromContacts = (ImageButton) findViewById(R.id.add_to); mAddCcFromContacts = (ImageButton) findViewById(R.id.add_cc); mAddBccFromContacts = (ImageButton) findViewById(R.id.add_bcc); mCcWrapper = (LinearLayout) findViewById(R.id.cc_wrapper); mBccWrapper = (LinearLayout) findViewById(R.id.bcc_wrapper); if (mAccount.isAlwaysShowCcBcc()) { onAddCcBcc(); } EolConvertingEditText upperSignature = (EolConvertingEditText)findViewById(R.id.upper_signature); EolConvertingEditText lowerSignature = (EolConvertingEditText)findViewById(R.id.lower_signature); mMessageContentView = (EolConvertingEditText)findViewById(R.id.message_content); mMessageContentView.getInputExtras(true).putBoolean("allowEmoji", true); mAttachments = (LinearLayout)findViewById(R.id.attachments); mQuotedTextShow = (Button)findViewById(R.id.quoted_text_show); mQuotedTextBar = findViewById(R.id.quoted_text_bar); mQuotedTextEdit = (ImageButton)findViewById(R.id.quoted_text_edit); mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete); mQuotedText = (EolConvertingEditText)findViewById(R.id.quoted_text); mQuotedText.getInputExtras(true).putBoolean("allowEmoji", true); mQuotedHTML = (MessageWebView) findViewById(R.id.quoted_html); mQuotedHTML.configure(); // Disable the ability to click links in the quoted HTML page. I think this is a nice feature, but if someone // feels this should be a preference (or should go away all together), I'm ok with that too. -achen 20101130 mQuotedHTML.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return true; } }); TextWatcher watcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } @Override public void afterTextChanged(android.text.Editable s) { /* do nothing */ } }; // For watching changes to the To:, Cc:, and Bcc: fields for auto-encryption on a matching // address. TextWatcher recipientWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; } @Override public void afterTextChanged(android.text.Editable s) { final CryptoProvider crypto = mAccount.getCryptoProvider(); if (mAutoEncrypt && crypto.isAvailable(getApplicationContext())) { for (Address address : getRecipientAddresses()) { if (crypto.hasPublicKeyForEmail(getApplicationContext(), address.getAddress())) { mEncryptCheckbox.setChecked(true); mContinueWithoutPublicKey = false; break; } } } } }; TextWatcher sigwatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { /* do nothing */ } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mDraftNeedsSaving = true; mSignatureChanged = true; } @Override public void afterTextChanged(android.text.Editable s) { /* do nothing */ } }; mToView.addTextChangedListener(recipientWatcher); mCcView.addTextChangedListener(recipientWatcher); mBccView.addTextChangedListener(recipientWatcher); mSubjectView.addTextChangedListener(watcher); mMessageContentView.addTextChangedListener(watcher); mQuotedText.addTextChangedListener(watcher); /* Yes, there really are poeple who ship versions of android without a contact picker */ if (mContacts.hasContactPicker()) { mAddToFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_TO); } }); mAddCcFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_CC); } }); mAddBccFromContacts.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doLaunchContactPicker(CONTACT_PICKER_BCC); } }); } else { mAddToFromContacts.setVisibility(View.GONE); mAddCcFromContacts.setVisibility(View.GONE); mAddBccFromContacts.setVisibility(View.GONE); } /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ showOrHideQuotedText(QuotedTextMode.NONE); mQuotedTextShow.setOnClickListener(this); mQuotedTextEdit.setOnClickListener(this); mQuotedTextDelete.setOnClickListener(this); mToView.setAdapter(mAddressAdapter); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(mAddressValidator); mCcView.setAdapter(mAddressAdapter); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(mAddressValidator); mBccView.setAdapter(mAddressAdapter); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(mAddressValidator); if (savedInstanceState != null) { /* * This data gets used in onCreate, so grab it here instead of onRestoreInstanceState */ mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false); } if (initFromIntent(intent)) { mAction = Action.COMPOSE; mDraftNeedsSaving = true; } else { String action = intent.getAction(); if (ACTION_COMPOSE.equals(action)) { mAction = Action.COMPOSE; } else if (ACTION_REPLY.equals(action)) { mAction = Action.REPLY; } else if (ACTION_REPLY_ALL.equals(action)) { mAction = Action.REPLY_ALL; } else if (ACTION_FORWARD.equals(action)) { mAction = Action.FORWARD; } else if (ACTION_EDIT_DRAFT.equals(action)) { mAction = Action.EDIT_DRAFT; } else { // This shouldn't happen Log.w(K9.LOG_TAG, "MessageCompose was started with an unsupported action"); mAction = Action.COMPOSE; } } if (mIdentity == null) { mIdentity = mAccount.getIdentity(0); } if (mAccount.isSignatureBeforeQuotedText()) { mSignatureView = upperSignature; lowerSignature.setVisibility(View.GONE); } else { mSignatureView = lowerSignature; upperSignature.setVisibility(View.GONE); } mSignatureView.addTextChangedListener(sigwatcher); if (!mIdentity.getSignatureUse()) { mSignatureView.setVisibility(View.GONE); } mReadReceipt = mAccount.isMessageReadReceiptAlways(); mQuoteStyle = mAccount.getQuoteStyle(); updateFrom(); if (!mSourceMessageProcessed) { updateSignature(); if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.FORWARD || mAction == Action.EDIT_DRAFT) { /* * If we need to load the message we add ourself as a message listener here * so we can kick it off. Normally we add in onResume but we don't * want to reload the message every time the activity is resumed. * There is no harm in adding twice. */ MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } if (mAction != Action.EDIT_DRAFT) { addAddresses(mBccView, mAccount.getAlwaysBcc()); } } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { mMessageReference.flag = Flag.ANSWERED; } if (mAction == Action.REPLY || mAction == Action.REPLY_ALL || mAction == Action.EDIT_DRAFT) { //change focus to message body. mMessageContentView.requestFocus(); } else { // Explicitly set focus to "To:" input field (see issue 2998) mToView.requestFocus(); } if (mAction == Action.FORWARD) { mMessageReference.flag = Flag.FORWARDED; } mEncryptLayout = findViewById(R.id.layout_encrypt); mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature); mCryptoSignatureUserId = (TextView)findViewById(R.id.userId); mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest); mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt); mEncryptCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateMessageFormat(); } }); if (mSourceMessageBody != null) { // mSourceMessageBody is set to something when replying to and forwarding decrypted // messages, so the sender probably wants the message to be encrypted. mEncryptCheckbox.setChecked(true); } initializeCrypto(); final CryptoProvider crypto = mAccount.getCryptoProvider(); if (crypto.isAvailable(this)) { mEncryptLayout.setVisibility(View.VISIBLE); mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox checkBox = (CheckBox) v; if (checkBox.isChecked()) { mPreventDraftSaving = true; if (!crypto.selectSecretKey(MessageCompose.this, mPgpData)) { mPreventDraftSaving = false; } checkBox.setChecked(false); } else { mPgpData.setSignatureKeyId(0); updateEncryptLayout(); } } }); if (mAccount.getCryptoAutoSignature()) { long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail()); if (ids != null && ids.length > 0) { mPgpData.setSignatureKeyId(ids[0]); mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0])); } else { mPgpData.setSignatureKeyId(0); mPgpData.setSignatureUserId(null); } } updateEncryptLayout(); mAutoEncrypt = mAccount.isCryptoAutoEncrypt(); } else { mEncryptLayout.setVisibility(View.GONE); } // Set font size of input controls int fontSize = mFontSizes.getMessageComposeInput(); mFontSizes.setViewTextSize(mToView, fontSize); mFontSizes.setViewTextSize(mCcView, fontSize); mFontSizes.setViewTextSize(mBccView, fontSize); mFontSizes.setViewTextSize(mSubjectView, fontSize); mFontSizes.setViewTextSize(mMessageContentView, fontSize); mFontSizes.setViewTextSize(mQuotedText, fontSize); mFontSizes.setViewTextSize(mSignatureView, fontSize); updateMessageFormat(); setTitle(); } /** * Handle external intents that trigger the message compose activity. * * <p> * Supported external intents: * <ul> * <li>{@link Intent#ACTION_VIEW}</li> * <li>{@link Intent#ACTION_SENDTO}</li> * <li>{@link Intent#ACTION_SEND}</li> * <li>{@link Intent#ACTION_SEND_MULTIPLE}</li> * </ul> * </p> * * @param intent * The (external) intent that started the activity. * * @return {@code true}, if this activity was started by an external intent. {@code false}, * otherwise. */ private boolean initFromIntent(final Intent intent) { boolean startedByExternalIntent = false; final String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action)) { startedByExternalIntent = true; /* * Someone has clicked a mailto: link. The address is in the URI. */ if (intent.getData() != null) { Uri uri = intent.getData(); if ("mailto".equals(uri.getScheme())) { initializeFromMailto(uri); } } /* * Note: According to the documenation ACTION_VIEW and ACTION_SENDTO don't accept * EXTRA_* parameters. * And previously we didn't process these EXTRAs. But it looks like nobody bothers to * read the official documentation and just copies wrong sample code that happens to * work with the AOSP Email application. And because even big players get this wrong, * we're now finally giving in and read the EXTRAs for ACTION_SENDTO (below). */ } if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action) || Intent.ACTION_SENDTO.equals(action)) { startedByExternalIntent = true; /* * Note: Here we allow a slight deviation from the documentated behavior. * EXTRA_TEXT is used as message body (if available) regardless of the MIME * type of the intent. In addition one or multiple attachments can be added * using EXTRA_STREAM. */ CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); // Only use EXTRA_TEXT if the body hasn't already been set by the mailto URI if (text != null && mMessageContentView.getText().length() == 0) { mMessageContentView.setCharacters(text); } String type = intent.getType(); if (Intent.ACTION_SEND.equals(action)) { Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (stream != null) { addAttachment(stream, type); } } else { ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri stream = (Uri) parcelable; if (stream != null) { addAttachment(stream, type); } } } } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); // Only use EXTRA_SUBJECT if the subject hasn't already been set by the mailto URI if (subject != null && mSubjectView.getText().length() == 0) { mSubjectView.setText(subject); } String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC); String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC); if (extraEmail != null) { addRecipients(mToView, Arrays.asList(extraEmail)); } boolean ccOrBcc = false; if (extraCc != null) { ccOrBcc |= addRecipients(mCcView, Arrays.asList(extraCc)); } if (extraBcc != null) { ccOrBcc |= addRecipients(mBccView, Arrays.asList(extraBcc)); } if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } } return startedByExternalIntent; } private boolean addRecipients(TextView view, List<String> recipients) { if (recipients == null || recipients.size() == 0) { return false; } StringBuilder addressList = new StringBuilder(); // Read current contents of the TextView String text = view.getText().toString(); addressList.append(text); // Add comma if necessary if (text.length() != 0 && !(text.endsWith(", ") || text.endsWith(","))) { addressList.append(", "); } // Add recipients for (String recipient : recipients) { addressList.append(recipient); addressList.append(", "); } view.setText(addressList); return true; } private void initializeCrypto() { if (mPgpData != null) { return; } mPgpData = new PgpData(); } /** * Fill the encrypt layout with the latest data about signature key and encryption keys. */ public void updateEncryptLayout() { if (!mPgpData.hasSignatureKey()) { mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign); mCryptoSignatureCheckbox.setChecked(false); mCryptoSignatureUserId.setVisibility(View.INVISIBLE); mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE); } else { // if a signature key is selected, then the checkbox itself has no text mCryptoSignatureCheckbox.setText(""); mCryptoSignatureCheckbox.setChecked(true); mCryptoSignatureUserId.setVisibility(View.VISIBLE); mCryptoSignatureUserIdRest.setVisibility(View.VISIBLE); mCryptoSignatureUserId.setText(R.string.unknown_crypto_signature_user_id); mCryptoSignatureUserIdRest.setText(""); String userId = mPgpData.getSignatureUserId(); if (userId == null) { userId = mAccount.getCryptoProvider().getUserId(this, mPgpData.getSignatureKeyId()); mPgpData.setSignatureUserId(userId); } if (userId != null) { String chunks[] = mPgpData.getSignatureUserId().split(" <", 2); mCryptoSignatureUserId.setText(chunks[0]); if (chunks.length > 1) { mCryptoSignatureUserIdRest.setText("<" + chunks[1]); } } } updateMessageFormat(); } @Override public void onResume() { super.onResume(); mIgnoreOnPause = false; MessagingController.getInstance(getApplication()).addListener(mListener); } @Override public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mListener); // Save email as draft when activity is changed (go to home screen, call received) or screen locked // don't do this if only changing orientations if (!mIgnoreOnPause && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) { saveIfNeeded(); } } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Attachment list, * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); ArrayList<Attachment> attachments = new ArrayList<Attachment>(); for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { View view = mAttachments.getChildAt(i); Attachment attachment = (Attachment) view.getTag(); attachments.add(attachment); } outState.putInt(STATE_KEY_NUM_ATTACHMENTS_LOADING, mNumAttachmentsLoading); outState.putString(STATE_KEY_WAITING_FOR_ATTACHMENTS, mWaitingForAttachments.name()); outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, attachments); outState.putBoolean(STATE_KEY_CC_SHOWN, mCcWrapper.getVisibility() == View.VISIBLE); outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccWrapper.getVisibility() == View.VISIBLE); outState.putSerializable(STATE_KEY_QUOTED_TEXT_MODE, mQuotedTextMode); outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed); outState.putLong(STATE_KEY_DRAFT_ID, mDraftId); outState.putSerializable(STATE_IDENTITY, mIdentity); outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged); outState.putSerializable(STATE_PGP_DATA, mPgpData); outState.putString(STATE_IN_REPLY_TO, mInReplyTo); outState.putString(STATE_REFERENCES, mReferences); outState.putSerializable(STATE_KEY_HTML_QUOTE, mQuotedHtmlContent); outState.putBoolean(STATE_KEY_READ_RECEIPT, mReadReceipt); outState.putBoolean(STATE_KEY_DRAFT_NEEDS_SAVING, mDraftNeedsSaving); outState.putBoolean(STATE_KEY_FORCE_PLAIN_TEXT, mForcePlainText); outState.putSerializable(STATE_KEY_QUOTED_TEXT_FORMAT, mQuotedTextFormat); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mAttachments.removeAllViews(); mMaxLoaderId = 0; mNumAttachmentsLoading = savedInstanceState.getInt(STATE_KEY_NUM_ATTACHMENTS_LOADING); mWaitingForAttachments = WaitingAction.NONE; try { String waitingFor = savedInstanceState.getString(STATE_KEY_WAITING_FOR_ATTACHMENTS); mWaitingForAttachments = WaitingAction.valueOf(waitingFor); } catch (Exception e) { Log.w(K9.LOG_TAG, "Couldn't read value \" + STATE_KEY_WAITING_FOR_ATTACHMENTS +" + "\" from saved instance state", e); } ArrayList<Attachment> attachments = savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS); for (Attachment attachment : attachments) { addAttachmentView(attachment); if (attachment.loaderId > mMaxLoaderId) { mMaxLoaderId = attachment.loaderId; } if (attachment.state == Attachment.LoadingState.URI_ONLY) { initAttachmentInfoLoader(attachment); } else if (attachment.state == Attachment.LoadingState.METADATA) { initAttachmentContentLoader(attachment); } } mReadReceipt = savedInstanceState .getBoolean(STATE_KEY_READ_RECEIPT); mCcWrapper.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE : View.GONE); mBccWrapper.setVisibility(savedInstanceState .getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE); // This method is called after the action bar menu has already been created and prepared. // So compute the visibility of the "Add Cc/Bcc" menu item again. computeAddCcBccVisibility(); showOrHideQuotedText( (QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE)); mQuotedHtmlContent = (InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE); if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) { mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } mDraftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID); mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY); mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED); mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA); mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO); mReferences = savedInstanceState.getString(STATE_REFERENCES); mDraftNeedsSaving = savedInstanceState.getBoolean(STATE_KEY_DRAFT_NEEDS_SAVING); mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT); mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable( STATE_KEY_QUOTED_TEXT_FORMAT); initializeCrypto(); updateFrom(); updateSignature(); updateEncryptLayout(); updateMessageFormat(); } private void setTitle() { switch (mAction) { case REPLY: { setTitle(R.string.compose_title_reply); break; } case REPLY_ALL: { setTitle(R.string.compose_title_reply_all); break; } case FORWARD: { setTitle(R.string.compose_title_forward); break; } case COMPOSE: default: { setTitle(R.string.compose_title_compose); break; } } } private void addAddresses(MultiAutoCompleteTextView view, String addresses) { if (StringUtils.isNullOrEmpty(addresses)) { return; } for (String address : addresses.split(",")) { addAddress(view, new Address(address, "")); } } private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) { if (addresses == null) { return; } for (Address address : addresses) { addAddress(view, address); } } private void addAddress(MultiAutoCompleteTextView view, Address address) { view.append(address + ", "); } private Address[] getAddresses(MultiAutoCompleteTextView view) { return Address.parseUnencoded(view.getText().toString().trim()); } /* * Returns an Address array of recipients this email will be sent to. * @return Address array of recipients this email will be sent to. */ private Address[] getRecipientAddresses() { String addresses = mToView.getText().toString() + mCcView.getText().toString() + mBccView.getText().toString(); return Address.parseUnencoded(addresses.trim()); } /* * Build the Body that will contain the text of the message. We'll decide where to * include it later. Draft messages are treated somewhat differently in that signatures are not * appended and HTML separators between composed text and quoted text are not added. * @param isDraft If we should build a message that will be saved as a draft (as opposed to sent). */ private TextBody buildText(boolean isDraft) { return buildText(isDraft, mMessageFormat); } /** * Build the {@link Body} that will contain the text of the message. * * <p> * Draft messages are treated somewhat differently in that signatures are not appended and HTML * separators between composed text and quoted text are not added. * </p> * * @param isDraft * If {@code true} we build a message that will be saved as a draft (as opposed to * sent). * @param messageFormat * Specifies what type of message to build ({@code text/plain} vs. {@code text/html}). * * @return {@link TextBody} instance that contains the entered text and possibly the quoted * original message. */ private TextBody buildText(boolean isDraft, SimpleMessageFormat messageFormat) { // The length of the formatted version of the user-supplied text/reply int composedMessageLength; // The offset of the user-supplied text/reply in the final text body int composedMessageOffset; /* * Find out if we need to include the original message as quoted text. * * We include the quoted text in the body if the user didn't choose to hide it. We always * include the quoted text when we're saving a draft. That's so the user is able to * "un-hide" the quoted text if (s)he opens a saved draft. */ boolean includeQuotedText = (mQuotedTextMode.equals(QuotedTextMode.SHOW) || isDraft); // Reply after quote makes no sense for HEADER style replies boolean replyAfterQuote = (mQuoteStyle == QuoteStyle.HEADER) ? false : mAccount.isReplyAfterQuote(); boolean signatureBeforeQuotedText = mAccount.isSignatureBeforeQuotedText(); // Get the user-supplied text String text = mMessageContentView.getCharacters(); // Handle HTML separate from the rest of the text content if (messageFormat == SimpleMessageFormat.HTML) { // Do we have to modify an existing message to include our reply? if (includeQuotedText && mQuotedHtmlContent != null) { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "insertable: " + mQuotedHtmlContent.toDebugString()); } if (!isDraft) { // Append signature to the reply if (replyAfterQuote || signatureBeforeQuotedText) { text = appendSignature(text); } } // Convert the text to HTML text = HtmlConverter.textToHtmlFragment(text); /* * Set the insertion location based upon our reply after quote setting. * Additionally, add some extra separators between the composed message and quoted * message depending on the quote location. We only add the extra separators when * we're sending, that way when we load a draft, we don't have to know the length * of the separators to remove them before editing. */ if (replyAfterQuote) { mQuotedHtmlContent.setInsertionLocation( InsertableHtmlContent.InsertionLocation.AFTER_QUOTE); if (!isDraft) { text = "<br clear=\"all\">" + text; } } else { mQuotedHtmlContent.setInsertionLocation( InsertableHtmlContent.InsertionLocation.BEFORE_QUOTE); if (!isDraft) { text += "<br><br>"; } } if (!isDraft) { // Place signature immediately after the quoted text if (!(replyAfterQuote || signatureBeforeQuotedText)) { mQuotedHtmlContent.insertIntoQuotedFooter(getSignatureHtml()); } } mQuotedHtmlContent.setUserContent(text); // Save length of the body and its offset. This is used when thawing drafts. composedMessageLength = text.length(); composedMessageOffset = mQuotedHtmlContent.getInsertionPoint(); text = mQuotedHtmlContent.toString(); } else { // There is no text to quote so simply append the signature if available if (!isDraft) { text = appendSignature(text); } // Convert the text to HTML text = HtmlConverter.textToHtmlFragment(text); //TODO: Wrap this in proper HTML tags composedMessageLength = text.length(); composedMessageOffset = 0; } } else { // Capture composed message length before we start attaching quoted parts and signatures. composedMessageLength = text.length(); composedMessageOffset = 0; if (!isDraft) { // Append signature to the text/reply if (replyAfterQuote || signatureBeforeQuotedText) { text = appendSignature(text); } } String quotedText = mQuotedText.getCharacters(); if (includeQuotedText && quotedText.length() > 0) { if (replyAfterQuote) { composedMessageOffset = quotedText.length() + "\r\n".length(); text = quotedText + "\r\n" + text; } else { text += "\r\n\r\n" + quotedText.toString(); } } if (!isDraft) { // Place signature immediately after the quoted text if (!(replyAfterQuote || signatureBeforeQuotedText)) { text = appendSignature(text); } } } TextBody body = new TextBody(text); body.setComposedMessageLength(composedMessageLength); body.setComposedMessageOffset(composedMessageOffset); return body; } /** * Build the final message to be sent (or saved). If there is another message quoted in this one, it will be baked * into the final message here. * @param isDraft Indicates if this message is a draft or not. Drafts do not have signatures * appended and have some extra metadata baked into their header for use during thawing. * @return Message to be sent. * @throws MessagingException */ private MimeMessage createMessage(boolean isDraft) throws MessagingException { MimeMessage message = new MimeMessage(); message.addSentDate(new Date()); Address from = new Address(mIdentity.getEmail(), mIdentity.getName()); message.setFrom(from); message.setRecipients(RecipientType.TO, getAddresses(mToView)); message.setRecipients(RecipientType.CC, getAddresses(mCcView)); message.setRecipients(RecipientType.BCC, getAddresses(mBccView)); message.setSubject(mSubjectView.getText().toString()); if (mReadReceipt) { message.setHeader("Disposition-Notification-To", from.toEncodedString()); message.setHeader("X-Confirm-Reading-To", from.toEncodedString()); message.setHeader("Return-Receipt-To", from.toEncodedString()); } message.setHeader("User-Agent", getString(R.string.message_header_mua)); final String replyTo = mIdentity.getReplyTo(); if (replyTo != null) { message.setReplyTo(new Address[] { new Address(replyTo) }); } if (mInReplyTo != null) { message.setInReplyTo(mInReplyTo); } if (mReferences != null) { message.setReferences(mReferences); } // Build the body. // TODO FIXME - body can be either an HTML or Text part, depending on whether we're in // HTML mode or not. Should probably fix this so we don't mix up html and text parts. TextBody body = null; if (mPgpData.getEncryptedData() != null) { String text = mPgpData.getEncryptedData(); body = new TextBody(text); } else { body = buildText(isDraft); } // text/plain part when mMessageFormat == MessageFormat.HTML TextBody bodyPlain = null; final boolean hasAttachments = mAttachments.getChildCount() > 0; if (mMessageFormat == SimpleMessageFormat.HTML) { // HTML message (with alternative text part) // This is the compiled MIME part for an HTML message. MimeMultipart composedMimeMessage = new MimeMultipart(); composedMimeMessage.setSubType("alternative"); // Let the receiver select either the text or the HTML part. composedMimeMessage.addBodyPart(new MimeBodyPart(body, "text/html")); bodyPlain = buildText(isDraft, SimpleMessageFormat.TEXT); composedMimeMessage.addBodyPart(new MimeBodyPart(bodyPlain, "text/plain")); if (hasAttachments) { // If we're HTML and have attachments, we have a MimeMultipart container to hold the // whole message (mp here), of which one part is a MimeMultipart container // (composedMimeMessage) with the user's composed messages, and subsequent parts for // the attachments. MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(composedMimeMessage)); addAttachmentsToMessage(mp); message.setBody(mp); } else { // If no attachments, our multipart/alternative part is the only one we need. message.setBody(composedMimeMessage); } } else if (mMessageFormat == SimpleMessageFormat.TEXT) { // Text-only message. if (hasAttachments) { MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(new MimeBodyPart(body, "text/plain")); addAttachmentsToMessage(mp); message.setBody(mp); } else { // No attachments to include, just stick the text body in the message and call it good. message.setBody(body); } } // If this is a draft, add metadata for thawing. if (isDraft) { // Add the identity to the message. message.addHeader(K9.IDENTITY_HEADER, buildIdentityHeader(body, bodyPlain)); } return message; } /** * Add attachments as parts into a MimeMultipart container. * @param mp MimeMultipart container in which to insert parts. * @throws MessagingException */ private void addAttachmentsToMessage(final MimeMultipart mp) throws MessagingException { Body body; for (int i = 0, count = mAttachments.getChildCount(); i < count; i++) { Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag(); if (attachment.state != Attachment.LoadingState.COMPLETE) { continue; } String contentType = attachment.contentType; if (MimeUtil.isMessage(contentType)) { body = new TempFileMessageBody(attachment.filename); } else { body = new TempFileBody(attachment.filename); } MimeBodyPart bp = new MimeBodyPart(body); /* * Correctly encode the filename here. Otherwise the whole * header value (all parameters at once) will be encoded by * MimeHeader.writeTo(). */ bp.addHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\r\n name=\"%s\"", contentType, EncoderUtil.encodeIfNecessary(attachment.name, EncoderUtil.Usage.WORD_ENTITY, 7))); bp.setEncoding(MimeUtility.getEncodingforType(contentType)); /* * TODO: Oh the joys of MIME... * * From RFC 2183 (The Content-Disposition Header Field): * "Parameter values longer than 78 characters, or which * contain non-ASCII characters, MUST be encoded as specified * in [RFC 2184]." * * Example: * * Content-Type: application/x-stuff * title*1*=us-ascii'en'This%20is%20even%20more%20 * title*2*=%2A%2A%2Afun%2A%2A%2A%20 * title*3="isn't it!" */ bp.addHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format( "attachment;\r\n filename=\"%s\";\r\n size=%d", attachment.name, attachment.size)); mp.addBodyPart(bp); } } // FYI, there's nothing in the code that requires these variables to one letter. They're one // letter simply to save space. This name sucks. It's too similar to Account.Identity. private enum IdentityField { LENGTH("l"), OFFSET("o"), FOOTER_OFFSET("fo"), PLAIN_LENGTH("pl"), PLAIN_OFFSET("po"), MESSAGE_FORMAT("f"), MESSAGE_READ_RECEIPT("r"), SIGNATURE("s"), NAME("n"), EMAIL("e"), // TODO - store a reference to the message being replied so we can mark it at the time of send. ORIGINAL_MESSAGE("m"), CURSOR_POSITION("p"), // Where in the message your cursor was when you saved. QUOTED_TEXT_MODE("q"), QUOTE_STYLE("qs"); private final String value; IdentityField(String value) { this.value = value; } public String value() { return value; } /** * Get the list of IdentityFields that should be integer values. * * <p> * These values are sanity checked for integer-ness during decoding. * </p> * * @return The list of integer {@link IdentityField}s. */ public static IdentityField[] getIntegerFields() { return new IdentityField[] { LENGTH, OFFSET, FOOTER_OFFSET, PLAIN_LENGTH, PLAIN_OFFSET }; } } // Version identifier for "new style" identity. ! is an impossible value in base64 encoding, so we // use that to determine which version we're in. private static final String IDENTITY_VERSION_1 = "!"; /** * Build the identity header string. This string contains metadata about a draft message to be * used upon loading a draft for composition. This should be generated at the time of saving a * draft.<br> * <br> * This is a URL-encoded key/value pair string. The list of possible values are in {@link IdentityField}. * @param body {@link TextBody} to analyze for body length and offset. * @param bodyPlain {@link TextBody} to analyze for body length and offset. May be null. * @return Identity string. */ private String buildIdentityHeader(final TextBody body, final TextBody bodyPlain) { Uri.Builder uri = new Uri.Builder(); if (body.getComposedMessageLength() != null && body.getComposedMessageOffset() != null) { // See if the message body length is already in the TextBody. uri.appendQueryParameter(IdentityField.LENGTH.value(), body.getComposedMessageLength().toString()); uri.appendQueryParameter(IdentityField.OFFSET.value(), body.getComposedMessageOffset().toString()); } else { // If not, calculate it now. uri.appendQueryParameter(IdentityField.LENGTH.value(), Integer.toString(body.getText().length())); uri.appendQueryParameter(IdentityField.OFFSET.value(), Integer.toString(0)); } if (mQuotedHtmlContent != null) { uri.appendQueryParameter(IdentityField.FOOTER_OFFSET.value(), Integer.toString(mQuotedHtmlContent.getFooterInsertionPoint())); } if (bodyPlain != null) { if (bodyPlain.getComposedMessageLength() != null && bodyPlain.getComposedMessageOffset() != null) { // See if the message body length is already in the TextBody. uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), bodyPlain.getComposedMessageLength().toString()); uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), bodyPlain.getComposedMessageOffset().toString()); } else { // If not, calculate it now. uri.appendQueryParameter(IdentityField.PLAIN_LENGTH.value(), Integer.toString(body.getText().length())); uri.appendQueryParameter(IdentityField.PLAIN_OFFSET.value(), Integer.toString(0)); } } // Save the quote style (useful for forwards). uri.appendQueryParameter(IdentityField.QUOTE_STYLE.value(), mQuoteStyle.name()); // Save the message format for this offset. uri.appendQueryParameter(IdentityField.MESSAGE_FORMAT.value(), mMessageFormat.name()); // If we're not using the standard identity of signature, append it on to the identity blob. if (mIdentity.getSignatureUse() && mSignatureChanged) { uri.appendQueryParameter(IdentityField.SIGNATURE.value(), mSignatureView.getCharacters()); } if (mIdentityChanged) { uri.appendQueryParameter(IdentityField.NAME.value(), mIdentity.getName()); uri.appendQueryParameter(IdentityField.EMAIL.value(), mIdentity.getEmail()); } if (mMessageReference != null) { uri.appendQueryParameter(IdentityField.ORIGINAL_MESSAGE.value(), mMessageReference.toIdentityString()); } uri.appendQueryParameter(IdentityField.CURSOR_POSITION.value(), Integer.toString(mMessageContentView.getSelectionStart())); uri.appendQueryParameter(IdentityField.QUOTED_TEXT_MODE.value(), mQuotedTextMode.name()); String k9identity = IDENTITY_VERSION_1 + uri.build().getEncodedQuery(); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Generated identity: " + k9identity); } return k9identity; } /** * Parse an identity string. Handles both legacy and new (!) style identities. * * @param identityString * The encoded identity string that was saved in a drafts header. * * @return A map containing the value for each {@link IdentityField} in the identity string. */ private Map<IdentityField, String> parseIdentityHeader(final String identityString) { Map<IdentityField, String> identity = new HashMap<IdentityField, String>(); if (K9.DEBUG) Log.d(K9.LOG_TAG, "Decoding identity: " + identityString); if (identityString == null || identityString.length() < 1) { return identity; } // Check to see if this is a "next gen" identity. if (identityString.charAt(0) == IDENTITY_VERSION_1.charAt(0) && identityString.length() > 2) { Uri.Builder builder = new Uri.Builder(); builder.encodedQuery(identityString.substring(1)); // Need to cut off the ! at the beginning. Uri uri = builder.build(); for (IdentityField key : IdentityField.values()) { String value = uri.getQueryParameter(key.value()); if (value != null) { identity.put(key, value); } } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Decoded identity: " + identity.toString()); // Sanity check our Integers so that recipients of this result don't have to. for (IdentityField key : IdentityField.getIntegerFields()) { if (identity.get(key) != null) { try { Integer.parseInt(identity.get(key)); } catch (NumberFormatException e) { Log.e(K9.LOG_TAG, "Invalid " + key.name() + " field in identity: " + identity.get(key)); } } } } else { // Legacy identity if (K9.DEBUG) Log.d(K9.LOG_TAG, "Got a saved legacy identity: " + identityString); StringTokenizer tokens = new StringTokenizer(identityString, ":", false); // First item is the body length. We use this to separate the composed reply from the quoted text. if (tokens.hasMoreTokens()) { String bodyLengthS = Utility.base64Decode(tokens.nextToken()); try { identity.put(IdentityField.LENGTH, Integer.valueOf(bodyLengthS).toString()); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'"); } } if (tokens.hasMoreTokens()) { identity.put(IdentityField.SIGNATURE, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.NAME, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.EMAIL, Utility.base64Decode(tokens.nextToken())); } if (tokens.hasMoreTokens()) { identity.put(IdentityField.QUOTED_TEXT_MODE, Utility.base64Decode(tokens.nextToken())); } } return identity; } private String appendSignature(String originalText) { String text = originalText; if (mIdentity.getSignatureUse()) { String signature = mSignatureView.getCharacters(); if (signature != null && !signature.contentEquals("")) { text += "\r\n" + signature; } } return text; } /** * Get an HTML version of the signature in the #mSignatureView, if any. * @return HTML version of signature. */ private String getSignatureHtml() { String signature = ""; if (mIdentity.getSignatureUse()) { signature = mSignatureView.getCharacters(); if(!StringUtils.isNullOrEmpty(signature)) { signature = HtmlConverter.textToHtmlFragment("\r\n" + signature); } } return signature; } private void sendMessage() { new SendMessageTask().execute(); } private void saveMessage() { new SaveMessageTask().execute(); } private void saveIfNeeded() { if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys() || mEncryptCheckbox.isChecked() || !mAccount.hasDraftsFolder()) { return; } mDraftNeedsSaving = false; saveMessage(); } public void onEncryptionKeySelectionDone() { if (mPgpData.hasEncryptionKeys()) { onSend(); } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } public void onEncryptDone() { if (mPgpData.getEncryptedData() != null) { onSend(); } else { Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show(); } } private void onSend() { if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) { mToView.setError(getString(R.string.message_compose_error_no_recipients)); Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show(); return; } if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SEND; showWaitingForAttachmentDialog(); } else { performSend(); } } private void performSend() { final CryptoProvider crypto = mAccount.getCryptoProvider(); if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) { // key selection before encryption StringBuilder emails = new StringBuilder(); for (Address address : getRecipientAddresses()) { if (emails.length() != 0) { emails.append(','); } emails.append(address.getAddress()); if (!mContinueWithoutPublicKey && !crypto.hasPublicKeyForEmail(this, address.getAddress())) { showDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); return; } } if (emails.length() != 0) { emails.append(','); } emails.append(mIdentity.getEmail()); mPreventDraftSaving = true; if (!crypto.selectEncryptionKeys(MessageCompose.this, emails.toString(), mPgpData)) { mPreventDraftSaving = false; } return; } if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) { if (mPgpData.getEncryptedData() == null) { String text = buildText(false).getText(); mPreventDraftSaving = true; if (!crypto.encrypt(this, text, mPgpData)) { mPreventDraftSaving = false; } return; } } sendMessage(); if (mMessageReference != null && mMessageReference.flag != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "Setting referenced message (" + mMessageReference.folderName + ", " + mMessageReference.uid + ") flag to " + mMessageReference.flag); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).setFlag(account, folderName, sourceMessageUid, mMessageReference.flag, true); } mDraftNeedsSaving = false; finish(); } private void onDiscard() { if (mDraftId != INVALID_DRAFT_ID) { MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftId); mDraftId = INVALID_DRAFT_ID; } mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT); mDraftNeedsSaving = false; finish(); } private void onSave() { if (mWaitingForAttachments != WaitingAction.NONE) { return; } if (mNumAttachmentsLoading > 0) { mWaitingForAttachments = WaitingAction.SAVE; showWaitingForAttachmentDialog(); } else { performSave(); } } private void performSave() { saveIfNeeded(); finish(); } private void onAddCcBcc() { mCcWrapper.setVisibility(View.VISIBLE); mBccWrapper.setVisibility(View.VISIBLE); computeAddCcBccVisibility(); } /** * Hide the 'Add Cc/Bcc' menu item when both fields are visible. */ private void computeAddCcBccVisibility() { if (mMenu != null && mCcWrapper.getVisibility() == View.VISIBLE && mBccWrapper.getVisibility() == View.VISIBLE) { mMenu.findItem(R.id.add_cc_bcc).setVisible(false); } } private void onReadReceipt() { CharSequence txt; if (mReadReceipt == false) { txt = getString(R.string.read_receipt_enabled); mReadReceipt = true; } else { txt = getString(R.string.read_receipt_disabled); mReadReceipt = false; } Context context = getApplicationContext(); Toast toast = Toast.makeText(context, txt, Toast.LENGTH_SHORT); toast.show(); } /** * Kick off a picker for whatever kind of MIME types we'll accept and let Android take over. */ private void onAddAttachment() { if (K9.isGalleryBuggy()) { if (K9.useGalleryBugWorkaround()) { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_use_workaround), Toast.LENGTH_LONG).show(); } else { Toast.makeText(MessageCompose.this, getString(R.string.message_compose_buggy_gallery), Toast.LENGTH_LONG).show(); } } onAddAttachment2("*/*"); } /** * Kick off a picker for the specified MIME type and let Android take over. * * @param mime_type * The MIME type we want our attachment to have. */ private void onAddAttachment2(final String mime_type) { if (mAccount.getCryptoProvider().isAvailable(this)) { Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show(); } Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(mime_type); mIgnoreOnPause = true; startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT); } private void addAttachment(Uri uri) { addAttachment(uri, null); } private void addAttachment(Uri uri, String contentType) { Attachment attachment = new Attachment(); attachment.state = Attachment.LoadingState.URI_ONLY; attachment.uri = uri; attachment.contentType = contentType; attachment.loaderId = ++mMaxLoaderId; addAttachmentView(attachment); initAttachmentInfoLoader(attachment); } private void initAttachmentInfoLoader(Attachment attachment) { LoaderManager loaderManager = getSupportLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentInfoLoaderCallback); } private void initAttachmentContentLoader(Attachment attachment) { LoaderManager loaderManager = getSupportLoaderManager(); Bundle bundle = new Bundle(); bundle.putParcelable(LOADER_ARG_ATTACHMENT, attachment); loaderManager.initLoader(attachment.loaderId, bundle, mAttachmentContentLoaderCallback); } private void addAttachmentView(Attachment attachment) { boolean hasMetadata = (attachment.state != Attachment.LoadingState.URI_ONLY); boolean isLoadingComplete = (attachment.state == Attachment.LoadingState.COMPLETE); View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachments, false); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); View progressBar = view.findViewById(R.id.progressBar); if (hasMetadata) { nameView.setText(attachment.name); } else { nameView.setText(R.string.loading_attachment); } progressBar.setVisibility(isLoadingComplete ? View.GONE : View.VISIBLE); ImageButton delete = (ImageButton) view.findViewById(R.id.attachment_delete); delete.setOnClickListener(MessageCompose.this); delete.setTag(view); view.setTag(attachment); mAttachments.addView(view); } private View getAttachmentView(int loaderId) { for (int i = 0, childCount = mAttachments.getChildCount(); i < childCount; i++) { View view = mAttachments.getChildAt(i); Attachment tag = (Attachment) view.getTag(); if (tag != null && tag.loaderId == loaderId) { return view; } } return null; } private LoaderManager.LoaderCallbacks<Attachment> mAttachmentInfoLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { onFetchAttachmentStarted(); Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentInfoLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { view.setTag(attachment); TextView nameView = (TextView) view.findViewById(R.id.attachment_name); nameView.setText(attachment.name); attachment.loaderId = ++mMaxLoaderId; initAttachmentContentLoader(attachment); } else { onFetchAttachmentFinished(); } getSupportLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; private LoaderManager.LoaderCallbacks<Attachment> mAttachmentContentLoaderCallback = new LoaderManager.LoaderCallbacks<Attachment>() { @Override public Loader<Attachment> onCreateLoader(int id, Bundle args) { Attachment attachment = args.getParcelable(LOADER_ARG_ATTACHMENT); return new AttachmentContentLoader(MessageCompose.this, attachment); } @Override public void onLoadFinished(Loader<Attachment> loader, Attachment attachment) { int loaderId = loader.getId(); View view = getAttachmentView(loaderId); if (view != null) { if (attachment.state == Attachment.LoadingState.COMPLETE) { view.setTag(attachment); View progressBar = view.findViewById(R.id.progressBar); progressBar.setVisibility(View.GONE); } else { mAttachments.removeView(view); } } onFetchAttachmentFinished(); getSupportLoaderManager().destroyLoader(loaderId); } @Override public void onLoaderReset(Loader<Attachment> loader) { onFetchAttachmentFinished(); } }; private void onFetchAttachmentStarted() { mNumAttachmentsLoading += 1; } private void onFetchAttachmentFinished() { // We're not allowed to perform fragment transactions when called from onLoadFinished(). // So we use the Handler to call performStalledAction(). mHandler.sendEmptyMessage(MSG_PERFORM_STALLED_ACTION); } private void performStalledAction() { mNumAttachmentsLoading -= 1; WaitingAction waitingFor = mWaitingForAttachments; mWaitingForAttachments = WaitingAction.NONE; if (waitingFor != WaitingAction.NONE) { dismissWaitingForAttachmentDialog(); } switch (waitingFor) { case SEND: { performSend(); break; } case SAVE: { performSave(); break; } case NONE: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true mPreventDraftSaving = false; if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) { return; } if (resultCode != RESULT_OK) return; if (data == null) { return; } switch (requestCode) { case ACTIVITY_REQUEST_PICK_ATTACHMENT: addAttachment(data.getData()); mDraftNeedsSaving = true; break; case CONTACT_PICKER_TO: case CONTACT_PICKER_CC: case CONTACT_PICKER_BCC: ContactItem contact = mContacts.extractInfoFromContactPickerIntent(data); if (contact == null) { Toast.makeText(this, getString(R.string.error_contact_address_not_found), Toast.LENGTH_LONG).show(); return; } if (contact.emailAddresses.size() > 1) { Intent i = new Intent(this, EmailAddressList.class); i.putExtra(EmailAddressList.EXTRA_CONTACT_ITEM, contact); if (requestCode == CONTACT_PICKER_TO) { startActivityForResult(i, CONTACT_PICKER_TO2); } else if (requestCode == CONTACT_PICKER_CC) { startActivityForResult(i, CONTACT_PICKER_CC2); } else if (requestCode == CONTACT_PICKER_BCC) { startActivityForResult(i, CONTACT_PICKER_BCC2); } return; } if (K9.DEBUG) { List<String> emails = contact.emailAddresses; for (int i = 0; i < emails.size(); i++) { Log.v(K9.LOG_TAG, "email[" + i + "]: " + emails.get(i)); } } String email = contact.emailAddresses.get(0); if (requestCode == CONTACT_PICKER_TO) { addAddress(mToView, new Address(email, "")); } else if (requestCode == CONTACT_PICKER_CC) { addAddress(mCcView, new Address(email, "")); } else if (requestCode == CONTACT_PICKER_BCC) { addAddress(mBccView, new Address(email, "")); } else { return; } break; case CONTACT_PICKER_TO2: case CONTACT_PICKER_CC2: case CONTACT_PICKER_BCC2: String emailAddr = data.getStringExtra(EmailAddressList.EXTRA_EMAIL_ADDRESS); if (requestCode == CONTACT_PICKER_TO2) { addAddress(mToView, new Address(emailAddr, "")); } else if (requestCode == CONTACT_PICKER_CC2) { addAddress(mCcView, new Address(emailAddr, "")); } else if (requestCode == CONTACT_PICKER_BCC2) { addAddress(mBccView, new Address(emailAddr, "")); } break; } } public void doLaunchContactPicker(int resultId) { mIgnoreOnPause = true; startActivityForResult(mContacts.contactPickerIntent(), resultId); } private void onAccountChosen(Account account, Identity identity) { if (!mAccount.equals(account)) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account); } // on draft edit, make sure we don't keep previous message UID if (mAction == Action.EDIT_DRAFT) { mMessageReference = null; } // test whether there is something to save if (mDraftNeedsSaving || (mDraftId != INVALID_DRAFT_ID)) { final long previousDraftId = mDraftId; final Account previousAccount = mAccount; // make current message appear as new mDraftId = INVALID_DRAFT_ID; // actual account switch mAccount = account; if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account"); } saveMessage(); if (previousDraftId != INVALID_DRAFT_ID) { if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: " + previousDraftId); } MessagingController.getInstance(getApplication()).deleteDraft(previousAccount, previousDraftId); } } else { mAccount = account; } // Show CC/BCC text input field when switching to an account that always wants them // displayed. // Please note that we're not hiding the fields if the user switches back to an account // that doesn't have this setting checked. if (mAccount.isAlwaysShowCcBcc()) { onAddCcBcc(); } // not sure how to handle mFolder, mSourceMessage? } switchToIdentity(identity); } private void switchToIdentity(Identity identity) { mIdentity = identity; mIdentityChanged = true; mDraftNeedsSaving = true; updateFrom(); updateBcc(); updateSignature(); updateMessageFormat(); } private void updateFrom() { mChooseIdentityButton.setText(mIdentity.getEmail()); } private void updateBcc() { if (mIdentityChanged) { mBccWrapper.setVisibility(View.VISIBLE); } mBccView.setText(""); addAddresses(mBccView, mAccount.getAlwaysBcc()); } private void updateSignature() { if (mIdentity.getSignatureUse()) { mSignatureView.setCharacters(mIdentity.getSignature()); mSignatureView.setVisibility(View.VISIBLE); } else { mSignatureView.setVisibility(View.GONE); } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.attachment_delete: /* * The view is the delete button, and we have previously set the tag of * the delete button to the view that owns it. We don't use parent because the * view is very complex and could change in the future. */ mAttachments.removeView((View) view.getTag()); mDraftNeedsSaving = true; break; case R.id.quoted_text_show: showOrHideQuotedText(QuotedTextMode.SHOW); updateMessageFormat(); mDraftNeedsSaving = true; break; case R.id.quoted_text_delete: showOrHideQuotedText(QuotedTextMode.HIDE); updateMessageFormat(); mDraftNeedsSaving = true; break; case R.id.quoted_text_edit: mForcePlainText = true; if (mMessageReference != null) { // shouldn't happen... // TODO - Should we check if mSourceMessageBody is already present and bypass the MessagingController call? MessagingController.getInstance(getApplication()).addListener(mListener); final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid); final String folderName = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null); } break; case R.id.identity: showDialog(DIALOG_CHOOSE_IDENTITY); break; } } /** * Show or hide the quoted text. * * @param mode * The value to set {@link #mQuotedTextMode} to. */ private void showOrHideQuotedText(QuotedTextMode mode) { mQuotedTextMode = mode; switch (mode) { case NONE: case HIDE: { if (mode == QuotedTextMode.NONE) { mQuotedTextShow.setVisibility(View.GONE); } else { mQuotedTextShow.setVisibility(View.VISIBLE); } mQuotedTextBar.setVisibility(View.GONE); mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); break; } case SHOW: { mQuotedTextShow.setVisibility(View.GONE); mQuotedTextBar.setVisibility(View.VISIBLE); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { mQuotedText.setVisibility(View.GONE); mQuotedHTML.setVisibility(View.VISIBLE); mQuotedTextEdit.setVisibility(View.VISIBLE); } else { mQuotedText.setVisibility(View.VISIBLE); mQuotedHTML.setVisibility(View.GONE); mQuotedTextEdit.setVisibility(View.GONE); } break; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send: mPgpData.setEncryptionKeys(null); onSend(); break; case R.id.save: if (mEncryptCheckbox.isChecked()) { showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } else { onSave(); } break; case R.id.discard: onDiscard(); break; case R.id.add_cc_bcc: onAddCcBcc(); break; case R.id.add_attachment: onAddAttachment(); break; case R.id.add_attachment_image: onAddAttachment2("image/*"); break; case R.id.add_attachment_video: onAddAttachment2("video/*"); break; case R.id.read_receipt: onReadReceipt(); default: return super.onOptionsItemSelected(item); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.message_compose_option, menu); mMenu = menu; // Disable the 'Save' menu option if Drafts folder is set to -NONE- if (!mAccount.hasDraftsFolder()) { menu.findItem(R.id.save).setEnabled(false); } /* * Show the menu items "Add attachment (Image)" and "Add attachment (Video)" * if the work-around for the Gallery bug is enabled (see Issue 1186). */ menu.findItem(R.id.add_attachment_image).setVisible(K9.useGalleryBugWorkaround()); menu.findItem(R.id.add_attachment_video).setVisible(K9.useGalleryBugWorkaround()); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); computeAddCcBccVisibility(); return true; } @Override public void onBackPressed() { if (mDraftNeedsSaving) { if (mEncryptCheckbox.isChecked()) { showDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } else if (!mAccount.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } else { // Check if editing an existing draft. if (mDraftId == INVALID_DRAFT_ID) { onDiscard(); } else { super.onBackPressed(); } } } private void showWaitingForAttachmentDialog() { String title; switch (mWaitingForAttachments) { case SEND: { title = getString(R.string.fetching_attachment_dialog_title_send); break; } case SAVE: { title = getString(R.string.fetching_attachment_dialog_title_save); break; } default: { return; } } ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(title, getString(R.string.fetching_attachment_dialog_message)); fragment.show(getSupportFragmentManager(), FRAGMENT_WAITING_FOR_ATTACHMENT); } public void onCancel(ProgressDialogFragment fragment) { attachmentProgressDialogCancelled(); } void attachmentProgressDialogCancelled() { mWaitingForAttachments = WaitingAction.NONE; } private void dismissWaitingForAttachmentDialog() { ProgressDialogFragment fragment = (ProgressDialogFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_WAITING_FOR_ATTACHMENT); if (fragment != null) { fragment.dismiss(); } } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE: return new AlertDialog.Builder(this) .setTitle(R.string.save_or_discard_draft_message_dlg_title) .setMessage(R.string.save_or_discard_draft_message_instructions_fmt) .setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onSave(); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); onDiscard(); } }) .create(); case DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED: return new AlertDialog.Builder(this) .setTitle(R.string.refuse_to_save_draft_marked_encrypted_dlg_title) .setMessage(R.string.refuse_to_save_draft_marked_encrypted_instructions_fmt) .setNeutralButton(R.string.okay_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_REFUSE_TO_SAVE_DRAFT_MARKED_ENCRYPTED); } }) .create(); case DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY: return new AlertDialog.Builder(this) .setTitle(R.string.continue_without_public_key_dlg_title) .setMessage(R.string.continue_without_public_key_instructions_fmt) .setPositiveButton(R.string.continue_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); mContinueWithoutPublicKey = true; onSend(); } }) .setNegativeButton(R.string.back_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY); mContinueWithoutPublicKey = false; } }) .create(); case DIALOG_CONFIRM_DISCARD_ON_BACK: return new AlertDialog.Builder(this) .setTitle(R.string.confirm_discard_draft_message_title) .setMessage(R.string.confirm_discard_draft_message) .setPositiveButton(R.string.cancel_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } }) .setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); Toast.makeText(MessageCompose.this, getString(R.string.message_discarded_toast), Toast.LENGTH_LONG).show(); onDiscard(); } }) .create(); case DIALOG_CHOOSE_IDENTITY: Context context = new ContextThemeWrapper(this, (K9.getK9Theme() == K9.Theme.LIGHT) ? R.style.Theme_K9_Dialog_Light : R.style.Theme_K9_Dialog_Dark); Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.send_as); final IdentityAdapter adapter = new IdentityAdapter(context); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { IdentityContainer container = (IdentityContainer) adapter.getItem(which); onAccountChosen(container.account, container.identity); } }); return builder.create(); } return super.onCreateDialog(id); } /** * Add all attachments of an existing message as if they were added by hand. * * @param part * The message part to check for being an attachment. This method will recurse if it's * a multipart part. * @param depth * The recursion depth. Currently unused. * * @return {@code true} if all attachments were able to be attached, {@code false} otherwise. * * @throws MessagingException * In case of an error */ private boolean loadAttachments(Part part, int depth) throws MessagingException { if (part.getBody() instanceof Multipart) { Multipart mp = (Multipart) part.getBody(); boolean ret = true; for (int i = 0, count = mp.getCount(); i < count; i++) { if (!loadAttachments(mp.getBodyPart(i), depth + 1)) { ret = false; } } return ret; } String contentType = MimeUtility.unfoldAndDecode(part.getContentType()); String name = MimeUtility.getHeaderParameter(contentType, "name"); if (name != null) { Body body = part.getBody(); if (body != null && body instanceof LocalAttachmentBody) { final Uri uri = ((LocalAttachmentBody) body).getContentUri(); mHandler.post(new Runnable() { @Override public void run() { addAttachment(uri); } }); } else { return false; } } return true; } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * * @param message * The source message used to populate the various text fields. */ private void processSourceMessage(Message message) { try { switch (mAction) { case REPLY: case REPLY_ALL: { processMessageToReplyTo(message); break; } case FORWARD: { processMessageToForward(message); break; } case EDIT_DRAFT: { processDraftMessage(message); break; } default: { Log.w(K9.LOG_TAG, "processSourceMessage() called with unsupported action"); break; } } } catch (MessagingException me) { /** * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. */ Log.e(K9.LOG_TAG, "Error while processing source message: ", me); } finally { mSourceMessageProcessed = true; mDraftNeedsSaving = false; } updateMessageFormat(); } private void processMessageToReplyTo(Message message) throws MessagingException { if (message.getSubject() != null) { final String subject = PREFIX.matcher(message.getSubject()).replaceFirst(""); if (!subject.toLowerCase(Locale.US).startsWith("re:")) { mSubjectView.setText("Re: " + subject); } else { mSubjectView.setText(subject); } } else { mSubjectView.setText(""); } /* * If a reply-to was included with the message use that, otherwise use the from * or sender address. */ Address[] replyToAddresses; if (message.getReplyTo().length > 0) { replyToAddresses = message.getReplyTo(); } else { replyToAddresses = message.getFrom(); } // if we're replying to a message we sent, we probably meant // to reply to the recipient of that message if (mAccount.isAnIdentity(replyToAddresses)) { replyToAddresses = message.getRecipients(RecipientType.TO); } addAddresses(mToView, replyToAddresses); if (message.getMessageId() != null && message.getMessageId().length() > 0) { mInReplyTo = message.getMessageId(); if (message.getReferences() != null && message.getReferences().length > 0) { StringBuilder buffy = new StringBuilder(); for (int i = 0; i < message.getReferences().length; i++) buffy.append(message.getReferences()[i]); mReferences = buffy.toString() + " " + mInReplyTo; } else { mReferences = mInReplyTo; } } else { if (K9.DEBUG) Log.d(K9.LOG_TAG, "could not get Message-ID."); } // Quote the message and setup the UI. populateUIWithQuotedMessage(mAccount.isDefaultQuotedTextShown()); if (mAction == Action.REPLY || mAction == Action.REPLY_ALL) { Identity useIdentity = null; for (Address address : message.getRecipients(RecipientType.TO)) { Identity identity = mAccount.findIdentity(address); if (identity != null) { useIdentity = identity; break; } } if (useIdentity == null) { if (message.getRecipients(RecipientType.CC).length > 0) { for (Address address : message.getRecipients(RecipientType.CC)) { Identity identity = mAccount.findIdentity(address); if (identity != null) { useIdentity = identity; break; } } } } if (useIdentity != null) { Identity defaultIdentity = mAccount.getIdentity(0); if (useIdentity != defaultIdentity) { switchToIdentity(useIdentity); } } } if (mAction == Action.REPLY_ALL) { if (message.getReplyTo().length > 0) { for (Address address : message.getFrom()) { if (!mAccount.isAnIdentity(address)) { addAddress(mToView, address); } } } for (Address address : message.getRecipients(RecipientType.TO)) { if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) { addAddress(mToView, address); } } if (message.getRecipients(RecipientType.CC).length > 0) { for (Address address : message.getRecipients(RecipientType.CC)) { if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address)) { addAddress(mCcView, address); } } mCcWrapper.setVisibility(View.VISIBLE); } } } private void processMessageToForward(Message message) throws MessagingException { String subject = message.getSubject(); if (subject != null && !subject.toLowerCase(Locale.US).startsWith("fwd:")) { mSubjectView.setText("Fwd: " + subject); } else { mSubjectView.setText(subject); } mQuoteStyle = QuoteStyle.HEADER; // "Be Like Thunderbird" - on forwarded messages, set the message ID // of the forwarded message in the references and the reply to. TB // only includes ID of the message being forwarded in the reference, // even if there are multiple references. if (!StringUtils.isNullOrEmpty(message.getMessageId())) { mInReplyTo = message.getMessageId(); mReferences = mInReplyTo; } else { if (K9.DEBUG) { Log.d(K9.LOG_TAG, "could not get Message-ID."); } } // Quote the message and setup the UI. populateUIWithQuotedMessage(true); if (!mSourceMessageProcessed) { if (!loadAttachments(message, 0)) { mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS); } } } private void processDraftMessage(Message message) throws MessagingException { String showQuotedTextMode = "NONE"; mDraftId = MessagingController.getInstance(getApplication()).getId(message); mSubjectView.setText(message.getSubject()); addAddresses(mToView, message.getRecipients(RecipientType.TO)); if (message.getRecipients(RecipientType.CC).length > 0) { addAddresses(mCcView, message.getRecipients(RecipientType.CC)); mCcWrapper.setVisibility(View.VISIBLE); } Address[] bccRecipients = message.getRecipients(RecipientType.BCC); if (bccRecipients.length > 0) { addAddresses(mBccView, bccRecipients); String bccAddress = mAccount.getAlwaysBcc(); if (bccRecipients.length == 1 && bccAddress != null && bccAddress.equals(bccRecipients[0].toString())) { // If the auto-bcc is the only entry in the BCC list, don't show the Bcc fields. mBccWrapper.setVisibility(View.GONE); } else { mBccWrapper.setVisibility(View.VISIBLE); } } // Read In-Reply-To header from draft final String[] inReplyTo = message.getHeader("In-Reply-To"); if ((inReplyTo != null) && (inReplyTo.length >= 1)) { mInReplyTo = inReplyTo[0]; } // Read References header from draft final String[] references = message.getHeader("References"); if ((references != null) && (references.length >= 1)) { mReferences = references[0]; } if (!mSourceMessageProcessed) { loadAttachments(message, 0); } // Decode the identity header when loading a draft. // See buildIdentityHeader(TextBody) for a detailed description of the composition of this blob. Map<IdentityField, String> k9identity = new HashMap<IdentityField, String>(); if (message.getHeader(K9.IDENTITY_HEADER) != null && message.getHeader(K9.IDENTITY_HEADER).length > 0 && message.getHeader(K9.IDENTITY_HEADER)[0] != null) { k9identity = parseIdentityHeader(message.getHeader(K9.IDENTITY_HEADER)[0]); } Identity newIdentity = new Identity(); if (k9identity.containsKey(IdentityField.SIGNATURE)) { newIdentity.setSignatureUse(true); newIdentity.setSignature(k9identity.get(IdentityField.SIGNATURE)); mSignatureChanged = true; } else { newIdentity.setSignatureUse(message.getFolder().getAccount().getSignatureUse()); newIdentity.setSignature(mIdentity.getSignature()); } if (k9identity.containsKey(IdentityField.NAME)) { newIdentity.setName(k9identity.get(IdentityField.NAME)); mIdentityChanged = true; } else { newIdentity.setName(mIdentity.getName()); } if (k9identity.containsKey(IdentityField.EMAIL)) { newIdentity.setEmail(k9identity.get(IdentityField.EMAIL)); mIdentityChanged = true; } else { newIdentity.setEmail(mIdentity.getEmail()); } if (k9identity.containsKey(IdentityField.ORIGINAL_MESSAGE)) { mMessageReference = null; try { String originalMessage = k9identity.get(IdentityField.ORIGINAL_MESSAGE); MessageReference messageReference = new MessageReference(originalMessage); // Check if this is a valid account in our database Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.accountUuid); if (account != null) { mMessageReference = messageReference; } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "Could not decode message reference in identity.", e); } } int cursorPosition = 0; if (k9identity.containsKey(IdentityField.CURSOR_POSITION)) { try { cursorPosition = Integer.valueOf(k9identity.get(IdentityField.CURSOR_POSITION)).intValue(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not parse cursor position for MessageCompose; continuing.", e); } } if (k9identity.containsKey(IdentityField.QUOTED_TEXT_MODE)) { showQuotedTextMode = k9identity.get(IdentityField.QUOTED_TEXT_MODE); } mIdentity = newIdentity; updateSignature(); updateFrom(); Integer bodyLength = k9identity.get(IdentityField.LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.LENGTH)) : 0; Integer bodyOffset = k9identity.get(IdentityField.OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.OFFSET)) : 0; Integer bodyFooterOffset = k9identity.get(IdentityField.FOOTER_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.FOOTER_OFFSET)) : null; Integer bodyPlainLength = k9identity.get(IdentityField.PLAIN_LENGTH) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_LENGTH)) : null; Integer bodyPlainOffset = k9identity.get(IdentityField.PLAIN_OFFSET) != null ? Integer.valueOf(k9identity.get(IdentityField.PLAIN_OFFSET)) : null; mQuoteStyle = k9identity.get(IdentityField.QUOTE_STYLE) != null ? QuoteStyle.valueOf(k9identity.get(IdentityField.QUOTE_STYLE)) : mAccount.getQuoteStyle(); QuotedTextMode quotedMode; try { quotedMode = QuotedTextMode.valueOf(showQuotedTextMode); } catch (Exception e) { quotedMode = QuotedTextMode.NONE; } // Always respect the user's current composition format preference, even if the // draft was saved in a different format. // TODO - The current implementation doesn't allow a user in HTML mode to edit a draft that wasn't saved with K9mail. String messageFormatString = k9identity.get(IdentityField.MESSAGE_FORMAT); MessageFormat messageFormat = null; if (messageFormatString != null) { try { messageFormat = MessageFormat.valueOf(messageFormatString); } catch (Exception e) { /* do nothing */ } } if (messageFormat == null) { // This message probably wasn't created by us. The exception is legacy // drafts created before the advent of HTML composition. In those cases, // we'll display the whole message (including the quoted part) in the // composition window. If that's the case, try and convert it to text to // match the behavior in text mode. mMessageContentView.setCharacters(getBodyTextFromMessage(message, SimpleMessageFormat.TEXT)); mForcePlainText = true; showOrHideQuotedText(quotedMode); return; } if (messageFormat == MessageFormat.HTML) { Part part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { // Shouldn't happen if we were the one who saved it. mQuotedTextFormat = SimpleMessageFormat.HTML; String text = MimeUtility.getTextFromPart(part); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } if (bodyOffset + bodyLength > text.length()) { // The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid LENGTH/OFFSET"); bodyOffset = 0; bodyLength = 0; } // Grab our reply text. String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); mMessageContentView.setCharacters(HtmlConverter.htmlToText(bodyText)); // Regenerate the quoted html without our user content in it. StringBuilder quotedHTML = new StringBuilder(); quotedHTML.append(text.substring(0, bodyOffset)); // stuff before the reply quotedHTML.append(text.substring(bodyOffset + bodyLength)); if (quotedHTML.length() > 0) { mQuotedHtmlContent = new InsertableHtmlContent(); mQuotedHtmlContent.setQuotedContent(quotedHTML); // We don't know if bodyOffset refers to the header or to the footer mQuotedHtmlContent.setHeaderInsertionPoint(bodyOffset); if (bodyFooterOffset != null) { mQuotedHtmlContent.setFooterInsertionPoint(bodyFooterOffset); } else { mQuotedHtmlContent.setFooterInsertionPoint(bodyOffset); } mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); } } if (bodyPlainOffset != null && bodyPlainLength != null) { processSourceMessageText(message, bodyPlainOffset, bodyPlainLength, false); } } else if (messageFormat == MessageFormat.TEXT) { mQuotedTextFormat = SimpleMessageFormat.TEXT; processSourceMessageText(message, bodyOffset, bodyLength, true); } else { Log.e(K9.LOG_TAG, "Unhandled message format."); } // Set the cursor position if we have it. try { mMessageContentView.setSelection(cursorPosition); } catch (Exception e) { Log.e(K9.LOG_TAG, "Could not set cursor position in MessageCompose; ignoring.", e); } showOrHideQuotedText(quotedMode); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. * @param message Source message * @param bodyOffset Insertion point for reply. * @param bodyLength Length of reply. * @param viewMessageContent Update mMessageContentView or not. * @throws MessagingException */ private void processSourceMessageText(Message message, Integer bodyOffset, Integer bodyLength, boolean viewMessageContent) throws MessagingException { Part textPart = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (textPart != null) { String text = MimeUtility.getTextFromPart(textPart); if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Loading message with offset " + bodyOffset + ", length " + bodyLength + ". Text length is " + text.length() + "."); } // If we had a body length (and it was valid), separate the composition from the quoted text // and put them in their respective places in the UI. if (bodyLength > 0) { try { String bodyText = text.substring(bodyOffset, bodyOffset + bodyLength); // Regenerate the quoted text without our user content in it nor added newlines. StringBuilder quotedText = new StringBuilder(); if (bodyOffset == 0 && text.substring(bodyLength, bodyLength + 4).equals("\r\n\r\n")) { // top-posting: ignore two newlines at start of quote quotedText.append(text.substring(bodyLength + 4)); } else if (bodyOffset + bodyLength == text.length() && text.substring(bodyOffset - 2, bodyOffset).equals("\r\n")) { // bottom-posting: ignore newline at end of quote quotedText.append(text.substring(0, bodyOffset - 2)); } else { quotedText.append(text.substring(0, bodyOffset)); // stuff before the reply quotedText.append(text.substring(bodyOffset + bodyLength)); } if (viewMessageContent) { mMessageContentView.setCharacters(bodyText); } mQuotedText.setCharacters(quotedText); } catch (IndexOutOfBoundsException e) { // Invalid bodyOffset or bodyLength. The draft was edited outside of K-9 Mail? Log.d(K9.LOG_TAG, "The identity field from the draft contains an invalid bodyOffset/bodyLength"); if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } else { if (viewMessageContent) { mMessageContentView.setCharacters(text); } } } } // Regexes to check for signature. private static final Pattern DASH_SIGNATURE_PLAIN = Pattern.compile("\r\n-- \r\n.*", Pattern.DOTALL); private static final Pattern DASH_SIGNATURE_HTML = Pattern.compile("(<br( /)?>|\r?\n)-- <br( /)?>", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_START = Pattern.compile("<blockquote", Pattern.CASE_INSENSITIVE); private static final Pattern BLOCKQUOTE_END = Pattern.compile("</blockquote>", Pattern.CASE_INSENSITIVE); /** * Build and populate the UI with the quoted message. * * @param showQuotedText * {@code true} if the quoted text should be shown, {@code false} otherwise. * * @throws MessagingException */ private void populateUIWithQuotedMessage(boolean showQuotedText) throws MessagingException { MessageFormat origMessageFormat = mAccount.getMessageFormat(); if (mForcePlainText || origMessageFormat == MessageFormat.TEXT) { // Use plain text for the quoted message mQuotedTextFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { // Figure out which message format to use for the quoted text by looking if the source // message contains a text/html part. If it does, we use that. mQuotedTextFormat = (MimeUtility.findFirstPartByMimeType(mSourceMessage, "text/html") == null) ? SimpleMessageFormat.TEXT : SimpleMessageFormat.HTML; } else { mQuotedTextFormat = SimpleMessageFormat.HTML; } // TODO -- I am assuming that mSourceMessageBody will always be a text part. Is this a safe assumption? // Handle the original message in the reply // If we already have mSourceMessageBody, use that. It's pre-populated if we've got crypto going on. String content = (mSourceMessageBody != null) ? mSourceMessageBody : getBodyTextFromMessage(mSourceMessage, mQuotedTextFormat); if (mQuotedTextFormat == SimpleMessageFormat.HTML) { // Strip signature. // closing tags such as </div>, </span>, </table>, </pre> will be cut off. if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { Matcher dashSignatureHtml = DASH_SIGNATURE_HTML.matcher(content); if (dashSignatureHtml.find()) { Matcher blockquoteStart = BLOCKQUOTE_START.matcher(content); Matcher blockquoteEnd = BLOCKQUOTE_END.matcher(content); List<Integer> start = new ArrayList<Integer>(); List<Integer> end = new ArrayList<Integer>(); while(blockquoteStart.find()) { start.add(blockquoteStart.start()); } while(blockquoteEnd.find()) { end.add(blockquoteEnd.start()); } if (start.size() != end.size()) { Log.d(K9.LOG_TAG, "There are " + start.size() + " <blockquote> tags, but " + end.size() + " </blockquote> tags. Refusing to strip."); } else if (start.size() > 0) { // Ignore quoted signatures in blockquotes. dashSignatureHtml.region(0, start.get(0)); if (dashSignatureHtml.find()) { // before first <blockquote>. content = content.substring(0, dashSignatureHtml.start()); } else { for (int i = 0; i < start.size() - 1; i++) { // within blockquotes. if (end.get(i) < start.get(i+1)) { dashSignatureHtml.region(end.get(i), start.get(i+1)); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); break; } } } if (end.get(end.size() - 1) < content.length()) { // after last </blockquote>. dashSignatureHtml.region(end.get(end.size() - 1), content.length()); if (dashSignatureHtml.find()) { content = content.substring(0, dashSignatureHtml.start()); } } } } else { // No blockquotes found. content = content.substring(0, dashSignatureHtml.start()); } } // Fix the stripping off of closing tags if a signature was stripped, // as well as clean up the HTML of the quoted message. HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties properties = cleaner.getProperties(); // see http://htmlcleaner.sourceforge.net/parameters.php for descriptions properties.setNamespacesAware(false); properties.setAdvancedXmlEscape(false); properties.setOmitXmlDeclaration(true); properties.setOmitDoctypeDeclaration(false); properties.setTranslateSpecialEntities(false); properties.setRecognizeUnicodeChars(false); TagNode node = cleaner.clean(content); SimpleHtmlSerializer htmlSerialized = new SimpleHtmlSerializer(properties); try { content = htmlSerialized.getAsString(node, "UTF8"); } catch (java.io.IOException ioe) { // Can't imagine this happening. Log.e(K9.LOG_TAG, "Problem cleaning quoted message.", ioe); } } // Add the HTML reply header to the top of the content. mQuotedHtmlContent = quoteOriginalHtmlMessage(mSourceMessage, content, mQuoteStyle); // Load the message with the reply header. mQuotedHTML.setText(mQuotedHtmlContent.getQuotedContent()); // TODO: Also strip the signature from the text/plain part mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, getBodyTextFromMessage(mSourceMessage, SimpleMessageFormat.TEXT), mQuoteStyle)); } else if (mQuotedTextFormat == SimpleMessageFormat.TEXT) { if (mAccount.isStripSignature() && (mAction == Action.REPLY || mAction == Action.REPLY_ALL)) { if (DASH_SIGNATURE_PLAIN.matcher(content).find()) { content = DASH_SIGNATURE_PLAIN.matcher(content).replaceFirst("\r\n"); } } mQuotedText.setCharacters(quoteOriginalTextMessage(mSourceMessage, content, mQuoteStyle)); } if (showQuotedText) { showOrHideQuotedText(QuotedTextMode.SHOW); } else { showOrHideQuotedText(QuotedTextMode.HIDE); } } /** * Fetch the body text from a message in the desired message format. This method handles * conversions between formats (html to text and vice versa) if necessary. * @param message Message to analyze for body part. * @param format Desired format. * @return Text in desired format. * @throws MessagingException */ private String getBodyTextFromMessage(final Message message, final SimpleMessageFormat format) throws MessagingException { Part part; if (format == SimpleMessageFormat.HTML) { // HTML takes precedence, then text. part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, HTML found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: HTML requested, text found."); return HtmlConverter.textToHtml(MimeUtility.getTextFromPart(part)); } } else if (format == SimpleMessageFormat.TEXT) { // Text takes precedence, then html. part = MimeUtility.findFirstPartByMimeType(message, "text/plain"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, text found."); return MimeUtility.getTextFromPart(part); } part = MimeUtility.findFirstPartByMimeType(message, "text/html"); if (part != null) { if (K9.DEBUG) Log.d(K9.LOG_TAG, "getBodyTextFromMessage: Text requested, HTML found."); return HtmlConverter.htmlToText(MimeUtility.getTextFromPart(part)); } } // If we had nothing interesting, return an empty string. return ""; } // Regular expressions to look for various HTML tags. This is no HTML::Parser, but hopefully it's good enough for // our purposes. private static final Pattern FIND_INSERTION_POINT_HTML = Pattern.compile("(?si:.*?(<html(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HEAD = Pattern.compile("(?si:.*?(<head(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_BODY = Pattern.compile("(?si:.*?(<body(?:>|\\s+[^>]*>)).*)"); private static final Pattern FIND_INSERTION_POINT_HTML_END = Pattern.compile("(?si:.*(</html>).*?)"); private static final Pattern FIND_INSERTION_POINT_BODY_END = Pattern.compile("(?si:.*(</body>).*?)"); // The first group in a Matcher contains the first capture group. We capture the tag found in the above REs so that // we can locate the *end* of that tag. private static final int FIND_INSERTION_POINT_FIRST_GROUP = 1; // HTML bits to insert as appropriate // TODO is it safe to assume utf-8 here? private static final String FIND_INSERTION_POINT_HTML_CONTENT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\r\n<html>"; private static final String FIND_INSERTION_POINT_HTML_END_CONTENT = "</html>"; private static final String FIND_INSERTION_POINT_HEAD_CONTENT = "<head><meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\"></head>"; // Index of the start of the beginning of a String. private static final int FIND_INSERTION_POINT_START_OF_STRING = 0; /** * <p>Find the start and end positions of the HTML in the string. This should be the very top * and bottom of the displayable message. It returns a {@link InsertableHtmlContent}, which * contains both the insertion points and potentially modified HTML. The modified HTML should be * used in place of the HTML in the original message.</p> * * <p>This method loosely mimics the HTML forward/reply behavior of BlackBerry OS 4.5/BIS 2.5, which in turn mimics * Outlook 2003 (as best I can tell).</p> * * @param content Content to examine for HTML insertion points * @return Insertion points and HTML to use for insertion. */ private InsertableHtmlContent findInsertionPoints(final String content) { InsertableHtmlContent insertable = new InsertableHtmlContent(); // If there is no content, don't bother doing any of the regex dancing. if (content == null || content.equals("")) { return insertable; } // Search for opening tags. boolean hasHtmlTag = false; boolean hasHeadTag = false; boolean hasBodyTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlMatcher = FIND_INSERTION_POINT_HTML.matcher(content); if (htmlMatcher.matches()) { hasHtmlTag = true; } // Look for a HEAD tag. If we're missing a BODY tag, we'll use the close of the HEAD to start our content. Matcher headMatcher = FIND_INSERTION_POINT_HEAD.matcher(content); if (headMatcher.matches()) { hasHeadTag = true; } // Look for a BODY tag. This is the ideal place for us to start our content. Matcher bodyMatcher = FIND_INSERTION_POINT_BODY.matcher(content); if (bodyMatcher.matches()) { hasBodyTag = true; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Open: hasHtmlTag:" + hasHtmlTag + " hasHeadTag:" + hasHeadTag + " hasBodyTag:" + hasBodyTag); // Given our inspections, let's figure out where to start our content. // This is the ideal case -- there's a BODY tag and we insert ourselves just after it. if (hasBodyTag) { insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(bodyMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHeadTag) { // Now search for a HEAD tag. We can insert after there. // If BlackBerry sees a HEAD tag, it inserts right after that, so long as there is no BODY tag. It doesn't // try to add BODY, either. Right or wrong, it seems to work fine. insertable.setQuotedContent(new StringBuilder(content)); insertable.setHeaderInsertionPoint(headMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlTag) { // Lastly, check for an HTML tag. // In this case, it will add a HEAD, but no BODY. StringBuilder newContent = new StringBuilder(content); // Insert the HEAD content just after the HTML tag. newContent.insert(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP), FIND_INSERTION_POINT_HEAD_CONTENT); insertable.setQuotedContent(newContent); // The new insertion point is the end of the HTML tag, plus the length of the HEAD content. insertable.setHeaderInsertionPoint(htmlMatcher.end(FIND_INSERTION_POINT_FIRST_GROUP) + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } else { // If we have none of the above, we probably have a fragment of HTML. Yahoo! and Gmail both do this. // Again, we add a HEAD, but not BODY. StringBuilder newContent = new StringBuilder(content); // Add the HTML and HEAD tags. newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HEAD_CONTENT); newContent.insert(FIND_INSERTION_POINT_START_OF_STRING, FIND_INSERTION_POINT_HTML_CONTENT); // Append the </HTML> tag. newContent.append(FIND_INSERTION_POINT_HTML_END_CONTENT); insertable.setQuotedContent(newContent); insertable.setHeaderInsertionPoint(FIND_INSERTION_POINT_HTML_CONTENT.length() + FIND_INSERTION_POINT_HEAD_CONTENT.length()); } // Search for closing tags. We have to do this after we deal with opening tags since it may // have modified the message. boolean hasHtmlEndTag = false; boolean hasBodyEndTag = false; // First see if we have an opening HTML tag. If we don't find one, we'll add one later. Matcher htmlEndMatcher = FIND_INSERTION_POINT_HTML_END.matcher(insertable.getQuotedContent()); if (htmlEndMatcher.matches()) { hasHtmlEndTag = true; } // Look for a BODY tag. This is the ideal place for us to place our footer. Matcher bodyEndMatcher = FIND_INSERTION_POINT_BODY_END.matcher(insertable.getQuotedContent()); if (bodyEndMatcher.matches()) { hasBodyEndTag = true; } if (K9.DEBUG) Log.d(K9.LOG_TAG, "Close: hasHtmlEndTag:" + hasHtmlEndTag + " hasBodyEndTag:" + hasBodyEndTag); // Now figure out where to put our footer. // This is the ideal case -- there's a BODY tag and we insert ourselves just before it. if (hasBodyEndTag) { insertable.setFooterInsertionPoint(bodyEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else if (hasHtmlEndTag) { // Check for an HTML tag. Add ourselves just before it. insertable.setFooterInsertionPoint(htmlEndMatcher.start(FIND_INSERTION_POINT_FIRST_GROUP)); } else { // If we have none of the above, we probably have a fragment of HTML. // Set our footer insertion point as the end of the string. insertable.setFooterInsertionPoint(insertable.getQuotedContent().length()); } return insertable; } class Listener extends MessagingListener { @Override public void loadMessageForViewStarted(Account account, String folder, String uid) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_ON); } @Override public void loadMessageForViewFinished(Account account, String folder, String uid, Message message) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); } @Override public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mSourceMessage = message; runOnUiThread(new Runnable() { @Override public void run() { // We check to see if we've previously processed the source message since this // could be called when switching from HTML to text replies. If that happens, we // only want to update the UI with quoted text (which picks the appropriate // part). if (mSourceProcessed) { try { populateUIWithQuotedMessage(true); } catch (MessagingException e) { // Hm, if we couldn't populate the UI after source reprocessing, let's just delete it? showOrHideQuotedText(QuotedTextMode.HIDE); Log.e(K9.LOG_TAG, "Could not re-process source message; deleting quoted text to be safe.", e); } updateMessageFormat(); } else { processSourceMessage(message); mSourceProcessed = true; } } }); } @Override public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t) { if ((mMessageReference == null) || !mMessageReference.uid.equals(uid)) { return; } mHandler.sendEmptyMessage(MSG_PROGRESS_OFF); // TODO show network error } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { // Track UID changes of the source message if (mMessageReference != null) { final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.accountUuid); final String sourceFolder = mMessageReference.folderName; final String sourceMessageUid = mMessageReference.uid; if (account.equals(sourceAccount) && (folder.equals(sourceFolder))) { if (oldUid.equals(sourceMessageUid)) { mMessageReference.uid = newUid; } if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid()))) { mSourceMessage.setUid(newUid); } } } } } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailtoUri * The mailto: URI we use to initialize the message fields. */ private void initializeFromMailto(Uri mailtoUri) { String schemaSpecific = mailtoUri.getSchemeSpecificPart(); int end = schemaSpecific.indexOf('?'); if (end == -1) { end = schemaSpecific.length(); } // Extract the recipient's email address from the mailto URI if there's one. String recipient = Uri.decode(schemaSpecific.substring(0, end)); /* * mailto URIs are not hierarchical. So calling getQueryParameters() * will throw an UnsupportedOperationException. We avoid this by * creating a new hierarchical dummy Uri object with the query * parameters of the original URI. */ CaseInsensitiveParamWrapper uri = new CaseInsensitiveParamWrapper( Uri.parse("foo://bar?" + mailtoUri.getEncodedQuery())); // Read additional recipients from the "to" parameter. List<String> to = uri.getQueryParameters("to"); if (recipient.length() != 0) { to = new ArrayList<String>(to); to.add(0, recipient); } addRecipients(mToView, to); // Read carbon copy recipients from the "cc" parameter. boolean ccOrBcc = addRecipients(mCcView, uri.getQueryParameters("cc")); // Read blind carbon copy recipients from the "bcc" parameter. ccOrBcc |= addRecipients(mBccView, uri.getQueryParameters("bcc")); if (ccOrBcc) { // Display CC and BCC text fields if CC or BCC recipients were set by the intent. onAddCcBcc(); } // Read subject from the "subject" parameter. List<String> subject = uri.getQueryParameters("subject"); if (!subject.isEmpty()) { mSubjectView.setText(subject.get(0)); } // Read message body from the "body" parameter. List<String> body = uri.getQueryParameters("body"); if (!body.isEmpty()) { mMessageContentView.setCharacters(body.get(0)); } } private static class CaseInsensitiveParamWrapper { private final Uri uri; private Set<String> mParamNames; public CaseInsensitiveParamWrapper(Uri uri) { this.uri = uri; } public List<String> getQueryParameters(String key) { final List<String> params = new ArrayList<String>(); for (String paramName : getQueryParameterNames()) { if (paramName.equalsIgnoreCase(key)) { params.addAll(uri.getQueryParameters(paramName)); } } return params; } @TargetApi(11) private Set<String> getQueryParameterNames() { if (Build.VERSION.SDK_INT >= 11) { return uri.getQueryParameterNames(); } return getQueryParameterNamesPreSdk11(); } private Set<String> getQueryParameterNamesPreSdk11() { if (mParamNames == null) { String query = uri.getQuery(); Set<String> paramNames = new HashSet<String>(); Collections.addAll(paramNames, query.split("(=[^&]*(&|$))|&")); mParamNames = paramNames; } return mParamNames; } } private class SendMessageTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; try { message = createMessage(false); // isDraft = true } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } try { mContacts.markAsContacted(message.getRecipients(RecipientType.TO)); mContacts.markAsContacted(message.getRecipients(RecipientType.CC)); mContacts.markAsContacted(message.getRecipients(RecipientType.BCC)); } catch (Exception e) { Log.e(K9.LOG_TAG, "Failed to mark contact as contacted.", e); } MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null); long draftId = mDraftId; if (draftId != INVALID_DRAFT_ID) { mDraftId = INVALID_DRAFT_ID; MessagingController.getInstance(getApplication()).deleteDraft(mAccount, draftId); } return null; } } private class SaveMessageTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { /* * Create the message from all the data the user has entered. */ MimeMessage message; try { message = createMessage(true); // isDraft = true } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me); throw new RuntimeException("Failed to create a new message for send or save.", me); } /* * Save a draft */ if (mAction == Action.EDIT_DRAFT) { /* * We're saving a previously saved draft, so update the new message's uid * to the old message's uid. */ if (mMessageReference != null) { message.setUid(mMessageReference.uid); } } final MessagingController messagingController = MessagingController.getInstance(getApplication()); Message draftMessage = messagingController.saveDraft(mAccount, message, mDraftId); mDraftId = messagingController.getId(draftMessage); mHandler.sendEmptyMessage(MSG_SAVED_DRAFT); return null; } } private static final int REPLY_WRAP_LINE_WIDTH = 72; private static final int QUOTE_BUFFER_LENGTH = 512; // amount of extra buffer to allocate to accommodate quoting headers or prefixes /** * Add quoting markup to a text message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Quoted text. * @throws MessagingException */ private String quoteOriginalTextMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { String body = messageBody == null ? "" : messageBody; String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); if (sentDate.length() != 0) { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt_with_date) + "\r\n", sentDate, Address.toString(originalMessage.getFrom()))); } else { quotedText.append(String.format( getString(R.string.message_compose_reply_header_fmt) + "\r\n", Address.toString(originalMessage.getFrom())) ); } final String prefix = mAccount.getQuotePrefix(); final String wrappedText = Utility.wrap(body, REPLY_WRAP_LINE_WIDTH - prefix.length()); // "$" and "\" in the quote prefix have to be escaped for // the replaceAll() invocation. final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1"); quotedText.append(wrappedText.replaceAll("(?m)^", escapedPrefix)); return quotedText.toString().replaceAll("\\\r", ""); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder quotedText = new StringBuilder(body.length() + QUOTE_BUFFER_LENGTH); quotedText.append("\r\n"); quotedText.append(getString(R.string.message_compose_quote_header_separator)).append("\r\n"); if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_from)).append(" ").append(Address.toString(originalMessage.getFrom())).append("\r\n"); } if (sentDate.length() != 0) { quotedText.append(getString(R.string.message_compose_quote_header_send_date)).append(" ").append(sentDate).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_to)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.TO))).append("\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { quotedText.append(getString(R.string.message_compose_quote_header_cc)).append(" ").append(Address.toString(originalMessage.getRecipients(RecipientType.CC))).append("\r\n"); } if (originalMessage.getSubject() != null) { quotedText.append(getString(R.string.message_compose_quote_header_subject)).append(" ").append(originalMessage.getSubject()).append("\r\n"); } quotedText.append("\r\n"); quotedText.append(body); return quotedText.toString(); } else { // Shouldn't ever happen. return body; } } /** * Add quoting markup to a HTML message. * @param originalMessage Metadata for message being quoted. * @param messageBody Text of the message to be quoted. * @param quoteStyle Style of quoting. * @return Modified insertable message. * @throws MessagingException */ private InsertableHtmlContent quoteOriginalHtmlMessage(final Message originalMessage, final String messageBody, final QuoteStyle quoteStyle) throws MessagingException { InsertableHtmlContent insertable = findInsertionPoints(messageBody); String sentDate = getSentDateText(originalMessage); if (quoteStyle == QuoteStyle.PREFIX) { StringBuilder header = new StringBuilder(QUOTE_BUFFER_LENGTH); header.append("<div class=\"gmail_quote\">"); if (sentDate.length() != 0) { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt_with_date), sentDate, Address.toString(originalMessage.getFrom())) )); } else { header.append(HtmlConverter.textToHtmlFragment(String.format( getString(R.string.message_compose_reply_header_fmt), Address.toString(originalMessage.getFrom())) )); } header.append("<blockquote class=\"gmail_quote\" " + "style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\">\r\n"); String footer = "</blockquote></div>"; insertable.insertIntoQuotedHeader(header.toString()); insertable.insertIntoQuotedFooter(footer); } else if (quoteStyle == QuoteStyle.HEADER) { StringBuilder header = new StringBuilder(); header.append("<div style='font-size:10.0pt;font-family:\"Tahoma\",\"sans-serif\";padding:3.0pt 0in 0in 0in'>\r\n"); header.append("<hr style='border:none;border-top:solid #E1E1E1 1.0pt'>\r\n"); // This gets converted into a horizontal line during html to text conversion. if (originalMessage.getFrom() != null && Address.toString(originalMessage.getFrom()).length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_from)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getFrom()))) .append("<br>\r\n"); } if (sentDate.length() != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_send_date)).append("</b> ") .append(sentDate) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.TO) != null && originalMessage.getRecipients(RecipientType.TO).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_to)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.TO)))) .append("<br>\r\n"); } if (originalMessage.getRecipients(RecipientType.CC) != null && originalMessage.getRecipients(RecipientType.CC).length != 0) { header.append("<b>").append(getString(R.string.message_compose_quote_header_cc)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(Address.toString(originalMessage.getRecipients(RecipientType.CC)))) .append("<br>\r\n"); } if (originalMessage.getSubject() != null) { header.append("<b>").append(getString(R.string.message_compose_quote_header_subject)).append("</b> ") .append(HtmlConverter.textToHtmlFragment(originalMessage.getSubject())) .append("<br>\r\n"); } header.append("</div>\r\n"); header.append("<br>\r\n"); insertable.insertIntoQuotedHeader(header.toString()); } return insertable; } /** * Used to store an {@link Identity} instance together with the {@link Account} it belongs to. * * @see IdentityAdapter */ static class IdentityContainer { public final Identity identity; public final Account account; IdentityContainer(Identity identity, Account account) { this.identity = identity; this.account = account; } } /** * Adapter for the <em>Choose identity</em> list view. * * <p> * Account names are displayed as section headers, identities as selectable list items. * </p> */ static class IdentityAdapter extends BaseAdapter { private LayoutInflater mLayoutInflater; private List<Object> mItems; public IdentityAdapter(Context context) { mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); List<Object> items = new ArrayList<Object>(); Preferences prefs = Preferences.getPreferences(context.getApplicationContext()); Account[] accounts = prefs.getAvailableAccounts().toArray(EMPTY_ACCOUNT_ARRAY); for (Account account : accounts) { items.add(account); List<Identity> identities = account.getIdentities(); for (Identity identity : identities) { items.add(new IdentityContainer(identity, account)); } } mItems = items; } @Override public int getCount() { return mItems.size(); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return (mItems.get(position) instanceof Account) ? 0 : 1; } @Override public boolean isEnabled(int position) { return (mItems.get(position) instanceof IdentityContainer); } @Override public Object getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int position, View convertView, ViewGroup parent) { Object item = mItems.get(position); View view = null; if (item instanceof Account) { if (convertView != null && convertView.getTag() instanceof AccountHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_account_item, parent, false); AccountHolder holder = new AccountHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.chip = view.findViewById(R.id.chip); view.setTag(holder); } Account account = (Account) item; AccountHolder holder = (AccountHolder) view.getTag(); holder.name.setText(account.getDescription()); holder.chip.setBackgroundColor(account.getChipColor()); } else if (item instanceof IdentityContainer) { if (convertView != null && convertView.getTag() instanceof IdentityHolder) { view = convertView; } else { view = mLayoutInflater.inflate(R.layout.choose_identity_item, parent, false); IdentityHolder holder = new IdentityHolder(); holder.name = (TextView) view.findViewById(R.id.name); holder.description = (TextView) view.findViewById(R.id.description); view.setTag(holder); } IdentityContainer identityContainer = (IdentityContainer) item; Identity identity = identityContainer.identity; IdentityHolder holder = (IdentityHolder) view.getTag(); holder.name.setText(identity.getDescription()); holder.description.setText(getIdentityDescription(identity)); } return view; } static class AccountHolder { public TextView name; public View chip; } static class IdentityHolder { public TextView name; public TextView description; } } private static String getIdentityDescription(Identity identity) { return String.format("%s <%s>", identity.getName(), identity.getEmail()); } private void setMessageFormat(SimpleMessageFormat format) { // This method will later be used to enable/disable the rich text editing mode. mMessageFormat = format; } private void updateMessageFormat() { MessageFormat origMessageFormat = mAccount.getMessageFormat(); SimpleMessageFormat messageFormat; if (origMessageFormat == MessageFormat.TEXT) { // The user wants to send text/plain messages. We don't override that choice under // any circumstances. messageFormat = SimpleMessageFormat.TEXT; } else if (mForcePlainText && includeQuotedText()) { // Right now we send a text/plain-only message when the quoted text was edited, no // matter what the user selected for the message format. messageFormat = SimpleMessageFormat.TEXT; } else if (mEncryptCheckbox.isChecked() || mCryptoSignatureCheckbox.isChecked()) { // Right now we only support PGP inline which doesn't play well with HTML. So force // plain text in those cases. messageFormat = SimpleMessageFormat.TEXT; } else if (origMessageFormat == MessageFormat.AUTO) { if (mAction == Action.COMPOSE || mQuotedTextFormat == SimpleMessageFormat.TEXT || !includeQuotedText()) { // If the message format is set to "AUTO" we use text/plain whenever possible. That // is, when composing new messages and replying to or forwarding text/plain // messages. messageFormat = SimpleMessageFormat.TEXT; } else { messageFormat = SimpleMessageFormat.HTML; } } else { // In all other cases use HTML messageFormat = SimpleMessageFormat.HTML; } setMessageFormat(messageFormat); } private boolean includeQuotedText() { return (mQuotedTextMode == QuotedTextMode.SHOW); } /** * Extract the date from a message and convert it into a locale-specific * date string suitable for use in a header for a quoted message. * * @param message * @return A string with the formatted date/time */ private String getSentDateText(Message message) { try { final int dateStyle = DateFormat.LONG; final int timeStyle = DateFormat.LONG; Date date = message.getSentDate(); Locale locale = getResources().getConfiguration().locale; return DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale) .format(date); } catch (Exception e) { return ""; } } /** * An {@link EditText} extension with methods that convert line endings from * {@code \r\n} to {@code \n} and back again when setting and getting text. * */ private static class EolConvertingEditText extends EditText { public EolConvertingEditText(Context context, AttributeSet attrs) { super(context, attrs); } /** * Return the text the EolConvertingEditText is displaying. * * @return A string with any line endings converted to {@code \r\n}. */ public String getCharacters() { return getText().toString().replace("\n", "\r\n"); } /** * Sets the string value of the EolConvertingEditText. Any line endings * in the string will be converted to {@code \n}. * * @param text */ public void setCharacters(CharSequence text) { setText(text.toString().replace("\r\n", "\n")); } } }
Restore instance state in correct order Fixes issue 5968
src/com/fsck/k9/activity/MessageCompose.java
Restore instance state in correct order
<ide><path>rc/com/fsck/k9/activity/MessageCompose.java <ide> // So compute the visibility of the "Add Cc/Bcc" menu item again. <ide> computeAddCcBccVisibility(); <ide> <del> showOrHideQuotedText( <del> (QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE)); <del> <ide> mQuotedHtmlContent = <ide> (InsertableHtmlContent) savedInstanceState.getSerializable(STATE_KEY_HTML_QUOTE); <ide> if (mQuotedHtmlContent != null && mQuotedHtmlContent.getQuotedContent() != null) { <ide> mForcePlainText = savedInstanceState.getBoolean(STATE_KEY_FORCE_PLAIN_TEXT); <ide> mQuotedTextFormat = (SimpleMessageFormat) savedInstanceState.getSerializable( <ide> STATE_KEY_QUOTED_TEXT_FORMAT); <add> <add> showOrHideQuotedText( <add> (QuotedTextMode) savedInstanceState.getSerializable(STATE_KEY_QUOTED_TEXT_MODE)); <ide> <ide> initializeCrypto(); <ide> updateFrom();
Java
bsd-3-clause
de229d4bec44bc012347f56effcbbceb1a32a947
0
yetanotherindie/jMonkey-Engine,skapi1992/jmonkeyengine,delftsre/jmonkeyengine,bertleft/jmonkeyengine,rbottema/jmonkeyengine,rbottema/jmonkeyengine,shurun19851206/jMonkeyEngine,davidB/jmonkeyengine,sandervdo/jmonkeyengine,wrvangeest/jmonkeyengine,bsmr-java/jmonkeyengine,delftsre/jmonkeyengine,danteinforno/jmonkeyengine,weilichuang/jmonkeyengine,zzuegg/jmonkeyengine,Georgeto/jmonkeyengine,g-rocket/jmonkeyengine,davidB/jmonkeyengine,olafmaas/jmonkeyengine,aaronang/jmonkeyengine,atomixnmc/jmonkeyengine,shurun19851206/jMonkeyEngine,OpenGrabeso/jmonkeyengine,OpenGrabeso/jmonkeyengine,OpenGrabeso/jmonkeyengine,zzuegg/jmonkeyengine,yetanotherindie/jMonkey-Engine,nickschot/jmonkeyengine,OpenGrabeso/jmonkeyengine,davidB/jmonkeyengine,yetanotherindie/jMonkey-Engine,shurun19851206/jMonkeyEngine,danteinforno/jmonkeyengine,jMonkeyEngine/jmonkeyengine,phr00t/jmonkeyengine,olafmaas/jmonkeyengine,tr0k/jmonkeyengine,yetanotherindie/jMonkey-Engine,bsmr-java/jmonkeyengine,delftsre/jmonkeyengine,aaronang/jmonkeyengine,Georgeto/jmonkeyengine,bsmr-java/jmonkeyengine,jMonkeyEngine/jmonkeyengine,atomixnmc/jmonkeyengine,skapi1992/jmonkeyengine,jMonkeyEngine/jmonkeyengine,weilichuang/jmonkeyengine,amit2103/jmonkeyengine,wrvangeest/jmonkeyengine,d235j/jmonkeyengine,atomixnmc/jmonkeyengine,sandervdo/jmonkeyengine,jMonkeyEngine/jmonkeyengine,shurun19851206/jMonkeyEngine,danteinforno/jmonkeyengine,g-rocket/jmonkeyengine,wrvangeest/jmonkeyengine,g-rocket/jmonkeyengine,GreenCubes/jmonkeyengine,g-rocket/jmonkeyengine,phr00t/jmonkeyengine,nickschot/jmonkeyengine,d235j/jmonkeyengine,weilichuang/jmonkeyengine,d235j/jmonkeyengine,danteinforno/jmonkeyengine,Georgeto/jmonkeyengine,d235j/jmonkeyengine,atomixnmc/jmonkeyengine,Georgeto/jmonkeyengine,phr00t/jmonkeyengine,d235j/jmonkeyengine,zzuegg/jmonkeyengine,skapi1992/jmonkeyengine,OpenGrabeso/jmonkeyengine,davidB/jmonkeyengine,aaronang/jmonkeyengine,OpenGrabeso/jmonkeyengine,GreenCubes/jmonkeyengine,tr0k/jmonkeyengine,bertleft/jmonkeyengine,mbenson/jmonkeyengine,bertleft/jmonkeyengine,amit2103/jmonkeyengine,atomixnmc/jmonkeyengine,delftsre/jmonkeyengine,mbenson/jmonkeyengine,olafmaas/jmonkeyengine,tr0k/jmonkeyengine,InShadow/jmonkeyengine,GreenCubes/jmonkeyengine,yetanotherindie/jMonkey-Engine,bsmr-java/jmonkeyengine,rbottema/jmonkeyengine,tr0k/jmonkeyengine,danteinforno/jmonkeyengine,davidB/jmonkeyengine,amit2103/jmonkeyengine,InShadow/jmonkeyengine,wrvangeest/jmonkeyengine,InShadow/jmonkeyengine,GreenCubes/jmonkeyengine,amit2103/jmonkeyengine,atomixnmc/jmonkeyengine,Georgeto/jmonkeyengine,davidB/jmonkeyengine,aaronang/jmonkeyengine,sandervdo/jmonkeyengine,skapi1992/jmonkeyengine,nickschot/jmonkeyengine,shurun19851206/jMonkeyEngine,g-rocket/jmonkeyengine,bertleft/jmonkeyengine,amit2103/jmonkeyengine,mbenson/jmonkeyengine,nickschot/jmonkeyengine,weilichuang/jmonkeyengine,weilichuang/jmonkeyengine,mbenson/jmonkeyengine,weilichuang/jmonkeyengine,sandervdo/jmonkeyengine,g-rocket/jmonkeyengine,danteinforno/jmonkeyengine,InShadow/jmonkeyengine,zzuegg/jmonkeyengine,phr00t/jmonkeyengine,mbenson/jmonkeyengine,yetanotherindie/jMonkey-Engine,mbenson/jmonkeyengine,olafmaas/jmonkeyengine,rbottema/jmonkeyengine,Georgeto/jmonkeyengine,shurun19851206/jMonkeyEngine,d235j/jmonkeyengine,amit2103/jmonkeyengine
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.util.blockparser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; public class BlockLanguageParser { private Reader reader; private ArrayList<Statement> statementStack = new ArrayList<Statement>(); private Statement lastStatement; private int lineNumber = 1; private BlockLanguageParser(){ } private void reset(){ statementStack.clear(); statementStack.add(new Statement(0, "<root>")); lastStatement = null; lineNumber = 1; } private void pushStatement(StringBuilder buffer){ String content = buffer.toString().trim(); if (content.length() > 0){ // push last statement onto the list lastStatement = new Statement(lineNumber, content); Statement parent = statementStack.get(statementStack.size()-1); parent.addStatement(lastStatement); buffer.setLength(0); } } private void load(InputStream in) throws IOException{ reset(); reader = new InputStreamReader(in); StringBuilder buffer = new StringBuilder(); boolean insideComment = false; char lastChar = '\0'; while (true){ int ci = reader.read(); char c = (char) ci; if (c == '\r'){ continue; } if (insideComment && c == '\n'){ insideComment = false; }else if (c == '/' && lastChar == '/'){ buffer.deleteCharAt(buffer.length()-1); insideComment = true; pushStatement(buffer); lastChar = '\0'; lineNumber++; }else if (!insideComment){ if (ci == -1 || c == '{' || c == '}' || c == '\n' || c == ';'){ pushStatement(buffer); lastChar = '\0'; if (c == '{'){ // push last statement onto the stack statementStack.add(lastStatement); continue; }else if (c == '}'){ // pop statement from stack statementStack.remove(statementStack.size()-1); continue; }else if (c == '\n'){ lineNumber++; }else if (ci == -1){ break; } }else{ buffer.append(c); lastChar = c; } } } } public static List<Statement> parse(InputStream in) throws IOException { BlockLanguageParser parser = new BlockLanguageParser(); parser.load(in); return parser.statementStack.get(0).getContents(); } }
engine/src/core/com/jme3/util/blockparser/BlockLanguageParser.java
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.util.blockparser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.List; public class BlockLanguageParser { private Reader reader; private ArrayList<Statement> statementStack = new ArrayList<Statement>(); private Statement lastStatement; private int lineNumber = 1; private BlockLanguageParser(){ } private void reset(){ statementStack.clear(); statementStack.add(new Statement(0, "<root>")); lastStatement = null; lineNumber = 1; } private void pushStatement(StringBuilder buffer){ String content = buffer.toString().trim(); if (content.length() > 0){ // push last statement onto the list lastStatement = new Statement(lineNumber, content); Statement parent = statementStack.get(statementStack.size()-1); parent.addStatement(lastStatement); buffer.setLength(0); } } private void load(InputStream in) throws IOException{ reset(); reader = new InputStreamReader(in); StringBuilder buffer = new StringBuilder(); boolean insideComment = false; char lastChar = '\0'; while (true){ int ci = reader.read(); char c = (char) ci; if (c == '\r'){ continue; } if (insideComment && c == '\n'){ insideComment = false; }else if (c == '/' && lastChar == '/'){ buffer.deleteCharAt(buffer.length()-1); insideComment = true; pushStatement(buffer); lastChar = '\0'; }else if (!insideComment){ if (ci == -1 || c == '{' || c == '}' || c == '\n' || c == ';'){ pushStatement(buffer); lastChar = '\0'; if (c == '{'){ // push last statement onto the stack statementStack.add(lastStatement); continue; }else if (c == '}'){ // pop statement from stack statementStack.remove(statementStack.size()-1); continue; }else if (c == '\n'){ lineNumber++; }else if (ci == -1){ break; } }else{ buffer.append(c); lastChar = c; } } } } public static List<Statement> parse(InputStream in) throws IOException { BlockLanguageParser parser = new BlockLanguageParser(); parser.load(in); return parser.statementStack.get(0).getContents(); } }
Material BlockLanguageParser now accounts for commented lines when computing the line number of a statement git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@10189 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/core/com/jme3/util/blockparser/BlockLanguageParser.java
Material BlockLanguageParser now accounts for commented lines when computing the line number of a statement
<ide><path>ngine/src/core/com/jme3/util/blockparser/BlockLanguageParser.java <ide> insideComment = true; <ide> pushStatement(buffer); <ide> lastChar = '\0'; <add> lineNumber++; <ide> }else if (!insideComment){ <ide> if (ci == -1 || c == '{' || c == '}' || c == '\n' || c == ';'){ <ide> pushStatement(buffer);
JavaScript
bsd-3-clause
e59319f4bff3fe71a33f602de9f47dad1b2a6b26
0
e-mission/e-mission-phone,shankari/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone,shankari/e-mission-phone,e-mission/e-mission-phone
'use strict'; angular.module('emission.incident.posttrip.prompt', ['emission.plugin.logger']) .factory("PostTripAutoPrompt", function($window, $ionicPlatform, $rootScope, $state, $ionicPopup, Logger) { var ptap = {}; var REPORT = 737678; // REPORT on the phone keypad var REPORT_INCIDENT_TEXT = 'REPORT_INCIDENT'; var reportMessage = function(platform) { var platformSpecificMessage = { "ios": "Swipe to ", "android": "Select to " }; var selMessage = platformSpecificMessage[platform]; if (!angular.isDefined(selMessage)) { selMessage = "Select to "; } return selMessage + " report incident"; }; var getTripEndReportNotification = function() { var actions = [{ identifier: 'MUTE', title: 'Mute', icon: 'res://ic_moreoptions', activationMode: 'foreground', destructive: false, authenticationRequired: false }, { identifier: 'REPORT', title: 'Yes', icon: 'res://ic_signin', activationMode: 'foreground', destructive: false, authenticationRequired: false }]; var reportNotifyConfig = { id: REPORT, title: "Trip just ended", text: reportMessage(ionic.Platform.platform()), icon: 'file://img/icon.png', // smallIcon: 'res://ic_mood_black.png', sound: null, actions: [actions[1]], category: REPORT_INCIDENT_TEXT, autoClear: true }; Logger.log("Returning notification config "+JSON.stringify(reportNotifyConfig)); return reportNotifyConfig; } ptap.registerTripEnd = function() { Logger.log( "registertripEnd received!" ); // iOS var notifyPlugin = $window.cordova.plugins.BEMTransitionNotification; notifyPlugin.TRIP_END = "trip_ended"; notifyPlugin.addEventListener(notifyPlugin.TRIP_END, getTripEndReportNotification()) .then(function(result) { // $window.broadcaster.addEventListener("TRANSITION_NAME", function(result) { Logger.log("Finished registering "+notifyPlugin.TRIP_END+" with result "+JSON.stringify(result)); }) .catch(function(error) { Logger.log(JSON.stringify(error)); $ionicPopup.alert({ title: "Unable to register notifications for trip end", template: JSON.stringify(error) }); });; } var getFormattedTime = function(ts_in_secs) { if (angular.isDefined(ts_in_secs)) { return moment(ts_in_secs * 1000).format('LT'); } else { return "---"; } }; var promptReport = function(notification, state, data) { Logger.log("About to prompt whether to report a trip"); var newScope = $rootScope.$new(); angular.extend(newScope, notification.data); newScope.getFormattedTime = getFormattedTime; Logger.log("notification = "+JSON.stringify(notification)); Logger.log("state = "+JSON.stringify(state)); Logger.log("data = "+JSON.stringify(data)); return $ionicPopup.show({title: "Report incident for trip", scope: newScope, template: "{{getFormattedTime(start_ts)}} -> {{getFormattedTime(end_ts)}}", buttons: [{ text: 'Report', type: 'button-positive', onTap: function(e) { // e.preventDefault() will stop the popup from closing when tapped. return true; } }, { text: 'Skip', type: 'button-positive', onTap: function(e) { return false; } }] }) } var cleanDataIfNecessary = function(notification, state, data) { if ($ionicPlatform.is('ios') && angular.isDefined(notification.data)) { Logger.log("About to parse "+notification.data); notification.data = JSON.parse(notification.data); } }; var displayCompletedTrip = function(notification, state, data) { Logger.log("About to display completed trip"); /* promptReport(notification, state, data).then(function(res) { if (res == true) { console.log("About to go to incident map page"); $state.go("root.main.incident", notification.data); } else { console.log("Skipped incident reporting"); } }); */ Logger.log("About to go to incident map page"); $state.go("root.main.control", notification.data).then(function(result) { Logger.log("result of moving to control screen = "+result); $state.go("root.main.incident"); }); }; var checkCategory = function(notification) { if (notification.category == REPORT_INCIDENT_TEXT) { return true; } else { return false; } } ptap.registerUserResponse = function() { Logger.log( "registerUserResponse received!" ); $window.cordova.plugins.notification.local.on('action', function (notification, state, data) { if (data.identifier === 'REPORT') { // alert("About to report"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); displayCompletedTrip(notification, state, data); } else if (data.identifier === 'MUTE') { // alert('About to mute'); } }); $window.cordova.plugins.notification.local.on('clear', function (notification, state, data) { // alert("notification cleared, no report"); }); $window.cordova.plugins.notification.local.on('cancel', function (notification, state, data) { // alert("notification cancelled, no report"); }); $window.cordova.plugins.notification.local.on('trigger', function (notification, state, data) { // alert("triggered, no action"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); promptReport(notification, state, data).then(function(res) { if (res == true) { Logger.log("About to go to incident map page"); displayCompletedTrip(notification, state, data); $state.go("root.main.incident", notification.data); } else { Logger.log("Skipped incident reporting"); } }); }); $window.cordova.plugins.notification.local.on('click', function (notification, state, data) { // alert("clicked, no action"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); displayCompletedTrip(notification, state, data); }); } $ionicPlatform.ready().then(function() { ptap.registerTripEnd(); ptap.registerUserResponse(); }); return ptap; });
www/js/incident/post-trip-prompt.js
'use strict'; angular.module('emission.incident.posttrip.prompt', ['emission.plugin.logger']) .factory("PostTripAutoPrompt", function($window, $ionicPlatform, $rootScope, $state, $ionicPopup, Logger) { var ptap = {}; var REPORT = 737678; // REPORT on the phone keypad var REPORT_INCIDENT_TEXT = 'REPORT_INCIDENT'; var getTripEndReportNotification = function() { var actions = [{ identifier: 'MUTE', title: 'Mute', icon: 'res://ic_moreoptions', activationMode: 'foreground', destructive: false, authenticationRequired: false }, { identifier: 'REPORT', title: 'Yes', icon: 'res://ic_signin', activationMode: 'foreground', destructive: false, authenticationRequired: false }]; var reportNotifyConfig = { id: REPORT, title: "Trip just ended", text: "Incident to report?", actions: [actions[1]], category: REPORT_INCIDENT_TEXT, autoClear: true }; Logger.log("Returning notification config "+JSON.stringify(reportNotifyConfig)); return reportNotifyConfig; } ptap.registerTripEnd = function() { Logger.log( "registertripEnd received!" ); // iOS var notifyPlugin = $window.cordova.plugins.BEMTransitionNotification; notifyPlugin.TRIP_END = "trip_ended"; notifyPlugin.addEventListener(notifyPlugin.TRIP_END, getTripEndReportNotification()) .then(function(result) { // $window.broadcaster.addEventListener("TRANSITION_NAME", function(result) { Logger.log("Finished registering "+notifyPlugin.TRIP_END+" with result "+JSON.stringify(result)); }) .catch(function(error) { Logger.log(JSON.stringify(error)); $ionicPopup.alert({ title: "Unable to register notifications for trip end", template: JSON.stringify(error) }); });; } var getFormattedTime = function(ts_in_secs) { if (angular.isDefined(ts_in_secs)) { return moment(ts_in_secs * 1000).format('LT'); } else { return "---"; } }; var promptReport = function(notification, state, data) { Logger.log("About to prompt whether to report a trip"); var newScope = $rootScope.$new(); angular.extend(newScope, notification.data); newScope.getFormattedTime = getFormattedTime; Logger.log("notification = "+JSON.stringify(notification)); Logger.log("state = "+JSON.stringify(state)); Logger.log("data = "+JSON.stringify(data)); return $ionicPopup.show({title: "Report incident for trip", scope: newScope, template: "{{getFormattedTime(start_ts)}} -> {{getFormattedTime(end_ts)}}", buttons: [{ text: 'Report', type: 'button-positive', onTap: function(e) { // e.preventDefault() will stop the popup from closing when tapped. return true; } }, { text: 'Skip', type: 'button-positive', onTap: function(e) { return false; } }] }) } var cleanDataIfNecessary = function(notification, state, data) { if ($ionicPlatform.is('ios') && angular.isDefined(notification.data)) { Logger.log("About to parse "+notification.data); notification.data = JSON.parse(notification.data); } }; var displayCompletedTrip = function(notification, state, data) { Logger.log("About to display completed trip"); /* promptReport(notification, state, data).then(function(res) { if (res == true) { console.log("About to go to incident map page"); $state.go("root.main.incident", notification.data); } else { console.log("Skipped incident reporting"); } }); */ Logger.log("About to go to incident map page"); $state.go("root.main.incident", notification.data); }; var checkCategory = function(notification) { if (notification.category == REPORT_INCIDENT_TEXT) { return true; } else { return false; } } ptap.registerUserResponse = function() { Logger.log( "registerUserResponse received!" ); $window.cordova.plugins.notification.local.on('action', function (notification, state, data) { if (data.identifier === 'REPORT') { // alert("About to report"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); displayCompletedTrip(notification, state, data); } else if (data.identifier === 'MUTE') { // alert('About to mute'); } }); $window.cordova.plugins.notification.local.on('clear', function (notification, state, data) { // alert("notification cleared, no report"); }); $window.cordova.plugins.notification.local.on('cancel', function (notification, state, data) { // alert("notification cancelled, no report"); }); $window.cordova.plugins.notification.local.on('trigger', function (notification, state, data) { // alert("triggered, no action"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); promptReport(notification, state, data).then(function(res) { if (res == true) { Logger.log("About to go to incident map page"); displayCompletedTrip(notification, state, data); $state.go("root.main.incident", notification.data); } else { Logger.log("Skipped incident reporting"); } }); }); $window.cordova.plugins.notification.local.on('click', function (notification, state, data) { // alert("clicked, no action"); if (!checkCategory(notification)) { Logger.log("notification "+notification+" is not an incident report, returning..."); return; } cleanDataIfNecessary(notification, state, data); displayCompletedTrip(notification, state, data); }); } $ionicPlatform.ready().then(function() { ptap.registerTripEnd(); ptap.registerUserResponse(); }); return ptap; });
Minor fixes to incident reporting based on feedback - There was no way to exit out of the incident screen. This is because we display the incident screen in the `main-control` view, but that view is not initialized unless we go to the profile. So instead of going to the incident directly, we need to first go to the profile and then go to the incident - Change the display message to indicate that we need to swipe on iOS. Otherwise, people get confused by the OS-generated "Press for more" message
www/js/incident/post-trip-prompt.js
Minor fixes to incident reporting based on feedback
<ide><path>ww/js/incident/post-trip-prompt.js <ide> var ptap = {}; <ide> var REPORT = 737678; // REPORT on the phone keypad <ide> var REPORT_INCIDENT_TEXT = 'REPORT_INCIDENT'; <add> <add> var reportMessage = function(platform) { <add> var platformSpecificMessage = { <add> "ios": "Swipe to ", <add> "android": "Select to " <add> }; <add> var selMessage = platformSpecificMessage[platform]; <add> if (!angular.isDefined(selMessage)) { <add> selMessage = "Select to "; <add> } <add> return selMessage + " report incident"; <add> }; <ide> <ide> var getTripEndReportNotification = function() { <ide> var actions = [{ <ide> var reportNotifyConfig = { <ide> id: REPORT, <ide> title: "Trip just ended", <del> text: "Incident to report?", <add> text: reportMessage(ionic.Platform.platform()), <add> icon: 'file://img/icon.png', <add> // smallIcon: 'res://ic_mood_black.png', <add> sound: null, <ide> actions: [actions[1]], <ide> category: REPORT_INCIDENT_TEXT, <ide> autoClear: true <ide> */ <ide> <ide> Logger.log("About to go to incident map page"); <del> $state.go("root.main.incident", notification.data); <add> $state.go("root.main.control", notification.data).then(function(result) { <add> Logger.log("result of moving to control screen = "+result); <add> $state.go("root.main.incident"); <add> }); <ide> }; <ide> <ide> var checkCategory = function(notification) {
Java
apache-2.0
32dbd33081121cedd99bd31e75cee3dbf6271751
0
internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea,internetisalie/lua-for-idea
/* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 30-Nov-2009 */ package com.sylvanaar.idea.Lua.copyright; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.maddyhome.idea.copyright.CopyrightProfile; import com.maddyhome.idea.copyright.options.LanguageOptions; import com.maddyhome.idea.copyright.psi.UpdateCopyright; import com.maddyhome.idea.copyright.psi.UpdateCopyrightsProvider; public class UpdateLuaCopyrightsProvider extends UpdateCopyrightsProvider { @Override public UpdateCopyright createInstance(Project project, Module module, VirtualFile file, FileType base, CopyrightProfile options) { return new UpdateLuaFileCopyright(project, module, file, options); } @Override public LanguageOptions getDefaultOptions() { LanguageOptions options = super.getDefaultOptions(); options.setFiller("="); options.setBlock(false); options.setPrefixLines(false); options.setFileTypeOverride(LanguageOptions.USE_TEXT); return options; } }
src/copyright/UpdateLuaCopyrightsProvider.java
/* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 30-Nov-2009 */ package com.sylvanaar.idea.Lua.copyright; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.maddyhome.idea.copyright.CopyrightProfile; import com.maddyhome.idea.copyright.options.LanguageOptions; import com.maddyhome.idea.copyright.psi.UpdateCopyright; import com.maddyhome.idea.copyright.psi.UpdateCopyrightsProvider; public class UpdateLuaCopyrightsProvider extends UpdateCopyrightsProvider { @Override public UpdateCopyright createInstance(Project project, Module module, VirtualFile file, FileType base, CopyrightProfile options) { return new UpdateLuaFileCopyright(project, module, file, options); } @Override public LanguageOptions getDefaultOptions() { LanguageOptions options = super.getDefaultOptions(); options.setFiller('='); options.setBlock(false); options.setPrefixLines(false); options.setFileTypeOverride(LanguageOptions.USE_TEXT); return options; } }
fix copyright options
src/copyright/UpdateLuaCopyrightsProvider.java
fix copyright options
<ide><path>rc/copyright/UpdateLuaCopyrightsProvider.java <ide> public LanguageOptions getDefaultOptions() { <ide> LanguageOptions options = super.getDefaultOptions(); <ide> <del> options.setFiller('='); <add> options.setFiller("="); <ide> options.setBlock(false); <ide> options.setPrefixLines(false); <ide> options.setFileTypeOverride(LanguageOptions.USE_TEXT);
JavaScript
mit
e6ad2766a967d121c46bc566348627a64ee93952
0
Flareninja/Hispano-Pokemon-Showdown,BasedGod7/PH,Flareninja/Hispano-Pokemon-Showdown
/** * System commands * Pokemon Showdown - http://pokemonshowdown.com/ * * These are system commands - commands required for Pokemon Showdown * to run. A lot of these are sent by the client. * * If you'd like to modify commands, please go to config/commands.js, * which also teaches you how to use commands. * * @license MIT license */ var crypto = require('crypto'); const MAX_REASON_LENGTH = 300; var commands = exports.commands = { version: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Server version: <b>'+CommandParser.package.version+'</b> <small>(<a href="http://pokemonshowdown.com/versions#' + CommandParser.serverVersion + '">' + CommandParser.serverVersion.substr(0,10) + '</a>)</small>'); }, me: function(target, room, user, connection) { // By default, /me allows a blank message if (target) target = this.canTalk(target); if (!target) return; return '/me ' + target; }, mee: function(target, room, user, connection) { // By default, /mee allows a blank message if (target) target = this.canTalk(target); if (!target) return; return '/mee ' + target; }, avatar: function(target, room, user) { if (!target) return this.parse('/avatars'); var parts = target.split(','); var avatar = parseInt(parts[0]); if (!avatar || avatar > 294 || avatar < 1) { if (!parts[1]) { this.sendReply("Invalid avatar."); } return false; } user.avatar = avatar; if (!parts[1]) { this.sendReply("Avatar changed to:\n" + '|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/'+avatar+'.png" alt="" width="80" height="80" />'); } }, logout: function(target, room, user) { user.resetName(); }, r: 'reply', reply: function(target, room, user) { if (!target) return this.parse('/help reply'); if (!user.lastPM) { return this.sendReply('No one has PMed you yet.'); } return this.parse('/msg '+(user.lastPM||'')+', '+target); }, pm: 'msg', whisper: 'msg', w: 'msg', msg: function(target, room, user) { if (!target) return this.parse('/help msg'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!target) { this.sendReply('You forgot the comma.'); return this.parse('/help msg'); } if (!targetUser || !targetUser.connected) { if (targetUser && !targetUser.connected) { this.popupReply('User '+this.targetUsername+' is offline.'); } else if (!target) { this.popupReply('User '+this.targetUsername+' not found. Did you forget a comma?'); } else { this.popupReply('User '+this.targetUsername+' not found. Did you misspell their name?'); } return this.parse('/help msg'); } if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to PM users.'); return false; } } if (user.locked && !targetUser.can('lock', user)) { return this.popupReply('You can only private message members of the moderation team (users marked by %, @, &, or ~) when locked.'); } if (targetUser.locked && !user.can('lock', targetUser)) { return this.popupReply('This user is locked and cannot PM.'); } if (targetUser.ignorePMs && !user.can('lock')) { if (!targetUser.can('lock')) { return this.popupReply('This user is blocking Private Messages right now.'); } else if (targetUser.can('hotpatch')) { return this.popupReply('This admin is too busy to answer Private Messages right now. Please contact a different staff member.'); } } target = this.canTalk(target, null); if (!target) return false; var message = '|pm|'+user.getIdentity()+'|'+targetUser.getIdentity()+'|'+target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, blockpm: 'ignorepms', blockpms: 'ignorepms', ignorepm: 'ignorepms', ignorepms: function(target, room, user) { if (user.ignorePMs) return this.sendReply('You are already blocking Private Messages!'); if (user.can('lock') && !user.can('hotpatch')) return this.sendReply('You are not allowed to block Private Messages.'); user.ignorePMs = true; return this.sendReply('You are now blocking Private Messages.'); }, unblockpm: 'unignorepms', unblockpms: 'unignorepms', unignorepm: 'unignorepms', unignorepms: function(target, room, user) { if (!user.ignorePMs) return this.sendReply('You are not blocking Private Messages!'); user.ignorePMs = false; return this.sendReply('You are no longer blocking Private Messages.'); }, makechatroom: function(target, room, user) { if (!this.can('makeroom')) return; var id = toId(target); if (!id) return this.parse('/help makechatroom'); if (Rooms.rooms[id]) { return this.sendReply("The room '"+target+"' already exists."); } if (Rooms.global.addChatRoom(target)) { return this.sendReply("The room '"+target+"' was created."); } return this.sendReply("An error occurred while trying to create the room '"+target+"'."); }, deregisterchatroom: function(target, room, user) { if (!this.can('makeroom')) return; var id = toId(target); if (!id) return this.parse('/help deregisterchatroom'); var targetRoom = Rooms.get(id); if (!targetRoom) return this.sendReply("The room '"+id+"' doesn't exist."); target = targetRoom.title || targetRoom.id; if (Rooms.global.deregisterChatRoom(id)) { this.sendReply("The room '"+target+"' was deregistered."); this.sendReply("It will be deleted as of the next server restart."); return; } return this.sendReply("The room '"+target+"' isn't registered."); }, privateroom: function(target, room, user) { if (!this.can('privateroom', null, room)) return; if (target === 'off') { delete room.isPrivate; this.addModCommand(user.name+' made this room public.'); if (room.chatRoomData) { delete room.chatRoomData.isPrivate; Rooms.global.writeChatRoomData(); } } else { room.isPrivate = true; this.addModCommand(user.name+' made this room private.'); if (room.chatRoomData) { room.chatRoomData.isPrivate = true; Rooms.global.writeChatRoomData(); } } }, officialchatroom: 'officialroom', officialroom: function(target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.sendReply("/officialroom - This room can't be made official"); } if (target === 'off') { delete room.isOfficial; this.addModCommand(user.name+' made this chat room unofficial.'); delete room.chatRoomData.isOfficial; Rooms.global.writeChatRoomData(); } else { room.isOfficial = true; this.addModCommand(user.name+' made this chat room official.'); room.chatRoomData.isOfficial = true; Rooms.global.writeChatRoomData(); } }, roomowner: function(target, room, user) { if (!room.chatRoomData) { return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added"); } var target = this.splitTarget(target, true); var targetUser = this.targetUser; if (!targetUser) return this.sendReply("User '"+this.targetUsername+"' is not online."); if (!this.can('makeroom', targetUser, room)) return false; if (!room.auth) room.auth = room.chatRoomData.auth = {}; var name = targetUser.name; room.auth[targetUser.userid] = '#'; this.addModCommand(''+name+' was appointed Room Owner by '+user.name+'.'); room.onUpdateIdentity(targetUser); Rooms.global.writeChatRoomData(); }, roomdeowner: 'deroomowner', deroomowner: function(target, room, user) { if (!room.auth) { return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation"); } var target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || userid === '') return this.sendReply("User '"+name+"' does not exist."); if (room.auth[userid] !== '#') return this.sendReply("User '"+name+"' is not a room owner."); if (!this.can('makeroom', null, room)) return false; delete room.auth[userid]; this.sendReply('('+name+' is no longer Room Owner.)'); if (targetUser) targetUser.updateIdentity(); if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } }, roomdesc: function(target, room, user) { if (!target) { if (!this.canBroadcast()) return; var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; if (!room.desc) return this.sendReply("This room does not have a description set."); this.sendReplyBox('The room description is: '+room.desc.replace(re, "<a href=\"$1\">$1</a>")); return; } if (!this.can('roommod', null, room)) return false; if (target.length > 80) { return this.sendReply('Error: Room description is too long (must be at most 80 characters).'); } room.desc = target; this.sendReply('(The room description is now: '+target+')'); if (room.chatRoomData) { room.chatRoomData.desc = room.desc; Rooms.global.writeChatRoomData(); } }, roomdemote: 'roompromote', roompromote: function(target, room, user, connection, cmd) { if (!room.auth) { this.sendReply("/roompromote - This room isn't designed for per-room moderation"); return this.sendReply("Before setting room mods, you need to set it up with /roomowner"); } if (!target) return this.parse('/help roompromote'); var target = this.splitTarget(target, true); var targetUser = this.targetUser; var userid = toUserid(this.targetUsername); var name = targetUser ? targetUser.name : this.targetUsername; if (!userid) { if (target && config.groups[target]) { var groupid = config.groups[target].id; return this.sendReply("/room"+groupid+" [username] - Promote a user to "+groupid+" in this room only"); } return this.parse("/help roompromote"); } var currentGroup = (room.auth[userid] || ' '); if (!targetUser && !room.auth[userid]) { return this.sendReply("User '"+this.targetUsername+"' is offline and unauthed, and so can't be promoted."); } var nextGroup = target || Users.getNextGroupSymbol(currentGroup, cmd === 'roomdemote', true); if (target === 'deauth') nextGroup = config.groupsranking[0]; if (!config.groups[nextGroup]) { return this.sendReply('Group \'' + nextGroup + '\' does not exist.'); } if (config.groups[nextGroup].globalonly) { return this.sendReply('Group \'room' + config.groups[nextGroup].id + '\' does not exist as a room rank.'); } if (currentGroup !== ' ' && !user.can('room'+config.groups[currentGroup].id, null, room)) { return this.sendReply('/' + cmd + ' - Access denied for promoting from '+config.groups[currentGroup].name+'.'); } if (nextGroup !== ' ' && !user.can('room'+config.groups[nextGroup].id, null, room)) { return this.sendReply('/' + cmd + ' - Access denied for promoting to '+config.groups[nextGroup].name+'.'); } if (currentGroup === nextGroup) { return this.sendReply("User '"+this.targetUsername+"' is already a "+(config.groups[nextGroup].name || 'regular user')+" in this room."); } if (config.groups[nextGroup].globalonly) { return this.sendReply("The rank of "+config.groups[nextGroup].name+" is global-only and can't be room-promoted to."); } var isDemotion = (config.groups[nextGroup].rank < config.groups[currentGroup].rank); var groupName = (config.groups[nextGroup].name || nextGroup || '').trim() || 'a regular user'; if (nextGroup === ' ') { delete room.auth[userid]; } else { room.auth[userid] = nextGroup; } if (isDemotion) { this.privateModCommand('('+name+' was appointed to Room ' + groupName + ' by '+user.name+'.)'); if (targetUser) { targetUser.popup('You were appointed to Room ' + groupName + ' by ' + user.name + '.'); } } else { this.addModCommand(''+name+' was appointed to Room ' + groupName + ' by '+user.name+'.'); } if (targetUser) { targetUser.updateIdentity(); } if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } }, autojoin: function(target, room, user, connection) { Rooms.global.autojoinRooms(user, connection); }, join: function(target, room, user, connection) { if (!target) return false; var targetRoom = Rooms.get(target) || Rooms.get(toId(target)); if (!targetRoom) { if (target === 'lobby') return connection.sendTo(target, "|noinit|nonexistent|"); return connection.sendTo(target, "|noinit|nonexistent|The room '"+target+"' does not exist."); } if (targetRoom.isPrivate && !user.named) { return connection.sendTo(target, "|noinit|namerequired|You must have a name in order to join the room '"+target+"'."); } if (!user.joinRoom(targetRoom || room, connection)) { return connection.sendTo(target, "|noinit|joinfailed|The room '"+target+"' could not be joined."); } if (target === 'lobby') { connection.sendTo('lobby','|html|<div class=\"broadcast-red\"><center><br><img src="http://i.imgur.com/aTpSGwf.png" height="100" width="100"><img src="http://pokemon-hispano.comxa.com/images/EvaBlack/logo.png"><img src="http://i.imgur.com/Lb5IwHb.png" height="100" width="100"></br><font size=4><center><b>BIENVENIDOS A POKÉMON HISPANO!!!</b></font><br></center>- Visita nuestro <a href=\"http://pokemon-hispano.comxa.com/\" target=\"_BLANK\">Foro</a></br><br>- Únete a nuestra página en <a href=\"https://www.facebook.com/groups/PokemonHispanoShowdown/\">Facebook</a></br><br> - Vísita nuestro <a href=\"http://www.twitch.tv/pokemonhispano/\">Livestream</a></br><br>- Para ver la lista de comandos del server escribe <b>/comandos</b>.<br>- Recuerda leer las reglas escribiendo <b>/reglas</b> para no tener ningún problema con ningún usuario y mucho menos con un miembro del Staff.<br>- Escribe <b>/lideres</b> para ver los lideres y alto mando de nuestra liga.</br> <br><center><br>Si tienes algún problema o duda no dudes en contactar a los miembros del staff ya sean <b>(+)Voices</b>, <b>(%)Drivers</b>, <b>(@)Moderadores</b>, <b>(&)Leaders</b> y en caso de ser un grave problema a los <b>(~)Administradores</b>.</div>'); } }, rb: 'roomban', roomban: function(target, room, user, connection) { if (!target) return this.parse('/help roomban'); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!Rooms.rooms[room.id].users[userid] && room.isPrivate) { return this.sendReply('User ' + this.targetUsername + ' is not in the room ' + room.id + '.'); } if (!room.bannedUsers || !room.bannedIps) { return this.sendReply('Room bans are not meant to be used in room ' + room.id + '.'); } room.bannedUsers[userid] = true; for (var ip in targetUser.ips) { room.bannedIps[ip] = true; } targetUser.popup(user.name+" has banned you from the room " + room.id + ". To appeal the ban, PM the moderator that banned you or a room owner." + (target ? " (" + target + ")" : "")); this.addModCommand(""+targetUser.name+" was banned from room " + room.id + " by "+user.name+"." + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also banned from room " + room.id + ": "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { var altId = toId(alts[i]); this.add('|unlink|' + altId); room.bannedUsers[altId] = true; } } this.add('|unlink|' + targetUser.userid); targetUser.leaveRoom(room.id); }, roomunban: function(target, room, user, connection) { if (!target) return this.parse('/help roomunban'); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '"+name+"' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!room.bannedUsers || !room.bannedIps) { return this.sendReply('Room bans are not meant to be used in room ' + room.id + '.'); } if (room.bannedUsers[userid]) delete room.bannedUsers[userid]; for (var ip in targetUser.ips) { if (room.bannedIps[ip]) delete room.bannedIps[ip]; } targetUser.popup(user.name+" has unbanned you from the room " + room.id + "."); this.addModCommand(""+targetUser.name+" was unbanned from room " + room.id + " by "+user.name+"."); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also unbanned from room " + room.id + ": "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { var altId = toId(alts[i]); if (room.bannedUsers[altId]) delete room.bannedUsers[altId]; } } }, roomauth: function(target, room, user, connection) { if (!room.auth) return this.sendReply("/roomauth - This room isn't designed for per-room moderation and therefore has no auth list."); var buffer = []; for (var u in room.auth) { buffer.push(room.auth[u] + u); } if (buffer.length > 0) { buffer = buffer.join(', '); } else { buffer = 'This room has no auth.'; } connection.popup(buffer); }, leave: 'part', part: function(target, room, user, connection) { if (room.id === 'global') return false; var targetRoom = Rooms.get(target); if (target && !targetRoom) { return this.sendReply("The room '"+target+"' does not exist."); } user.leaveRoom(targetRoom || room, connection); }, /********************************************************* * Moderating: Punishments *********************************************************/ k: 'kick', kick: function(target, room, user){ if (!target) return; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply("User " + this.targetUsername + " not found."); } if (!this.can('kick', targetUser, room)) return false; var msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + "."; this.addModCommand(targetUser.name + " was " + msg); targetUser.popup("You have been " + msg); targetUser.disconnectAll(); }, warn: function(target, room, user) { if (!target) return this.parse('/help warn'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (room.isPrivate && room.auth) { return this.sendReply('You can\'t warn here: This is a privately-owned room not subject to global rules.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('warn', targetUser, room)) return false; this.addModCommand(''+targetUser.name+' was warned by '+user.name+'.' + (target ? " (" + target + ")" : "")); targetUser.send('|c|~|/warn '+target); this.add('|unlink|' + targetUser.userid); }, redirect: 'redir', redir: function (target, room, user, connection) { if (!target) return this.parse('/help redirect'); target = this.splitTarget(target); var targetUser = this.targetUser; var targetRoom = Rooms.get(target) || Rooms.get(toId(target)); if (!targetRoom) { return this.sendReply("The room '" + target + "' does not exist."); } if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (Rooms.rooms[targetRoom.id].users[targetUser.userid]) { return this.sendReply("User " + targetUser.name + " is already in the room " + target + "!"); } if (!Rooms.rooms[room.id].users[targetUser.userid]) { return this.sendReply('User '+this.targetUsername+' is not in the room ' + room.id + '.'); } if (targetUser.joinRoom(target) === false) return this.sendReply('User "' + targetUser.name + '" could not be joined to room ' + target + '. They could be banned from the room.'); var roomName = (targetRoom.isPrivate)? 'a private room' : 'room ' + targetRoom.title; this.addModCommand(targetUser.name + ' was redirected to ' + roomName + ' by ' + user.name + '.'); targetUser.leaveRoom(room); }, m: 'mute', mute: function(target, room, user) { if (!target) return this.parse('/help mute'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute', targetUser, room)) return false; if (targetUser.mutedRooms[room.id] || targetUser.locked || !targetUser.connected) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); if (!target) { return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } return this.addModCommand(''+targetUser.name+' would be muted by '+user.name+problem+'.' + (target ? " (" + target + ")" : "")); } targetUser.popup(user.name+' has muted you for 7 minutes. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 7 minutes.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.mute(room.id, 7*60*1000); }, hm: 'hourmute', hourmute: function(target, room, user) { if (!target) return this.parse('/help hourmute'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute', targetUser, room)) return false; if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has muted you for 60 minutes. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 60 minutes.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.mute(room.id, 60*60*1000, true); }, um: 'unmute', unmute: function(target, room, user) { if (!target) return this.parse('/help unmute'); var targetUser = Users.get(target); if (!targetUser) { return this.sendReply('User '+target+' not found.'); } if (!this.can('mute', targetUser, room)) return false; if (!targetUser.mutedRooms[room.id]) { return this.sendReply(''+targetUser.name+' isn\'t muted.'); } this.addModCommand(''+targetUser.name+' was unmuted by '+user.name+'.'); targetUser.unmute(room.id); }, l: 'lock', ipmute: 'lock', lock: function(target, room, user) { if (!target) return this.parse('/help lock'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUser+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!user.can('lock', targetUser)) { return this.sendReply('/lock - Access denied.'); } if ((targetUser.locked || Users.checkBanned(targetUser.latestIp)) && !target) { var problem = ' but was already '+(targetUser.locked ? 'locked' : 'banned'); return this.privateModCommand('('+targetUser.name+' would be locked by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has locked you from talking in chats, battles, and PMing regular users.\n\n'+target+'\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it.'); this.addModCommand(""+targetUser.name+" was locked from talking by "+user.name+"." + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also locked: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.lock(); }, unlock: function(target, room, user) { if (!target) return this.parse('/help unlock'); if (!this.can('lock')) return false; var unlocked = Users.unlock(target); if (unlocked) { var names = Object.keys(unlocked); this.addModCommand('' + names.join(', ') + ' ' + ((names.length > 1) ? 'were' : 'was') + ' unlocked by ' + user.name + '.'); } else { this.sendReply('User '+target+' is not locked.'); } }, b: 'ban', ban: function(target, room, user) { if (!target) return this.parse('/help ban'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('ban', targetUser)) return false; if (Users.checkBanned(targetUser.latestIp) && !target && !targetUser.connected) { var problem = ' but was already banned'; return this.privateModCommand('('+targetUser.name+' would be banned by '+user.name+problem+'.)'); } targetUser.popup(user.name+" has banned you." + (config.appealurl ? (" If you feel that your banning was unjustified you can appeal the ban:\n" + config.appealurl) : "") + "\n\n"+target); this.addModCommand(""+targetUser.name+" was banned by "+user.name+"." + (target ? " (" + target + ")" : ""), ' ('+targetUser.latestIp+')'); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also banned: "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } this.add('|unlink|' + targetUser.userid); targetUser.ban(); }, unban: function(target, room, user) { if (!target) return this.parse('/help unban'); if (!user.can('ban')) { return this.sendReply('/unban - Access denied.'); } var name = Users.unban(target); if (name) { this.addModCommand(''+name+' was unbanned by '+user.name+'.'); } else { this.sendReply('User '+target+' is not banned.'); } }, unbanall: function(target, room, user) { if (!user.can('ban')) { return this.sendReply('/unbanall - Access denied.'); } // we have to do this the hard way since it's no longer a global for (var i in Users.bannedIps) { delete Users.bannedIps[i]; } for (var i in Users.lockedIps) { delete Users.lockedIps[i]; } this.addModCommand('All bans and locks have been lifted by '+user.name+'.'); }, banip: function(target, room, user) { target = target.trim(); if (!target) { return this.parse('/help banip'); } if (!this.can('rangeban')) return false; Users.bannedIps[target] = '#ipban'; this.addModCommand(user.name+' temporarily banned the '+(target.charAt(target.length-1)==='*'?'IP range':'IP')+': '+target); }, unbanip: function(target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Users.bannedIps[target]) { return this.sendReply(''+target+' is not a banned IP or IP range.'); } delete Users.bannedIps[target]; this.addModCommand(user.name+' unbanned the '+(target.charAt(target.length-1)==='*'?'IP range':'IP')+': '+target); }, /********************************************************* * Moderating: Other *********************************************************/ modnote: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help note'); if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The note is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute')) return false; return this.privateModCommand('(' + user.name + ' notes: ' + target + ')'); }, demote: 'promote', promote: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help promote'); var target = this.splitTarget(target, true); var targetUser = this.targetUser; var userid = toUserid(this.targetUsername); var name = targetUser ? targetUser.name : this.targetUsername; if (!userid) { if (target && config.groups[target]) { var groupid = config.groups[target].id; return this.sendReply("/"+groupid+" [username] - Promote a user to "+groupid+" globally"); } return this.parse("/help promote"); } var currentGroup = ' '; if (targetUser) { currentGroup = targetUser.group; } else if (Users.usergroups[userid]) { currentGroup = Users.usergroups[userid].substr(0,1); } var nextGroup = target ? target : Users.getNextGroupSymbol(currentGroup, cmd === 'demote', true); if (target === 'deauth') nextGroup = config.groupsranking[0]; if (!config.groups[nextGroup]) { return this.sendReply('Group \'' + nextGroup + '\' does not exist.'); } if (config.groups[nextGroup].roomonly) { return this.sendReply('Group \'' + config.groups[nextGroup].id + '\' does not exist as a global rank.'); } if (!user.canPromote(currentGroup, nextGroup)) { return this.sendReply('/' + cmd + ' - Access denied.'); } var isDemotion = (config.groups[nextGroup].rank < config.groups[currentGroup].rank); if (!Users.setOfflineGroup(name, nextGroup)) { return this.sendReply('/promote - WARNING: This user is offline and could be unregistered. Use /forcepromote if you\'re sure you want to risk it.'); } var groupName = (config.groups[nextGroup].name || nextGroup || '').trim() || 'a regular user'; if (isDemotion) { this.privateModCommand('('+name+' was demoted to ' + groupName + ' by '+user.name+'.)'); if (targetUser) { targetUser.popup('You were demoted to ' + groupName + ' by ' + user.name + '.'); } } else { this.addModCommand(''+name+' was promoted to ' + groupName + ' by '+user.name+'.'); } if (targetUser) { targetUser.updateIdentity(); } }, forcepromote: function(target, room, user) { // warning: never document this command in /help if (!this.can('forcepromote')) return false; var target = this.splitTarget(target, true); var name = this.targetUsername; var nextGroup = target ? target : Users.getNextGroupSymbol(' ', false); if (!Users.setOfflineGroup(name, nextGroup, true)) { return this.sendReply('/forcepromote - Don\'t forcepromote unless you have to.'); } var groupName = config.groups[nextGroup].name || nextGroup || ''; this.addModCommand(''+name+' was promoted to ' + (groupName.trim()) + ' by '+user.name+'.'); }, deauth: function(target, room, user) { return this.parse('/demote '+target+', deauth'); }, modchat: function(target, room, user) { if (!target) { return this.sendReply('Moderated chat is currently set to: '+room.modchat); } if (!this.can('modchat', null, room)) return false; if (room.modchat && room.modchat.length <= 1 && config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) { return this.sendReply('/modchat - Access denied for removing a setting higher than ' + config.groupsranking[1] + '.'); } target = target.toLowerCase(); switch (target) { case 'on': case 'true': case 'yes': case 'registered': this.sendReply("Modchat registered is no longer available."); return false; break; case 'off': case 'false': case 'no': room.modchat = false; break; case 'ac': case 'autoconfirmed': room.modchat = 'autoconfirmed'; break; case '*': case 'player': target = '\u2605'; // fallthrough default: if (!config.groups[target]) { return this.parse('/help modchat'); } if (config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) { return this.sendReply('/modchat - Access denied for setting higher than ' + config.groupsranking[1] + '.'); } room.modchat = target; break; } if (room.modchat === true) { this.add('|raw|<div class="broadcast-red"><b>Moderated chat was enabled!</b><br />Only registered users can talk.</div>'); } else if (!room.modchat) { this.add('|raw|<div class="broadcast-blue"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>'); } else { var modchat = sanitize(room.modchat); this.add('|raw|<div class="broadcast-red"><b>Moderated chat was set to '+modchat+'!</b><br />Only users of rank '+modchat+' and higher can talk.</div>'); } this.logModCommand(user.name+' set modchat to '+room.modchat); }, declare: function(target, room, user) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.add('|raw|<div class="broadcast-blue"><b>'+target+'</b></div>'); this.logModCommand(user.name+' declared '+target); }, gdeclare: 'globaldeclare', globaldeclare: function(target, room, user) { if (!target) return this.parse('/help globaldeclare'); if (!this.can('gdeclare')) return false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' globally declared '+target); }, cdeclare: 'chatdeclare', chatdeclare: function(target, room, user) { if (!target) return this.parse('/help chatdeclare'); if (!this.can('gdeclare')) return false; for (var id in Rooms.rooms) { if (id !== 'global') if (Rooms.rooms[id].type !== 'battle') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' globally declared (chat level) '+target); }, wall: 'announce', announce: function(target, room, user) { if (!target) return this.parse('/help announce'); if (!this.can('announce', null, room)) return false; target = this.canTalk(target); if (!target) return; return '/announce '+target; }, fr: 'forcerename', forcerename: function(target, room, user) { if (!target) return this.parse('/help forcerename'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('forcerename', targetUser)) return false; if (targetUser.userid === toUserid(this.targetUser)) { var entry = ''+targetUser.name+' was forced to choose a new name by '+user.name+'' + (target ? ": " + target + "" : ""); this.privateModCommand('(' + entry + ')'); Rooms.global.cancelSearch(targetUser); targetUser.resetName(); targetUser.send('|nametaken||'+user.name+" has forced you to change your name. "+target); } else { this.sendReply("User "+targetUser.name+" is no longer using that name."); } }, modlog: function(target, room, user, connection) { if (!this.can('modlog')) return false; var lines = 0; // Specific case for modlog command. Room can be indicated with a comma, lines go after the comma. // Otherwise, the text is defaulted to text search in current room's modlog. var roomId = room.id; var roomLogs = {}; var fs = require('fs'); if (target.indexOf(',') > -1) { var targets = target.split(','); target = targets[1].trim(); roomId = toId(targets[0]) || room.id; } // Let's check the number of lines to retrieve or if it's a word instead if (!target.match('[^0-9]')) { lines = parseInt(target || 15, 10); if (lines > 100) lines = 100; } var wordSearch = (!lines || lines < 0); // Control if we really, really want to check all modlogs for a word. var roomNames = ''; var filename = ''; var command = ''; if (roomId === 'all' && wordSearch) { roomNames = 'all rooms'; // Get a list of all the rooms var fileList = fs.readdirSync('logs/modlog'); for (var i=0; i<fileList.length; i++) { filename += 'logs/modlog/' + fileList[i] + ' '; } } else { roomId = room.id; roomNames = 'the room ' + roomId; filename = 'logs/modlog/modlog_' + roomId + '.txt'; } // Seek for all input rooms for the lines or text command = 'tail -' + lines + ' ' + filename; var grepLimit = 100; if (wordSearch) { // searching for a word instead if (target.match(/^["'].+["']$/)) target = target.substring(1,target.length-1); command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m"+grepLimit+" -i '"+target.replace(/\\/g,'\\\\\\\\').replace(/["'`]/g,'\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g,'[$&]')+"'"; } // Execute the file search to see modlog require('child_process').exec(command, function(error, stdout, stderr) { if (error && stderr) { connection.popup('/modlog empty on ' + roomNames + ' or erred - modlog does not support Windows'); console.log('/modlog error: '+error); return false; } if (lines) { if (!stdout) { connection.popup('The modlog is empty. (Weird.)'); } else { connection.popup('Displaying the last '+lines+' lines of the Moderator Log of ' + roomNames + ':\n\n'+stdout); } } else { if (!stdout) { connection.popup('No moderator actions containing "'+target+'" were found on ' + roomNames + '.'); } else { connection.popup('Displaying the last '+grepLimit+' logged actions containing "'+target+'" on ' + roomNames + ':\n\n'+stdout); } } }); }, bw: 'banword', banword: function(target, room, user) { if (!this.can('declare')) return false; target = toId(target); if (!target) { return this.sendReply('Specify a word or phrase to ban.'); } Users.addBannedWord(target); this.sendReply('Added \"'+target+'\" to the list of banned words.'); }, ubw: 'unbanword', unbanword: function(target, room, user) { if (!this.can('declare')) return false; target = toId(target); if (!target) { return this.sendReply('Specify a word or phrase to unban.'); } Users.removeBannedWord(target); this.sendReply('Removed \"'+target+'\" from the list of banned words.'); }, /********************************************************* * Server management commands *********************************************************/ hotpatch: function(target, room, user) { if (!target) return this.parse('/help hotpatch'); if (!this.can('hotpatch')) return false; this.logEntry(user.name + ' used /hotpatch ' + target); if (target === 'chat' || target === 'commands') { try { CommandParser.uncacheTree('./command-parser.js'); CommandParser = require('./command-parser.js'); CommandParser.uncacheTree('./tour.js'); global.tour = new (require('./tour.js').tour)(tour); return this.sendReply('Chat commands have been hot-patched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch chat: \n' + e.stack); } } else if (target === 'battles') { /*Simulator.SimulatorProcess.respawn(); return this.sendReply('Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code.');*/ return this.sendReply('Battle hotpatching is not supported with the single process hack.'); } else if (target === 'formats') { /*try { // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools.js'); // reload tools.js Tools = require('./tools.js'); // note: this will lock up the server for a few seconds // rebuild the formats list Rooms.global.formatListText = Rooms.global.getFormatListText(); // respawn validator processes TeamValidator.ValidatorProcess.respawn(); // respawn simulator processes Simulator.SimulatorProcess.respawn(); // broadcast the new formats list to clients Rooms.global.send(Rooms.global.formatListText); return this.sendReply('Formats have been hotpatched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch formats: \n' + e.stack); }*/ return this.sendReply('Formats hotpatching is not supported with the single process hack.'); } else if (target === 'learnsets') { try { // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools.js'); // reload tools.js Tools = require('./tools.js'); // note: this will lock up the server for a few seconds return this.sendReply('Learnsets have been hotpatched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch learnsets: \n' + e.stack); } } this.sendReply('Your hot-patch command was unrecognized.'); }, savelearnsets: function(target, room, user) { if (!this.can('hotpatch')) return false; fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = '+JSON.stringify(BattleLearnsets)+";\n"); this.sendReply('learnsets.js saved.'); }, disableladder: function(target, room, user) { if (!this.can('disableladder')) return false; if (LoginServer.disabled) { return this.sendReply('/disableladder - Ladder is already disabled.'); } LoginServer.disabled = true; this.logModCommand('The ladder was disabled by ' + user.name + '.'); this.add('|raw|<div class="broadcast-red"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>'); }, enableladder: function(target, room, user) { if (!this.can('disableladder')) return false; if (!LoginServer.disabled) { return this.sendReply('/enable - Ladder is already enabled.'); } LoginServer.disabled = false; this.logModCommand('The ladder was enabled by ' + user.name + '.'); this.add('|raw|<div class="broadcast-green"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>'); }, lockdown: function(target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>'); if (Rooms.rooms[id].requestKickInactive && !Rooms.rooms[id].battle.ended) Rooms.rooms[id].requestKickInactive(user, true); } this.logEntry(user.name + ' used /lockdown'); }, endlockdown: function(target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.sendReply("We're not under lockdown right now."); } Rooms.global.lockdown = false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b>The server shutdown was canceled.</b></div>'); } this.logEntry(user.name + ' used /endlockdown'); }, emergency: function(target, room, user) { if (!this.can('lockdown')) return false; if (config.emergency) { return this.sendReply("We're already in emergency mode."); } config.emergency = true; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red">The server has entered emergency mode. Some features might be disabled or limited.</div>'); } this.logEntry(user.name + ' used /emergency'); }, endemergency: function(target, room, user) { if (!this.can('lockdown')) return false; if (!config.emergency) { return this.sendReply("We're not in emergency mode."); } config.emergency = false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b>The server is no longer in emergency mode.</b></div>'); } this.logEntry(user.name + ' used /endemergency'); }, kill: function(target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.sendReply('For safety reasons, /kill can only be used during lockdown.'); } if (CommandParser.updateServerLock) { return this.sendReply('Wait for /updateserver to finish before using /kill.'); } /*for (var i in Sockets.workers) { Sockets.workers[i].kill(); }*/ if (!room.destroyLog) { process.exit(); return; } room.destroyLog(function() { room.logEntry(user.name + ' used /kill'); }, function() { process.exit(); }); // Just in the case the above never terminates, kill the process // after 10 seconds. setTimeout(function() { process.exit(); }, 10000); }, loadbanlist: function(target, room, user, connection) { if (!this.can('hotpatch')) return false; connection.sendTo(room, 'Loading ipbans.txt...'); fs.readFile('config/ipbans.txt', function (err, data) { if (err) return; data = (''+data).split("\n"); var rangebans = []; for (var i=0; i<data.length; i++) { var line = data[i].split('#')[0].trim(); if (!line) continue; if (line.indexOf('/') >= 0) { rangebans.push(line); } else if (line && !Users.bannedIps[line]) { Users.bannedIps[line] = '#ipban'; } } Users.checkRangeBanned = Cidr.checker(rangebans); connection.sendTo(room, 'ibans.txt has been reloaded.'); }); }, refreshpage: function(target, room, user) { if (!this.can('hotpatch')) return false; Rooms.global.send('|refresh|'); this.logEntry(user.name + ' used /refreshpage'); }, updateserver: function(target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.sendReply('/updateserver - Access denied.'); } if (CommandParser.updateServerLock) { return this.sendReply('/updateserver - Another update is already in progress.'); } CommandParser.updateServerLock = true; var logQueue = []; logQueue.push(user.name + ' used /updateserver'); connection.sendTo(room, 'updating...'); var exec = require('child_process').exec; exec('git diff-index --quiet HEAD --', function(error) { var cmd = 'git pull --rebase'; if (error) { if (error.code === 1) { // The working directory or index have local changes. cmd = 'git stash;' + cmd + ';git stash pop'; } else { // The most likely case here is that the user does not have // `git` on the PATH (which would be error.code === 127). connection.sendTo(room, '' + error); logQueue.push('' + error); logQueue.forEach(function(line) { room.logEntry(line); }); CommandParser.updateServerLock = false; return; } } var entry = 'Running `' + cmd + '`'; connection.sendTo(room, entry); logQueue.push(entry); exec(cmd, function(error, stdout, stderr) { ('' + stdout + stderr).split('\n').forEach(function(s) { connection.sendTo(room, s); logQueue.push(s); }); logQueue.forEach(function(line) { room.logEntry(line); }); CommandParser.updateServerLock = false; }); }); }, crashfixed: function(target, room, user) { if (!Rooms.global.lockdown) { return this.sendReply('/crashfixed - There is no active crash.'); } if (!this.can('hotpatch')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw('<div class="broadcast-green"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>'); } this.logEntry(user.name + ' used /crashfixed'); }, crashlogged: function(target, room, user) { if (!Rooms.global.lockdown) { return this.sendReply('/crashlogged - There is no active crash.'); } if (!this.can('declare')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw('<div class="broadcast-green"><b>We have logged the crash and are working on fixing it!</b><br />You may resume talking in the lobby and starting new battles.</div>'); } this.logEntry(user.name + ' used /crashlogged'); }, 'memusage': 'memoryusage', memoryusage: function(target) { if (!this.can('hotpatch')) return false; target = toId(target) || 'all'; if (target === 'all') { this.sendReply('Loading memory usage, this might take a while.'); } if (target === 'all' || target === 'rooms' || target === 'room') { this.sendReply('Calculating Room size...'); var roomSize = ResourceMonitor.sizeOfObject(Rooms); this.sendReply("Rooms are using " + roomSize + " bytes of memory."); } if (target === 'all' || target === 'config') { this.sendReply('Calculating config size...'); var configSize = ResourceMonitor.sizeOfObject(config); this.sendReply("Config is using " + configSize + " bytes of memory."); } if (target === 'all' || target === 'resourcemonitor' || target === 'rm') { this.sendReply('Calculating Resource Monitor size...'); var rmSize = ResourceMonitor.sizeOfObject(ResourceMonitor); this.sendReply("The Resource Monitor is using " + rmSize + " bytes of memory."); } if (target === 'all' || target === 'cmdp' || target === 'cp' || target === 'commandparser') { this.sendReply('Calculating Command Parser size...'); var cpSize = ResourceMonitor.sizeOfObject(CommandParser); this.sendReply("Command Parser is using " + cpSize + " bytes of memory."); } if (target === 'all' || target === 'sim' || target === 'simulator') { this.sendReply('Calculating Simulator size...'); var simSize = ResourceMonitor.sizeOfObject(Simulator); this.sendReply("Simulator is using " + simSize + " bytes of memory."); } if (target === 'all' || target === 'users') { this.sendReply('Calculating Users size...'); var usersSize = ResourceMonitor.sizeOfObject(Users); this.sendReply("Users is using " + usersSize + " bytes of memory."); } if (target === 'all' || target === 'tools') { this.sendReply('Calculating Tools size...'); var toolsSize = ResourceMonitor.sizeOfObject(Tools); this.sendReply("Tools are using " + toolsSize + " bytes of memory."); } if (target === 'all' || target === 'v8') { this.sendReply('Retrieving V8 memory usage...'); var o = process.memoryUsage(); this.sendReply( 'Resident set size: ' + o.rss + ', ' + o.heapUsed +' heap used of ' + o.heapTotal + ' total heap. ' + (o.heapTotal - o.heapUsed) + ' heap left.' ); delete o; } if (target === 'all') { this.sendReply('Calculating Total size...'); var total = (roomSize + configSize + rmSize + appSize + cpSize + simSize + toolsSize + usersSize) || 0; var units = ['bytes', 'K', 'M', 'G']; var converted = total; var unit = 0; while (converted > 1024) { converted /= 1024; unit++; } converted = Math.round(converted); this.sendReply("Total memory used: " + converted + units[unit] + " (" + total + " bytes)."); } return; }, bash: function(target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.sendReply('/bash - Access denied.'); } var exec = require('child_process').exec; exec(target, function(error, stdout, stderr) { connection.sendTo(room, ('' + stdout + stderr)); }); }, eval: function(target, room, user, connection, cmd, message) { if (!user.hasConsoleAccess(connection)) { return this.sendReply("/eval - Access denied."); } if (!this.canBroadcast()) return; if (!this.broadcasting) this.sendReply('||>> '+target); try { var battle = room.battle; var me = user; this.sendReply('||<< '+eval(target)); } catch (e) { this.sendReply('||<< error: '+e.message); var stack = '||'+(''+e.stack).replace(/\n/g,'\n||'); connection.sendTo(room, stack); } }, evalbattle: function(target, room, user, connection, cmd, message) { if (!user.hasConsoleAccess(connection)) { return this.sendReply("/evalbattle - Access denied."); } if (!this.canBroadcast()) return; if (!room.battle) { return this.sendReply("/evalbattle - This isn't a battle room."); } room.battle.send('eval', target.replace(/\n/g, '\f')); }, /********************************************************* * Battle commands *********************************************************/ concede: 'forfeit', surrender: 'forfeit', forfeit: function(target, room, user) { if (!room.battle) { return this.sendReply("There's nothing to forfeit here."); } if (!room.forfeit(user)) { return this.sendReply("You can't forfeit this battle."); } }, savereplay: function(target, room, user, connection) { if (!room || !room.battle) return; var logidx = 2; // spectator log (no exact HP) if (room.battle.ended) { // If the battle is finished when /savereplay is used, include // exact HP in the replay log. logidx = 3; } var data = room.getLog(logidx).join("\n"); var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g,'')).digest('hex'); LoginServer.request('prepreplay', { id: room.id.substr(7), loghash: datahash, p1: room.p1.name, p2: room.p2.name, format: room.format }, function(success) { connection.send('|queryresponse|savereplay|'+JSON.stringify({ log: data, id: room.id.substr(7) })); }); }, mv: 'move', attack: 'move', move: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'move '+target); }, sw: 'switch', switch: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'switch '+parseInt(target,10)); }, choose: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', target); }, undo: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'undo', target); }, team: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'team '+target); }, joinbattle: function(target, room, user) { if (!room.joinBattle) return this.sendReply('You can only do this in battle rooms.'); if (!user.can('joinbattle', null, room)) return this.popupReply("You must be a roomvoice to join a battle you didn't start. Ask a player to use /roomvoice on you to join this battle."); room.joinBattle(user); }, partbattle: 'leavebattle', leavebattle: function(target, room, user) { if (!room.leaveBattle) return this.sendReply('You can only do this in battle rooms.'); room.leaveBattle(user); }, kickbattle: function(target, room, user) { if (!room.leaveBattle) return this.sendReply('You can only do this in battle rooms.'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('kick', targetUser)) return false; if (room.leaveBattle(targetUser)) { this.addModCommand(''+targetUser.name+' was kicked from a battle by '+user.name+'' + (target ? " (" + target + ")" : "")); } else { this.sendReply("/kickbattle - User isn\'t in battle."); } }, kickinactive: function(target, room, user) { if (room.requestKickInactive) { room.requestKickInactive(user); } else { this.sendReply('You can only kick inactive players from inside a room.'); } }, timer: function(target, room, user) { target = toId(target); if (room.requestKickInactive) { if (target === 'off' || target === 'false' || target === 'stop') { room.stopKickInactive(user, user.can('timer')); } else if (target === 'on' || target === 'true' || !target) { room.requestKickInactive(user, user.can('timer')); } else { this.sendReply("'"+target+"' is not a recognized timer state."); } } else { this.sendReply('You can only set the timer from inside a room.'); } }, autotimer: 'forcetimer', forcetimer: function(target, room, user) { target = toId(target); if (!this.can('autotimer')) return; if (target === 'off' || target === 'false' || target === 'stop') { config.forcetimer = false; this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by "+user.name+")"); } else if (target === 'on' || target === 'true' || !target) { config.forcetimer = true; this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by "+user.name+")"); } else { this.sendReply("'"+target+"' is not a recognized forcetimer setting."); } }, forcetie: 'forcewin', forcewin: function(target, room, user) { if (!this.can('forcewin')) return false; if (!room.battle) { this.sendReply('/forcewin - This is not a battle room.'); return false; } room.battle.endType = 'forced'; if (!target) { room.battle.tie(); this.logModCommand(user.name+' forced a tie.'); return false; } target = Users.get(target); if (target) target = target.userid; else target = ''; if (target) { room.battle.win(target); this.logModCommand(user.name+' forced a win for '+target+'.'); } }, /********************************************************* * Challenging and searching commands *********************************************************/ cancelsearch: 'search', search: function(target, room, user) { if (target) { if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to search for a battle.'); return false; } } Rooms.global.searchBattle(user, target); } else { Rooms.global.cancelSearch(user); } }, chall: 'challenge', challenge: function(target, room, user, connection) { target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.popupReply("The user '"+this.targetUsername+"' was not found."); } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { return this.popupReply("The user '"+this.targetUsername+"' is not accepting challenges right now."); } if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to challenge users.'); return false; } } user.prepBattle(target, 'challenge', connection, function (result) { if (result) user.makeChallenge(targetUser, target); }); }, away: 'blockchallenges', idle: 'blockchallenges', blockchallenges: function(target, room, user) { user.blockChallenges = true; this.sendReply('You are now blocking all incoming challenge requests.'); }, back: 'allowchallenges', allowchallenges: function(target, room, user) { user.blockChallenges = false; this.sendReply('You are available for challenges from now on.'); }, cchall: 'cancelChallenge', cancelchallenge: function(target, room, user) { user.cancelChallengeTo(target); }, accept: function(target, room, user, connection) { var userid = toUserid(target); var format = ''; if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format; if (!format) { this.popupReply(target+" cancelled their challenge before you could accept it."); return false; } user.prepBattle(format, 'challenge', connection, function (result) { if (result) user.acceptChallengeFrom(userid); }); }, reject: function(target, room, user) { user.rejectChallengeFrom(toUserid(target)); }, saveteam: 'useteam', utm: 'useteam', useteam: function(target, room, user) { user.team = target; }, /********************************************************* * Low-level *********************************************************/ cmd: 'query', query: function(target, room, user, connection) { // Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode var trustable = (!config.emergency || (user.named && user.authenticated)); if (config.emergency && ResourceMonitor.countCmd(connection.ip, user.name)) return false; var spaceIndex = target.indexOf(' '); var cmd = target; if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex); target = target.substr(spaceIndex+1); } else { target = ''; } if (cmd === 'userdetails') { var targetUser = Users.get(target); if (!trustable || !targetUser) { connection.send('|queryresponse|userdetails|'+JSON.stringify({ userid: toId(target), rooms: false })); return false; } var roomList = {}; for (var i in targetUser.roomCount) { if (i==='global') continue; var targetRoom = Rooms.get(i); if (!targetRoom || targetRoom.isPrivate) continue; var roomData = {}; if (targetRoom.battle) { var battle = targetRoom.battle; roomData.p1 = battle.p1?' '+battle.p1:''; roomData.p2 = battle.p2?' '+battle.p2:''; } roomList[i] = roomData; } if (!targetUser.roomCount['global']) roomList = false; var userdetails = { userid: targetUser.userid, avatar: targetUser.avatar, rooms: roomList }; if (user.can('ip', targetUser)) { var ips = Object.keys(targetUser.ips); if (ips.length === 1) { userdetails.ip = ips[0]; } else { userdetails.ips = ips; } } connection.send('|queryresponse|userdetails|'+JSON.stringify(userdetails)); } else if (cmd === 'roomlist') { if (!trustable) return false; connection.send('|queryresponse|roomlist|'+JSON.stringify({ rooms: Rooms.global.getRoomList(true) })); } else if (cmd === 'rooms') { if (!trustable) return false; connection.send('|queryresponse|rooms|'+JSON.stringify( Rooms.global.getRooms() )); } }, trn: function(target, room, user, connection) { var commaIndex = target.indexOf(','); var targetName = target; var targetAuth = false; var targetToken = ''; if (commaIndex >= 0) { targetName = target.substr(0,commaIndex); target = target.substr(commaIndex+1); commaIndex = target.indexOf(','); targetAuth = target; if (commaIndex >= 0) { targetAuth = !!parseInt(target.substr(0,commaIndex),10); targetToken = target.substr(commaIndex+1); } } user.rename(targetName, targetToken, targetAuth, connection); }, };
commands.js
/** * System commands * Pokemon Showdown - http://pokemonshowdown.com/ * * These are system commands - commands required for Pokemon Showdown * to run. A lot of these are sent by the client. * * If you'd like to modify commands, please go to config/commands.js, * which also teaches you how to use commands. * * @license MIT license */ var crypto = require('crypto'); const MAX_REASON_LENGTH = 300; var commands = exports.commands = { version: function(target, room, user) { if (!this.canBroadcast()) return; this.sendReplyBox('Server version: <b>'+CommandParser.package.version+'</b> <small>(<a href="http://pokemonshowdown.com/versions#' + CommandParser.serverVersion + '">' + CommandParser.serverVersion.substr(0,10) + '</a>)</small>'); }, me: function(target, room, user, connection) { // By default, /me allows a blank message if (target) target = this.canTalk(target); if (!target) return; return '/me ' + target; }, mee: function(target, room, user, connection) { // By default, /mee allows a blank message if (target) target = this.canTalk(target); if (!target) return; return '/mee ' + target; }, avatar: function(target, room, user) { if (!target) return this.parse('/avatars'); var parts = target.split(','); var avatar = parseInt(parts[0]); if (!avatar || avatar > 294 || avatar < 1) { if (!parts[1]) { this.sendReply("Invalid avatar."); } return false; } user.avatar = avatar; if (!parts[1]) { this.sendReply("Avatar changed to:\n" + '|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/'+avatar+'.png" alt="" width="80" height="80" />'); } }, logout: function(target, room, user) { user.resetName(); }, r: 'reply', reply: function(target, room, user) { if (!target) return this.parse('/help reply'); if (!user.lastPM) { return this.sendReply('No one has PMed you yet.'); } return this.parse('/msg '+(user.lastPM||'')+', '+target); }, pm: 'msg', whisper: 'msg', w: 'msg', msg: function(target, room, user) { if (!target) return this.parse('/help msg'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!target) { this.sendReply('You forgot the comma.'); return this.parse('/help msg'); } if (!targetUser || !targetUser.connected) { if (targetUser && !targetUser.connected) { this.popupReply('User '+this.targetUsername+' is offline.'); } else if (!target) { this.popupReply('User '+this.targetUsername+' not found. Did you forget a comma?'); } else { this.popupReply('User '+this.targetUsername+' not found. Did you misspell their name?'); } return this.parse('/help msg'); } if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to PM users.'); return false; } } if (user.locked && !targetUser.can('lock', user)) { return this.popupReply('You can only private message members of the moderation team (users marked by %, @, &, or ~) when locked.'); } if (targetUser.locked && !user.can('lock', targetUser)) { return this.popupReply('This user is locked and cannot PM.'); } if (targetUser.ignorePMs && !user.can('lock')) { if (!targetUser.can('lock')) { return this.popupReply('This user is blocking Private Messages right now.'); } else if (targetUser.can('hotpatch')) { return this.popupReply('This admin is too busy to answer Private Messages right now. Please contact a different staff member.'); } } target = this.canTalk(target, null); if (!target) return false; var message = '|pm|'+user.getIdentity()+'|'+targetUser.getIdentity()+'|'+target; user.send(message); if (targetUser !== user) targetUser.send(message); targetUser.lastPM = user.userid; user.lastPM = targetUser.userid; }, blockpm: 'ignorepms', blockpms: 'ignorepms', ignorepm: 'ignorepms', ignorepms: function(target, room, user) { if (user.ignorePMs) return this.sendReply('You are already blocking Private Messages!'); if (user.can('lock') && !user.can('hotpatch')) return this.sendReply('You are not allowed to block Private Messages.'); user.ignorePMs = true; return this.sendReply('You are now blocking Private Messages.'); }, unblockpm: 'unignorepms', unblockpms: 'unignorepms', unignorepm: 'unignorepms', unignorepms: function(target, room, user) { if (!user.ignorePMs) return this.sendReply('You are not blocking Private Messages!'); user.ignorePMs = false; return this.sendReply('You are no longer blocking Private Messages.'); }, makechatroom: function(target, room, user) { if (!this.can('makeroom')) return; var id = toId(target); if (!id) return this.parse('/help makechatroom'); if (Rooms.rooms[id]) { return this.sendReply("The room '"+target+"' already exists."); } if (Rooms.global.addChatRoom(target)) { return this.sendReply("The room '"+target+"' was created."); } return this.sendReply("An error occurred while trying to create the room '"+target+"'."); }, deregisterchatroom: function(target, room, user) { if (!this.can('makeroom')) return; var id = toId(target); if (!id) return this.parse('/help deregisterchatroom'); var targetRoom = Rooms.get(id); if (!targetRoom) return this.sendReply("The room '"+id+"' doesn't exist."); target = targetRoom.title || targetRoom.id; if (Rooms.global.deregisterChatRoom(id)) { this.sendReply("The room '"+target+"' was deregistered."); this.sendReply("It will be deleted as of the next server restart."); return; } return this.sendReply("The room '"+target+"' isn't registered."); }, privateroom: function(target, room, user) { if (!this.can('privateroom', null, room)) return; if (target === 'off') { delete room.isPrivate; this.addModCommand(user.name+' made this room public.'); if (room.chatRoomData) { delete room.chatRoomData.isPrivate; Rooms.global.writeChatRoomData(); } } else { room.isPrivate = true; this.addModCommand(user.name+' made this room private.'); if (room.chatRoomData) { room.chatRoomData.isPrivate = true; Rooms.global.writeChatRoomData(); } } }, officialchatroom: 'officialroom', officialroom: function(target, room, user) { if (!this.can('makeroom')) return; if (!room.chatRoomData) { return this.sendReply("/officialroom - This room can't be made official"); } if (target === 'off') { delete room.isOfficial; this.addModCommand(user.name+' made this chat room unofficial.'); delete room.chatRoomData.isOfficial; Rooms.global.writeChatRoomData(); } else { room.isOfficial = true; this.addModCommand(user.name+' made this chat room official.'); room.chatRoomData.isOfficial = true; Rooms.global.writeChatRoomData(); } }, roomowner: function(target, room, user) { if (!room.chatRoomData) { return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added"); } var target = this.splitTarget(target, true); var targetUser = this.targetUser; if (!targetUser) return this.sendReply("User '"+this.targetUsername+"' is not online."); if (!this.can('makeroom', targetUser, room)) return false; if (!room.auth) room.auth = room.chatRoomData.auth = {}; var name = targetUser.name; room.auth[targetUser.userid] = '#'; this.addModCommand(''+name+' was appointed Room Owner by '+user.name+'.'); room.onUpdateIdentity(targetUser); Rooms.global.writeChatRoomData(); }, roomdeowner: 'deroomowner', deroomowner: function(target, room, user) { if (!room.auth) { return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation"); } var target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || userid === '') return this.sendReply("User '"+name+"' does not exist."); if (room.auth[userid] !== '#') return this.sendReply("User '"+name+"' is not a room owner."); if (!this.can('makeroom', null, room)) return false; delete room.auth[userid]; this.sendReply('('+name+' is no longer Room Owner.)'); if (targetUser) targetUser.updateIdentity(); if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } }, roomdesc: function(target, room, user) { if (!target) { if (!this.canBroadcast()) return; var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g; if (!room.desc) return this.sendReply("This room does not have a description set."); this.sendReplyBox('The room description is: '+room.desc.replace(re, "<a href=\"$1\">$1</a>")); return; } if (!this.can('roommod', null, room)) return false; if (target.length > 80) { return this.sendReply('Error: Room description is too long (must be at most 80 characters).'); } room.desc = target; this.sendReply('(The room description is now: '+target+')'); if (room.chatRoomData) { room.chatRoomData.desc = room.desc; Rooms.global.writeChatRoomData(); } }, roomdemote: 'roompromote', roompromote: function(target, room, user, connection, cmd) { if (!room.auth) { this.sendReply("/roompromote - This room isn't designed for per-room moderation"); return this.sendReply("Before setting room mods, you need to set it up with /roomowner"); } if (!target) return this.parse('/help roompromote'); var target = this.splitTarget(target, true); var targetUser = this.targetUser; var userid = toUserid(this.targetUsername); var name = targetUser ? targetUser.name : this.targetUsername; if (!userid) { if (target && config.groups[target]) { var groupid = config.groups[target].id; return this.sendReply("/room"+groupid+" [username] - Promote a user to "+groupid+" in this room only"); } return this.parse("/help roompromote"); } var currentGroup = (room.auth[userid] || ' '); if (!targetUser && !room.auth[userid]) { return this.sendReply("User '"+this.targetUsername+"' is offline and unauthed, and so can't be promoted."); } var nextGroup = target || Users.getNextGroupSymbol(currentGroup, cmd === 'roomdemote', true); if (target === 'deauth') nextGroup = config.groupsranking[0]; if (!config.groups[nextGroup]) { return this.sendReply('Group \'' + nextGroup + '\' does not exist.'); } if (config.groups[nextGroup].globalonly) { return this.sendReply('Group \'room' + config.groups[nextGroup].id + '\' does not exist as a room rank.'); } if (currentGroup !== ' ' && !user.can('room'+config.groups[currentGroup].id, null, room)) { return this.sendReply('/' + cmd + ' - Access denied for promoting from '+config.groups[currentGroup].name+'.'); } if (nextGroup !== ' ' && !user.can('room'+config.groups[nextGroup].id, null, room)) { return this.sendReply('/' + cmd + ' - Access denied for promoting to '+config.groups[nextGroup].name+'.'); } if (currentGroup === nextGroup) { return this.sendReply("User '"+this.targetUsername+"' is already a "+(config.groups[nextGroup].name || 'regular user')+" in this room."); } if (config.groups[nextGroup].globalonly) { return this.sendReply("The rank of "+config.groups[nextGroup].name+" is global-only and can't be room-promoted to."); } var isDemotion = (config.groups[nextGroup].rank < config.groups[currentGroup].rank); var groupName = (config.groups[nextGroup].name || nextGroup || '').trim() || 'a regular user'; if (nextGroup === ' ') { delete room.auth[userid]; } else { room.auth[userid] = nextGroup; } if (isDemotion) { this.privateModCommand('('+name+' was appointed to Room ' + groupName + ' by '+user.name+'.)'); if (targetUser) { targetUser.popup('You were appointed to Room ' + groupName + ' by ' + user.name + '.'); } } else { this.addModCommand(''+name+' was appointed to Room ' + groupName + ' by '+user.name+'.'); } if (targetUser) { targetUser.updateIdentity(); } if (room.chatRoomData) { Rooms.global.writeChatRoomData(); } }, autojoin: function(target, room, user, connection) { Rooms.global.autojoinRooms(user, connection); }, join: function(target, room, user, connection) { if (!target) return false; var targetRoom = Rooms.get(target) || Rooms.get(toId(target)); if (!targetRoom) { if (target === 'lobby') return connection.sendTo(target, "|noinit|nonexistent|"); return connection.sendTo(target, "|noinit|nonexistent|The room '"+target+"' does not exist."); } if (targetRoom.isPrivate && !user.named) { return connection.sendTo(target, "|noinit|namerequired|You must have a name in order to join the room '"+target+"'."); } if (!user.joinRoom(targetRoom || room, connection)) { return connection.sendTo(target, "|noinit|joinfailed|The room '"+target+"' could not be joined."); } }, rb: 'roomban', roomban: function(target, room, user, connection) { if (!target) return this.parse('/help roomban'); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!Rooms.rooms[room.id].users[userid] && room.isPrivate) { return this.sendReply('User ' + this.targetUsername + ' is not in the room ' + room.id + '.'); } if (!room.bannedUsers || !room.bannedIps) { return this.sendReply('Room bans are not meant to be used in room ' + room.id + '.'); } room.bannedUsers[userid] = true; for (var ip in targetUser.ips) { room.bannedIps[ip] = true; } targetUser.popup(user.name+" has banned you from the room " + room.id + ". To appeal the ban, PM the moderator that banned you or a room owner." + (target ? " (" + target + ")" : "")); this.addModCommand(""+targetUser.name+" was banned from room " + room.id + " by "+user.name+"." + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also banned from room " + room.id + ": "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { var altId = toId(alts[i]); this.add('|unlink|' + altId); room.bannedUsers[altId] = true; } } this.add('|unlink|' + targetUser.userid); targetUser.leaveRoom(room.id); }, roomunban: function(target, room, user, connection) { if (!target) return this.parse('/help roomunban'); target = this.splitTarget(target, true); var targetUser = this.targetUser; var name = this.targetUsername; var userid = toId(name); if (!userid || !targetUser) return this.sendReply("User '"+name+"' does not exist."); if (!this.can('ban', targetUser, room)) return false; if (!room.bannedUsers || !room.bannedIps) { return this.sendReply('Room bans are not meant to be used in room ' + room.id + '.'); } if (room.bannedUsers[userid]) delete room.bannedUsers[userid]; for (var ip in targetUser.ips) { if (room.bannedIps[ip]) delete room.bannedIps[ip]; } targetUser.popup(user.name+" has unbanned you from the room " + room.id + "."); this.addModCommand(""+targetUser.name+" was unbanned from room " + room.id + " by "+user.name+"."); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also unbanned from room " + room.id + ": "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { var altId = toId(alts[i]); if (room.bannedUsers[altId]) delete room.bannedUsers[altId]; } } }, roomauth: function(target, room, user, connection) { if (!room.auth) return this.sendReply("/roomauth - This room isn't designed for per-room moderation and therefore has no auth list."); var buffer = []; for (var u in room.auth) { buffer.push(room.auth[u] + u); } if (buffer.length > 0) { buffer = buffer.join(', '); } else { buffer = 'This room has no auth.'; } connection.popup(buffer); }, leave: 'part', part: function(target, room, user, connection) { if (room.id === 'global') return false; var targetRoom = Rooms.get(target); if (target && !targetRoom) { return this.sendReply("The room '"+target+"' does not exist."); } user.leaveRoom(targetRoom || room, connection); }, /********************************************************* * Moderating: Punishments *********************************************************/ k: 'kick', kick: function(target, room, user){ if (!target) return; target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply("User " + this.targetUsername + " not found."); } if (!this.can('kick', targetUser, room)) return false; var msg = "kicked by " + user.name + (target ? " (" + target + ")" : "") + "."; this.addModCommand(targetUser.name + " was " + msg); targetUser.popup("You have been " + msg); targetUser.disconnectAll(); }, warn: function(target, room, user) { if (!target) return this.parse('/help warn'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (room.isPrivate && room.auth) { return this.sendReply('You can\'t warn here: This is a privately-owned room not subject to global rules.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('warn', targetUser, room)) return false; this.addModCommand(''+targetUser.name+' was warned by '+user.name+'.' + (target ? " (" + target + ")" : "")); targetUser.send('|c|~|/warn '+target); this.add('|unlink|' + targetUser.userid); }, redirect: 'redir', redir: function (target, room, user, connection) { if (!target) return this.parse('/help redirect'); target = this.splitTarget(target); var targetUser = this.targetUser; var targetRoom = Rooms.get(target) || Rooms.get(toId(target)); if (!targetRoom) { return this.sendReply("The room '" + target + "' does not exist."); } if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (Rooms.rooms[targetRoom.id].users[targetUser.userid]) { return this.sendReply("User " + targetUser.name + " is already in the room " + target + "!"); } if (!Rooms.rooms[room.id].users[targetUser.userid]) { return this.sendReply('User '+this.targetUsername+' is not in the room ' + room.id + '.'); } if (targetUser.joinRoom(target) === false) return this.sendReply('User "' + targetUser.name + '" could not be joined to room ' + target + '. They could be banned from the room.'); var roomName = (targetRoom.isPrivate)? 'a private room' : 'room ' + targetRoom.title; this.addModCommand(targetUser.name + ' was redirected to ' + roomName + ' by ' + user.name + '.'); targetUser.leaveRoom(room); }, m: 'mute', mute: function(target, room, user) { if (!target) return this.parse('/help mute'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute', targetUser, room)) return false; if (targetUser.mutedRooms[room.id] || targetUser.locked || !targetUser.connected) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); if (!target) { return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } return this.addModCommand(''+targetUser.name+' would be muted by '+user.name+problem+'.' + (target ? " (" + target + ")" : "")); } targetUser.popup(user.name+' has muted you for 7 minutes. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 7 minutes.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.mute(room.id, 7*60*1000); }, hm: 'hourmute', hourmute: function(target, room, user) { if (!target) return this.parse('/help hourmute'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute', targetUser, room)) return false; if (((targetUser.mutedRooms[room.id] && (targetUser.muteDuration[room.id]||0) >= 50*60*1000) || targetUser.locked) && !target) { var problem = ' but was already '+(!targetUser.connected ? 'offline' : targetUser.locked ? 'locked' : 'muted'); return this.privateModCommand('('+targetUser.name+' would be muted by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has muted you for 60 minutes. '+target); this.addModCommand(''+targetUser.name+' was muted by '+user.name+' for 60 minutes.' + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also muted: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.mute(room.id, 60*60*1000, true); }, um: 'unmute', unmute: function(target, room, user) { if (!target) return this.parse('/help unmute'); var targetUser = Users.get(target); if (!targetUser) { return this.sendReply('User '+target+' not found.'); } if (!this.can('mute', targetUser, room)) return false; if (!targetUser.mutedRooms[room.id]) { return this.sendReply(''+targetUser.name+' isn\'t muted.'); } this.addModCommand(''+targetUser.name+' was unmuted by '+user.name+'.'); targetUser.unmute(room.id); }, l: 'lock', ipmute: 'lock', lock: function(target, room, user) { if (!target) return this.parse('/help lock'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUser+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!user.can('lock', targetUser)) { return this.sendReply('/lock - Access denied.'); } if ((targetUser.locked || Users.checkBanned(targetUser.latestIp)) && !target) { var problem = ' but was already '+(targetUser.locked ? 'locked' : 'banned'); return this.privateModCommand('('+targetUser.name+' would be locked by '+user.name+problem+'.)'); } targetUser.popup(user.name+' has locked you from talking in chats, battles, and PMing regular users.\n\n'+target+'\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it.'); this.addModCommand(""+targetUser.name+" was locked from talking by "+user.name+"." + (target ? " (" + target + ")" : "")); var alts = targetUser.getAlts(); if (alts.length) this.addModCommand(""+targetUser.name+"'s alts were also locked: "+alts.join(", ")); this.add('|unlink|' + targetUser.userid); targetUser.lock(); }, unlock: function(target, room, user) { if (!target) return this.parse('/help unlock'); if (!this.can('lock')) return false; var unlocked = Users.unlock(target); if (unlocked) { var names = Object.keys(unlocked); this.addModCommand('' + names.join(', ') + ' ' + ((names.length > 1) ? 'were' : 'was') + ' unlocked by ' + user.name + '.'); } else { this.sendReply('User '+target+' is not locked.'); } }, b: 'ban', ban: function(target, room, user) { if (!target) return this.parse('/help ban'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The reason is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('ban', targetUser)) return false; if (Users.checkBanned(targetUser.latestIp) && !target && !targetUser.connected) { var problem = ' but was already banned'; return this.privateModCommand('('+targetUser.name+' would be banned by '+user.name+problem+'.)'); } targetUser.popup(user.name+" has banned you." + (config.appealurl ? (" If you feel that your banning was unjustified you can appeal the ban:\n" + config.appealurl) : "") + "\n\n"+target); this.addModCommand(""+targetUser.name+" was banned by "+user.name+"." + (target ? " (" + target + ")" : ""), ' ('+targetUser.latestIp+')'); var alts = targetUser.getAlts(); if (alts.length) { this.addModCommand(""+targetUser.name+"'s alts were also banned: "+alts.join(", ")); for (var i = 0; i < alts.length; ++i) { this.add('|unlink|' + toId(alts[i])); } } this.add('|unlink|' + targetUser.userid); targetUser.ban(); }, unban: function(target, room, user) { if (!target) return this.parse('/help unban'); if (!user.can('ban')) { return this.sendReply('/unban - Access denied.'); } var name = Users.unban(target); if (name) { this.addModCommand(''+name+' was unbanned by '+user.name+'.'); } else { this.sendReply('User '+target+' is not banned.'); } }, unbanall: function(target, room, user) { if (!user.can('ban')) { return this.sendReply('/unbanall - Access denied.'); } // we have to do this the hard way since it's no longer a global for (var i in Users.bannedIps) { delete Users.bannedIps[i]; } for (var i in Users.lockedIps) { delete Users.lockedIps[i]; } this.addModCommand('All bans and locks have been lifted by '+user.name+'.'); }, banip: function(target, room, user) { target = target.trim(); if (!target) { return this.parse('/help banip'); } if (!this.can('rangeban')) return false; Users.bannedIps[target] = '#ipban'; this.addModCommand(user.name+' temporarily banned the '+(target.charAt(target.length-1)==='*'?'IP range':'IP')+': '+target); }, unbanip: function(target, room, user) { target = target.trim(); if (!target) { return this.parse('/help unbanip'); } if (!this.can('rangeban')) return false; if (!Users.bannedIps[target]) { return this.sendReply(''+target+' is not a banned IP or IP range.'); } delete Users.bannedIps[target]; this.addModCommand(user.name+' unbanned the '+(target.charAt(target.length-1)==='*'?'IP range':'IP')+': '+target); }, /********************************************************* * Moderating: Other *********************************************************/ modnote: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help note'); if (target.length > MAX_REASON_LENGTH) { return this.sendReply('The note is too long. It cannot exceed ' + MAX_REASON_LENGTH + ' characters.'); } if (!this.can('mute')) return false; return this.privateModCommand('(' + user.name + ' notes: ' + target + ')'); }, demote: 'promote', promote: function(target, room, user, connection, cmd) { if (!target) return this.parse('/help promote'); var target = this.splitTarget(target, true); var targetUser = this.targetUser; var userid = toUserid(this.targetUsername); var name = targetUser ? targetUser.name : this.targetUsername; if (!userid) { if (target && config.groups[target]) { var groupid = config.groups[target].id; return this.sendReply("/"+groupid+" [username] - Promote a user to "+groupid+" globally"); } return this.parse("/help promote"); } var currentGroup = ' '; if (targetUser) { currentGroup = targetUser.group; } else if (Users.usergroups[userid]) { currentGroup = Users.usergroups[userid].substr(0,1); } var nextGroup = target ? target : Users.getNextGroupSymbol(currentGroup, cmd === 'demote', true); if (target === 'deauth') nextGroup = config.groupsranking[0]; if (!config.groups[nextGroup]) { return this.sendReply('Group \'' + nextGroup + '\' does not exist.'); } if (config.groups[nextGroup].roomonly) { return this.sendReply('Group \'' + config.groups[nextGroup].id + '\' does not exist as a global rank.'); } if (!user.canPromote(currentGroup, nextGroup)) { return this.sendReply('/' + cmd + ' - Access denied.'); } var isDemotion = (config.groups[nextGroup].rank < config.groups[currentGroup].rank); if (!Users.setOfflineGroup(name, nextGroup)) { return this.sendReply('/promote - WARNING: This user is offline and could be unregistered. Use /forcepromote if you\'re sure you want to risk it.'); } var groupName = (config.groups[nextGroup].name || nextGroup || '').trim() || 'a regular user'; if (isDemotion) { this.privateModCommand('('+name+' was demoted to ' + groupName + ' by '+user.name+'.)'); if (targetUser) { targetUser.popup('You were demoted to ' + groupName + ' by ' + user.name + '.'); } } else { this.addModCommand(''+name+' was promoted to ' + groupName + ' by '+user.name+'.'); } if (targetUser) { targetUser.updateIdentity(); } }, forcepromote: function(target, room, user) { // warning: never document this command in /help if (!this.can('forcepromote')) return false; var target = this.splitTarget(target, true); var name = this.targetUsername; var nextGroup = target ? target : Users.getNextGroupSymbol(' ', false); if (!Users.setOfflineGroup(name, nextGroup, true)) { return this.sendReply('/forcepromote - Don\'t forcepromote unless you have to.'); } var groupName = config.groups[nextGroup].name || nextGroup || ''; this.addModCommand(''+name+' was promoted to ' + (groupName.trim()) + ' by '+user.name+'.'); }, deauth: function(target, room, user) { return this.parse('/demote '+target+', deauth'); }, modchat: function(target, room, user) { if (!target) { return this.sendReply('Moderated chat is currently set to: '+room.modchat); } if (!this.can('modchat', null, room)) return false; if (room.modchat && room.modchat.length <= 1 && config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) { return this.sendReply('/modchat - Access denied for removing a setting higher than ' + config.groupsranking[1] + '.'); } target = target.toLowerCase(); switch (target) { case 'on': case 'true': case 'yes': case 'registered': this.sendReply("Modchat registered is no longer available."); return false; break; case 'off': case 'false': case 'no': room.modchat = false; break; case 'ac': case 'autoconfirmed': room.modchat = 'autoconfirmed'; break; case '*': case 'player': target = '\u2605'; // fallthrough default: if (!config.groups[target]) { return this.parse('/help modchat'); } if (config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) { return this.sendReply('/modchat - Access denied for setting higher than ' + config.groupsranking[1] + '.'); } room.modchat = target; break; } if (room.modchat === true) { this.add('|raw|<div class="broadcast-red"><b>Moderated chat was enabled!</b><br />Only registered users can talk.</div>'); } else if (!room.modchat) { this.add('|raw|<div class="broadcast-blue"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>'); } else { var modchat = sanitize(room.modchat); this.add('|raw|<div class="broadcast-red"><b>Moderated chat was set to '+modchat+'!</b><br />Only users of rank '+modchat+' and higher can talk.</div>'); } this.logModCommand(user.name+' set modchat to '+room.modchat); }, declare: function(target, room, user) { if (!target) return this.parse('/help declare'); if (!this.can('declare', null, room)) return false; if (!this.canTalk()) return; this.add('|raw|<div class="broadcast-blue"><b>'+target+'</b></div>'); this.logModCommand(user.name+' declared '+target); }, gdeclare: 'globaldeclare', globaldeclare: function(target, room, user) { if (!target) return this.parse('/help globaldeclare'); if (!this.can('gdeclare')) return false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' globally declared '+target); }, cdeclare: 'chatdeclare', chatdeclare: function(target, room, user) { if (!target) return this.parse('/help chatdeclare'); if (!this.can('gdeclare')) return false; for (var id in Rooms.rooms) { if (id !== 'global') if (Rooms.rooms[id].type !== 'battle') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>'+target+'</b></div>'); } this.logModCommand(user.name+' globally declared (chat level) '+target); }, wall: 'announce', announce: function(target, room, user) { if (!target) return this.parse('/help announce'); if (!this.can('announce', null, room)) return false; target = this.canTalk(target); if (!target) return; return '/announce '+target; }, fr: 'forcerename', forcerename: function(target, room, user) { if (!target) return this.parse('/help forcerename'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('forcerename', targetUser)) return false; if (targetUser.userid === toUserid(this.targetUser)) { var entry = ''+targetUser.name+' was forced to choose a new name by '+user.name+'' + (target ? ": " + target + "" : ""); this.privateModCommand('(' + entry + ')'); Rooms.global.cancelSearch(targetUser); targetUser.resetName(); targetUser.send('|nametaken||'+user.name+" has forced you to change your name. "+target); } else { this.sendReply("User "+targetUser.name+" is no longer using that name."); } }, modlog: function(target, room, user, connection) { if (!this.can('modlog')) return false; var lines = 0; // Specific case for modlog command. Room can be indicated with a comma, lines go after the comma. // Otherwise, the text is defaulted to text search in current room's modlog. var roomId = room.id; var roomLogs = {}; var fs = require('fs'); if (target.indexOf(',') > -1) { var targets = target.split(','); target = targets[1].trim(); roomId = toId(targets[0]) || room.id; } // Let's check the number of lines to retrieve or if it's a word instead if (!target.match('[^0-9]')) { lines = parseInt(target || 15, 10); if (lines > 100) lines = 100; } var wordSearch = (!lines || lines < 0); // Control if we really, really want to check all modlogs for a word. var roomNames = ''; var filename = ''; var command = ''; if (roomId === 'all' && wordSearch) { roomNames = 'all rooms'; // Get a list of all the rooms var fileList = fs.readdirSync('logs/modlog'); for (var i=0; i<fileList.length; i++) { filename += 'logs/modlog/' + fileList[i] + ' '; } } else { roomId = room.id; roomNames = 'the room ' + roomId; filename = 'logs/modlog/modlog_' + roomId + '.txt'; } // Seek for all input rooms for the lines or text command = 'tail -' + lines + ' ' + filename; var grepLimit = 100; if (wordSearch) { // searching for a word instead if (target.match(/^["'].+["']$/)) target = target.substring(1,target.length-1); command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m"+grepLimit+" -i '"+target.replace(/\\/g,'\\\\\\\\').replace(/["'`]/g,'\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g,'[$&]')+"'"; } // Execute the file search to see modlog require('child_process').exec(command, function(error, stdout, stderr) { if (error && stderr) { connection.popup('/modlog empty on ' + roomNames + ' or erred - modlog does not support Windows'); console.log('/modlog error: '+error); return false; } if (lines) { if (!stdout) { connection.popup('The modlog is empty. (Weird.)'); } else { connection.popup('Displaying the last '+lines+' lines of the Moderator Log of ' + roomNames + ':\n\n'+stdout); } } else { if (!stdout) { connection.popup('No moderator actions containing "'+target+'" were found on ' + roomNames + '.'); } else { connection.popup('Displaying the last '+grepLimit+' logged actions containing "'+target+'" on ' + roomNames + ':\n\n'+stdout); } } }); }, bw: 'banword', banword: function(target, room, user) { if (!this.can('declare')) return false; target = toId(target); if (!target) { return this.sendReply('Specify a word or phrase to ban.'); } Users.addBannedWord(target); this.sendReply('Added \"'+target+'\" to the list of banned words.'); }, ubw: 'unbanword', unbanword: function(target, room, user) { if (!this.can('declare')) return false; target = toId(target); if (!target) { return this.sendReply('Specify a word or phrase to unban.'); } Users.removeBannedWord(target); this.sendReply('Removed \"'+target+'\" from the list of banned words.'); }, /********************************************************* * Server management commands *********************************************************/ hotpatch: function(target, room, user) { if (!target) return this.parse('/help hotpatch'); if (!this.can('hotpatch')) return false; this.logEntry(user.name + ' used /hotpatch ' + target); if (target === 'chat' || target === 'commands') { try { CommandParser.uncacheTree('./command-parser.js'); CommandParser = require('./command-parser.js'); CommandParser.uncacheTree('./tour.js'); global.tour = new (require('./tour.js').tour)(tour); return this.sendReply('Chat commands have been hot-patched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch chat: \n' + e.stack); } } else if (target === 'battles') { /*Simulator.SimulatorProcess.respawn(); return this.sendReply('Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code.');*/ return this.sendReply('Battle hotpatching is not supported with the single process hack.'); } else if (target === 'formats') { /*try { // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools.js'); // reload tools.js Tools = require('./tools.js'); // note: this will lock up the server for a few seconds // rebuild the formats list Rooms.global.formatListText = Rooms.global.getFormatListText(); // respawn validator processes TeamValidator.ValidatorProcess.respawn(); // respawn simulator processes Simulator.SimulatorProcess.respawn(); // broadcast the new formats list to clients Rooms.global.send(Rooms.global.formatListText); return this.sendReply('Formats have been hotpatched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch formats: \n' + e.stack); }*/ return this.sendReply('Formats hotpatching is not supported with the single process hack.'); } else if (target === 'learnsets') { try { // uncache the tools.js dependency tree CommandParser.uncacheTree('./tools.js'); // reload tools.js Tools = require('./tools.js'); // note: this will lock up the server for a few seconds return this.sendReply('Learnsets have been hotpatched.'); } catch (e) { return this.sendReply('Something failed while trying to hotpatch learnsets: \n' + e.stack); } } this.sendReply('Your hot-patch command was unrecognized.'); }, savelearnsets: function(target, room, user) { if (!this.can('hotpatch')) return false; fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = '+JSON.stringify(BattleLearnsets)+";\n"); this.sendReply('learnsets.js saved.'); }, disableladder: function(target, room, user) { if (!this.can('disableladder')) return false; if (LoginServer.disabled) { return this.sendReply('/disableladder - Ladder is already disabled.'); } LoginServer.disabled = true; this.logModCommand('The ladder was disabled by ' + user.name + '.'); this.add('|raw|<div class="broadcast-red"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>'); }, enableladder: function(target, room, user) { if (!this.can('disableladder')) return false; if (!LoginServer.disabled) { return this.sendReply('/enable - Ladder is already enabled.'); } LoginServer.disabled = false; this.logModCommand('The ladder was enabled by ' + user.name + '.'); this.add('|raw|<div class="broadcast-green"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>'); }, lockdown: function(target, room, user) { if (!this.can('lockdown')) return false; Rooms.global.lockdown = true; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>'); if (Rooms.rooms[id].requestKickInactive && !Rooms.rooms[id].battle.ended) Rooms.rooms[id].requestKickInactive(user, true); } this.logEntry(user.name + ' used /lockdown'); }, endlockdown: function(target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.sendReply("We're not under lockdown right now."); } Rooms.global.lockdown = false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b>The server shutdown was canceled.</b></div>'); } this.logEntry(user.name + ' used /endlockdown'); }, emergency: function(target, room, user) { if (!this.can('lockdown')) return false; if (config.emergency) { return this.sendReply("We're already in emergency mode."); } config.emergency = true; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red">The server has entered emergency mode. Some features might be disabled or limited.</div>'); } this.logEntry(user.name + ' used /emergency'); }, endemergency: function(target, room, user) { if (!this.can('lockdown')) return false; if (!config.emergency) { return this.sendReply("We're not in emergency mode."); } config.emergency = false; for (var id in Rooms.rooms) { if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b>The server is no longer in emergency mode.</b></div>'); } this.logEntry(user.name + ' used /endemergency'); }, kill: function(target, room, user) { if (!this.can('lockdown')) return false; if (!Rooms.global.lockdown) { return this.sendReply('For safety reasons, /kill can only be used during lockdown.'); } if (CommandParser.updateServerLock) { return this.sendReply('Wait for /updateserver to finish before using /kill.'); } /*for (var i in Sockets.workers) { Sockets.workers[i].kill(); }*/ if (!room.destroyLog) { process.exit(); return; } room.destroyLog(function() { room.logEntry(user.name + ' used /kill'); }, function() { process.exit(); }); // Just in the case the above never terminates, kill the process // after 10 seconds. setTimeout(function() { process.exit(); }, 10000); }, loadbanlist: function(target, room, user, connection) { if (!this.can('hotpatch')) return false; connection.sendTo(room, 'Loading ipbans.txt...'); fs.readFile('config/ipbans.txt', function (err, data) { if (err) return; data = (''+data).split("\n"); var rangebans = []; for (var i=0; i<data.length; i++) { var line = data[i].split('#')[0].trim(); if (!line) continue; if (line.indexOf('/') >= 0) { rangebans.push(line); } else if (line && !Users.bannedIps[line]) { Users.bannedIps[line] = '#ipban'; } } Users.checkRangeBanned = Cidr.checker(rangebans); connection.sendTo(room, 'ibans.txt has been reloaded.'); }); }, refreshpage: function(target, room, user) { if (!this.can('hotpatch')) return false; Rooms.global.send('|refresh|'); this.logEntry(user.name + ' used /refreshpage'); }, updateserver: function(target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.sendReply('/updateserver - Access denied.'); } if (CommandParser.updateServerLock) { return this.sendReply('/updateserver - Another update is already in progress.'); } CommandParser.updateServerLock = true; var logQueue = []; logQueue.push(user.name + ' used /updateserver'); connection.sendTo(room, 'updating...'); var exec = require('child_process').exec; exec('git diff-index --quiet HEAD --', function(error) { var cmd = 'git pull --rebase'; if (error) { if (error.code === 1) { // The working directory or index have local changes. cmd = 'git stash;' + cmd + ';git stash pop'; } else { // The most likely case here is that the user does not have // `git` on the PATH (which would be error.code === 127). connection.sendTo(room, '' + error); logQueue.push('' + error); logQueue.forEach(function(line) { room.logEntry(line); }); CommandParser.updateServerLock = false; return; } } var entry = 'Running `' + cmd + '`'; connection.sendTo(room, entry); logQueue.push(entry); exec(cmd, function(error, stdout, stderr) { ('' + stdout + stderr).split('\n').forEach(function(s) { connection.sendTo(room, s); logQueue.push(s); }); logQueue.forEach(function(line) { room.logEntry(line); }); CommandParser.updateServerLock = false; }); }); }, crashfixed: function(target, room, user) { if (!Rooms.global.lockdown) { return this.sendReply('/crashfixed - There is no active crash.'); } if (!this.can('hotpatch')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw('<div class="broadcast-green"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>'); } this.logEntry(user.name + ' used /crashfixed'); }, crashlogged: function(target, room, user) { if (!Rooms.global.lockdown) { return this.sendReply('/crashlogged - There is no active crash.'); } if (!this.can('declare')) return false; Rooms.global.lockdown = false; if (Rooms.lobby) { Rooms.lobby.modchat = false; Rooms.lobby.addRaw('<div class="broadcast-green"><b>We have logged the crash and are working on fixing it!</b><br />You may resume talking in the lobby and starting new battles.</div>'); } this.logEntry(user.name + ' used /crashlogged'); }, 'memusage': 'memoryusage', memoryusage: function(target) { if (!this.can('hotpatch')) return false; target = toId(target) || 'all'; if (target === 'all') { this.sendReply('Loading memory usage, this might take a while.'); } if (target === 'all' || target === 'rooms' || target === 'room') { this.sendReply('Calculating Room size...'); var roomSize = ResourceMonitor.sizeOfObject(Rooms); this.sendReply("Rooms are using " + roomSize + " bytes of memory."); } if (target === 'all' || target === 'config') { this.sendReply('Calculating config size...'); var configSize = ResourceMonitor.sizeOfObject(config); this.sendReply("Config is using " + configSize + " bytes of memory."); } if (target === 'all' || target === 'resourcemonitor' || target === 'rm') { this.sendReply('Calculating Resource Monitor size...'); var rmSize = ResourceMonitor.sizeOfObject(ResourceMonitor); this.sendReply("The Resource Monitor is using " + rmSize + " bytes of memory."); } if (target === 'all' || target === 'cmdp' || target === 'cp' || target === 'commandparser') { this.sendReply('Calculating Command Parser size...'); var cpSize = ResourceMonitor.sizeOfObject(CommandParser); this.sendReply("Command Parser is using " + cpSize + " bytes of memory."); } if (target === 'all' || target === 'sim' || target === 'simulator') { this.sendReply('Calculating Simulator size...'); var simSize = ResourceMonitor.sizeOfObject(Simulator); this.sendReply("Simulator is using " + simSize + " bytes of memory."); } if (target === 'all' || target === 'users') { this.sendReply('Calculating Users size...'); var usersSize = ResourceMonitor.sizeOfObject(Users); this.sendReply("Users is using " + usersSize + " bytes of memory."); } if (target === 'all' || target === 'tools') { this.sendReply('Calculating Tools size...'); var toolsSize = ResourceMonitor.sizeOfObject(Tools); this.sendReply("Tools are using " + toolsSize + " bytes of memory."); } if (target === 'all' || target === 'v8') { this.sendReply('Retrieving V8 memory usage...'); var o = process.memoryUsage(); this.sendReply( 'Resident set size: ' + o.rss + ', ' + o.heapUsed +' heap used of ' + o.heapTotal + ' total heap. ' + (o.heapTotal - o.heapUsed) + ' heap left.' ); delete o; } if (target === 'all') { this.sendReply('Calculating Total size...'); var total = (roomSize + configSize + rmSize + appSize + cpSize + simSize + toolsSize + usersSize) || 0; var units = ['bytes', 'K', 'M', 'G']; var converted = total; var unit = 0; while (converted > 1024) { converted /= 1024; unit++; } converted = Math.round(converted); this.sendReply("Total memory used: " + converted + units[unit] + " (" + total + " bytes)."); } return; }, bash: function(target, room, user, connection) { if (!user.hasConsoleAccess(connection)) { return this.sendReply('/bash - Access denied.'); } var exec = require('child_process').exec; exec(target, function(error, stdout, stderr) { connection.sendTo(room, ('' + stdout + stderr)); }); }, eval: function(target, room, user, connection, cmd, message) { if (!user.hasConsoleAccess(connection)) { return this.sendReply("/eval - Access denied."); } if (!this.canBroadcast()) return; if (!this.broadcasting) this.sendReply('||>> '+target); try { var battle = room.battle; var me = user; this.sendReply('||<< '+eval(target)); } catch (e) { this.sendReply('||<< error: '+e.message); var stack = '||'+(''+e.stack).replace(/\n/g,'\n||'); connection.sendTo(room, stack); } }, evalbattle: function(target, room, user, connection, cmd, message) { if (!user.hasConsoleAccess(connection)) { return this.sendReply("/evalbattle - Access denied."); } if (!this.canBroadcast()) return; if (!room.battle) { return this.sendReply("/evalbattle - This isn't a battle room."); } room.battle.send('eval', target.replace(/\n/g, '\f')); }, /********************************************************* * Battle commands *********************************************************/ concede: 'forfeit', surrender: 'forfeit', forfeit: function(target, room, user) { if (!room.battle) { return this.sendReply("There's nothing to forfeit here."); } if (!room.forfeit(user)) { return this.sendReply("You can't forfeit this battle."); } }, savereplay: function(target, room, user, connection) { if (!room || !room.battle) return; var logidx = 2; // spectator log (no exact HP) if (room.battle.ended) { // If the battle is finished when /savereplay is used, include // exact HP in the replay log. logidx = 3; } var data = room.getLog(logidx).join("\n"); var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g,'')).digest('hex'); LoginServer.request('prepreplay', { id: room.id.substr(7), loghash: datahash, p1: room.p1.name, p2: room.p2.name, format: room.format }, function(success) { connection.send('|queryresponse|savereplay|'+JSON.stringify({ log: data, id: room.id.substr(7) })); }); }, mv: 'move', attack: 'move', move: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'move '+target); }, sw: 'switch', switch: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'switch '+parseInt(target,10)); }, choose: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', target); }, undo: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'undo', target); }, team: function(target, room, user) { if (!room.decision) return this.sendReply('You can only do this in battle rooms.'); room.decision(user, 'choose', 'team '+target); }, joinbattle: function(target, room, user) { if (!room.joinBattle) return this.sendReply('You can only do this in battle rooms.'); if (!user.can('joinbattle', null, room)) return this.popupReply("You must be a roomvoice to join a battle you didn't start. Ask a player to use /roomvoice on you to join this battle."); room.joinBattle(user); }, partbattle: 'leavebattle', leavebattle: function(target, room, user) { if (!room.leaveBattle) return this.sendReply('You can only do this in battle rooms.'); room.leaveBattle(user); }, kickbattle: function(target, room, user) { if (!room.leaveBattle) return this.sendReply('You can only do this in battle rooms.'); target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.sendReply('User '+this.targetUsername+' not found.'); } if (!this.can('kick', targetUser)) return false; if (room.leaveBattle(targetUser)) { this.addModCommand(''+targetUser.name+' was kicked from a battle by '+user.name+'' + (target ? " (" + target + ")" : "")); } else { this.sendReply("/kickbattle - User isn\'t in battle."); } }, kickinactive: function(target, room, user) { if (room.requestKickInactive) { room.requestKickInactive(user); } else { this.sendReply('You can only kick inactive players from inside a room.'); } }, timer: function(target, room, user) { target = toId(target); if (room.requestKickInactive) { if (target === 'off' || target === 'false' || target === 'stop') { room.stopKickInactive(user, user.can('timer')); } else if (target === 'on' || target === 'true' || !target) { room.requestKickInactive(user, user.can('timer')); } else { this.sendReply("'"+target+"' is not a recognized timer state."); } } else { this.sendReply('You can only set the timer from inside a room.'); } }, autotimer: 'forcetimer', forcetimer: function(target, room, user) { target = toId(target); if (!this.can('autotimer')) return; if (target === 'off' || target === 'false' || target === 'stop') { config.forcetimer = false; this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by "+user.name+")"); } else if (target === 'on' || target === 'true' || !target) { config.forcetimer = true; this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by "+user.name+")"); } else { this.sendReply("'"+target+"' is not a recognized forcetimer setting."); } }, forcetie: 'forcewin', forcewin: function(target, room, user) { if (!this.can('forcewin')) return false; if (!room.battle) { this.sendReply('/forcewin - This is not a battle room.'); return false; } room.battle.endType = 'forced'; if (!target) { room.battle.tie(); this.logModCommand(user.name+' forced a tie.'); return false; } target = Users.get(target); if (target) target = target.userid; else target = ''; if (target) { room.battle.win(target); this.logModCommand(user.name+' forced a win for '+target+'.'); } }, /********************************************************* * Challenging and searching commands *********************************************************/ cancelsearch: 'search', search: function(target, room, user) { if (target) { if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to search for a battle.'); return false; } } Rooms.global.searchBattle(user, target); } else { Rooms.global.cancelSearch(user); } }, chall: 'challenge', challenge: function(target, room, user, connection) { target = this.splitTarget(target); var targetUser = this.targetUser; if (!targetUser || !targetUser.connected) { return this.popupReply("The user '"+this.targetUsername+"' was not found."); } if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) { return this.popupReply("The user '"+this.targetUsername+"' is not accepting challenges right now."); } if (config.pmmodchat) { var userGroup = user.group; if (config.groupsranking.indexOf(userGroup) < config.groupsranking.indexOf(config.pmmodchat)) { var groupName = config.groups[config.pmmodchat].name; if (!groupName) groupName = config.pmmodchat; this.popupReply('Because moderated chat is set, you must be of rank ' + groupName +' or higher to challenge users.'); return false; } } user.prepBattle(target, 'challenge', connection, function (result) { if (result) user.makeChallenge(targetUser, target); }); }, away: 'blockchallenges', idle: 'blockchallenges', blockchallenges: function(target, room, user) { user.blockChallenges = true; this.sendReply('You are now blocking all incoming challenge requests.'); }, back: 'allowchallenges', allowchallenges: function(target, room, user) { user.blockChallenges = false; this.sendReply('You are available for challenges from now on.'); }, cchall: 'cancelChallenge', cancelchallenge: function(target, room, user) { user.cancelChallengeTo(target); }, accept: function(target, room, user, connection) { var userid = toUserid(target); var format = ''; if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format; if (!format) { this.popupReply(target+" cancelled their challenge before you could accept it."); return false; } user.prepBattle(format, 'challenge', connection, function (result) { if (result) user.acceptChallengeFrom(userid); }); }, reject: function(target, room, user) { user.rejectChallengeFrom(toUserid(target)); }, saveteam: 'useteam', utm: 'useteam', useteam: function(target, room, user) { user.team = target; }, /********************************************************* * Low-level *********************************************************/ cmd: 'query', query: function(target, room, user, connection) { // Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode var trustable = (!config.emergency || (user.named && user.authenticated)); if (config.emergency && ResourceMonitor.countCmd(connection.ip, user.name)) return false; var spaceIndex = target.indexOf(' '); var cmd = target; if (spaceIndex > 0) { cmd = target.substr(0, spaceIndex); target = target.substr(spaceIndex+1); } else { target = ''; } if (cmd === 'userdetails') { var targetUser = Users.get(target); if (!trustable || !targetUser) { connection.send('|queryresponse|userdetails|'+JSON.stringify({ userid: toId(target), rooms: false })); return false; } var roomList = {}; for (var i in targetUser.roomCount) { if (i==='global') continue; var targetRoom = Rooms.get(i); if (!targetRoom || targetRoom.isPrivate) continue; var roomData = {}; if (targetRoom.battle) { var battle = targetRoom.battle; roomData.p1 = battle.p1?' '+battle.p1:''; roomData.p2 = battle.p2?' '+battle.p2:''; } roomList[i] = roomData; } if (!targetUser.roomCount['global']) roomList = false; var userdetails = { userid: targetUser.userid, avatar: targetUser.avatar, rooms: roomList }; if (user.can('ip', targetUser)) { var ips = Object.keys(targetUser.ips); if (ips.length === 1) { userdetails.ip = ips[0]; } else { userdetails.ips = ips; } } connection.send('|queryresponse|userdetails|'+JSON.stringify(userdetails)); } else if (cmd === 'roomlist') { if (!trustable) return false; connection.send('|queryresponse|roomlist|'+JSON.stringify({ rooms: Rooms.global.getRoomList(true) })); } else if (cmd === 'rooms') { if (!trustable) return false; connection.send('|queryresponse|rooms|'+JSON.stringify( Rooms.global.getRooms() )); } }, trn: function(target, room, user, connection) { var commaIndex = target.indexOf(','); var targetName = target; var targetAuth = false; var targetToken = ''; if (commaIndex >= 0) { targetName = target.substr(0,commaIndex); target = target.substr(commaIndex+1); commaIndex = target.indexOf(','); targetAuth = target; if (commaIndex >= 0) { targetAuth = !!parseInt(target.substr(0,commaIndex),10); targetToken = target.substr(commaIndex+1); } } user.rename(targetName, targetToken, targetAuth, connection); }, };
Add join message
commands.js
Add join message
<ide><path>ommands.js <ide> } <ide> if (!user.joinRoom(targetRoom || room, connection)) { <ide> return connection.sendTo(target, "|noinit|joinfailed|The room '"+target+"' could not be joined."); <add> } <add> if (target === 'lobby') { <add> connection.sendTo('lobby','|html|<div class=\"broadcast-red\"><center><br><img src="http://i.imgur.com/aTpSGwf.png" height="100" width="100"><img src="http://pokemon-hispano.comxa.com/images/EvaBlack/logo.png"><img src="http://i.imgur.com/Lb5IwHb.png" height="100" width="100"></br><font size=4><center><b>BIENVENIDOS A POKÉMON HISPANO!!!</b></font><br></center>- Visita nuestro <a href=\"http://pokemon-hispano.comxa.com/\" target=\"_BLANK\">Foro</a></br><br>- Únete a nuestra página en <a href=\"https://www.facebook.com/groups/PokemonHispanoShowdown/\">Facebook</a></br><br> - Vísita nuestro <a href=\"http://www.twitch.tv/pokemonhispano/\">Livestream</a></br><br>- Para ver la lista de comandos del server escribe <b>/comandos</b>.<br>- Recuerda leer las reglas escribiendo <b>/reglas</b> para no tener ningún problema con ningún usuario y mucho menos con un miembro del Staff.<br>- Escribe <b>/lideres</b> para ver los lideres y alto mando de nuestra liga.</br> <br><center><br>Si tienes algún problema o duda no dudes en contactar a los miembros del staff ya sean <b>(+)Voices</b>, <b>(%)Drivers</b>, <b>(@)Moderadores</b>, <b>(&)Leaders</b> y en caso de ser un grave problema a los <b>(~)Administradores</b>.</div>'); <ide> } <ide> }, <ide>
JavaScript
mit
ee4aee8e8ee39561ebb7cb0cbf7eb5fb8cdb112d
0
France-ioi/bebras-modules,France-ioi/bebras-modules,be-oi/beoi-contest-modules,be-oi/beoi-contest-modules
/* interface: Main interface for quickAlgo, common to all languages. */ var quickAlgoInterface = { strings: {}, nbTestCases: 0, delayFactory: new DelayFactory(), curMode: null, fullscreen: false, lastHeight: null, checkHeightInterval: null, hasHelp: false, editorMenuIsOpen: false, longIntroShown: false, taskIntroContent: '', enterFullscreen: function() { var el = document.documentElement; if(el.requestFullscreen) { el.requestFullscreen(); } else if(el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if(el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if(el.msRequestFullscreen) { el.msRequestFullscreen(); } this.fullscreen = true; this.updateFullscreenElements(); }, exitFullscreen: function() { var el = document; if(el.exitFullscreen) { el.exitFullscreen(); } else if(el.mozCancelFullScreen) { el.mozCancelFullScreen(); } else if(el.webkitExitFullscreen) { el.webkitExitFullscreen(); } else if(el.msExitFullscreen) { el.msExitFullscreen(); } this.fullscreen = false; this.updateFullscreenElements(); }, toggleFullscreen: function() { this.fullscreen = !this.fullscreen; if(this.fullscreen) { this.enterFullscreen(); } else { this.exitFullscreen(); } var that = this; setTimeout(function() { that.onResize(); }, 500); }, updateFullscreenState: function() { if(document.fullscreenElement || document.msFullscreenElement || document.mozFullScreen || document.webkitIsFullScreen) { this.fullscreen = true; } else { this.fullscreen = false; } this.updateFullscreenElements(); }, updateFullscreenElements: function() { if(this.fullscreen) { $('body').addClass('fullscreen'); $('#fullscreenButton').html('<i class="fas fa-compress"></i>'); } else { $('body').removeClass('fullscreen'); $('#fullscreenButton').html('<i class="fas fa-expand"></i>'); } }, registerFullscreenEvents: function() { if(this.fullscreenEvents) { return; } document.addEventListener("fullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("webkitfullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("mozfullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("MSFullscreenChange", this.updateFullscreenState.bind(this)); this.fullscreenEvents = true; }, loadInterface: function(context, level) { ////TODO: function is called twice // Load quickAlgo interface into the DOM var self = this; this.context = context; this.strings = window.languageStrings; var gridHtml = ""; gridHtml += "<div id='gridButtonsBefore'></div>"; gridHtml += "<div id='grid'></div>"; gridHtml += "<div id='gridButtonsAfter'></div>"; $("#gridContainer").html(gridHtml); var displayHelpBtn = this.hasHelp ? this.displayHelpBtn() : ''; $("#blocklyLibContent").html( "<div id='editorBar'>" + "<div id='capacity'></div>" + "<div class='buttons'>" + "<button type='button' id='fullscreenButton'><span class='fas fa-expand'></span></button>" + displayHelpBtn + "</div>" + "</div>" + "<div id='languageInterface'></div>" ); var iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)); if(iOS) { $('#fullscreenButton').remove(); } else { $('#fullscreenButton').click(function() { self.toggleFullscreen(); }); } // TODO :: something cleaner (add when editorMenu is opened, remove when closed?) $('#editorMenu div[rel=example]').click(function(e) { self.closeEditorMenu(); task.displayedSubTask.loadExample() }); $('#editorMenu div[rel=save]').click(function(e) { self.closeEditorMenu(); task.displayedSubTask.blocklyHelper.saveProgram(); }); $('#editorMenu div[rel=restart]').click(function(e) { self.closeEditorMenu(); displayHelper.restartAll(); }); $('#editorMenu div[rel=best-answer]').click(function(e) { self.closeEditorMenu(); displayHelper.retrieveAnswer(); }); // Buttons from buttonsAndMessages var addTaskHTML = '<div id="displayHelperAnswering" class="contentCentered" style="padding: 1px;">'; var placementNames = ['graderMessage', 'validate', 'saved']; for (var iPlacement = 0; iPlacement < placementNames.length; iPlacement++) { var placement = 'displayHelper_' + placementNames[iPlacement]; if ($('#' + placement).length === 0) { addTaskHTML += '<div id="' + placement + '"></div>'; } } addTaskHTML += '</div>'; /* if(!$('#displayHelper_cancel').length) { $('body').append($('<div class="contentCentered" style="margin-top: 15px;"><div id="displayHelper_cancel"></div></div>')); } */ var scaleControl = ''; if(context.display && context.infos.buttonScaleDrawing) { var scaleControl = '<div class="scaleDrawingControl">' + '<label for="scaleDrawing"><input id="scaleDrawing" type="checkbox">' + this.strings.scaleDrawing + '</label>' + '</div>'; } var gridButtonsAfter = scaleControl + "<div id='testSelector'></div>" //+ "<button type='button' id='submitBtn' class='btn btn-primary' onclick='task.displayedSubTask.submit()'>" //+ this.strings.submitProgram //+ "</button><br/>" //+ "<div id='messages'><span id='tooltip'></span><span id='errors'></span></div>" + addTaskHTML; $("#gridButtonsAfter").html(gridButtonsAfter); $('#scaleDrawing').change(this.onScaleDrawingChange.bind(this)); this.createModeTaskToolbar(); this.createEditorMenu(); this.setupTaskIntro(level); this.wrapIntroAndGrid(); this.checkFonts(); this.registerFullscreenEvents(); if(!this.checkHeightInterval) { this.checkHeightInterval = setInterval(this.checkHeight.bind(this), 1000); } var that = this; setTimeout(function() { that.onResize(); }, 0); }, createEditorMenu: function() { var self = this; if(!$('#openEditorMenu').length) { $("#tabsContainer").append("<div id='openEditorMenu' class='icon'><span class='fas fa-bars'></span></div>"); } if($('#editorMenu').length) { return; } $("body").append('' + "<div id='editorMenu' style='display: none;'>" + "<div class='editorMenuHeader'>" + "<div id='closeEditorMenu'><span class='fas fa-times'></span></div>" + "<div>Menu</div>" + "</div>" + "<div class='editorActions'>" + "<div rel='example' class='item'><span class='fas fa-paste'></span> " + this.strings.loadExample + "</div>" + "<div rel='restart' class='item'><span class='fas fa-trash-alt'></span> " + this.strings.restart + "</div>" + "<div rel='save' class='item'><span class='fas fa-download'></span> " + this.strings.saveProgram + "</div>" + "<div rel='best-answer' class='item'><span class='fas fa-trophy'></span> " + this.strings.loadBestAnswer+ "</div>" + "<div rel='load' class='item'>" + "<input type='file' id='task-upload-file' " + "onchange='\ task.displayedSubTask.blocklyHelper.handleFiles(this.files);\ resetFormElement($(this));\ $(\"#editorMenu\").hide();'>" + "<span class='fas fa-upload'></span> " + this.strings.reloadProgram + "</div>" + "</div>" + "<span id='saveUrl'></span>" + "</div>" ); $('#openEditorMenu').click(function() { self.editorMenuIsOpen ? self.closeEditorMenu() : self.openEditorMenu(); }); $("#closeEditorMenu").click(function() { self.closeEditorMenu(); }); }, openEditorMenu: function() { this.editorMenuIsOpen = true; var menuWidth = $('#editorMenu').css('width'); $('#editorMenu').css('display','block'); $('body').animate({left: '-' + menuWidth}, 500); }, closeEditorMenu: function() { this.editorMenuIsOpen = false; $('body').animate({left: '0'}, 500, function() { $('#editorMenu').css('display','none') }); }, setOptions: function(opt) { // Load options from the task $('#editorMenu div[rel=example]').toggle(opt.hasExample); $('#editorMenu div[rel=save]').toggle(!opt.hideSaveOrLoad); $('#editorMenu div[rel=load]').toggle(!opt.hideSaveOrLoad); $('#editorMenu div[rel=best-answer]').toggle(!opt.hideLoadBestAnswer); if(opt.conceptViewer) { conceptViewer.load(opt.conceptViewerLang); this.hasHelp = true; } else { this.hasHelp = false; } }, devMode: function() { $('#editorMenu .item').show(); }, onScaleDrawingChange: function(e) { var scaled = $(e.target).prop('checked'); $("#gridContainer").toggleClass('gridContainerScaled', scaled); $("#blocklyLibContent").toggleClass('blocklyLibContentScaled', scaled); this.context.setScale(scaled ? 2 : 1); }, blinkRemaining: function(times, red) { var capacity = $('#capacity'); if(times % 2 == 0) { capacity.removeClass('capacityRed'); } else { capacity.addClass('capacityRed'); } if(times > (red ? 1 : 0)) { var that = this; this.delayFactory.destroy('blinkRemaining'); this.delayFactory.createTimeout('blinkRemaining', function() { that.blinkRemaining(times - 1, red); }, 200); } }, stepDelayMin: 25, stepDelayMax: 250, refreshStepDelay: function() { var v = parseInt($('.speedCursor').val(), 10), delay = this.stepDelayMin + this.stepDelayMax - v; task.displayedSubTask.setStepDelay(delay); }, initPlaybackControls: function() { var self = this; var speedControls = '<div class="speedControls">' + '<div class="playerControls">' + '<div class="icon backToFirst"><span class="fas fa-fast-backward"></span></div>' + '<div class="icon playPause play"><span class="fas fa-play-circle"></span></div>' + '<div class="icon nextStep"><span class="fas fa-step-forward"></span></div>' + '<div class="icon goToEnd"><span class="fas fa-fast-forward"></span></div>' + '<div class="icon displaySpeedSlider"><span class="fas fa-tachometer-alt"></span></div>' + '</div>' + '<div class="speedSlider">' + '<span class="icon hideSpeedSlider"><span class="fas fa-tachometer-alt"></span></span>' + '<span class="icon speedSlower"><span class="fas fa-walking"></span></span>' + '<input type="range" min="0" max="' + (this.stepDelayMax - this.stepDelayMin) + '" value="0" class="slider speedCursor"/>' + '<span class="icon speedFaster"><span class="fas fa-running"></span></span>' + '</div>' + '</div>'; $('#task').find('.speedControls').remove(); // place speed controls depending on layout // speed controls in taskToolbar on mobiles // in intro on portrait tablets // in introGrid on other layouts (landscape tablets and desktop) $('#mode-player').append(speedControls); $('#introGrid').append(speedControls); $('.speedCursor').on('input change', function(e) { self.refreshStepDelay(); }); $('.speedSlower').click(function() { var el = $('.speedCursor'), maxVal = parseInt(el.attr('max'), 10), delta = Math.floor(maxVal / 10), newVal = parseInt(el.val(), 10) - delta; el.val(Math.max(newVal, 0)); self.refreshStepDelay(); }); $('.speedFaster').click(function() { var el = $('.speedCursor'), maxVal = parseInt(el.attr('max'), 10), delta = Math.floor(maxVal / 10), newVal = parseInt(el.val(), 10) + delta; el.val(Math.min(newVal, maxVal)); self.refreshStepDelay(); }); $('.playerControls .backToFirst').click(function() { task.displayedSubTask.stop(); // task.displayedSubTask.play(); // self.setPlayPause(true); }); $('.playerControls .playPause').click(function(e) { if($(this).hasClass('play')) { self.refreshStepDelay(); task.displayedSubTask.play(); self.setPlayPause(true); } else { task.displayedSubTask.pause(); self.setPlayPause(false); } }) $('.playerControls .nextStep').click(function() { self.setPlayPause(false); task.displayedSubTask.step(); }); $('.playerControls .goToEnd').click(function() { task.displayedSubTask.setStepDelay(0); task.displayedSubTask.play(); self.setPlayPause(false); }); $('.playerControls .displaySpeedSlider').click(function() { $('#mode-player').addClass('displaySpeedSlider'); }); $('.speedSlider .hideSpeedSlider').click(function() { $('#mode-player').removeClass('displaySpeedSlider'); }); }, setPlayPause: function(isPlaying) { if(isPlaying) { $('.playerControls .playPause').html('<span class="fas fa-pause-circle"></span>'); $('.playerControls .playPause').removeClass('play').addClass('pause'); } else { $('.playerControls .playPause').html('<span class="fas fa-play-circle"></span>'); $('.playerControls .playPause').removeClass('pause').addClass('play'); } }, initTestSelector: function (nbTestCases) { var self = this; // Create the DOM for the tests display this.nbTestCases = nbTestCases; var testTabs = '<div class="tabs">'; for(var iTest=0; iTest<this.nbTestCases; iTest++) { if(this.nbTestCases > 1) { testTabs += '' + '<div id="testTab'+iTest+'" class="testTab" onclick="task.displayedSubTask.changeTestTo('+iTest+')">' + '<span class="testTitle"></span>' + '</div>'; } } testTabs += "</div>"; $('#testSelector').html(testTabs); this.updateTestSelector(0); this.resetTestScores(); this.initPlaybackControls(); }, updateTestScores: function (testScores) { // Display test results for(var iTest=0; iTest<testScores.length; iTest++) { if(!testScores[iTest]) { continue; } if(testScores[iTest].evaluating) { var icon = '<span class="testResultIcon testEvaluating fas fa-spinner fa-spin" title="'+this.strings.evaluatingAnswer+'"></span>'; } else if(testScores[iTest].successRate >= 1) { var icon = '\ <span class="testResultIcon testSuccess" title="'+this.strings.correctAnswer+'">\ <span class="fas fa-check"></span>\ </span>'; } else if(testScores[iTest].successRate > 0) { var icon = '\ <span class="testResultIcon testPartial" title="'+this.strings.partialAnswer+'">\ <span class="fas fa-times"></span>\ </span>'; } else { var icon = '\ <span class="testResultIcon testFailure" title="'+this.strings.wrongAnswer+'">\ <span class="fas fa-times"></span>\ </span>'; } $('#testTab'+iTest+' .testTitle').html(icon+' Test '+(iTest+1)); } }, resetTestScores: function () { // Reset test results display for(var iTest=0; iTest<this.nbTestCases; iTest++) { $('#testTab'+iTest+' .testTitle').html('<span class="testResultIcon">&nbsp;</span> Test '+(iTest+1)); } }, updateTestSelector: function (newCurTest) { $("#testSelector .testTab").removeClass('currentTest'); $("#testTab"+newCurTest).addClass('currentTest'); $("#task").append($('#messages')); //$("#testTab"+newCurTest+" .panel-body").prepend($('#grid')).append($('#messages')).show(); }, displayHelpBtn: function() { var helpBtn = '<button type="button" class="displayHelpBtn" onclick="conceptViewer.show()">\ <span class="fas fa-question"></span></button>'; return helpBtn; }, createModeTaskToolbar: function() { if($('#taskToolbar').length) { return; } var displayHelpBtn = this.hasHelp ? this.displayHelpBtn() : ''; var self = this; $("#task").append('' + '<div id="taskToolbar">' + '<div id="modeSelector">' + '<div id="mode-instructions" class="mode">' + '<span><span class="fas fa-file-alt"></span><span class="label ToTranslate">Énoncé</span></span>' + '</div>' + '<div id="mode-editor" class="mode">' + '<span><span class="fas fa-pencil-alt"></span>' + '<span class="label ToTranslate">Éditeur</span></span>' + displayHelpBtn + '</div>' + '<div id="mode-player" class="mode">' + '<span class="fas fa-play"></span>' + '</div>' + '</div>' + '</div>'); $('#modeSelector div').click(function() { self.selectMode($(this).attr('id')); self.onResize(); }) }, selectMode: function(mode) { if(mode === this.curMode) return; $('#modeSelector').children('div').removeClass('active'); $('#modeSelector #' + mode).addClass('active'); $('#task').removeClass(this.curMode).addClass(mode); $('#mode-player').removeClass('displaySpeedSlider'); // there should be a better way to achieve this /*if(mode == 'mode-instructions') { $('#taskIntro .short').hide(); $('#taskIntro .long').show(); } if(mode == 'mode-player') { $('#taskIntro .short').show(); $('#taskIntro .long').hide(); }*/ this.curMode = mode; this.onResize(); }, setupTaskIntro: function(level) { var self = this; if (! this.taskIntroContent.length ) { this.taskIntroContent = $('#taskIntro').html(); } var hasLong = $('#taskIntro').find('.long').length; if (hasLong) { $('#taskIntro').addClass('hasLongIntro'); // if long version of introduction exists, append its content to #blocklyLibContent // with proper title and close button // add titles // add display long version button var introLong = '' + '<div id="taskIntroLong" style="display:none;" class="panel">' + '<div class="panel-heading">'+ '<h2 class="sectionTitle"><i class="fas fa-search-plus icon"></i>Détail de la mission</h2>' + '<button type="button" class="closeLongIntro exit"><i class="fas fa-times"></i></button>' + '</div><div class="panel-body">' + this.taskIntroContent + '</div>' + '<div>'; $('#blocklyLibContent').append(introLong); $('#taskIntroLong .closeLongIntro').click(function(e) { self.toggleLongIntro(false); }); if (! $('#taskIntro .sectionTitle').length) { var renderTaskIntro = '' + '<h2 class="sectionTitle longIntroTitle">' + '<span class="fas fa-book icon"></span>Énoncé' + '</h2>' + '<h2 class="sectionTitle shortIntroTitle">' + '<span class="fas fa-book icon"></span>Votre mission' + '</h2>' + this.taskIntroContent + '<button type="button" class="showLongIntro"></button>'; $('#taskIntro').html(renderTaskIntro); $('#taskIntro .showLongIntro').click(function(e) { self.toggleLongIntro(); }); } self.toggleLongIntro(false); } else { if (! $('#taskIntro .sectionTitle').length) { $('#taskIntro').prepend('' + '<h2 class="sectionTitle longIntroTitle">' + '<span class="fas fa-book icon"></span>Énoncé' + '</h2>'); } } if(level) { for(var otherLevel in displayHelper.levelsRanks) { $('.' + otherLevel).hide(); } $('.' + level).show(); } }, toggleLongIntro: function(forceNewState) { if(forceNewState === false || this.longIntroShown) { $('#taskIntroLong').removeClass('displayIntroLong'); $('.showLongIntro').html('<span class="fas fa-plus-circle icon"></span>Plus de détails</button>'); this.longIntroShown = false; } else { $('#taskIntroLong').addClass('displayIntroLong'); $('.showLongIntro').html('<span class="fas fa-minus-circle icon"></span>Masquer les détails</button>'); this.longIntroShown = true; } }, unloadLevel: function() { // Called when level is unloaded this.resetTestScores(); if(this.curMode == 'mode-editor') { // Don't stay in editor mode as it can cause task display issues this.selectMode('mode-instructions'); } }, onResize: function(e) { // 100% and 100vh work erratically on some mobile browsers (Safari on // iOS) because of the toolbar var browserHeight = document.documentElement.clientHeight; $('body').css('height', browserHeight); var blocklyArea = document.getElementById('blocklyContainer'); if(!blocklyArea) { return; } var blocklyDiv = document.getElementById('blocklyDiv'); var toolbarDiv = document.getElementById('taskToolbar'); var heightBeforeToolbar = toolbarDiv ? toolbarDiv.getBoundingClientRect().top - blocklyArea.getBoundingClientRect().top : Infinity; var heightBeforeWindow = browserHeight - blocklyArea.getBoundingClientRect().top - 10; if($('#taskToolbar').is(':visible') && window.innerHeight < window.innerWidth) { blocklyDiv.style.height = Math.floor(Math.min(heightBeforeToolbar, heightBeforeWindow)) + 'px'; } else { blocklyDiv.style.height = Math.floor(heightBeforeWindow) + 'px'; } if($('#miniPlatformHeader').length) { $('#task').css('height', (browserHeight - 40) + 'px'); } else { $('#task').css('height', ''); } Blockly.svgResize(window.blocklyWorkspace); task.displayedSubTask.updateScale(); }, checkHeight: function() { var browserHeight = document.documentElement.clientHeight; if(this.lastHeight !== null && this.lastHeight != browserHeight) { this.onResize(); } this.lastHeight = browserHeight; }, displayError: function(message) { $('.errorMessage').remove(); if(!message) return; var html = '<div class="errorMessage">' + '<button type="button" class="btn close">'+ '<span class="fas fa-times"></span>'+ '</button>' + '<div class="messageWrapper">' + '<span class="icon fas fa-bell"></span>' + '<p class="message">' + message + '</p>' + '</div>' + '</div>'; $("#taskToolbar").append($(html)); $("#introGrid .speedControls").append($(html)); $(".errorMessage").show(); $(".errorMessage").click(function(e) { $(e.currentTarget).hide(); }); }, wrapIntroAndGrid: function() { if ($('#introGrid').length) { return; } $("#taskIntro, #gridContainer").wrapAll("<div id='introGrid'></div>"); }, checkFonts: function() { // Check if local fonts loaded properly, else use a CDN // (issue mostly happens when opening a task locally in Firefox) if(!document.fonts) { return; } document.fonts.ready.then(function() { // iOS will always return true to document.fonts.check var iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)); if(iOS || !document.fonts.check('12px "Titillium Web"')) { if(!iOS && window.modulesPath) { // Load fonts from CSS files with embedded fonts if(window.embeddedFontsAdded) { return; } $('head').append('' + '<link rel="stylesheet" href="' + window.modulesPath + '/fonts/embed-titilliumweb.css">' + '<link rel="stylesheet" href="' + window.modulesPath + '/fonts/embed-fontawesome.css">' ); window.embeddedFontsAdded = true; } else { // Load fonts from CDN // (especially for iOS on which the embed doesn't work) $('head').append('' + '<link href="https://fonts.googleapis.com/css?family=Titillium+Web:300,400,700" rel="stylesheet">' + '<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">' ); } } }); } }; $(document).ready(function() { $('head').append('\ <link rel="stylesheet"\ href="../../modules/fonts/fontAwesome/css/all.css">'); var taskTitleTarget = $("#miniPlatformHeader table td").first(); if(taskTitleTarget.length) { // Put title in miniPlatformHeader $("#task h1").appendTo(taskTitleTarget); } else { // Remove title, the platform displays it $("#task h1").remove(); } quickAlgoInterface.selectMode('mode-instructions'); window.addEventListener('resize', quickAlgoInterface.onResize, false); // Set up task calls if(window.task) { // Add autoHeight = true to metadata sent back var beaverGetMetaData = window.task.getMetaData; window.task.getMetaData = function(callback) { beaverGetMetaData(function(res) { res.autoHeight = true; callback(res); }); } // If platform still calls getHeight despite autoHeight set to true, // send back a fixed height of 720px to avoid infinite expansion window.task.getHeight = function(callback) { callback(720); } } });
pemFioi/quickAlgo/interface-mobileFirst.js
/* interface: Main interface for quickAlgo, common to all languages. */ var quickAlgoInterface = { strings: {}, nbTestCases: 0, delayFactory: new DelayFactory(), curMode: null, fullscreen: false, lastHeight: null, checkHeightInterval: null, hasHelp: false, editorMenuIsOpen: false, longIntroShown: false, taskIntroContent: '', enterFullscreen: function() { var el = document.documentElement; if(el.requestFullscreen) { el.requestFullscreen(); } else if(el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if(el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if(el.msRequestFullscreen) { el.msRequestFullscreen(); } this.fullscreen = true; this.updateFullscreenElements(); }, exitFullscreen: function() { var el = document; if(el.exitFullscreen) { el.exitFullscreen(); } else if(el.mozCancelFullScreen) { el.mozCancelFullScreen(); } else if(el.webkitExitFullscreen) { el.webkitExitFullscreen(); } else if(el.msExitFullscreen) { el.msExitFullscreen(); } this.fullscreen = false; this.updateFullscreenElements(); }, toggleFullscreen: function() { this.fullscreen = !this.fullscreen; if(this.fullscreen) { this.enterFullscreen(); } else { this.exitFullscreen(); } var that = this; setTimeout(function() { that.onResize(); }, 500); }, updateFullscreenState: function() { if(document.fullscreenElement || document.msFullscreenElement || document.mozFullScreen || document.webkitIsFullScreen) { this.fullscreen = true; } else { this.fullscreen = false; } this.updateFullscreenElements(); }, updateFullscreenElements: function() { if(this.fullscreen) { $('body').addClass('fullscreen'); $('#fullscreenButton').html('<i class="fas fa-compress"></i>'); } else { $('body').removeClass('fullscreen'); $('#fullscreenButton').html('<i class="fas fa-expand"></i>'); } }, registerFullscreenEvents: function() { if(this.fullscreenEvents) { return; } document.addEventListener("fullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("webkitfullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("mozfullscreenchange", this.updateFullscreenState.bind(this)); document.addEventListener("MSFullscreenChange", this.updateFullscreenState.bind(this)); this.fullscreenEvents = true; }, loadInterface: function(context, level) { ////TODO: function is called twice // Load quickAlgo interface into the DOM var self = this; this.context = context; this.strings = window.languageStrings; var gridHtml = ""; gridHtml += "<div id='gridButtonsBefore'></div>"; gridHtml += "<div id='grid'></div>"; gridHtml += "<div id='gridButtonsAfter'></div>"; $("#gridContainer").html(gridHtml); var displayHelpBtn = this.hasHelp ? this.displayHelpBtn() : ''; $("#blocklyLibContent").html( "<div id='editorBar'>" + "<div id='capacity'></div>" + "<div class='buttons'>" + "<button type='button' id='fullscreenButton'><span class='fas fa-expand'></span></button>" + displayHelpBtn + "</div>" + "</div>" + "<div id='languageInterface'></div>" ); $('#fullscreenButton').click(function() { self.toggleFullscreen(); }); // TODO :: something cleaner (add when editorMenu is opened, remove when closed?) $('#editorMenu div[rel=example]').click(function(e) { self.closeEditorMenu(); task.displayedSubTask.loadExample() }); $('#editorMenu div[rel=save]').click(function(e) { self.closeEditorMenu(); task.displayedSubTask.blocklyHelper.saveProgram(); }); $('#editorMenu div[rel=restart]').click(function(e) { self.closeEditorMenu(); displayHelper.restartAll(); }); $('#editorMenu div[rel=best-answer]').click(function(e) { self.closeEditorMenu(); displayHelper.retrieveAnswer(); }); // Buttons from buttonsAndMessages var addTaskHTML = '<div id="displayHelperAnswering" class="contentCentered" style="padding: 1px;">'; var placementNames = ['graderMessage', 'validate', 'saved']; for (var iPlacement = 0; iPlacement < placementNames.length; iPlacement++) { var placement = 'displayHelper_' + placementNames[iPlacement]; if ($('#' + placement).length === 0) { addTaskHTML += '<div id="' + placement + '"></div>'; } } addTaskHTML += '</div>'; /* if(!$('#displayHelper_cancel').length) { $('body').append($('<div class="contentCentered" style="margin-top: 15px;"><div id="displayHelper_cancel"></div></div>')); } */ var scaleControl = ''; if(context.display && context.infos.buttonScaleDrawing) { var scaleControl = '<div class="scaleDrawingControl">' + '<label for="scaleDrawing"><input id="scaleDrawing" type="checkbox">' + this.strings.scaleDrawing + '</label>' + '</div>'; } var gridButtonsAfter = scaleControl + "<div id='testSelector'></div>" //+ "<button type='button' id='submitBtn' class='btn btn-primary' onclick='task.displayedSubTask.submit()'>" //+ this.strings.submitProgram //+ "</button><br/>" //+ "<div id='messages'><span id='tooltip'></span><span id='errors'></span></div>" + addTaskHTML; $("#gridButtonsAfter").html(gridButtonsAfter); $('#scaleDrawing').change(this.onScaleDrawingChange.bind(this)); this.createModeTaskToolbar(); this.createEditorMenu(); this.setupTaskIntro(level); this.wrapIntroAndGrid(); this.checkFonts(); this.registerFullscreenEvents(); if(!this.checkHeightInterval) { this.checkHeightInterval = setInterval(this.checkHeight.bind(this), 1000); } var that = this; setTimeout(function() { that.onResize(); }, 0); }, createEditorMenu: function() { var self = this; if(!$('#openEditorMenu').length) { $("#tabsContainer").append("<div id='openEditorMenu' class='icon'><span class='fas fa-bars'></span></div>"); } if($('#editorMenu').length) { return; } $("body").append('' + "<div id='editorMenu' style='display: none;'>" + "<div class='editorMenuHeader'>" + "<div id='closeEditorMenu'><span class='fas fa-times'></span></div>" + "<div>Menu</div>" + "</div>" + "<div class='editorActions'>" + "<div rel='example' class='item'><span class='fas fa-paste'></span> " + this.strings.loadExample + "</div>" + "<div rel='restart' class='item'><span class='fas fa-trash-alt'></span> " + this.strings.restart + "</div>" + "<div rel='save' class='item'><span class='fas fa-download'></span> " + this.strings.saveProgram + "</div>" + "<div rel='best-answer' class='item'><span class='fas fa-trophy'></span> " + this.strings.loadBestAnswer+ "</div>" + "<div rel='load' class='item'>" + "<input type='file' id='task-upload-file' " + "onchange='\ task.displayedSubTask.blocklyHelper.handleFiles(this.files);\ resetFormElement($(this));\ $(\"#editorMenu\").hide();'>" + "<span class='fas fa-upload'></span> " + this.strings.reloadProgram + "</div>" + "</div>" + "<span id='saveUrl'></span>" + "</div>" ); $('#openEditorMenu').click(function() { self.editorMenuIsOpen ? self.closeEditorMenu() : self.openEditorMenu(); }); $("#closeEditorMenu").click(function() { self.closeEditorMenu(); }); }, openEditorMenu: function() { this.editorMenuIsOpen = true; var menuWidth = $('#editorMenu').css('width'); $('#editorMenu').css('display','block'); $('body').animate({left: '-' + menuWidth}, 500); }, closeEditorMenu: function() { this.editorMenuIsOpen = false; $('body').animate({left: '0'}, 500, function() { $('#editorMenu').css('display','none') }); }, setOptions: function(opt) { // Load options from the task $('#editorMenu div[rel=example]').toggle(opt.hasExample); $('#editorMenu div[rel=save]').toggle(!opt.hideSaveOrLoad); $('#editorMenu div[rel=load]').toggle(!opt.hideSaveOrLoad); $('#editorMenu div[rel=best-answer]').toggle(!opt.hideLoadBestAnswer); if(opt.conceptViewer) { conceptViewer.load(opt.conceptViewerLang); this.hasHelp = true; } else { this.hasHelp = false; } }, devMode: function() { $('#editorMenu .item').show(); }, onScaleDrawingChange: function(e) { var scaled = $(e.target).prop('checked'); $("#gridContainer").toggleClass('gridContainerScaled', scaled); $("#blocklyLibContent").toggleClass('blocklyLibContentScaled', scaled); this.context.setScale(scaled ? 2 : 1); }, blinkRemaining: function(times, red) { var capacity = $('#capacity'); if(times % 2 == 0) { capacity.removeClass('capacityRed'); } else { capacity.addClass('capacityRed'); } if(times > (red ? 1 : 0)) { var that = this; this.delayFactory.destroy('blinkRemaining'); this.delayFactory.createTimeout('blinkRemaining', function() { that.blinkRemaining(times - 1, red); }, 200); } }, stepDelayMin: 25, stepDelayMax: 250, refreshStepDelay: function() { var v = parseInt($('.speedCursor').val(), 10), delay = this.stepDelayMin + this.stepDelayMax - v; task.displayedSubTask.setStepDelay(delay); }, initPlaybackControls: function() { var self = this; var speedControls = '<div class="speedControls">' + '<div class="playerControls">' + '<div class="icon backToFirst"><span class="fas fa-fast-backward"></span></div>' + '<div class="icon playPause play"><span class="fas fa-play-circle"></span></div>' + '<div class="icon nextStep"><span class="fas fa-step-forward"></span></div>' + '<div class="icon goToEnd"><span class="fas fa-fast-forward"></span></div>' + '<div class="icon displaySpeedSlider"><span class="fas fa-tachometer-alt"></span></div>' + '</div>' + '<div class="speedSlider">' + '<span class="icon hideSpeedSlider"><span class="fas fa-tachometer-alt"></span></span>' + '<span class="icon speedSlower"><span class="fas fa-walking"></span></span>' + '<input type="range" min="0" max="' + (this.stepDelayMax - this.stepDelayMin) + '" value="0" class="slider speedCursor"/>' + '<span class="icon speedFaster"><span class="fas fa-running"></span></span>' + '</div>' + '</div>'; $('#task').find('.speedControls').remove(); // place speed controls depending on layout // speed controls in taskToolbar on mobiles // in intro on portrait tablets // in introGrid on other layouts (landscape tablets and desktop) $('#mode-player').append(speedControls); $('#introGrid').append(speedControls); $('.speedCursor').on('input change', function(e) { self.refreshStepDelay(); }); $('.speedSlower').click(function() { var el = $('.speedCursor'), maxVal = parseInt(el.attr('max'), 10), delta = Math.floor(maxVal / 10), newVal = parseInt(el.val(), 10) - delta; el.val(Math.max(newVal, 0)); self.refreshStepDelay(); }); $('.speedFaster').click(function() { var el = $('.speedCursor'), maxVal = parseInt(el.attr('max'), 10), delta = Math.floor(maxVal / 10), newVal = parseInt(el.val(), 10) + delta; el.val(Math.min(newVal, maxVal)); self.refreshStepDelay(); }); $('.playerControls .backToFirst').click(function() { task.displayedSubTask.stop(); // task.displayedSubTask.play(); // self.setPlayPause(true); }); $('.playerControls .playPause').click(function(e) { if($(this).hasClass('play')) { self.refreshStepDelay(); task.displayedSubTask.play(); self.setPlayPause(true); } else { task.displayedSubTask.pause(); self.setPlayPause(false); } }) $('.playerControls .nextStep').click(function() { self.setPlayPause(false); task.displayedSubTask.step(); }); $('.playerControls .goToEnd').click(function() { task.displayedSubTask.setStepDelay(0); task.displayedSubTask.play(); self.setPlayPause(false); }); $('.playerControls .displaySpeedSlider').click(function() { $('#mode-player').addClass('displaySpeedSlider'); }); $('.speedSlider .hideSpeedSlider').click(function() { $('#mode-player').removeClass('displaySpeedSlider'); }); }, setPlayPause: function(isPlaying) { if(isPlaying) { $('.playerControls .playPause').html('<span class="fas fa-pause-circle"></span>'); $('.playerControls .playPause').removeClass('play').addClass('pause'); } else { $('.playerControls .playPause').html('<span class="fas fa-play-circle"></span>'); $('.playerControls .playPause').removeClass('pause').addClass('play'); } }, initTestSelector: function (nbTestCases) { var self = this; // Create the DOM for the tests display this.nbTestCases = nbTestCases; var testTabs = '<div class="tabs">'; for(var iTest=0; iTest<this.nbTestCases; iTest++) { if(this.nbTestCases > 1) { testTabs += '' + '<div id="testTab'+iTest+'" class="testTab" onclick="task.displayedSubTask.changeTestTo('+iTest+')">' + '<span class="testTitle"></span>' + '</div>'; } } testTabs += "</div>"; $('#testSelector').html(testTabs); this.updateTestSelector(0); this.resetTestScores(); this.initPlaybackControls(); }, updateTestScores: function (testScores) { // Display test results for(var iTest=0; iTest<testScores.length; iTest++) { if(!testScores[iTest]) { continue; } if(testScores[iTest].evaluating) { var icon = '<span class="testResultIcon testEvaluating fas fa-spinner fa-spin" title="'+this.strings.evaluatingAnswer+'"></span>'; } else if(testScores[iTest].successRate >= 1) { var icon = '\ <span class="testResultIcon testSuccess" title="'+this.strings.correctAnswer+'">\ <span class="fas fa-check"></span>\ </span>'; } else if(testScores[iTest].successRate > 0) { var icon = '\ <span class="testResultIcon testPartial" title="'+this.strings.partialAnswer+'">\ <span class="fas fa-times"></span>\ </span>'; } else { var icon = '\ <span class="testResultIcon testFailure" title="'+this.strings.wrongAnswer+'">\ <span class="fas fa-times"></span>\ </span>'; } $('#testTab'+iTest+' .testTitle').html(icon+' Test '+(iTest+1)); } }, resetTestScores: function () { // Reset test results display for(var iTest=0; iTest<this.nbTestCases; iTest++) { $('#testTab'+iTest+' .testTitle').html('<span class="testResultIcon">&nbsp;</span> Test '+(iTest+1)); } }, updateTestSelector: function (newCurTest) { $("#testSelector .testTab").removeClass('currentTest'); $("#testTab"+newCurTest).addClass('currentTest'); $("#task").append($('#messages')); //$("#testTab"+newCurTest+" .panel-body").prepend($('#grid')).append($('#messages')).show(); }, displayHelpBtn: function() { var helpBtn = '<button type="button" class="displayHelpBtn" onclick="conceptViewer.show()">\ <span class="fas fa-question"></span></button>'; return helpBtn; }, createModeTaskToolbar: function() { if($('#taskToolbar').length) { return; } var displayHelpBtn = this.hasHelp ? this.displayHelpBtn() : ''; var self = this; $("#task").append('' + '<div id="taskToolbar">' + '<div id="modeSelector">' + '<div id="mode-instructions" class="mode">' + '<span><span class="fas fa-file-alt"></span><span class="label ToTranslate">Énoncé</span></span>' + '</div>' + '<div id="mode-editor" class="mode">' + '<span><span class="fas fa-pencil-alt"></span>' + '<span class="label ToTranslate">Éditeur</span></span>' + displayHelpBtn + '</div>' + '<div id="mode-player" class="mode">' + '<span class="fas fa-play"></span>' + '</div>' + '</div>' + '</div>'); $('#modeSelector div').click(function() { self.selectMode($(this).attr('id')); self.onResize(); }) }, selectMode: function(mode) { if(mode === this.curMode) return; $('#modeSelector').children('div').removeClass('active'); $('#modeSelector #' + mode).addClass('active'); $('#task').removeClass(this.curMode).addClass(mode); $('#mode-player').removeClass('displaySpeedSlider'); // there should be a better way to achieve this /*if(mode == 'mode-instructions') { $('#taskIntro .short').hide(); $('#taskIntro .long').show(); } if(mode == 'mode-player') { $('#taskIntro .short').show(); $('#taskIntro .long').hide(); }*/ this.curMode = mode; this.onResize(); }, setupTaskIntro: function(level) { var self = this; if (! this.taskIntroContent.length ) { this.taskIntroContent = $('#taskIntro').html(); } var hasLong = $('#taskIntro').find('.long').length; if (hasLong) { $('#taskIntro').addClass('hasLongIntro'); // if long version of introduction exists, append its content to #blocklyLibContent // with proper title and close button // add titles // add display long version button var introLong = '' + '<div id="taskIntroLong" style="display:none;" class="panel">' + '<div class="panel-heading">'+ '<h2 class="sectionTitle"><i class="fas fa-search-plus icon"></i>Détail de la mission</h2>' + '<button type="button" class="closeLongIntro exit"><i class="fas fa-times"></i></button>' + '</div><div class="panel-body">' + this.taskIntroContent + '</div>' + '<div>'; $('#blocklyLibContent').append(introLong); $('#taskIntroLong .closeLongIntro').click(function(e) { self.toggleLongIntro(false); }); if (! $('#taskIntro .sectionTitle').length) { var renderTaskIntro = '' + '<h2 class="sectionTitle longIntroTitle">' + '<span class="fas fa-book icon"></span>Énoncé' + '</h2>' + '<h2 class="sectionTitle shortIntroTitle">' + '<span class="fas fa-book icon"></span>Votre mission' + '</h2>' + this.taskIntroContent + '<button type="button" class="showLongIntro"></button>'; $('#taskIntro').html(renderTaskIntro); $('#taskIntro .showLongIntro').click(function(e) { self.toggleLongIntro(); }); } self.toggleLongIntro(false); } else { if (! $('#taskIntro .sectionTitle').length) { $('#taskIntro').prepend('' + '<h2 class="sectionTitle longIntroTitle">' + '<span class="fas fa-book icon"></span>Énoncé' + '</h2>'); } } if(level) { for(var otherLevel in displayHelper.levelsRanks) { $('.' + otherLevel).hide(); } $('.' + level).show(); } }, toggleLongIntro: function(forceNewState) { if(forceNewState === false || this.longIntroShown) { $('#taskIntroLong').removeClass('displayIntroLong'); $('.showLongIntro').html('<span class="fas fa-plus-circle icon"></span>Plus de détails</button>'); this.longIntroShown = false; } else { $('#taskIntroLong').addClass('displayIntroLong'); $('.showLongIntro').html('<span class="fas fa-minus-circle icon"></span>Masquer les détails</button>'); this.longIntroShown = true; } }, unloadLevel: function() { // Called when level is unloaded this.resetTestScores(); if(this.curMode == 'mode-editor') { // Don't stay in editor mode as it can cause task display issues this.selectMode('mode-instructions'); } }, onResize: function(e) { // 100% and 100vh work erratically on some mobile browsers (Safari on // iOS) because of the toolbar var browserHeight = document.documentElement.clientHeight; $('body').css('height', browserHeight); var blocklyArea = document.getElementById('blocklyContainer'); if(!blocklyArea) { return; } var blocklyDiv = document.getElementById('blocklyDiv'); var toolbarDiv = document.getElementById('taskToolbar'); var heightBeforeToolbar = toolbarDiv ? toolbarDiv.getBoundingClientRect().top - blocklyArea.getBoundingClientRect().top : Infinity; var heightBeforeWindow = browserHeight - blocklyArea.getBoundingClientRect().top - 10; if($('#taskToolbar').is(':visible') && window.innerHeight < window.innerWidth) { blocklyDiv.style.height = Math.floor(Math.min(heightBeforeToolbar, heightBeforeWindow)) + 'px'; } else { blocklyDiv.style.height = Math.floor(heightBeforeWindow) + 'px'; } if($('#miniPlatformHeader').length) { $('#task').css('height', (browserHeight - 40) + 'px'); } else { $('#task').css('height', ''); } Blockly.svgResize(window.blocklyWorkspace); task.displayedSubTask.updateScale(); }, checkHeight: function() { var browserHeight = document.documentElement.clientHeight; if(this.lastHeight !== null && this.lastHeight != browserHeight) { this.onResize(); } this.lastHeight = browserHeight; }, displayError: function(message) { $('.errorMessage').remove(); if(!message) return; var html = '<div class="errorMessage">' + '<button type="button" class="btn close">'+ '<span class="fas fa-times"></span>'+ '</button>' + '<div class="messageWrapper">' + '<span class="icon fas fa-bell"></span>' + '<p class="message">' + message + '</p>' + '</div>' + '</div>'; $("#taskToolbar").append($(html)); $("#introGrid .speedControls").append($(html)); $(".errorMessage").show(); $(".errorMessage").click(function(e) { $(e.currentTarget).hide(); }); }, wrapIntroAndGrid: function() { if ($('#introGrid').length) { return; } $("#taskIntro, #gridContainer").wrapAll("<div id='introGrid'></div>"); }, checkFonts: function() { // Check if local fonts loaded properly, else use a CDN // (issue mostly happens when opening a task locally in Firefox) if(!document.fonts) { return; } document.fonts.ready.then(function() { // iOS will always return true to document.fonts.check var iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)); if(iOS || !document.fonts.check('12px "Titillium Web"')) { if(!iOS && window.modulesPath) { // Load fonts from CSS files with embedded fonts if(window.embeddedFontsAdded) { return; } $('head').append('' + '<link rel="stylesheet" href="' + window.modulesPath + '/fonts/embed-titilliumweb.css">' + '<link rel="stylesheet" href="' + window.modulesPath + '/fonts/embed-fontawesome.css">' ); window.embeddedFontsAdded = true; } else { // Load fonts from CDN // (especially for iOS on which the embed doesn't work) $('head').append('' + '<link href="https://fonts.googleapis.com/css?family=Titillium+Web:300,400,700" rel="stylesheet">' + '<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">' ); } } }); } }; $(document).ready(function() { $('head').append('\ <link rel="stylesheet"\ href="../../modules/fonts/fontAwesome/css/all.css">'); var taskTitleTarget = $("#miniPlatformHeader table td").first(); if(taskTitleTarget.length) { // Put title in miniPlatformHeader $("#task h1").appendTo(taskTitleTarget); } else { // Remove title, the platform displays it $("#task h1").remove(); } quickAlgoInterface.selectMode('mode-instructions'); window.addEventListener('resize', quickAlgoInterface.onResize, false); // Set up task calls if(window.task) { // Add autoHeight = true to metadata sent back var beaverGetMetaData = window.task.getMetaData; window.task.getMetaData = function(callback) { beaverGetMetaData(function(res) { res.autoHeight = true; callback(res); }); } // If platform still calls getHeight despite autoHeight set to true, // send back a fixed height of 720px to avoid infinite expansion window.task.getHeight = function(callback) { callback(720); } } });
quickAlgo-mobileFirst: Disable fullscreen on iPad Safari on iPad will resize automatically the iframes, unless we have the attribute scrolling="no" set directly in the HTML (adding through JavaScript doesn't seem to work). Hopefully, a solution will be found...
pemFioi/quickAlgo/interface-mobileFirst.js
quickAlgo-mobileFirst: Disable fullscreen on iPad
<ide><path>emFioi/quickAlgo/interface-mobileFirst.js <ide> "<div id='languageInterface'></div>" <ide> ); <ide> <del> <del> $('#fullscreenButton').click(function() { <del> self.toggleFullscreen(); <del> }); <add> var iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)); <add> if(iOS) { <add> $('#fullscreenButton').remove(); <add> } else { <add> $('#fullscreenButton').click(function() { <add> self.toggleFullscreen(); <add> }); <add> } <ide> <ide> <ide> // TODO :: something cleaner (add when editorMenu is opened, remove when closed?)
Java
apache-2.0
33b6b40eb1d1eca5d1c16eb2e60a911e59ccc2e5
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import javax.jdo.JDOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.dao.DataAccessException; /** * Base class for JdoTemplate and JdoInterceptor, defining common * properties like PersistenceManagerFactory and flushing behavior. * * <p>Note: With JDO, modifications to persistent objects are just possible * within a transaction (in contrast to Hibernate). Therefore, eager flushing * will just get applied when in a transaction. Furthermore, there is no * explicit notion of flushing never, as this would not imply a performance * gain due to JDO's field interception mechanism that doesn't involve * the overhead of snapshot comparisons. * * <p>Eager flushing is just available for specific JDO providers. * You need to a corresponding JdoDialect to make eager flushing work. * * <p>Not intended to be used directly. See JdoTemplate and JdoInterceptor. * * @author Juergen Hoeller * @since 02.11.2003 * @see JdoTemplate * @see JdoInterceptor * @see #setFlushEager */ public abstract class JdoAccessor implements InitializingBean { protected final Log logger = LogFactory.getLog(getClass()); private PersistenceManagerFactory persistenceManagerFactory; private JdoDialect jdoDialect; private boolean flushEager = false; /** * Set the JDO PersistenceManagerFactory that should be used to create * PersistenceManagers. */ public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) { this.persistenceManagerFactory = pmf; } /** * Return the JDO PersistenceManagerFactory that should be used to create * PersistenceManagers. */ public PersistenceManagerFactory getPersistenceManagerFactory() { return persistenceManagerFactory; } /** * Set the JDO dialect to use for this accessor. * <p>The dialect object can be used to retrieve the underlying JDBC * connection and to eagerly flush changes to the database. */ public void setJdoDialect(JdoDialect jdoDialect) { this.jdoDialect = jdoDialect; } /** * Return the JDO dialect to use for this accessor. * <p>Creates a default one for the specified PersistenceManagerFactory if none set. */ public JdoDialect getJdoDialect() { if (this.jdoDialect == null) { this.jdoDialect = new DefaultJdoDialect(); } return this.jdoDialect; } /** * Set if this accessor should flush changes to the database eagerly. * <p>Eager flushing leads to immediate synchronization with the database, * even if in a transaction. This causes inconsistencies to show up and throw * a respective exception immediately, and JDBC access code that participates * in the same transaction will see the changes as the database is already * aware of them then. But the drawbacks are: * <ul> * <li>additional communication roundtrips with the database, instead of a * single batch at transaction commit; * <li>the fact that an actual database rollback is needed if the JDO * transaction rolls back (due to already submitted SQL statements). * </ul> */ public void setFlushEager(boolean flushEager) { this.flushEager = flushEager; } /** * Return if this accessor should flush changes to the database eagerly. */ public boolean isFlushEager() { return flushEager; } /** * Eagerly initialize the JDO dialect, creating a default one * for the specified PersistenceManagerFactory if none set. */ public void afterPropertiesSet() { if (getPersistenceManagerFactory() == null) { throw new IllegalArgumentException("persistenceManagerFactory is required"); } getJdoDialect(); } /** * Flush the given JDO persistence manager if necessary. * @param pm the current JDO PersistenceManager * @param existingTransaction if executing within an existing transaction * (within an existing JDO PersistenceManager that won't be closed immediately) * @throws JDOException in case of JDO flushing errors */ protected void flushIfNecessary(PersistenceManager pm, boolean existingTransaction) throws JDOException { if (isFlushEager()) { logger.debug("Eagerly flushing JDO persistence manager"); getJdoDialect().flush(pm); } } /** * Convert the given JDOException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. * <p>Default implementation delegates to the JdoDialect. * May be overridden in subclasses. * @param ex JDOException that occured * @return the corresponding DataAccessException instance * @see JdoDialect#translateException */ public DataAccessException convertJdoAccessException(JDOException ex) { return getJdoDialect().translateException(ex); } }
src/org/springframework/orm/jdo/JdoAccessor.java
/* * Copyright 2002-2006 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jdo; import javax.jdo.JDOException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.dao.DataAccessException; /** * Base class for JdoTemplate and JdoInterceptor, defining common * properties like PersistenceManagerFactory and flushing behavior. * * <p>Note: With JDO, modifications to persistent objects are just possible * within a transaction (in contrast to Hibernate). Therefore, eager flushing * will just get applied when in a transaction. Furthermore, there is no * explicit notion of flushing never, as this would not imply a performance * gain due to JDO's field interception mechanism that doesn't involve * the overhead of snapshot comparisons. * * <p>Eager flushing is just available for specific JDO providers. * You need to a corresponding JdoDialect to make eager flushing work. * * <p>Not intended to be used directly. See JdoTemplate and JdoInterceptor. * * @author Juergen Hoeller * @since 02.11.2003 * @see JdoTemplate * @see JdoInterceptor * @see #setFlushEager */ public abstract class JdoAccessor implements InitializingBean { protected final Log logger = LogFactory.getLog(getClass()); private PersistenceManagerFactory persistenceManagerFactory; private JdoDialect jdoDialect; private boolean flushEager = false; /** * Set the JDO PersistenceManagerFactory that should be used to create * PersistenceManagers. */ public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) { this.persistenceManagerFactory = pmf; } /** * Return the JDO PersistenceManagerFactory that should be used to create * PersistenceManagers. */ public PersistenceManagerFactory getPersistenceManagerFactory() { return persistenceManagerFactory; } /** * Set the JDO dialect to use for this accessor. * <p>The dialect object can be used to retrieve the underlying JDBC * connection and to eagerly flush changes to the database. */ public void setJdoDialect(JdoDialect jdoDialect) { this.jdoDialect = jdoDialect; } /** * Return the JDO dialect to use for this accessor. * <p>Creates a default one for the specified PersistenceManagerFactory if none set. */ public JdoDialect getJdoDialect() { if (this.jdoDialect == null) { this.jdoDialect = new DefaultJdoDialect(); } return this.jdoDialect; } /** * Set if this accessor should flush changes to the database eagerly. * <p>Eager flushing leads to immediate synchronization with the database, * even if in a transaction. This causes inconsistencies to show up and throw * a respective exception immediately, and JDBC access code that participates * in the same transaction will see the changes as the database is already * aware of them then. But the drawbacks are: * <ul> * <li>additional communication roundtrips with the database, instead of a * single batch at transaction commit; * <li>the fact that an actual database rollback is needed if the JDO * transaction rolls back (due to already submitted SQL statements). * </ul> */ public void setFlushEager(boolean flushEager) { this.flushEager = flushEager; } /** * Return if this accessor should flush changes to the database eagerly. */ public boolean isFlushEager() { return flushEager; } /** * Eagerly initialize the JDO dialect, creating a default one * for the specified PersistenceManagerFactory if none set. */ public void afterPropertiesSet() { if (getPersistenceManagerFactory() == null) { throw new IllegalArgumentException("persistenceManagerFactory is required"); } getJdoDialect(); } /** * Flush the given JDO persistence manager if necessary. * @param pm the current JDO PersistenceManager * @param existingTransaction if executing within an existing transaction * (within an existing JDO PersistenceManager that won't be closed immediately) * @throws JDOException in case of JDO flushing errors */ public void flushIfNecessary(PersistenceManager pm, boolean existingTransaction) throws JDOException { if (isFlushEager()) { logger.debug("Eagerly flushing JDO persistence manager"); getJdoDialect().flush(pm); } } /** * Convert the given JDOException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. * <p>Default implementation delegates to the JdoDialect. * May be overridden in subclasses. * @param ex JDOException that occured * @return the corresponding DataAccessException instance * @see JdoDialect#translateException */ public DataAccessException convertJdoAccessException(JDOException ex) { return getJdoDialect().translateException(ex); } }
reduced visibility of "flushIfNecessary" method from public to protected git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@11472 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
src/org/springframework/orm/jdo/JdoAccessor.java
reduced visibility of "flushIfNecessary" method from public to protected
<ide><path>rc/org/springframework/orm/jdo/JdoAccessor.java <ide> * (within an existing JDO PersistenceManager that won't be closed immediately) <ide> * @throws JDOException in case of JDO flushing errors <ide> */ <del> public void flushIfNecessary(PersistenceManager pm, boolean existingTransaction) throws JDOException { <add> protected void flushIfNecessary(PersistenceManager pm, boolean existingTransaction) throws JDOException { <ide> if (isFlushEager()) { <ide> logger.debug("Eagerly flushing JDO persistence manager"); <ide> getJdoDialect().flush(pm);
Java
apache-2.0
803a3edde8bc7f3ba546ccfe449e16278c954fd8
0
allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.changes; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import git4idea.GitContentRevision; import git4idea.GitRevisionNumber; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.commands.*; import git4idea.history.browser.SHAHash; import git4idea.repo.GitRepository; import git4idea.util.StringScanner; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; import static java.util.Collections.emptySet; /** * Change related utilities */ public class GitChangeUtils { /** * the pattern for committed changelist assumed. */ public static final String COMMITTED_CHANGELIST_FORMAT = "%ct%n%H%n%P%n%an%x20%x3C%ae%x3E%n%cn%x20%x3C%ce%x3E%n%s%n%x03%n%b%n%x03"; private static final Logger LOG = Logger.getInstance(GitChangeUtils.class); /** * A private constructor for utility class */ private GitChangeUtils() { } /** * Parse changes from lines * * @param project the context project * @param vcsRoot the git root * @param thisRevision the current revision * @param parentRevision the parent revision for this change list * @param s the lines to parse * @param changes a list of changes to update * @param ignoreNames a set of names ignored during collection of the changes * @throws VcsException if the input format does not matches expected format */ public static void parseChanges(Project project, VirtualFile vcsRoot, @Nullable GitRevisionNumber thisRevision, GitRevisionNumber parentRevision, String s, Collection<Change> changes, final Set<String> ignoreNames) throws VcsException { StringScanner sc = new StringScanner(s); parseChanges(project, vcsRoot, thisRevision, parentRevision, sc, changes, ignoreNames); if (sc.hasMoreData()) { throw new IllegalStateException("Unknown file status: " + sc.line()); } } public static Collection<String> parseDiffForPaths(final String rootPath, final StringScanner s) throws VcsException { final Collection<String> result = new ArrayList<>(); while (s.hasMoreData()) { if (s.isEol()) { s.nextLine(); continue; } if ("CADUMR".indexOf(s.peek()) == -1) { // exit if there is no next character break; } assert 'M' != s.peek() : "Moves are not yet handled"; String[] tokens = s.line().split("\t"); String path = tokens[tokens.length - 1]; path = rootPath + File.separator + GitUtil.unescapePath(path); path = FileUtil.toSystemDependentName(path); result.add(path); } return result; } /** * Parse changes from lines * * @param project the context project * @param vcsRoot the git root * @param thisRevision the current revision * @param parentRevision the parent revision for this change list * @param s the lines to parse * @param changes a list of changes to update * @param ignoreNames a set of names ignored during collection of the changes * @throws VcsException if the input format does not matches expected format */ private static void parseChanges(Project project, VirtualFile vcsRoot, @Nullable GitRevisionNumber thisRevision, @Nullable GitRevisionNumber parentRevision, StringScanner s, Collection<Change> changes, final Set<String> ignoreNames) throws VcsException { while (s.hasMoreData()) { FileStatus status = null; if (s.isEol()) { s.nextLine(); continue; } if ("CADUMRT".indexOf(s.peek()) == -1) { // exit if there is no next character return; } String[] tokens = s.line().split("\t"); final ContentRevision before; final ContentRevision after; final String path = tokens[tokens.length - 1]; switch (tokens[0].charAt(0)) { case 'C': case 'A': before = null; status = FileStatus.ADDED; after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'U': status = FileStatus.MERGED_WITH_CONFLICTS; case 'M': if (status == null) { status = FileStatus.MODIFIED; } before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'D': status = FileStatus.DELETED; before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = null; break; case 'R': status = FileStatus.MODIFIED; before = GitContentRevision.createRevision(vcsRoot, tokens[1], parentRevision, project, true, true); after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'T': status = FileStatus.MODIFIED; before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = GitContentRevision.createRevisionForTypeChange(project, vcsRoot, path, thisRevision, true); break; default: throw new VcsException("Unknown file status: " + Arrays.asList(tokens)); } if (ignoreNames == null || !ignoreNames.contains(path)) { changes.add(new Change(before, after, status)); } } } /** * Load actual revision number with timestamp basing on a reference: name of a branch or tag, or revision number expression. */ @NotNull public static GitRevisionNumber resolveReference(@NotNull Project project, @NotNull VirtualFile vcsRoot, @NotNull String reference) throws VcsException { GitLineHandler handler = createRefResolveHandler(project, vcsRoot, reference); String output = Git.getInstance().runCommand(handler).getOutputOrThrow(); StringTokenizer stk = new StringTokenizer(output, "\n\r \t", false); if (!stk.hasMoreTokens()) { try { GitLineHandler dh = new GitLineHandler(project, vcsRoot, GitCommand.LOG); dh.addParameters("-1", "HEAD"); dh.setSilent(true); String out = Git.getInstance().runCommand(dh).getOutputOrThrow(); LOG.info("Diagnostic output from 'git log -1 HEAD': [" + out + "]"); dh = createRefResolveHandler(project, vcsRoot, reference); out = Git.getInstance().runCommand(dh).getOutputOrThrow(); LOG.info("Diagnostic output from 'git rev-list -1 --timestamp HEAD': [" + out + "]"); } catch (VcsException e) { LOG.info("Exception while trying to get some diagnostics info", e); } throw new VcsException(String.format("The string '%s' does not represent a revision number. Output: [%s]\n Root: %s", reference, output, vcsRoot)); } Date timestamp = GitUtil.parseTimestampWithNFEReport(stk.nextToken(), handler, output); return new GitRevisionNumber(stk.nextToken(), timestamp); } @NotNull private static GitLineHandler createRefResolveHandler(@NotNull Project project, @NotNull VirtualFile root, @NotNull String reference) { GitLineHandler handler = new GitLineHandler(project, root, GitCommand.REV_LIST); handler.addParameters("--timestamp", "--max-count=1", reference); handler.endOptions(); handler.setSilent(true); return handler; } /** * Check if the exception means that HEAD is missing for the current repository. * * @param e the exception to examine * @return true if the head is missing */ public static boolean isHeadMissing(final VcsException e) { @NonNls final String errorText = "fatal: bad revision 'HEAD'\n"; return e.getMessage().equals(errorText); } /** * Get list of changes. Because native Git non-linear revision tree structure is not * supported by the current IDEA interfaces some simplifications are made in the case * of the merge, so changes are reported as difference with the first revision * listed on the the merge that has at least some changes. * * * * @param project the project file * @param root the git root * @param revisionName the name of revision (might be tag) * @param skipDiffsForMerge * @param local * @param revertable * @return change list for the respective revision * @throws VcsException in case of problem with running git */ public static GitCommittedChangeList getRevisionChanges(Project project, VirtualFile root, String revisionName, boolean skipDiffsForMerge, boolean local, boolean revertable) throws VcsException { GitLineHandler h = new GitLineHandler(project, root, GitCommand.SHOW); h.setSilent(true); h.addParameters("--name-status", "--first-parent", "--no-abbrev", "-M", "--pretty=format:" + COMMITTED_CHANGELIST_FORMAT, "--encoding=UTF-8", revisionName, "--"); String output = Git.getInstance().runCommand(h).getOutputOrThrow(); StringScanner s = new StringScanner(output); return parseChangeList(project, root, s, skipDiffsForMerge, h, local, revertable); } @Nullable public static SHAHash commitExists(final Project project, final VirtualFile root, final String anyReference, List<VirtualFile> paths, final String... parameters) { GitLineHandler h = new GitLineHandler(project, root, GitCommand.LOG); h.setSilent(true); h.addParameters(parameters); h.addParameters("--max-count=1", "--pretty=%H", "--encoding=UTF-8", anyReference, "--"); if (paths != null && ! paths.isEmpty()) { h.addRelativeFiles(paths); } try { final String output = Git.getInstance().runCommand(h).getOutputOrThrow().trim(); if (StringUtil.isEmptyOrSpaces(output)) return null; return new SHAHash(output); } catch (VcsException e) { return null; } } /** * Parse changelist * * * * @param project the project * @param root the git root * @param s the scanner for log or show command output * @param skipDiffsForMerge * @param handler the handler that produced the output to parse. - for debugging purposes. * @param local pass {@code true} to indicate that this revision should be an editable * {@link com.intellij.openapi.vcs.changes.CurrentContentRevision}. * Pass {@code false} for * @param revertable * @return the parsed changelist * @throws VcsException if there is a problem with running git */ public static GitCommittedChangeList parseChangeList(Project project, VirtualFile root, StringScanner s, boolean skipDiffsForMerge, GitHandler handler, boolean local, boolean revertable) throws VcsException { ArrayList<Change> changes = new ArrayList<>(); // parse commit information final Date commitDate = GitUtil.parseTimestampWithNFEReport(s.line(), handler, s.getAllText()); final String revisionNumber = s.line(); final String parentsLine = s.line(); final String[] parents = parentsLine.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : parentsLine.split(" "); String authorName = s.line(); String committerName = s.line(); committerName = GitUtil.adjustAuthorName(authorName, committerName); String commentSubject = s.boundedToken('\u0003', true); s.nextLine(); String commentBody = s.boundedToken('\u0003', true); // construct full comment String fullComment; if (commentSubject.length() == 0) { fullComment = commentBody; } else if (commentBody.length() == 0) { fullComment = commentSubject; } else { fullComment = commentSubject + "\n" + commentBody; } GitRevisionNumber thisRevision = new GitRevisionNumber(revisionNumber, commitDate); if (skipDiffsForMerge || (parents.length <= 1)) { final GitRevisionNumber parentRevision = parents.length > 0 ? resolveReference(project, root, parents[0]) : null; // This is the first or normal commit with the single parent. // Just parse changes in this commit as returned by the show command. parseChanges(project, root, thisRevision, local ? null : parentRevision, s, changes, null); } else { // This is the merge commit. It has multiple parent commits. // Find the first commit with changes and report it as a change list. // If no changes are found (why to merge then?). Empty changelist is reported. for (String parent : parents) { final GitRevisionNumber parentRevision = resolveReference(project, root, parent); GitLineHandler diffHandler = new GitLineHandler(project, root, GitCommand.DIFF); diffHandler.setSilent(true); diffHandler.addParameters("--name-status", "-M", parentRevision.getRev(), thisRevision.getRev()); String diff = Git.getInstance().runCommand(diffHandler).getOutputOrThrow(); parseChanges(project, root, thisRevision, parentRevision, diff, changes, null); if (changes.size() > 0) { break; } } } String changeListName = String.format("%s(%s)", commentSubject, revisionNumber); return new GitCommittedChangeList(changeListName, fullComment, committerName, thisRevision, commitDate, changes, GitVcs.getInstance(project), revertable); } public static long longForSHAHash(String revisionNumber) { return Long.parseLong(revisionNumber.substring(0, 15), 16) << 4 + Integer.parseInt(revisionNumber.substring(15, 16), 16); } @NotNull public static Collection<Change> getDiff(@NotNull Project project, @NotNull VirtualFile root, @Nullable String oldRevision, @Nullable String newRevision, @Nullable Collection<FilePath> dirtyPaths) throws VcsException { return getDiff(project, root, oldRevision, newRevision, dirtyPaths, true); } @NotNull private static Collection<Change> getDiff(@NotNull Project project, @NotNull VirtualFile root, @Nullable String oldRevision, @Nullable String newRevision, @Nullable Collection<FilePath> dirtyPaths, boolean detectRenames) throws VcsException { LOG.assertTrue(oldRevision != null || newRevision != null, "Both old and new revisions can't be null"); String range; GitRevisionNumber newRev; GitRevisionNumber oldRev; if (newRevision == null) { // current revision at the right range = oldRevision + ".."; oldRev = resolveReference(project, root, oldRevision); newRev = null; } else if (oldRevision == null) { // current revision at the left range = ".." + newRevision; oldRev = null; newRev = resolveReference(project, root, newRevision); } else { range = oldRevision + ".." + newRevision; oldRev = resolveReference(project, root, oldRevision); newRev = resolveReference(project, root, newRevision); } String output = getDiffOutput(project, root, range, dirtyPaths, false, detectRenames); Collection<Change> changes = new ArrayList<>(); parseChanges(project, root, newRev, oldRev, output, changes, emptySet()); return changes; } @NotNull public static Collection<Change> getStagedChanges(@NotNull Project project, @NotNull VirtualFile root) throws VcsException { GitLineHandler diff = new GitLineHandler(project, root, GitCommand.DIFF); diff.addParameters("--name-status", "--cached", "-M"); String output = Git.getInstance().runCommand(diff).getOutputOrThrow(); Collection<Change> changes = new ArrayList<>(); parseChanges(project, root, null, GitRevisionNumber.HEAD, output, changes, emptySet()); return changes; } @NotNull public static Collection<Change> getDiffWithWorkingDir(@NotNull Project project, @NotNull VirtualFile root, @NotNull String oldRevision, @Nullable Collection<FilePath> dirtyPaths, boolean reverse) throws VcsException { return getDiffWithWorkingDir(project, root, oldRevision, dirtyPaths, reverse, true); } @NotNull private static Collection<Change> getDiffWithWorkingDir(@NotNull Project project, @NotNull VirtualFile root, @NotNull String oldRevision, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) throws VcsException { String output = getDiffOutput(project, root, oldRevision, dirtyPaths, reverse, detectRenames); Collection<Change> changes = new ArrayList<>(); final GitRevisionNumber revisionNumber = resolveReference(project, root, oldRevision); parseChanges(project, root, reverse ? revisionNumber : null, reverse ? null : revisionNumber, output, changes, emptySet()); return changes; } /** * Calls {@code git diff} on the given range. * @param project * @param root * @param diffRange range or just revision (will be compared with current working tree). * @param dirtyPaths limit the command by paths if needed or pass null. * @param reverse swap two revision; that is, show differences from index or on-disk file to tree contents. * @return output of the 'git diff' command. * @throws VcsException */ @NotNull private static String getDiffOutput(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) throws VcsException { GitLineHandler handler = getDiffHandler(project, root, diffRange, dirtyPaths, reverse, detectRenames); if (handler.isLargeCommandLine()) { // if there are too much files, just get all changes for the project handler = getDiffHandler(project, root, diffRange, null, reverse, detectRenames); } return Git.getInstance().runCommand(handler).getOutputOrThrow(); } @NotNull public static String getDiffOutput(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths) throws VcsException { return getDiffOutput(project, root, diffRange, dirtyPaths, false, true); } @NotNull private static GitLineHandler getDiffHandler(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) { GitLineHandler handler = new GitLineHandler(project, root, GitCommand.DIFF); if (reverse) { handler.addParameters("-R"); } handler.addParameters("--name-status", "--diff-filter=ADCMRUXT"); if (detectRenames) { handler.addParameters("-M"); } handler.addParameters(diffRange); handler.setSilent(true); handler.setStdoutSuppressed(true); handler.endOptions(); if (dirtyPaths != null) { handler.addRelativePaths(dirtyPaths); } return handler; } /** * Returns the changes between current working tree state and the given ref, or null if fails to get the diff. */ @Nullable public static Collection<Change> getDiffWithWorkingTree(@NotNull GitRepository repository, @NotNull String refToCompare, boolean detectRenames) { Collection<Change> changes; try { changes = getDiffWithWorkingDir(repository.getProject(), repository.getRoot(), refToCompare, null, false, detectRenames); } catch (VcsException e) { LOG.warn("Couldn't collect diff", e); changes = null; } return changes; } @Nullable public static Collection<Change> getDiff(@NotNull GitRepository repository, @NotNull String oldRevision, @NotNull String newRevision, boolean detectRenames) { try { return getDiff(repository.getProject(), repository.getRoot(), oldRevision, newRevision, null, detectRenames); } catch (VcsException e) { LOG.info("Couldn't collect changes between " + oldRevision + " and " + newRevision, e); return null; } } }
plugins/git4idea/src/git4idea/changes/GitChangeUtils.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.changes; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import git4idea.GitContentRevision; import git4idea.GitRevisionNumber; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.commands.*; import git4idea.history.browser.SHAHash; import git4idea.repo.GitRepository; import git4idea.util.StringScanner; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.*; import static java.util.Collections.emptySet; /** * Change related utilities */ public class GitChangeUtils { /** * the pattern for committed changelist assumed. */ public static final String COMMITTED_CHANGELIST_FORMAT = "%ct%n%H%n%P%n%an%x20%x3C%ae%x3E%n%cn%x20%x3C%ce%x3E%n%s%n%x03%n%b%n%x03"; private static final Logger LOG = Logger.getInstance(GitChangeUtils.class); /** * A private constructor for utility class */ private GitChangeUtils() { } /** * Parse changes from lines * * @param project the context project * @param vcsRoot the git root * @param thisRevision the current revision * @param parentRevision the parent revision for this change list * @param s the lines to parse * @param changes a list of changes to update * @param ignoreNames a set of names ignored during collection of the changes * @throws VcsException if the input format does not matches expected format */ public static void parseChanges(Project project, VirtualFile vcsRoot, @Nullable GitRevisionNumber thisRevision, GitRevisionNumber parentRevision, String s, Collection<Change> changes, final Set<String> ignoreNames) throws VcsException { StringScanner sc = new StringScanner(s); parseChanges(project, vcsRoot, thisRevision, parentRevision, sc, changes, ignoreNames); if (sc.hasMoreData()) { throw new IllegalStateException("Unknown file status: " + sc.line()); } } public static Collection<String> parseDiffForPaths(final String rootPath, final StringScanner s) throws VcsException { final Collection<String> result = new ArrayList<>(); while (s.hasMoreData()) { if (s.isEol()) { s.nextLine(); continue; } if ("CADUMR".indexOf(s.peek()) == -1) { // exit if there is no next character break; } assert 'M' != s.peek() : "Moves are not yet handled"; String[] tokens = s.line().split("\t"); String path = tokens[tokens.length - 1]; path = rootPath + File.separator + GitUtil.unescapePath(path); path = FileUtil.toSystemDependentName(path); result.add(path); } return result; } /** * Parse changes from lines * * @param project the context project * @param vcsRoot the git root * @param thisRevision the current revision * @param parentRevision the parent revision for this change list * @param s the lines to parse * @param changes a list of changes to update * @param ignoreNames a set of names ignored during collection of the changes * @throws VcsException if the input format does not matches expected format */ private static void parseChanges(Project project, VirtualFile vcsRoot, @Nullable GitRevisionNumber thisRevision, @Nullable GitRevisionNumber parentRevision, StringScanner s, Collection<Change> changes, final Set<String> ignoreNames) throws VcsException { while (s.hasMoreData()) { FileStatus status = null; if (s.isEol()) { s.nextLine(); continue; } if ("CADUMRT".indexOf(s.peek()) == -1) { // exit if there is no next character return; } String[] tokens = s.line().split("\t"); final ContentRevision before; final ContentRevision after; final String path = tokens[tokens.length - 1]; switch (tokens[0].charAt(0)) { case 'C': case 'A': before = null; status = FileStatus.ADDED; after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'U': status = FileStatus.MERGED_WITH_CONFLICTS; case 'M': if (status == null) { status = FileStatus.MODIFIED; } before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'D': status = FileStatus.DELETED; before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = null; break; case 'R': status = FileStatus.MODIFIED; before = GitContentRevision.createRevision(vcsRoot, tokens[1], parentRevision, project, true, true); after = GitContentRevision.createRevision(vcsRoot, path, thisRevision, project, false, true); break; case 'T': status = FileStatus.MODIFIED; before = GitContentRevision.createRevision(vcsRoot, path, parentRevision, project, true, true); after = GitContentRevision.createRevisionForTypeChange(project, vcsRoot, path, thisRevision, true); break; default: throw new VcsException("Unknown file status: " + Arrays.asList(tokens)); } if (ignoreNames == null || !ignoreNames.contains(path)) { changes.add(new Change(before, after, status)); } } } /** * Load actual revision number with timestamp basing on a reference: name of a branch or tag, or revision number expression. */ @NotNull public static GitRevisionNumber resolveReference(@NotNull Project project, @NotNull VirtualFile vcsRoot, @NotNull String reference) throws VcsException { GitLineHandler handler = createRefResolveHandler(project, vcsRoot, reference); String output = Git.getInstance().runCommand(handler).getOutputOrThrow(); StringTokenizer stk = new StringTokenizer(output, "\n\r \t", false); if (!stk.hasMoreTokens()) { try { GitLineHandler dh = new GitLineHandler(project, vcsRoot, GitCommand.LOG); dh.addParameters("-1", "HEAD"); dh.setSilent(true); String out = Git.getInstance().runCommand(dh).getOutputOrThrow(); LOG.info("Diagnostic output from 'git log -1 HEAD': [" + out + "]"); dh = createRefResolveHandler(project, vcsRoot, reference); out = Git.getInstance().runCommand(dh).getOutputOrThrow(); LOG.info("Diagnostic output from 'git rev-list -1 --timestamp HEAD': [" + out + "]"); } catch (VcsException e) { LOG.info("Exception while trying to get some diagnostics info", e); } throw new VcsException(String.format("The string '%s' does not represent a revision number. Output: [%s]\n Root: %s", reference, output, vcsRoot)); } Date timestamp = GitUtil.parseTimestampWithNFEReport(stk.nextToken(), handler, output); return new GitRevisionNumber(stk.nextToken(), timestamp); } @NotNull private static GitLineHandler createRefResolveHandler(@NotNull Project project, @NotNull VirtualFile root, @NotNull String reference) { GitLineHandler handler = new GitLineHandler(project, root, GitCommand.REV_LIST); handler.addParameters("--timestamp", "--max-count=1", reference); handler.endOptions(); handler.setSilent(true); return handler; } /** * Check if the exception means that HEAD is missing for the current repository. * * @param e the exception to examine * @return true if the head is missing */ public static boolean isHeadMissing(final VcsException e) { @NonNls final String errorText = "fatal: bad revision 'HEAD'\n"; return e.getMessage().equals(errorText); } /** * Get list of changes. Because native Git non-linear revision tree structure is not * supported by the current IDEA interfaces some simplifications are made in the case * of the merge, so changes are reported as difference with the first revision * listed on the the merge that has at least some changes. * * * * @param project the project file * @param root the git root * @param revisionName the name of revision (might be tag) * @param skipDiffsForMerge * @param local * @param revertable * @return change list for the respective revision * @throws VcsException in case of problem with running git */ public static GitCommittedChangeList getRevisionChanges(Project project, VirtualFile root, String revisionName, boolean skipDiffsForMerge, boolean local, boolean revertable) throws VcsException { GitLineHandler h = new GitLineHandler(project, root, GitCommand.SHOW); h.setSilent(true); h.addParameters("--name-status", "--first-parent", "--no-abbrev", "-M", "--pretty=format:" + COMMITTED_CHANGELIST_FORMAT, "--encoding=UTF-8", revisionName, "--"); String output = Git.getInstance().runCommand(h).getOutputOrThrow(); StringScanner s = new StringScanner(output); return parseChangeList(project, root, s, skipDiffsForMerge, h, local, revertable); } @Nullable public static SHAHash commitExists(final Project project, final VirtualFile root, final String anyReference, List<VirtualFile> paths, final String... parameters) { GitLineHandler h = new GitLineHandler(project, root, GitCommand.LOG); h.setSilent(true); h.addParameters(parameters); h.addParameters("--max-count=1", "--pretty=%H", "--encoding=UTF-8", anyReference, "--"); if (paths != null && ! paths.isEmpty()) { h.addRelativeFiles(paths); } try { final String output = Git.getInstance().runCommand(h).getOutputOrThrow().trim(); if (StringUtil.isEmptyOrSpaces(output)) return null; return new SHAHash(output); } catch (VcsException e) { return null; } } /** * Parse changelist * * * * @param project the project * @param root the git root * @param s the scanner for log or show command output * @param skipDiffsForMerge * @param handler the handler that produced the output to parse. - for debugging purposes. * @param local pass {@code true} to indicate that this revision should be an editable * {@link com.intellij.openapi.vcs.changes.CurrentContentRevision}. * Pass {@code false} for * @param revertable * @return the parsed changelist * @throws VcsException if there is a problem with running git */ public static GitCommittedChangeList parseChangeList(Project project, VirtualFile root, StringScanner s, boolean skipDiffsForMerge, GitHandler handler, boolean local, boolean revertable) throws VcsException { ArrayList<Change> changes = new ArrayList<>(); // parse commit information final Date commitDate = GitUtil.parseTimestampWithNFEReport(s.line(), handler, s.getAllText()); final String revisionNumber = s.line(); final String parentsLine = s.line(); final String[] parents = parentsLine.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : parentsLine.split(" "); String authorName = s.line(); String committerName = s.line(); committerName = GitUtil.adjustAuthorName(authorName, committerName); String commentSubject = s.boundedToken('\u0003', true); s.nextLine(); String commentBody = s.boundedToken('\u0003', true); // construct full comment String fullComment; if (commentSubject.length() == 0) { fullComment = commentBody; } else if (commentBody.length() == 0) { fullComment = commentSubject; } else { fullComment = commentSubject + "\n" + commentBody; } GitRevisionNumber thisRevision = new GitRevisionNumber(revisionNumber, commitDate); if (skipDiffsForMerge || (parents.length <= 1)) { final GitRevisionNumber parentRevision = parents.length > 0 ? resolveReference(project, root, parents[0]) : null; // This is the first or normal commit with the single parent. // Just parse changes in this commit as returned by the show command. parseChanges(project, root, thisRevision, local ? null : parentRevision, s, changes, null); } else { // This is the merge commit. It has multiple parent commits. // Find the first commit with changes and report it as a change list. // If no changes are found (why to merge then?). Empty changelist is reported. for (String parent : parents) { final GitRevisionNumber parentRevision = resolveReference(project, root, parent); GitLineHandler diffHandler = new GitLineHandler(project, root, GitCommand.DIFF); diffHandler.setSilent(true); diffHandler.addParameters("--name-status", "-M", parentRevision.getRev(), thisRevision.getRev()); String diff = Git.getInstance().runCommand(diffHandler).getOutputOrThrow(); parseChanges(project, root, thisRevision, parentRevision, diff, changes, null); if (changes.size() > 0) { break; } } } String changeListName = String.format("%s(%s)", commentSubject, revisionNumber); return new GitCommittedChangeList(changeListName, fullComment, committerName, thisRevision, commitDate, changes, GitVcs.getInstance(project), revertable); } public static long longForSHAHash(String revisionNumber) { return Long.parseLong(revisionNumber.substring(0, 15), 16) << 4 + Integer.parseInt(revisionNumber.substring(15, 16), 16); } @NotNull public static Collection<Change> getDiff(@NotNull Project project, @NotNull VirtualFile root, @Nullable String oldRevision, @Nullable String newRevision, @Nullable Collection<FilePath> dirtyPaths) throws VcsException { return getDiff(project, root, oldRevision, newRevision, dirtyPaths, true); } @NotNull private static Collection<Change> getDiff(@NotNull Project project, @NotNull VirtualFile root, @Nullable String oldRevision, @Nullable String newRevision, @Nullable Collection<FilePath> dirtyPaths, boolean detectRenames) throws VcsException { LOG.assertTrue(oldRevision != null || newRevision != null, "Both old and new revisions can't be null"); String range; GitRevisionNumber newRev; GitRevisionNumber oldRev; if (newRevision == null) { // current revision at the right range = oldRevision + ".."; oldRev = resolveReference(project, root, oldRevision); newRev = null; } else if (oldRevision == null) { // current revision at the left range = ".." + newRevision; oldRev = null; newRev = resolveReference(project, root, newRevision); } else { range = oldRevision + ".." + newRevision; oldRev = resolveReference(project, root, oldRevision); newRev = resolveReference(project, root, newRevision); } String output = getDiffOutput(project, root, range, dirtyPaths, false, detectRenames); Collection<Change> changes = new ArrayList<>(); parseChanges(project, root, newRev, oldRev, output, changes, emptySet()); return changes; } @NotNull public static Collection<Change> getStagedChanges(@NotNull Project project, @NotNull VirtualFile root) throws VcsException { GitLineHandler diff = new GitLineHandler(project, root, GitCommand.DIFF); diff.addParameters("--name-status", "--cached", "-M"); String output = Git.getInstance().runCommand(diff).getOutputOrThrow(); Collection<Change> changes = new ArrayList<>(); parseChanges(project, root, null, GitRevisionNumber.HEAD, output, changes, emptySet()); return changes; } @NotNull public static Collection<Change> getDiffWithWorkingDir(@NotNull Project project, @NotNull VirtualFile root, @NotNull String oldRevision, @Nullable Collection<FilePath> dirtyPaths, boolean reverse) throws VcsException { return getDiffWithWorkingDir(project, root, oldRevision, dirtyPaths, reverse, true); } @NotNull private static Collection<Change> getDiffWithWorkingDir(@NotNull Project project, @NotNull VirtualFile root, @NotNull String oldRevision, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) throws VcsException { String output = getDiffOutput(project, root, oldRevision, dirtyPaths, reverse, detectRenames); Collection<Change> changes = new ArrayList<>(); final GitRevisionNumber revisionNumber = resolveReference(project, root, oldRevision); parseChanges(project, root, reverse ? revisionNumber : null, reverse ? null : revisionNumber, output, changes, emptySet()); return changes; } /** * Calls {@code git diff} on the given range. * @param project * @param root * @param diffRange range or just revision (will be compared with current working tree). * @param dirtyPaths limit the command by paths if needed or pass null. * @param reverse swap two revision; that is, show differences from index or on-disk file to tree contents. * @return output of the 'git diff' command. * @throws VcsException */ @NotNull private static String getDiffOutput(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) throws VcsException { GitLineHandler handler = getDiffHandler(project, root, diffRange, dirtyPaths, reverse, detectRenames); if (handler.isLargeCommandLine()) { // if there are too much files, just get all changes for the project handler = getDiffHandler(project, root, diffRange, null, reverse, detectRenames); } return Git.getInstance().runCommand(handler).getOutputOrThrow(); } @NotNull public static String getDiffOutput(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths) throws VcsException { return getDiffOutput(project, root, diffRange, dirtyPaths, false, true); } @NotNull private static GitLineHandler getDiffHandler(@NotNull Project project, @NotNull VirtualFile root, @NotNull String diffRange, @Nullable Collection<FilePath> dirtyPaths, boolean reverse, boolean detectRenames) { GitLineHandler handler = new GitLineHandler(project, root, GitCommand.DIFF); if (reverse) { handler.addParameters("-R"); } handler.addParameters("--name-status", "--diff-filter=ADCMRUXT"); if (detectRenames) { handler.addParameters("-M"); } handler.addParameters(diffRange); handler.setSilent(true); handler.setStdoutSuppressed(true); handler.endOptions(); if (dirtyPaths != null) { handler.addRelativePaths(dirtyPaths); } return handler; } /** * Returns the changes between current working tree state and the given ref, or null if fails to get the diff. */ @Nullable public static Collection<Change> getDiffWithWorkingTree(@NotNull GitRepository repository, @NotNull String refToCompare, boolean detectRenames) { Collection<Change> changes; try { changes = getDiffWithWorkingDir(repository.getProject(), repository.getRoot(), refToCompare, null, false, detectRenames); } catch (VcsException e) { LOG.warn("Couldn't collect diff", e); changes = null; } return changes; } @Nullable public static Collection<Change> getDiff(@NotNull GitRepository repository, @NotNull String oldRevision, @NotNull String newRevision, boolean detectRenames) { try { return getDiff(repository.getProject(), repository.getRoot(), oldRevision, newRevision, null, detectRenames); } catch (VcsException e) { LOG.warn("Couldn't collect changes between " + oldRevision + " and " + newRevision, e); return null; } } }
git: log info instead of warn No difference for production, but less spam in tests. The error itself is valid, e.g. when trying to checkout a reference which exists not in all repositories, collecting the pre-diff fails, but it is easier and faster to try to call diff and fail instead of calculating whether the reference exists (e.g. if it is a hash).
plugins/git4idea/src/git4idea/changes/GitChangeUtils.java
git: log info instead of warn
<ide><path>lugins/git4idea/src/git4idea/changes/GitChangeUtils.java <ide> return getDiff(repository.getProject(), repository.getRoot(), oldRevision, newRevision, null, detectRenames); <ide> } <ide> catch (VcsException e) { <del> LOG.warn("Couldn't collect changes between " + oldRevision + " and " + newRevision, e); <add> LOG.info("Couldn't collect changes between " + oldRevision + " and " + newRevision, e); <ide> return null; <ide> } <ide> }
Java
apache-2.0
d951928f795344fab32e9817cd5c7d454e6f102a
0
spearal/spearal-jpa2
/** * == @Spearal ==> * * Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spearal.jpa2.impl; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.IdentifiableType; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.SingularAttribute; import org.spearal.configuration.PartialObjectFactory.PartialObjectProxy; import org.spearal.configuration.PropertyFactory.Property; /** * @author William DRAI */ public class ProxyMerger { private final Logger log = Logger.getLogger(ProxyMerger.class.getName()); private final EntityManager entityManager; public ProxyMerger(EntityManager entityManager) { this.entityManager = entityManager; } public boolean isProxy(Object entity) { IdentityHashMap<Object, Object> cache = new IdentityHashMap<Object, Object>(); return isProxy(entity, cache); } public boolean isProxy(Object entity, IdentityHashMap<Object, Object> cache) { if (entity == null) return false; if (entity instanceof String || entity instanceof Number || entity instanceof Date || entity instanceof Type) return false; if (entity instanceof PartialObjectProxy) return true; if (cache.containsKey(entity)) return false; cache.put(entity, entity); PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } ManagedType<?> managedType = null; try { managedType = entityManager.getMetamodel().managedType(entity.getClass()); } catch (IllegalArgumentException iae) { throw new RuntimeException(entity.getClass().getName() + " is not a managed class", iae); } for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Object value = null; boolean fieldAccess = false; boolean readable = true; try { Attribute<?, ?> attribute = managedType.getAttribute(propertyDescriptor.getName()); if (attribute.getJavaMember() instanceof Field) { try { ((Field)attribute.getJavaMember()).setAccessible(true); value = ((Field)attribute.getJavaMember()).get(entity); fieldAccess = true; } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read field " + attribute.getName() + " of class " + entity.getClass(), iace); } } } catch (IllegalArgumentException iae) { // No JPA attribute } if (!fieldAccess) { if (propertyDescriptor.getReadMethod() != null) { try { value = propertyDescriptor.getReadMethod().invoke(entity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } else readable = false; } if (!readable) continue; if (value instanceof Collection<?>) { for (Object element : ((Collection<?>)value)) { if (isProxy(element, cache)) return true; } } else if (value instanceof Map<?, ?>) { for (Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) { if (isProxy(entry.getKey(), cache)) return true; if (isProxy(entry.getValue(), cache)) return true; } } else if (isProxy(value, cache)) return true; } return false; } @SuppressWarnings("unchecked") public <T> T merge(T entity) { IdentityHashMap<Object, Object> cache = new IdentityHashMap<Object, Object>(); return (T)merge(entity, cache); } private Object merge(Object detachedEntity, IdentityHashMap<Object, Object> cache) { if (detachedEntity == null) return null; if (cache.containsKey(detachedEntity)) return detachedEntity; cache.put(detachedEntity, detachedEntity); boolean isProxy = false; Class<?> entityClass = detachedEntity.getClass(); if (PartialObjectProxy.class.isInstance(detachedEntity)) { entityClass = entityClass.getSuperclass(); // proxy is a subclass of real entity class isProxy = true; } IdentifiableType<?> identifiableType; try { ManagedType<?> managedType = entityManager.getMetamodel().managedType(entityClass); if (!(managedType instanceof IdentifiableType<?>)) throw new RuntimeException("Entity class " + entityClass.getName() + " is not an entity"); identifiableType = (IdentifiableType<?>)managedType; } catch (IllegalArgumentException iae) { throw new RuntimeException("Entity class " + entityClass.getName() + " is not an entity", iae); } SingularAttribute<?, ?> idAttribute = identifiableType.getId(identifiableType.getIdType().getJavaType()); Object id = null; if (idAttribute.getJavaMember() instanceof Field && !isProxy) { ((Field)idAttribute.getJavaMember()).setAccessible(true); try { id = ((Field)idAttribute.getJavaMember()).get(detachedEntity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read id field " + idAttribute.getName(), iace); } } else { try { // Try JPA getter if (idAttribute.getJavaMember() instanceof Method) { id = ((Method)idAttribute.getJavaMember()).invoke(detachedEntity); } else { Method idGetter; try { idGetter = detachedEntity.getClass().getMethod("get" + idAttribute.getName().substring(0, 1).toUpperCase() + idAttribute.getName().substring(1)); id = idGetter.invoke(detachedEntity); } catch (NoSuchMethodException nsme) { throw new RuntimeException("Could not find id getter " + idAttribute.getName(), nsme); } } } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read id property " + idAttribute.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read id property " + idAttribute.getName(), ite); } } Object entity = null; if (id != null) entity = entityManager.find(entityClass, id); if (entity == null) { try { entity = entityClass.newInstance(); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not instantiate class " + entityClass, iace); } catch (InstantiationException ie) { throw new RuntimeException("Could not instantiate class " + entityClass, ie); } } // SingularAttribute<?, ?> versionAttribute = getVersionAttribute(entityManager.getMetamodel().managedType(entityClass)); // if (versionAttribute != null) { // Member versionMember = versionAttribute.getJavaMember(); // Object incomingVersion = null; // Object currentVersion = null; // String versionPropertyName = null; // // if (versionMember instanceof Field) { // versionPropertyName = Introspector.getBeanInfo(entityClass).get // currentVersion = ((Field)versionMember).get(entity); // } // if (versionMember instanceof Method) { // currentVersion = ((Method)versionMember).invoke(entity); // incomingVersion = ((Method)versionMember).invoke(detachedEntity); // if ((incomingVersion == null && currentVersion != null) // || (incomingVersion != null && currentVersion != null && incomingVersion instanceof Number && ((Number)incomingVersion).longValue() < ((Number)currentVersion).longValue()) // || (incomingVersion != null && currentVersion != null && incomingVersion instanceof Timestamp && ((Timestamp)incomingVersion).before(((Timestamp)currentVersion)))) { // throw new OptimisticLockException(entity); // } // } // } if (detachedEntity instanceof PartialObjectProxy) return mergeProxy(entity, (PartialObjectProxy)detachedEntity, cache); return mergeObject(entity, detachedEntity, cache); } private Object mergeProxy(Object entity, PartialObjectProxy detachedProxy, IdentityHashMap<Object, Object> cache) { PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } for (Property property : detachedProxy.$getDefinedProperties()) { String propertyName = property.getName(); Object value = null; try { value = property.getGetter().invoke(detachedProxy); } catch (IllegalAccessException iae) { throw new RuntimeException("Could not read property " + propertyName, iae); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyName, ite); } PropertyDescriptor propertyDescriptor = null; for (PropertyDescriptor pd : propertyDescriptors) { if (pd.getName().equals(propertyName)) { propertyDescriptor = pd; break; } } Attribute<?, ?> attribute = null; try { attribute = entityManager.getMetamodel().managedType(entity.getClass()).getAttribute(propertyName); } catch (IllegalArgumentException iae) { // Not a JPA attribute } if ((attribute != null && (attribute.isAssociation() || attribute.isCollection())) || attribute == null) value = merge(value, cache); // Should convert ??? // if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) { // value = convert(value, propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0]); // } try { // Persistent attributes if (attribute.getJavaMember() instanceof Field) { ((Field)attribute.getJavaMember()).setAccessible(true); try { ((Field)attribute.getJavaMember()).set(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write field " + attribute.getName(), iace); } } else if (attribute.getJavaMember() instanceof Method && propertyDescriptor.getWriteMethod() != null) { // Use setter try { propertyDescriptor.getWriteMethod().invoke(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write property " + attribute.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not write property " + attribute.getName(), ite); } } else log.logp(Level.FINE, ProxyMerger.class.getName(), "merge", "Property {0} on class {1} does not exist or is not writeable", new Object[] { propertyName, entity.getClass().getName() }); } catch (IllegalArgumentException iae) { if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) { try { propertyDescriptor.getWriteMethod().invoke(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write property " + propertyDescriptor.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not write property " + propertyDescriptor.getName(), ite); } } else log.logp(Level.FINE, ProxyMerger.class.getName(), "merge", "Property {0} on class {1} does not exist or is not writeable", new Object[] { propertyName, entity.getClass().getName() }); } } return entity; } protected Object mergeObject(Object entity, Object detachedEntity, IdentityHashMap<Object, Object> cache) { if (detachedEntity == null) return null; PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } if (entity != null && !entityManager.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(entity)) { // cache.contains() cannot be called on un unintialized proxy because hashCode will fail !! ManagedType<?> managedType = entityManager.getMetamodel().managedType(entity.getClass()); if (managedType instanceof IdentifiableType<?>) { // Class<?> idType = ((IdentifiableType<?>)managedType).getIdType().getJavaType(); // SingularAttribute<?, ?> idAttribute = ((IdentifiableType<?>)managedType).getId(idType); Object id = entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(detachedEntity); return entityManager.find(entity.getClass(), id); } } // If the detached entity has an id, we should get the managed instance ManagedType<?> managedType = entityManager.getMetamodel().managedType(entity.getClass()); Object id = entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(detachedEntity); if (id != null && managedType instanceof IdentifiableType<?>) { // Class<?> idType = ((IdentifiableType<?>)managedType).getIdType().getJavaType(); // SingularAttribute<?, ?> idAttribute = ((IdentifiableType<?>)managedType).getId(idType); return entityManager.find(entity.getClass(), id); } // If there is no id, traverse the object graph to merge associated objects for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Object value = null; boolean fieldAccess = false; boolean readable = true; Attribute<?, ?> attribute = null; try { attribute = managedType.getAttribute(propertyDescriptor.getName()); if (attribute.getJavaMember() instanceof Field) { try { ((Field)attribute.getJavaMember()).setAccessible(true); value = ((Field)attribute.getJavaMember()).get(entity); fieldAccess = true; } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read field " + attribute.getName() + " of class " + entity.getClass(), iace); } } } catch (IllegalArgumentException iae) { // No JPA attribute } if (!fieldAccess) { if (propertyDescriptor.getReadMethod() != null) { try { value = propertyDescriptor.getReadMethod().invoke(entity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } else readable = false; } if (!readable) continue; if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>)value; for (int idx = 0; idx < list.size(); idx++) { Object element = list.get(idx); if (element == null) continue; Object newElement = merge(element, cache); if (newElement != element) list.set(idx, newElement); } } else if (value instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> coll = (Collection<Object>)value; Iterator<Object> icoll = coll.iterator(); Set<Object> addedElements = new HashSet<Object>(); while (icoll.hasNext()) { Object element = icoll.next(); if (element != null) { Object newElement = merge(element, cache); if (newElement != element) { icoll.remove(); addedElements.add(newElement); } } } coll.addAll(addedElements); } else if (value instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>)value; Iterator<Entry<Object, Object>> ime = map.entrySet().iterator(); Map<Object, Object> addedElements = new HashMap<Object, Object>(); while (ime.hasNext()) { Entry<Object, Object> me = ime.next(); Object val = me.getValue(); if (val != null) { Object newVal = merge(val, cache); if (newVal != val) me.setValue(newVal); } Object key = me.getKey(); if (key != null) { Object newKey = merge(key, cache); if (newKey != key) { ime.remove(); addedElements.put(newKey, me.getValue()); } } } map.putAll(addedElements); } else { Object newValue = value; try { entityManager.getMetamodel().managedType(value.getClass()); newValue = merge(value, cache); } catch (IllegalArgumentException iae) { // Not an entity } if (fieldAccess) { try { ((Field)attribute.getJavaMember()).set(entity, newValue); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write field " + attribute.getName() + " of class " + entity.getClass(), iace); } } else { if (propertyDescriptor.getWriteMethod() != null) { try { propertyDescriptor.getWriteMethod().invoke(entity, newValue); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } } } } return entity; } public static SingularAttribute<?, ?> getVersionAttribute(ManagedType<?> managedType) { if (!(managedType instanceof IdentifiableType<?>)) return null; IdentifiableType<?> identifiableType = (IdentifiableType<?>)managedType; if (!identifiableType.hasVersionAttribute()) return null; for (SingularAttribute<?, ?> attribute : identifiableType.getSingularAttributes()) { if (attribute.isVersion()) return attribute; } return null; } }
src/main/java/org/spearal/jpa2/impl/ProxyMerger.java
/** * == @Spearal ==> * * Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spearal.jpa2.impl; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManager; import javax.persistence.metamodel.Attribute; import javax.persistence.metamodel.IdentifiableType; import javax.persistence.metamodel.ManagedType; import javax.persistence.metamodel.SingularAttribute; import org.spearal.configuration.PartialObjectFactory.PartialObjectProxy; import org.spearal.configuration.PropertyFactory.Property; /** * @author William DRAI */ public class ProxyMerger { private final Logger log = Logger.getLogger(ProxyMerger.class.getName()); private final EntityManager entityManager; public ProxyMerger(EntityManager entityManager) { this.entityManager = entityManager; } public boolean isProxy(Object entity) { IdentityHashMap<Object, Object> cache = new IdentityHashMap<Object, Object>(); return isProxy(entity, cache); } public boolean isProxy(Object entity, IdentityHashMap<Object, Object> cache) { if (entity == null) return false; if (entity instanceof String || entity instanceof Number || entity instanceof Date || entity instanceof Type) return false; if (entity instanceof PartialObjectProxy) return true; if (cache.containsKey(entity)) return false; cache.put(entity, entity); PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } ManagedType<?> managedType = null; try { managedType = entityManager.getMetamodel().managedType(entity.getClass()); } catch (IllegalArgumentException iae) { throw new RuntimeException(entity.getClass().getName() + " is not a managed class", iae); } for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Object value = null; boolean fieldAccess = false; boolean readable = true; try { Attribute<?, ?> attribute = managedType.getAttribute(propertyDescriptor.getName()); if (attribute.getJavaMember() instanceof Field) { try { ((Field)attribute.getJavaMember()).setAccessible(true); value = ((Field)attribute.getJavaMember()).get(entity); fieldAccess = true; } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read field " + attribute.getName() + " of class " + entity.getClass(), iace); } } } catch (IllegalArgumentException iae) { // No JPA attribute } if (!fieldAccess) { if (propertyDescriptor.getReadMethod() != null) { try { value = propertyDescriptor.getReadMethod().invoke(entity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } else readable = false; } if (!readable) continue; if (value instanceof Collection<?>) { for (Object element : ((Collection<?>)value)) { if (isProxy(element, cache)) return true; } } else if (value instanceof Map<?, ?>) { for (Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) { if (isProxy(entry.getKey(), cache)) return true; if (isProxy(entry.getValue(), cache)) return true; } } else if (isProxy(value, cache)) return true; } return false; } @SuppressWarnings("unchecked") public <T> T merge(T entity) { IdentityHashMap<Object, Object> cache = new IdentityHashMap<Object, Object>(); return (T)merge(entity, cache); } private Object merge(Object detachedEntity, IdentityHashMap<Object, Object> cache) { if (detachedEntity == null) return null; if (cache.containsKey(detachedEntity)) return detachedEntity; cache.put(detachedEntity, detachedEntity); boolean isProxy = false; Class<?> entityClass = detachedEntity.getClass(); if (PartialObjectProxy.class.isInstance(detachedEntity)) { entityClass = entityClass.getSuperclass(); // proxy is a subclass of real entity class isProxy = true; } IdentifiableType<?> identifiableType; try { ManagedType<?> managedType = entityManager.getMetamodel().managedType(entityClass); if (!(managedType instanceof IdentifiableType<?>)) throw new RuntimeException("Entity class " + entityClass.getName() + " is not an entity"); identifiableType = (IdentifiableType<?>)managedType; } catch (IllegalArgumentException iae) { throw new RuntimeException("Entity class " + entityClass.getName() + " is not an entity", iae); } SingularAttribute<?, ?> idAttribute = identifiableType.getId(identifiableType.getIdType().getJavaType()); Object id = null; if (idAttribute.getJavaMember() instanceof Field && !isProxy) { ((Field)idAttribute.getJavaMember()).setAccessible(true); try { id = ((Field)idAttribute.getJavaMember()).get(detachedEntity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read id field " + idAttribute.getName(), iace); } } else { try { // Try JPA getter if (idAttribute.getJavaMember() instanceof Method) { id = ((Method)idAttribute.getJavaMember()).invoke(detachedEntity); } else { Method idGetter; try { idGetter = detachedEntity.getClass().getMethod("get" + idAttribute.getName().substring(0, 1).toUpperCase() + idAttribute.getName().substring(1)); id = idGetter.invoke(detachedEntity); } catch (NoSuchMethodException nsme) { throw new RuntimeException("Could not find id getter " + idAttribute.getName(), nsme); } } } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read id property " + idAttribute.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read id property " + idAttribute.getName(), ite); } } Object entity = null; if (id != null) entity = entityManager.find(entityClass, (Serializable)id); if (entity == null) { try { entity = entityClass.newInstance(); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not instantiate class " + entityClass, iace); } catch (InstantiationException ie) { throw new RuntimeException("Could not instantiate class " + entityClass, ie); } } // SingularAttribute<?, ?> versionAttribute = getVersionAttribute(entityManager.getMetamodel().managedType(entityClass)); // if (versionAttribute != null) { // Member versionMember = versionAttribute.getJavaMember(); // Object incomingVersion = null; // Object currentVersion = null; // String versionPropertyName = null; // // if (versionMember instanceof Field) { // versionPropertyName = Introspector.getBeanInfo(entityClass).get // currentVersion = ((Field)versionMember).get(entity); // } // if (versionMember instanceof Method) { // currentVersion = ((Method)versionMember).invoke(entity); // incomingVersion = ((Method)versionMember).invoke(detachedEntity); // if ((incomingVersion == null && currentVersion != null) // || (incomingVersion != null && currentVersion != null && incomingVersion instanceof Number && ((Number)incomingVersion).longValue() < ((Number)currentVersion).longValue()) // || (incomingVersion != null && currentVersion != null && incomingVersion instanceof Timestamp && ((Timestamp)incomingVersion).before(((Timestamp)currentVersion)))) { // throw new OptimisticLockException(entity); // } // } // } if (detachedEntity instanceof PartialObjectProxy) return mergeProxy(entity, (PartialObjectProxy)detachedEntity, cache); else return mergeObject(entity, detachedEntity, cache); } private Object mergeProxy(Object entity, PartialObjectProxy detachedProxy, IdentityHashMap<Object, Object> cache) { PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } for (Property property : detachedProxy.$getDefinedProperties()) { String propertyName = property.getName(); Object value = null; try { value = property.getGetter().invoke(detachedProxy); } catch (IllegalAccessException iae) { throw new RuntimeException("Could not read property " + propertyName, iae); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyName, ite); } PropertyDescriptor propertyDescriptor = null; for (PropertyDescriptor pd : propertyDescriptors) { if (pd.getName().equals(propertyName)) { propertyDescriptor = pd; break; } } Attribute<?, ?> attribute = null; try { attribute = entityManager.getMetamodel().managedType(entity.getClass()).getAttribute(propertyName); } catch (IllegalArgumentException iae) { // Not a JPA attribute } if ((attribute != null && (attribute.isAssociation() || attribute.isCollection())) || attribute == null) value = merge(value, cache); // Should convert ??? // if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) { // value = convert(value, propertyDescriptor.getWriteMethod().getGenericParameterTypes()[0]); // } try { // Persistent attributes if (attribute.getJavaMember() instanceof Field) { ((Field)attribute.getJavaMember()).setAccessible(true); try { ((Field)attribute.getJavaMember()).set(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write field " + attribute.getName(), iace); } } else if (attribute.getJavaMember() instanceof Method && propertyDescriptor.getWriteMethod() != null) { // Use setter try { propertyDescriptor.getWriteMethod().invoke(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write property " + attribute.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not write property " + attribute.getName(), ite); } } else log.logp(Level.FINE, ProxyMerger.class.getName(), "merge", "Property {0} on class {1} does not exist or is not writeable", new Object[] { propertyName, entity.getClass().getName() }); } catch (IllegalArgumentException iae) { if (propertyDescriptor != null && propertyDescriptor.getWriteMethod() != null) { try { propertyDescriptor.getWriteMethod().invoke(entity, value); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write property " + propertyDescriptor.getName(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not write property " + propertyDescriptor.getName(), ite); } } else log.logp(Level.FINE, ProxyMerger.class.getName(), "merge", "Property {0} on class {1} does not exist or is not writeable", new Object[] { propertyName, entity.getClass().getName() }); } } return entity; } protected Object mergeObject(Object entity, Object detachedEntity, IdentityHashMap<Object, Object> cache) { if (detachedEntity == null) return null; PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(entity.getClass(), Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors(); } catch (IntrospectionException ie) { throw new RuntimeException("Could not introspect class " + entity.getClass(), ie); } if (entity != null && !entityManager.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(entity)) { // cache.contains() cannot be called on un unintialized proxy because hashCode will fail !! ManagedType<?> managedType = entityManager.getMetamodel().managedType(entity.getClass()); if (managedType instanceof IdentifiableType<?>) { // Class<?> idType = ((IdentifiableType<?>)managedType).getIdType().getJavaType(); // SingularAttribute<?, ?> idAttribute = ((IdentifiableType<?>)managedType).getId(idType); Object id = entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(detachedEntity); return entityManager.find(entity.getClass(), id); } } // If the detached entity has an id, we should get the managed instance ManagedType<?> managedType = entityManager.getMetamodel().managedType(entity.getClass()); Object id = entityManager.getEntityManagerFactory().getPersistenceUnitUtil().getIdentifier(detachedEntity); if (id != null && managedType instanceof IdentifiableType<?>) { // Class<?> idType = ((IdentifiableType<?>)managedType).getIdType().getJavaType(); // SingularAttribute<?, ?> idAttribute = ((IdentifiableType<?>)managedType).getId(idType); return entityManager.find(entity.getClass(), id); } // If there is no id, traverse the object graph to merge associated objects for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Object value = null; boolean fieldAccess = false; boolean readable = true; Attribute<?, ?> attribute = null; try { attribute = managedType.getAttribute(propertyDescriptor.getName()); if (attribute.getJavaMember() instanceof Field) { try { ((Field)attribute.getJavaMember()).setAccessible(true); value = ((Field)attribute.getJavaMember()).get(entity); fieldAccess = true; } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read field " + attribute.getName() + " of class " + entity.getClass(), iace); } } } catch (IllegalArgumentException iae) { // No JPA attribute } if (!fieldAccess) { if (propertyDescriptor.getReadMethod() != null) { try { value = propertyDescriptor.getReadMethod().invoke(entity); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } else readable = false; } if (!readable) continue; if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> list = (List<Object>)value; for (int idx = 0; idx < list.size(); idx++) { Object element = list.get(idx); if (element == null) continue; Object newElement = merge(element, cache); if (newElement != element) list.set(idx, newElement); } } else if (value instanceof Collection<?>) { @SuppressWarnings("unchecked") Collection<Object> coll = (Collection<Object>)value; Iterator<Object> icoll = coll.iterator(); Set<Object> addedElements = new HashSet<Object>(); while (icoll.hasNext()) { Object element = icoll.next(); if (element != null) { Object newElement = merge(element, cache); if (newElement != element) { icoll.remove(); addedElements.add(newElement); } } } coll.addAll(addedElements); } else if (value instanceof Map<?, ?>) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>)value; Iterator<Entry<Object, Object>> ime = map.entrySet().iterator(); Map<Object, Object> addedElements = new HashMap<Object, Object>(); while (ime.hasNext()) { Entry<Object, Object> me = ime.next(); Object val = me.getValue(); if (val != null) { Object newVal = merge(val, cache); if (newVal != val) me.setValue(newVal); } Object key = me.getKey(); if (key != null) { Object newKey = merge(key, cache); if (newKey != key) { ime.remove(); addedElements.put(newKey, me.getValue()); } } } map.putAll(addedElements); } else { Object newValue = value; try { entityManager.getMetamodel().managedType(value.getClass()); newValue = merge(value, cache); } catch (IllegalArgumentException iae) { // Not an entity } if (fieldAccess) { try { ((Field)attribute.getJavaMember()).set(entity, newValue); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not write field " + attribute.getName() + " of class " + entity.getClass(), iace); } } else { if (propertyDescriptor.getWriteMethod() != null) { try { propertyDescriptor.getWriteMethod().invoke(entity, newValue); } catch (IllegalAccessException iace) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), iace); } catch (InvocationTargetException ite) { throw new RuntimeException("Could not read property " + propertyDescriptor.getName() + " of class " + entity.getClass(), ite); } } } } } return entity; } public static SingularAttribute<?, ?> getVersionAttribute(ManagedType<?> managedType) { if (!(managedType instanceof IdentifiableType<?>)) return null; IdentifiableType<?> identifiableType = (IdentifiableType<?>)managedType; if (!identifiableType.hasVersionAttribute()) return null; for (SingularAttribute<?, ?> attribute : identifiableType.getSingularAttributes()) { if (attribute.isVersion()) return attribute; } return null; } }
Supress warnings...
src/main/java/org/spearal/jpa2/impl/ProxyMerger.java
Supress warnings...
<ide><path>rc/main/java/org/spearal/jpa2/impl/ProxyMerger.java <ide> import java.beans.IntrospectionException; <ide> import java.beans.Introspector; <ide> import java.beans.PropertyDescriptor; <del>import java.io.Serializable; <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.InvocationTargetException; <ide> import java.lang.reflect.Method; <ide> <ide> Object entity = null; <ide> if (id != null) <del> entity = entityManager.find(entityClass, (Serializable)id); <add> entity = entityManager.find(entityClass, id); <ide> <ide> if (entity == null) { <ide> try { <ide> <ide> if (detachedEntity instanceof PartialObjectProxy) <ide> return mergeProxy(entity, (PartialObjectProxy)detachedEntity, cache); <del> else <del> return mergeObject(entity, detachedEntity, cache); <add> return mergeObject(entity, detachedEntity, cache); <ide> } <ide> <ide>
Java
apache-2.0
4c6550a36fdd9a504692556561effbac964de9e9
0
chasehd/openwayback,kris-sigur/openwayback,kris-sigur/openwayback,kris-sigur/openwayback,chasehd/openwayback,MohammedElsayyed/openwayback,ukwa/openwayback,ukwa/openwayback,kris-sigur/openwayback,MohammedElsayyed/openwayback,iipc/openwayback,iipc/openwayback,chasehd/openwayback,MohammedElsayyed/openwayback,kris-sigur/openwayback,ukwa/openwayback,iipc/openwayback
/* * This file is part of the Wayback archival access software * (http://archive-access.sourceforge.net/projects/wayback/). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.archive.wayback.authenticationcontrol; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.util.IPRange; import org.archive.wayback.util.operator.BooleanOperator; /** * A BooleanOperator which results in true value if a users request originated * from within a list of configured IP ranges. * @author brad * */ public class IPMatchesBooleanOperator implements BooleanOperator<WaybackRequest> { private static final Logger LOGGER = Logger.getLogger(IPMatchesBooleanOperator .class.getName()); private List<IPRange> allowedRanges = null; private List<IPRange> trustedProxies = null; /** * @return null. this is a placeholder for Spring's getter/setter * examination */ public List<String> getAllowedRanges() { return null; } /** * @param allowedRanges parses each String IPRange provided, added them to * the list of IPRanges which this operator matches */ public void setAllowedRanges(List<String> allowedRanges) { this.allowedRanges = new ArrayList<IPRange>(); for(String ip : allowedRanges) { IPRange range = new IPRange(); if(range.setRange(ip)) { this.allowedRanges.add(range); } else { LOGGER.severe("Unable to parse range (" + ip + ")"); } } } /** * @return null. this is a placeholder for Spring's getter/setter * examination */ public List<String> getTrustedProxies() { return null; } /** * @param trustedProxies parses each String IPRange provided for the proxies, adding them to * the list of IPRanges which must be ignored by the IP match operator */ public void setTrustedProxies(List<String> trustedProxies) { this.trustedProxies = new ArrayList<IPRange>(); for (String ip : trustedProxies) { IPRange range = new IPRange(); if (range.setRange(ip)) { this.trustedProxies.add(range); } else { LOGGER.severe("Unable to parse range (" + ip + ")"); } } } public String getClientIPFromForwardedForHeader(String forwardedForHeader){ ArrayList<String> forwardingIPs; String ip = null; Boolean containsIP = false; if (forwardedForHeader.contains(",")) { forwardingIPs = new ArrayList<String>(Arrays.asList(forwardedForHeader.replace(" ", "").split(","))); Collections.reverse(forwardingIPs); for (String forwardingIP : forwardingIPs){ for (IPRange range : trustedProxies) { if (range.contains(forwardingIP)) { containsIP = true; break; } } if (!containsIP || (containsIP && forwardingIPs.get(forwardingIPs.size() -1).equals(forwardingIP))) { ip = forwardingIP; break; } } } else { ip = forwardedForHeader; } return ip; } public boolean isTrue(WaybackRequest value) { if(allowedRanges == null) { return false; } String ipString = value.getRemoteIPAddress(); if(ipString != null) { ipString = getClientIPFromForwardedForHeader(ipString); } else { return false; } byte[] ip = IPRange.matchIP(ipString); if(ip == null) { LOGGER.severe("Unable to parse remote IP address("+ipString+")"); } else { for(IPRange range : allowedRanges) { if(range.contains(ip)) { if(LOGGER.isLoggable(Level.FINE)){ LOGGER.fine(String.format("Range(%s) matched(%s)", range.getOriginal(),ipString)); } return true; } else { if(LOGGER.isLoggable(Level.FINE)){ LOGGER.fine(String.format("Range(%s) NO match(%s)", range.getOriginal(),ipString)); } } } } return false; } }
wayback-core/src/main/java/org/archive/wayback/authenticationcontrol/IPMatchesBooleanOperator.java
/* * This file is part of the Wayback archival access software * (http://archive-access.sourceforge.net/projects/wayback/). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.archive.wayback.authenticationcontrol; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.archive.wayback.core.WaybackRequest; import org.archive.wayback.util.IPRange; import org.archive.wayback.util.operator.BooleanOperator; /** * A BooleanOperator which results in true value if a users request originated * from within a list of configured IP ranges. * @author brad * */ public class IPMatchesBooleanOperator implements BooleanOperator<WaybackRequest> { private static final Logger LOGGER = Logger.getLogger(IPMatchesBooleanOperator .class.getName()); private List<IPRange> allowedRanges = null; private List<IPRange> trustedProxies = null; /** * @return null. this is a placeholder for Spring's getter/setter * examination */ public List<String> getAllowedRanges() { return null; } /** * @param allowedRanges parses each String IPRange provided, added them to * the list of IPRanges which this operator matches */ public void setAllowedRanges(List<String> allowedRanges) { this.allowedRanges = new ArrayList<IPRange>(); for(String ip : allowedRanges) { IPRange range = new IPRange(); if(range.setRange(ip)) { this.allowedRanges.add(range); } else { LOGGER.severe("Unable to parse range (" + ip + ")"); } } } /** * @return null. this is a placeholder for Spring's getter/setter * examination */ public List<String> getTrustedProxies() { return null; } /** * @param trustedProxies parses each String IPRange provided for the proxies, adding them to * the list of IPRanges which must be ignored by the IP match operator */ public void setTrustedProxies(List<String> trustedProxies) { this.trustedProxies = new ArrayList<IPRange>(); for (String ip : trustedProxies) { IPRange range = new IPRange(); if (range.setRange(ip)) { this.trustedProxies.add(range); } else { LOGGER.severe("Unable to parse range (" + ip + ")"); } } } public String getClientIPFromForwardedForHeader(String forwardedForHeader){ ArrayList<String> forwardingIPs; String ip = null; Boolean containsIP = false; if (forwardedForHeader.contains(",")) { forwardingIPs = new ArrayList<String>(Arrays.asList(forwardedForHeader.replace(" ", "").split(","))); Collections.reverse(forwardingIPs); for (String forwardingIP : forwardingIPs){ for (IPRange range : trustedProxies) { if (range.contains(forwardingIP)) { containsIP = true; break; } } if (!containsIP || (containsIP && forwardingIPs.get(forwardingIP.size() -1).equals(forwardingIP))) { ip = forwardingIP; break; } } } else { ip = forwardedForHeader; } return ip; } public boolean isTrue(WaybackRequest value) { if(allowedRanges == null) { return false; } String ipString = value.getRemoteIPAddress(); if(ipString != null) { ipString = getClientIPFromForwardedForHeader(ipString); } else { return false; } byte[] ip = IPRange.matchIP(ipString); if(ip == null) { LOGGER.severe("Unable to parse remote IP address("+ipString+")"); } else { for(IPRange range : allowedRanges) { if(range.contains(ip)) { if(LOGGER.isLoggable(Level.FINE)){ LOGGER.fine(String.format("Range(%s) matched(%s)", range.getOriginal(),ipString)); } return true; } else { if(LOGGER.isLoggable(Level.FINE)){ LOGGER.fine(String.format("Range(%s) NO match(%s)", range.getOriginal(),ipString)); } } } } return false; } }
Fixed typo getClientIPFromForwardedForHeader: changed forwardingIP.size() to forwardingIPs.size()
wayback-core/src/main/java/org/archive/wayback/authenticationcontrol/IPMatchesBooleanOperator.java
Fixed typo getClientIPFromForwardedForHeader:
<ide><path>ayback-core/src/main/java/org/archive/wayback/authenticationcontrol/IPMatchesBooleanOperator.java <ide> } <ide> } <ide> if (!containsIP || <del> (containsIP && forwardingIPs.get(forwardingIP.size() -1).equals(forwardingIP))) { <add> (containsIP && forwardingIPs.get(forwardingIPs.size() -1).equals(forwardingIP))) { <ide> ip = forwardingIP; <ide> break; <ide> }
Java
apache-2.0
b2c9b229f285fc96874a71cdbcb57f0417dc8260
0
tokee/lucene,adichad/lucene,adichad/lucene,tokee/lucene,tokee/lucene,adichad/lucene-new,tokee/lucene,adichad/lucene-new,adichad/lucene-new,adichad/lucene,adichad/lucene,adichad/lucene-new,adichad/lucene,adichad/lucene-new
package org.apache.lucene.index; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache Lucene" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache Lucene", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.IOException; import org.apache.lucene.util.BitVector; import org.apache.lucene.store.InputStream; class SegmentTermDocs implements TermDocs { protected SegmentReader parent; private InputStream freqStream; private int count; private int df; private BitVector deletedDocs; int doc = 0; int freq; private int skipInterval; private int numSkips; private int skipCount; private InputStream skipStream; private int skipDoc; private long freqPointer; private long proxPointer; private long skipPointer; private boolean haveSkipped; SegmentTermDocs(SegmentReader parent) throws IOException { this.parent = parent; this.freqStream = (InputStream) parent.freqStream.clone(); this.deletedDocs = parent.deletedDocs; this.skipInterval = parent.tis.getSkipInterval(); } public void seek(Term term) throws IOException { TermInfo ti = parent.tis.get(term); seek(ti); } public void seek(TermEnum enum) throws IOException { TermInfo ti; if (enum instanceof SegmentTermEnum) // optimized case ti = ((SegmentTermEnum) enum).termInfo(); else // punt case ti = parent.tis.get(enum.term()); seek(ti); } void seek(TermInfo ti) throws IOException { count = 0; if (ti == null) { df = 0; } else { df = ti.docFreq; doc = 0; skipDoc = 0; skipCount = 0; numSkips = df / skipInterval; freqPointer = ti.freqPointer; proxPointer = ti.proxPointer; skipPointer = freqPointer + ti.skipOffset; freqStream.seek(freqPointer); haveSkipped = false; } } public void close() throws IOException { freqStream.close(); } public final int doc() { return doc; } public final int freq() { return freq; } protected void skippingDoc() throws IOException { } public boolean next() throws IOException { while (true) { if (count == df) return false; int docCode = freqStream.readVInt(); doc += docCode >>> 1; // shift off low bit if ((docCode & 1) != 0) // if low bit is set freq = 1; // freq is one else freq = freqStream.readVInt(); // else read freq count++; if (deletedDocs == null || !deletedDocs.get(doc)) break; skippingDoc(); } return true; } /** Optimized implementation. */ public int read(final int[] docs, final int[] freqs) throws IOException { final int length = docs.length; int i = 0; while (i < length && count < df) { // manually inlined call to next() for speed final int docCode = freqStream.readVInt(); doc += docCode >>> 1; // shift off low bit if ((docCode & 1) != 0) // if low bit is set freq = 1; // freq is one else freq = freqStream.readVInt(); // else read freq count++; if (deletedDocs == null || !deletedDocs.get(doc)) { docs[i] = doc; freqs[i] = freq; ++i; } } return i; } /** Overridden by SegmentTermPositions to skip in prox stream. */ protected void skipProx(long proxPointer) throws IOException {} /** Optimized implementation. */ public boolean skipTo(int target) throws IOException { if (df > skipInterval) { // optimized case if (skipStream == null) skipStream = (InputStream) freqStream.clone(); // lazily clone if (!haveSkipped) { // lazily seek skip stream skipStream.seek(skipPointer); haveSkipped = true; } // scan skip data int lastSkipDoc = skipDoc; long lastFreqPointer = freqStream.getFilePointer(); long lastProxPointer = -1; int numSkipped = -1 - (count % skipInterval); while (target > skipDoc && skipCount < numSkips) { lastSkipDoc = skipDoc; lastFreqPointer = freqPointer; lastProxPointer = proxPointer; if (skipDoc != 0 && skipDoc >= doc) numSkipped += skipInterval; skipDoc += skipStream.readVInt(); freqPointer += skipStream.readVInt(); proxPointer += skipStream.readVInt(); skipCount++; } // if we found something to skip, then skip it if (lastFreqPointer > freqStream.getFilePointer()) { freqStream.seek(lastFreqPointer); skipProx(lastProxPointer); doc = lastSkipDoc; count += numSkipped; } } // done skipping, now just scan do { if (!next()) return false; } while (target > doc); return true; } }
src/java/org/apache/lucene/index/SegmentTermDocs.java
package org.apache.lucene.index; /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache Lucene" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache Lucene", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.IOException; import org.apache.lucene.util.BitVector; import org.apache.lucene.store.InputStream; class SegmentTermDocs implements TermDocs { protected SegmentReader parent; private InputStream freqStream; private int count; private int df; private BitVector deletedDocs; int doc = 0; int freq; private int skipInterval; private int skipCount; private InputStream skipStream; private int skipDoc; private long freqPointer; private long proxPointer; private long skipPointer; private boolean haveSkipped; SegmentTermDocs(SegmentReader parent) throws IOException { this.parent = parent; this.freqStream = (InputStream) parent.freqStream.clone(); this.deletedDocs = parent.deletedDocs; this.skipInterval = parent.tis.getSkipInterval(); } public void seek(Term term) throws IOException { TermInfo ti = parent.tis.get(term); seek(ti); } public void seek(TermEnum enum) throws IOException { TermInfo ti; if (enum instanceof SegmentTermEnum) // optimized case ti = ((SegmentTermEnum) enum).termInfo(); else // punt case ti = parent.tis.get(enum.term()); seek(ti); } void seek(TermInfo ti) throws IOException { count = 0; if (ti == null) { df = 0; } else { df = ti.docFreq; doc = 0; skipDoc = 0; skipCount = 0; freqPointer = ti.freqPointer; proxPointer = ti.proxPointer; skipPointer = freqPointer + ti.skipOffset; freqStream.seek(freqPointer); haveSkipped = false; } } public void close() throws IOException { freqStream.close(); } public final int doc() { return doc; } public final int freq() { return freq; } protected void skippingDoc() throws IOException { } public boolean next() throws IOException { while (true) { if (count == df) return false; int docCode = freqStream.readVInt(); doc += docCode >>> 1; // shift off low bit if ((docCode & 1) != 0) // if low bit is set freq = 1; // freq is one else freq = freqStream.readVInt(); // else read freq count++; if (deletedDocs == null || !deletedDocs.get(doc)) break; skippingDoc(); } return true; } /** Optimized implementation. */ public int read(final int[] docs, final int[] freqs) throws IOException { final int length = docs.length; int i = 0; while (i < length && count < df) { // manually inlined call to next() for speed final int docCode = freqStream.readVInt(); doc += docCode >>> 1; // shift off low bit if ((docCode & 1) != 0) // if low bit is set freq = 1; // freq is one else freq = freqStream.readVInt(); // else read freq count++; if (deletedDocs == null || !deletedDocs.get(doc)) { docs[i] = doc; freqs[i] = freq; ++i; } } return i; } /** Overridden by SegmentTermPositions to skip in prox stream. */ protected void skipProx(long proxPointer) throws IOException {} /** Optimized implementation. */ public boolean skipTo(int target) throws IOException { if (df > skipInterval) { // optimized case if (skipStream == null) skipStream = (InputStream) freqStream.clone(); // lazily clone if (!haveSkipped) { // lazily seek skip stream skipStream.seek(skipPointer); haveSkipped = true; } // scan skip data int lastSkipDoc = skipDoc; long lastFreqPointer = freqStream.getFilePointer(); long lastProxPointer = -1; int numSkipped = -1 - (count % skipInterval); while (target > skipDoc) { lastSkipDoc = skipDoc; lastFreqPointer = freqPointer; lastProxPointer = proxPointer; if (skipDoc != 0 && skipDoc >= doc) numSkipped += skipInterval; if ((count + numSkipped + skipInterval) >= df) break; // no more skips skipDoc += skipStream.readVInt(); freqPointer += skipStream.readVInt(); proxPointer += skipStream.readVInt(); skipCount++; } // if we found something to skip, then skip it if (lastFreqPointer > freqStream.getFilePointer()) { freqStream.seek(lastFreqPointer); skipProx(lastProxPointer); doc = lastSkipDoc; count += numSkipped; } } // done skipping, now just scan do { if (!next()) return false; } while (target > doc); return true; } }
Fix for bug 27799. git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150254 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/lucene/index/SegmentTermDocs.java
Fix for bug 27799.
<ide><path>rc/java/org/apache/lucene/index/SegmentTermDocs.java <ide> int freq; <ide> <ide> private int skipInterval; <add> private int numSkips; <ide> private int skipCount; <ide> private InputStream skipStream; <ide> private int skipDoc; <ide> doc = 0; <ide> skipDoc = 0; <ide> skipCount = 0; <add> numSkips = df / skipInterval; <ide> freqPointer = ti.freqPointer; <ide> proxPointer = ti.proxPointer; <ide> skipPointer = freqPointer + ti.skipOffset; <ide> long lastProxPointer = -1; <ide> int numSkipped = -1 - (count % skipInterval); <ide> <del> while (target > skipDoc) { <add> while (target > skipDoc && skipCount < numSkips) { <ide> lastSkipDoc = skipDoc; <ide> lastFreqPointer = freqPointer; <ide> lastProxPointer = proxPointer; <add> <ide> if (skipDoc != 0 && skipDoc >= doc) <ide> numSkipped += skipInterval; <del> <del> if ((count + numSkipped + skipInterval) >= df) <del> break; // no more skips <ide> <ide> skipDoc += skipStream.readVInt(); <ide> freqPointer += skipStream.readVInt();